text stringlengths 2 1.04M | meta dict |
|---|---|
chenxinlong translating
Who needs a GUI? How to live in a Linux terminal
=================================================

### The best Linux shell apps for handling common functions
Ever consider the idea of living entirely in a Linux terminal? No graphical desktop. No modern GUI software. Just text—and nothing but text—inside a Linux shell. It may not be easy, but it’s absolutely doable. [I recently tried living completely in a Linux shell for 30 days][1]. What follows are my favorite shell applications for handling some of the most common bits of computer functionality (web browsing, word processing, etc.). With a few obvious holes. Because being text-only is hard.

### Emailing within a Linux terminal
For emailing in a terminal, we are spoiled for choice. Many people recommend mutt and notmuch. Both of those are powerful and excellent, but I prefer alpine. Why? Not only does it work well, but it’s also much more of a familiar interface if you are used to GUI email software like Thunderbird.

### Web browsing within a Linux terminal
I have one word for you: [w3m][5]. Well, I suppose that’s not even really a word. But w3m is definitely my terminal web browser of choice. It tenders things fairly well and is powerful enough to even let you post to sites such as Google Plus (albeit, not in a terribly fun way). Lynx may be the de facto text-based web browser, but w3m is my favorite.

### Text editing within a Linux terminal
For editing simple text files, I have one application that I straight-up love. No, not emacs. Also, definitely not vim. For editing of a text file or jotting down some notes, I like nano. Yes, nano. It’s simple, easy to learn and pleasant to use. Are there pieces of software with more features? Sure. But nano is just delightful.

### Word processing within a Linux terminal
In a shell—with nothing but text—there really isn’t a huge difference between a “text editor” and a “word processor.” But being as I do a lot of writing, having a piece of software built specifically for long-form writing is a definite must. My favorite is wordgrinder. It has just enough tools to make me happy, a nice menu-driven interface (with hot-keys), and it supports multiple file types, including OpenDocument, HTML and a bunch of other ones.

### Music playing within a Linux terminal
When it comes to playing music (mp3, Ogg, etc.) from a shell, one piece of software is king: [cmus][7]. It supports every conceivable file format. It’s super easy to use and incredibly fast and light on system resource usage. So clean. So streamlined. This is what a good music player should be like.

### Instant messaging within a Linux terminal
When I realized how will I could instant message from the terminal, my head exploded. You know Pidgin, the multi-protocol IM client? Well, it has a version for the terminal, called “[finch][8],” that allows you to connect to multiple networks and chat with multiple people at once. The interface is even similar to Pidgin. Just amazing. Use Google Hangouts? Try [hangups][9]. It has a nice tabbed interface and works amazingly well. Seriously. Other than needing perhaps some emoji and inline pictures, instant messaging from the shell is a great experience.

### Tweeting within a Linux terminal
No joke. Twitter, in your terminal, thanks to [rainbowstream][10]. I hit a few bugs here and there, but overall, it works rather well. Not as well as the website itself—and not as well as the official mobile clients—but, come on, this is Twitter in a shell. Even if it has one or two rough edges, this is pretty stinkin’ cool.

### Reddit-ing within a Linux terminal
Spending time on Reddit from the comforts of the command line feels right somehow. And with rtv, it’s a rather pleasant experience. Reading. Commenting. Voting. It all works. The experience isn’t actually all that different than the website itself.

### Process managing within a Linux terminal
Use [htop][12]. It’s like top—only better and prettier. Sometimes I just leave htop up and running all the time. Just because. In that regard, it’s like a music visualizer—only for RAM and CPU usage.

### File managing within a Linux terminal
Just because you’re in a text-based shell doesn’t mean you don’t enjoy the finer things in life. Like having a nice file browser and manager. In that regard, [Midnight Commander][13] is a pretty doggone great one.

### Terminal managing within a Linux terminal
If you spend much time in the shell, you’re going to need a terminal multiplexer. Basically it’s a piece of software that lets you split up your terminal session into a customizable grid, allowing you to use and see multiple terminal applications at the same time. It’s a tiled window manager for your shell. My favorite is [tmux][14]. But [GNU Screen][15] is also quite nice. It might take a few minutes to learn how to use it, but once you do, you’ll be glad you did.

### Presentation-ing within a Linux terminal
LibreOffice, Google Slides or, gasp, PowerPoint. I spend a lot of time in presentation software. The fact that one exists for the shell pleases me greatly. It’s called, appropriately, “[text presentation program][16].” There are no images (obviously), just a simple program for displaying slides put together in a simple markup language. It may not let you embed pictures of cats, but you’ll earn some serious nerd-cred for doing an entire presentation from the terminal.
--------------------------------------------------------------------------------
via: http://www.networkworld.com/article/3091139/linux/who-needs-a-gui-how-to-live-in-a-linux-terminal.html#slide1
作者:[Bryan Lunduke][a]
译者:[译者ID](https://github.com/chenxinlong)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: http://www.networkworld.com/author/Bryan-Lunduke/
[1]: http://www.networkworld.com/article/3083268/linux/30-days-in-a-terminal-day-0-the-adventure-begins.html
[2]: https://en.wikipedia.org/wiki/Mutt_(email_client)
[3]: https://notmuchmail.org/
[4]: https://en.wikipedia.org/wiki/Alpine_(email_client)
[5]: https://en.wikipedia.org/wiki/W3m
[6]: http://cowlark.com/wordgrinder/index.html
[7]: https://en.wikipedia.org/wiki/Cmus
[8]: https://developer.pidgin.im/wiki/Using%20Finch
[9]: https://github.com/tdryer/hangups
[10]: http://www.rainbowstream.org/
[11]: https://github.com/michael-lazar/rtv
[12]: http://hisham.hm/htop/
[13]: https://en.wikipedia.org/wiki/Midnight_Commander
[14]: https://tmux.github.io/
[15]: https://en.wikipedia.org/wiki/GNU_Screen
[16]: http://www.ngolde.de/tpp.html
| {
"content_hash": "3fbab0cb3e941ff1f28f14719ba081ac",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 558,
"avg_line_length": 72.0091743119266,
"alnum_prop": 0.7537265893744426,
"repo_name": "jiajia9linuxer/TranslateProject",
"id": "148d75821693d7404412d0bf0999547c4cdacde1",
"size": "7983",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "sources/talk/20160606 Who needs a GUI - How to live in a Linux terminal.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GCC Machine Description",
"bytes": "33"
}
],
"symlink_target": ""
} |
package chatty.bot.commands;
import chatty.bot.Matchpreview.PreviewBot;
public class CmdTurnNotifications extends Cmd{
private boolean mode;
public CmdTurnNotifications(boolean mode){
this.mode = mode;
}
@Override
public void CallPreviewBot(PreviewBot pb) {
pb.TurnNotifications(super.getName(), mode);
}
public boolean isMode() {
return mode;
}
public void setMode(boolean mode) {
this.mode = mode;
}
}
| {
"content_hash": "b141dea8d86174aa77e0fc1888d35823",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 46,
"avg_line_length": 18.2,
"alnum_prop": 0.6967032967032967,
"repo_name": "Jolicost/ChattyTpp",
"id": "b9184b7d3a262d8d16e97da91f2cbeb45926af77",
"size": "455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/chatty/bot/commands/CmdTurnNotifications.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2136"
},
{
"name": "HTML",
"bytes": "315587"
},
{
"name": "Java",
"bytes": "2458341"
}
],
"symlink_target": ""
} |
<?xml version='1.0'?>
<!--
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.
-->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.activemq.examples.failover</groupId>
<artifactId>broker-failover</artifactId>
<version>1.6.0-SNAPSHOT</version>
</parent>
<artifactId>ha-policy-autobackup</artifactId>
<packaging>jar</packaging>
<name>ActiveMQ Artemis JMS HA Policy Auto backup example</name>
<properties>
<activemq.basedir>${project.basedir}/../../../..</activemq.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-cli</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-jms-client</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-maven-plugin</artifactId>
<executions>
<execution>
<id>create</id>
<goals>
<goal>create</goal>
</goals>
<configuration>
<!-- this makes it easier in certain envs -->
<javaOptions>-Djava.net.preferIPv4Stack=true</javaOptions>
<instance>${basedir}/target/server0</instance>
<configuration>${basedir}/target/classes/activemq/server0</configuration>
</configuration>
</execution>
<execution>
<id>create2</id>
<goals>
<goal>create</goal>
</goals>
<configuration>
<!-- this makes it easier in certain envs -->
<javaOptions>-Djava.net.preferIPv4Stack=true</javaOptions>
<instance>${basedir}/target/server1</instance>
<configuration>${basedir}/target/classes/activemq/server1</configuration>
</configuration>
</execution>
<execution>
<id>runClient</id>
<goals>
<goal>runClient</goal>
</goals>
<configuration>
<clientClass>org.apache.activemq.artemis.jms.example.HAPolicyAutoBackupExample</clientClass>
<args>
<param>${basedir}/target/server0</param>
<param>${basedir}/target/server1</param>
</args>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.activemq.examples.failover</groupId>
<artifactId>ha-policy-autobackup</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "4bfad5f952480b0f2b4de865388887f5",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 201,
"avg_line_length": 38.867924528301884,
"alnum_prop": 0.5740291262135923,
"repo_name": "paulgallagher75/activemq-artemis",
"id": "a3842868b59504e33bc775db9a1e2a2688951959",
"size": "4120",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/features/ha/ha-policy-autobackup/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11634"
},
{
"name": "C",
"bytes": "26484"
},
{
"name": "C++",
"bytes": "1197"
},
{
"name": "CMake",
"bytes": "4260"
},
{
"name": "CSS",
"bytes": "11732"
},
{
"name": "HTML",
"bytes": "19329"
},
{
"name": "Java",
"bytes": "23726369"
},
{
"name": "Shell",
"bytes": "34795"
}
],
"symlink_target": ""
} |
'use strict';
/**
* @ngdoc overview
* @name digitalCasefileApp
* @description
* # digitalCasefileApp
*
* Main module of the application.
*/
angular
.module('digitalCasefileApp', [
'ngCookies',
'ngAnimate',
'ngAria',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ngTable'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/disclaimer.html',
controller: 'DisclaimerCtrl'
})
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
controller: 'DashboardCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/casefile/:urn', {
templateUrl: 'views/casefile.html',
controller: 'CasefileCtrl'
})
.when('/contactsheet/', {
templateUrl: 'views/contactsheet.html',
controller: 'ContactsheetCtrl'
})
.when('/dcfdelete', {
templateUrl: 'views/dcfdelete.html',
controller: 'DcfdeleteCtrl'
})
.otherwise({
redirectTo: '/'
});
}).run(['$anchorScroll', function ($anchorScroll) {
$anchorScroll.yOffset = 210; // always scroll by 50 extra pixels
}]);
| {
"content_hash": "506808b79db0fbe3463326cfbd1106b2",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 66,
"avg_line_length": 22.163636363636364,
"alnum_prop": 0.5972108285479901,
"repo_name": "cleargif/digital-casefile-frontend",
"id": "3bbd0647eaef07cbb82c27e1885069ea5dae2484",
"size": "1219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/scripts/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "3507"
},
{
"name": "HTML",
"bytes": "69951"
},
{
"name": "JavaScript",
"bytes": "66695"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title><?php print $cabecalho_title;?></title>
<link href="https://fonts.googleapis.com/css?family=PT+Sans|Bad+Script" rel="stylesheet"> <!--Importano a font do site do google-->
<link rel="stylesheet" href="css/reset.css">
<!--Cada página incluir o arquivo css própio-->
<?php print @$cabecalho_css;?> <!--Utilizamos o '@' para tratar o erro, caso a variável não exista-->
<!--Ajustar a media query para aplicar o css de adaptação a qualquer tamanho de tela menor que os 940px do desktop(ou seja, no máximo,939px)-->
<link rel="stylesheet" href="css/mobile.css" media="(max-width:939px)">
<!--Adaptação para mobile-->
<meta name="viewport" content="width=device-width">
</head>
<body class="container">
<header>
<!--Suporte HTML5 no Internet Explorer Antigo-->
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<!--Fim código do suporte-->
<h1>
<img src="img/logo.png" alt="Mirror Fashion">
</h1>
<div class="sacola">
Nenhum item na sacola de compras
</div>
<nav class="menu-opcoes">
<ul>
<li><a href="#">Sua Conta</a></li>
<li><a href="#">Lista de desejos</a></li>
<li><a href="#">Cartão Fidelidade</a></li>
<li><a href="sobre.php">Sobre</a></li>
<li><a href="#">Ajuda</a></li>
</ul>
</nav>
</header>
| {
"content_hash": "811dc213506f097bcfb52e7020098680",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 147,
"avg_line_length": 38.645833333333336,
"alnum_prop": 0.477088948787062,
"repo_name": "ValeriaNiceria/ApostilaCaelum",
"id": "40e63f3e468344710b1f96a2948b92caf2f1730a",
"size": "1866",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cabecalho.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "29572"
},
{
"name": "HTML",
"bytes": "3706"
},
{
"name": "JavaScript",
"bytes": "12668"
},
{
"name": "PHP",
"bytes": "27181"
}
],
"symlink_target": ""
} |
package control;
import jdbc.UpdateCopy;
import vo.Copy;
public class CopyControl {
public static int newCopy(Copy copy) {
if (!UpdateCopy.newCopy(copy.getDocument().getId(), copy.getBranch().getId(), copy.getPosition())) {
return Constant.EXCEPTION;
}
return Constant.SUCCESSFUL;
}
}
| {
"content_hash": "f6be9c17000fdb5d0c1e49fbd507be3d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 102,
"avg_line_length": 23.923076923076923,
"alnum_prop": 0.6977491961414791,
"repo_name": "rs843/CS631Phase3",
"id": "f8714a3074a4b4c65f191baed611341d0f837d8f",
"size": "311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/control/CopyControl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "125080"
}
],
"symlink_target": ""
} |
Pi is responsible for sending the beats at the appropriate rate. It sends a column
Note a recent change, to make this easier to implement in PXT which has comparisons
but not positional indexing in strings
on radio rx:
if string matches “A” + “,” + myX + “,” + myY + “1”
etc
# Changelog
0.2
* Add the provisioning section
* Change the format for row/column size changes to allow a blocks-only implementation in PXT
* Clarify rows and columsn mapping to music
# Message Format
## TxBit
1. State changes are sent via the radio.
2. State changes come in as acknowledgements (could re-send on timeout)
3. Beat syncs come in, and are processed by their column
### State Change
TxBit sends: (only on change)
C,{0-8},{0-8},(1,0) state change message
format:
C,%d,%d,%d\n
### State Change Ack
TxBit receives:
If Pi receives a C message, acks with with
A,{0-8},{0-8},(1,0) ack state change message
format:
A,%d,%d,%d\n
### Beat Sync
TxBit receives:
B,NN
format:
B,%d\n
## BRIDGEBIT
1. Sends all incoming radio messages over serial.
2. Sends all incomingserial messages over radio.
3. Buttons used to change grid size (send via serial)
4. Buttons used to change BPM (send via serial)
### Grid Size Change
Bridge sends serial:
rows:N
or
cols:N
format:
{rows,cols},%d\n
### BPM Change
Bridge sends serial:
speed:N
format:
speed,%d\n
N is in beats per minute
## PI
1. Handles grid size changes
2. Handles BPM changes
3. Handles state changes of TxBits, with acknowledgement
4. Generates beat timing
5. Generates chords on speaker
6. (Optionally) Handles provisiioning of micro:bits if they are turned on 1-by-1
### Grid size change
Pi receives:
S,NN,NN size of grid change
format:
S,%d,%d\n
### BPM Change
Pi receives:
T,NNN time in BPM
format:
T,%d\n
### State change
Pi receives:
C,NN,NN,N
format:
C,%d,%d,%d
Pi transmits (ack)
A,{0-8},{0-8},(1,0) ack state change message
format:
A,%d,%d,%d\n
### Provisioning
Pi receives:
"??"
Pi response:
two separate messages, each just numbers, the next number in the grid to be filled
X
Y
format:
%01d
# Grid to music mapping
Rows are pitch, columns are beats in a bar
# Provisioning flow
When a node micro:bit is first turned on, it sends "??" which is a request for the Pi to tell it
the next available slot in the grid.
If the Pi responds, it should respond with two messages, each a single character between 0-9.
The grid should fill up along the rows first, then down to the next column.
| {
"content_hash": "2a7d5a16828970bc83d44c3dd9b18213",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 96,
"avg_line_length": 19.35135135135135,
"alnum_prop": 0.6218575418994413,
"repo_name": "whaleygeek/tonematrix",
"id": "ada009c24d74021c4051d6b916a59c89450f576c",
"size": "2906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protocol_spec.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5370"
},
{
"name": "Python",
"bytes": "265270"
},
{
"name": "Shell",
"bytes": "203"
}
],
"symlink_target": ""
} |
package org.apache.jmeter.report.dashboard;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.jmeter.JMeter;
import org.apache.jmeter.report.config.ConfigurationException;
import org.apache.jmeter.report.config.ExporterConfiguration;
import org.apache.jmeter.report.config.GraphConfiguration;
import org.apache.jmeter.report.config.ReportGeneratorConfiguration;
import org.apache.jmeter.report.config.SubConfiguration;
import org.apache.jmeter.report.core.DataContext;
import org.apache.jmeter.report.core.TimeHelper;
import org.apache.jmeter.report.processor.ListResultData;
import org.apache.jmeter.report.processor.MapResultData;
import org.apache.jmeter.report.processor.ResultData;
import org.apache.jmeter.report.processor.ResultDataVisitor;
import org.apache.jmeter.report.processor.SampleContext;
import org.apache.jmeter.report.processor.ValueResultData;
import org.apache.jmeter.report.processor.graph.AbstractGraphConsumer;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
/**
* The class HtmlTemplateExporter provides a data exporter that generates and
* processes template files using freemarker.
*
* @since 3.0
*/
public class HtmlTemplateExporter extends AbstractDataExporter {
/** Format used for non null check of parameters. */
private static final String MUST_NOT_BE_NULL = "%s must not be null";
private static final Logger LOG = LoggingManager.getLoggerForClass();
public static final String DATA_CTX_TESTFILE = "testFile";
public static final String DATA_CTX_BEGINDATE = "beginDate";
public static final String DATA_CTX_ENDDATE = "endDate";
public static final String DATA_CTX_TIMEZONE = "timeZone";
public static final String DATA_CTX_TIMEZONE_OFFSET = "timeZoneOffset";
public static final String DATA_CTX_OVERALL_FILTER = "overallFilter";
public static final String DATA_CTX_SHOW_CONTROLLERS_ONLY = "showControllersOnly";
public static final String DATA_CTX_RESULT = "result";
public static final String DATA_CTX_EXTRA_OPTIONS = "extraOptions";
public static final String DATA_CTX_SERIES_FILTER = "seriesFilter";
public static final String DATA_CTX_FILTERS_ONLY_SAMPLE_SERIES = "filtersOnlySampleSeries";
public static final String TIMESTAMP_FORMAT_MS = "ms";
private static final String INVALID_TEMPLATE_DIRECTORY_FMT = "\"%s\" is not a valid template directory";
private static final String INVALID_PROPERTY_CONFIG_FMT = "Wrong property \"%s\" in \"%s\" export configuration";
private static final String EMPTY_GRAPH_FMT = "The graph \"%s\" will be empty : %s";
// Template directory
private static final String TEMPLATE_DIR = "template_dir";
private static final String TEMPLATE_DIR_NAME_DEFAULT = "report-template";
// Output directory
private static final String OUTPUT_DIR = "output_dir";
// Default output folder name
private static final String OUTPUT_DIR_NAME_DEFAULT = "report-output";
private void addToContext(String key, Object value, DataContext context) {
if (value instanceof String) {
value = '"' + (String) value + '"';
}
context.put(key, value);
}
/**
* This class allows to customize data before exporting them
*
*/
private interface ResultCustomizer {
ResultData customizeResult(ResultData result);
}
/**
* This class allows to inject graph_options properties to the exported data
*
*/
private class ExtraOptionsResultCustomizer implements ResultCustomizer {
private SubConfiguration extraOptions;
/**
* Sets the extra options to inject in the result data
*
* @param extraOptions
*/
public final void setExtraOptions(SubConfiguration extraOptions) {
this.extraOptions = extraOptions;
}
/*
* (non-Javadoc)
*
* @see org.apache.jmeter.report.dashboard.HtmlTemplateExporter.
* ResultCustomizer#customizeResult(org.apache.jmeter.report.processor.
* ResultData)
*/
@Override
public ResultData customizeResult(ResultData result) {
MapResultData customizedResult = new MapResultData();
customizedResult.setResult(DATA_CTX_RESULT, result);
if (extraOptions != null) {
MapResultData extraResult = new MapResultData();
for (Map.Entry<String, String> extraEntry : extraOptions
.getProperties().entrySet()) {
extraResult.setResult(extraEntry.getKey(),
new ValueResultData(extraEntry.getValue()));
}
customizedResult.setResult(DATA_CTX_EXTRA_OPTIONS, extraResult);
}
return customizedResult;
}
}
/**
* This class allows to check exported data
*
*/
private interface ResultChecker {
void checkResult(ResultData result);
}
/**
* This class allows to detect empty graphs
*
*/
private class EmptyGraphChecker implements ResultChecker {
private final boolean filtersOnlySampleSeries;
private final boolean showControllerSeriesOnly;
private final Pattern filterPattern;
private boolean excludesControllers;
private String graphId;
public final void setExcludesControllers(boolean excludesControllers) {
this.excludesControllers = excludesControllers;
}
public final void setGraphId(String graphId) {
this.graphId = graphId;
}
/**
* Instantiates a new EmptyGraphChecker.
*
* @param filtersOnlySampleSeries
* @param showControllerSeriesOnly
* @param filterPattern
*/
public EmptyGraphChecker(boolean filtersOnlySampleSeries,
boolean showControllerSeriesOnly, Pattern filterPattern) {
this.filtersOnlySampleSeries = filtersOnlySampleSeries;
this.showControllerSeriesOnly = showControllerSeriesOnly;
this.filterPattern = filterPattern;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.jmeter.report.dashboard.HtmlTemplateExporter.ResultChecker
* #checkResult(org.apache.jmeter.report.processor.ResultData)
*/
@Override
public void checkResult(ResultData result) {
Boolean supportsControllerDiscrimination = findValue(Boolean.class,
AbstractGraphConsumer.RESULT_SUPPORTS_CONTROLLERS_DISCRIMINATION,
result);
String message = null;
if (supportsControllerDiscrimination.booleanValue() && showControllerSeriesOnly
&& excludesControllers) {
// Exporter shows controller series only
// whereas the current graph support controller
// discrimination and excludes
// controllers
message = ReportGeneratorConfiguration.EXPORTER_KEY_SHOW_CONTROLLERS_ONLY
+ " is set while the graph excludes controllers.";
} else {
if (filterPattern != null) {
// Detect whether none series matches
// the series filter.
ResultData seriesResult = findData(
AbstractGraphConsumer.RESULT_SERIES, result);
if (seriesResult instanceof ListResultData) {
// Try to find at least one pattern matching
ListResultData seriesList = (ListResultData) seriesResult;
int count = seriesList.getSize();
int index = 0;
boolean matches = false;
while (index < count && !matches) {
ResultData currentResult = seriesList.get(index);
if (currentResult instanceof MapResultData) {
MapResultData seriesData = (MapResultData) currentResult;
String name = findValue(String.class,
AbstractGraphConsumer.RESULT_SERIES_NAME,
seriesData);
// Is the current series a controller series ?
boolean isController = findValue(Boolean.class,
AbstractGraphConsumer.RESULT_SERIES_IS_CONTROLLER,
seriesData).booleanValue();
matches = filterPattern.matcher(name).matches();
if (matches) {
// If the name matches pattern, other
// properties can discard the series
matches = !filtersOnlySampleSeries
|| !supportsControllerDiscrimination.booleanValue()
|| isController
|| !showControllerSeriesOnly;
} else {
// If the name does not match the pattern,
// other properties can hold the series
matches = filtersOnlySampleSeries
&& !supportsControllerDiscrimination.booleanValue();
}
}
index++;
}
if (!matches) {
// None series matches the pattern
message = "None series matches the "
+ ReportGeneratorConfiguration.EXPORTER_KEY_SERIES_FILTER;
}
}
}
}
// Log empty graph when needed.
if (message != null) {
LOG.warn(String.format(EMPTY_GRAPH_FMT, graphId, message));
}
}
}
private <TVisit> void addResultToContext(String resultKey,
Map<String, Object> storage, DataContext dataContext,
ResultDataVisitor<TVisit> visitor) {
addResultToContext(resultKey, storage, dataContext, visitor, null,
null);
}
private <TVisit> void addResultToContext(String resultKey,
Map<String, Object> storage, DataContext dataContext,
ResultDataVisitor<TVisit> visitor, ResultCustomizer customizer,
ResultChecker checker) {
Object data = storage.get(resultKey);
if (data instanceof ResultData) {
ResultData result = (ResultData) data;
if (checker != null) {
checker.checkResult(result);
}
if (customizer != null) {
result = customizer.customizeResult(result);
}
dataContext.put(resultKey, result.accept(visitor));
}
}
private long formatTimestamp(String key, DataContext context) {
// FIXME Why convert to double then long (rounding ?)
double result = Double.parseDouble((String) context.get(key));
long timestamp = (long) result;
// Quote the string to respect Json spec.
context.put(key, '"' + TimeHelper.formatTimeStamp(timestamp) + '"');
return timestamp;
}
private <TProperty> TProperty getPropertyFromConfig(SubConfiguration cfg,
String property, TProperty defaultValue, Class<TProperty> clazz)
throws ExportException {
try {
return cfg.getProperty(property, defaultValue, clazz);
} catch (ConfigurationException ex) {
throw new ExportException(String.format(INVALID_PROPERTY_CONFIG_FMT,
property, getName()), ex);
}
}
/*
* (non-Javadoc)
*
* @see
* org.apache.jmeter.report.dashboard.DataExporter#Export(org.apache.jmeter
* .report.processor.SampleContext,
* org.apache.jmeter.report.config.ReportGeneratorConfiguration)
*/
@Override
public void export(SampleContext context, File file,
ReportGeneratorConfiguration configuration) throws ExportException {
Validate.notNull(context, MUST_NOT_BE_NULL, "context");
Validate.notNull(file, MUST_NOT_BE_NULL, "file");
Validate.notNull(configuration, MUST_NOT_BE_NULL, "configuration");
LOG.debug("Start template processing");
// Create data context and populate it
DataContext dataContext = new DataContext();
// Get the configuration of the current exporter
final ExporterConfiguration exportCfg = configuration
.getExportConfigurations().get(getName());
// Get template directory property value
File templateDirectory = getPropertyFromConfig(exportCfg, TEMPLATE_DIR,
new File(JMeterUtils.getJMeterBinDir(), TEMPLATE_DIR_NAME_DEFAULT), File.class);
if (!templateDirectory.isDirectory()) {
String message = String.format(INVALID_TEMPLATE_DIRECTORY_FMT,
templateDirectory.getAbsolutePath());
LOG.error(message);
throw new ExportException(message);
}
// Get output directory property value
File outputDir = getPropertyFromConfig(exportCfg, OUTPUT_DIR,
new File(JMeterUtils.getJMeterBinDir(), OUTPUT_DIR_NAME_DEFAULT), File.class);
String globallyDefinedOutputDir = JMeterUtils.getProperty(JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY);
if(!StringUtils.isEmpty(globallyDefinedOutputDir)) {
outputDir = new File(globallyDefinedOutputDir);
}
JOrphanUtils.canSafelyWriteToFolder(outputDir);
LOG.info("Will generate dashboard in folder:" + outputDir.getAbsolutePath());
// Add the flag defining whether only sample series are filtered to the
// context
final boolean filtersOnlySampleSeries = exportCfg
.filtersOnlySampleSeries();
addToContext(DATA_CTX_FILTERS_ONLY_SAMPLE_SERIES,
Boolean.valueOf(filtersOnlySampleSeries), dataContext);
// Add the series filter to the context
final String seriesFilter = exportCfg.getSeriesFilter();
Pattern filterPattern = null;
if (StringUtils.isNotBlank(seriesFilter)) {
try {
filterPattern = Pattern.compile(seriesFilter);
} catch (PatternSyntaxException ex) {
LOG.error(String.format("Invalid series filter: \"%s\", %s",
seriesFilter, ex.getDescription()));
}
}
addToContext(DATA_CTX_SERIES_FILTER, seriesFilter, dataContext);
// Add the flag defining whether only controller series are displayed
final boolean showControllerSeriesOnly = exportCfg
.showControllerSeriesOnly();
addToContext(DATA_CTX_SHOW_CONTROLLERS_ONLY,
Boolean.valueOf(showControllerSeriesOnly), dataContext);
JsonizerVisitor jsonizer = new JsonizerVisitor();
Map<String, Object> storedData = context.getData();
// Add begin date consumer result to the data context
addResultToContext(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, storedData,
dataContext, jsonizer);
// Add end date summary consumer result to the data context
addResultToContext(ReportGenerator.END_DATE_CONSUMER_NAME, storedData,
dataContext, jsonizer);
// Add Apdex summary consumer result to the data context
addResultToContext(ReportGenerator.APDEX_SUMMARY_CONSUMER_NAME,
storedData, dataContext, jsonizer);
// Add errors summary consumer result to the data context
addResultToContext(ReportGenerator.ERRORS_SUMMARY_CONSUMER_NAME,
storedData, dataContext, jsonizer);
// Add requests summary consumer result to the data context
addResultToContext(ReportGenerator.REQUESTS_SUMMARY_CONSUMER_NAME,
storedData, dataContext, jsonizer);
// Add statistics summary consumer result to the data context
addResultToContext(ReportGenerator.STATISTICS_SUMMARY_CONSUMER_NAME,
storedData, dataContext, jsonizer);
// Collect graph results from sample context and transform them into
// Json strings to inject in the data context
ExtraOptionsResultCustomizer customizer = new ExtraOptionsResultCustomizer();
EmptyGraphChecker checker = new EmptyGraphChecker(
filtersOnlySampleSeries, showControllerSeriesOnly,
filterPattern);
for (Map.Entry<String, GraphConfiguration> graphEntry : configuration
.getGraphConfigurations().entrySet()) {
final String graphId = graphEntry.getKey();
final GraphConfiguration graphConfiguration = graphEntry.getValue();
final SubConfiguration extraOptions = exportCfg
.getGraphExtraConfigurations().get(graphId);
// Initialize customizer and checker
customizer.setExtraOptions(extraOptions);
checker.setExcludesControllers(
graphConfiguration.excludesControllers());
checker.setGraphId(graphId);
// Export graph data
addResultToContext(graphId, storedData, dataContext, jsonizer,
customizer, checker);
}
// Replace the begin date with its formatted string and store the old
// timestamp
long oldTimestamp = formatTimestamp(
ReportGenerator.BEGIN_DATE_CONSUMER_NAME, dataContext);
// Replace the end date with its formatted string
formatTimestamp(ReportGenerator.END_DATE_CONSUMER_NAME, dataContext);
// Add time zone offset (that matches the begin date) to the context
TimeZone timezone = TimeZone.getDefault();
addToContext(DATA_CTX_TIMEZONE_OFFSET,
Integer.valueOf(timezone.getOffset(oldTimestamp)), dataContext);
// Add the test file name to the context
addToContext(DATA_CTX_TESTFILE, file.getName(), dataContext);
// Add the overall filter property to the context
addToContext(DATA_CTX_OVERALL_FILTER, configuration.getSampleFilter(),
dataContext);
// Walk template directory to copy files and process templated ones
Configuration templateCfg = new Configuration(
Configuration.getVersion());
try {
templateCfg.setDirectoryForTemplateLoading(templateDirectory);
templateCfg.setTemplateExceptionHandler(
TemplateExceptionHandler.RETHROW_HANDLER);
LOG.info(
"Report will be generated in:" + outputDir.getAbsolutePath()
+ ", creating folder structure");
FileUtils.forceMkdir(outputDir);
TemplateVisitor visitor = new TemplateVisitor(
templateDirectory.toPath(), outputDir.toPath(), templateCfg,
dataContext);
Files.walkFileTree(templateDirectory.toPath(), visitor);
} catch (IOException ex) {
throw new ExportException("Unable to process template files.", ex);
}
LOG.debug("End of template processing");
}
}
| {
"content_hash": "17878b6cd60788e40d5309313ccee195",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 117,
"avg_line_length": 43.28051391862955,
"alnum_prop": 0.62363942212547,
"repo_name": "d0k1/jmeter",
"id": "6a9dfb7b1f882100fa92bd8195ed4bae76de3017",
"size": "21014",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "src/core/org/apache/jmeter/report/dashboard/HtmlTemplateExporter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "21218"
},
{
"name": "CSS",
"bytes": "36983"
},
{
"name": "HTML",
"bytes": "93491"
},
{
"name": "Java",
"bytes": "7498610"
},
{
"name": "JavaScript",
"bytes": "58096"
},
{
"name": "Shell",
"bytes": "17485"
},
{
"name": "XSLT",
"bytes": "57215"
}
],
"symlink_target": ""
} |
package org.apache.nutch.scoring;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.protocol.Content;
/**
* Creates and caches {@link ScoringFilter} implementing plugins.
*
* @author Andrzej Bialecki
*/
public class ScoringFilters extends Configured implements ScoringFilter {
private ScoringFilter[] filters;
public ScoringFilters(Configuration conf) {
super(conf);
this.filters = (ScoringFilter[]) PluginRepository.get(conf)
.getOrderedPlugins(ScoringFilter.class, ScoringFilter.X_POINT_ID,
"scoring.filter.order");
}
/** Calculate a sort value for Generate. */
public float generatorSortValue(Text url, CrawlDatum datum, float initSort)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
initSort = this.filters[i].generatorSortValue(url, datum, initSort);
}
return initSort;
}
/** Calculate a new initial score, used when adding newly discovered pages. */
public void initialScore(Text url, CrawlDatum datum)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].initialScore(url, datum);
}
}
/** Calculate a new initial score, used when injecting new pages. */
public void injectedScore(Text url, CrawlDatum datum)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].injectedScore(url, datum);
}
}
/** Calculate updated page score during CrawlDb.update(). */
public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
List<CrawlDatum> inlinked) throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].updateDbScore(url, old, datum, inlinked);
}
}
public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].passScoreBeforeParsing(url, datum, content);
}
}
public void passScoreAfterParsing(Text url, Content content, Parse parse)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
this.filters[i].passScoreAfterParsing(url, content, parse);
}
}
public CrawlDatum distributeScoreToOutlinks(Text fromUrl,
ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,
CrawlDatum adjust, int allCount) throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
adjust = this.filters[i].distributeScoreToOutlinks(fromUrl, parseData,
targets, adjust, allCount);
}
return adjust;
}
public float indexerScore(Text url, NutchDocument doc, CrawlDatum dbDatum,
CrawlDatum fetchDatum, Parse parse, Inlinks inlinks, float initScore)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
initScore = this.filters[i].indexerScore(url, doc, dbDatum, fetchDatum,
parse, inlinks, initScore);
}
return initScore;
}
}
| {
"content_hash": "1b312c9c4da10dbccd99bf540f4210f8",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 81,
"avg_line_length": 33.922330097087375,
"alnum_prop": 0.7069261591299371,
"repo_name": "nhahv/apache-nutch-1.x",
"id": "5bad78f6024882aebe6477b8c952d3ebe231e0e2",
"size": "4296",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/java/org/apache/nutch/scoring/ScoringFilters.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "56042"
},
{
"name": "Java",
"bytes": "2288304"
},
{
"name": "Shell",
"bytes": "18445"
},
{
"name": "XSLT",
"bytes": "1822"
}
],
"symlink_target": ""
} |
namespace NuGetFeed.Infrastructure.Repositories
{
public interface IRepository<T>
{
void Insert(T obj);
void Save(T obj);
}
} | {
"content_hash": "9e4f38e14830b695442d8b6bb7207514",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 18,
"alnum_prop": 0.5987654320987654,
"repo_name": "NuGetFeed/NuGetFeed",
"id": "a82cf26d435e726c2a325839b977c530e1e3ea9a",
"size": "162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NuGetFeed/Infrastructure/Repositories/IRepository.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "101"
},
{
"name": "C#",
"bytes": "131901"
},
{
"name": "CSS",
"bytes": "1924"
},
{
"name": "HTML",
"bytes": "106"
},
{
"name": "JavaScript",
"bytes": "44928"
}
],
"symlink_target": ""
} |
<?php
class Google_Service_CloudTasks_Task extends Google_Model
{
protected $appEngineHttpRequestType = 'Google_Service_CloudTasks_AppEngineHttpRequest';
protected $appEngineHttpRequestDataType = '';
public $createTime;
public $dispatchCount;
protected $firstAttemptType = 'Google_Service_CloudTasks_Attempt';
protected $firstAttemptDataType = '';
protected $lastAttemptType = 'Google_Service_CloudTasks_Attempt';
protected $lastAttemptDataType = '';
public $name;
public $responseCount;
public $scheduleTime;
public $view;
/**
* @param Google_Service_CloudTasks_AppEngineHttpRequest
*/
public function setAppEngineHttpRequest(Google_Service_CloudTasks_AppEngineHttpRequest $appEngineHttpRequest)
{
$this->appEngineHttpRequest = $appEngineHttpRequest;
}
/**
* @return Google_Service_CloudTasks_AppEngineHttpRequest
*/
public function getAppEngineHttpRequest()
{
return $this->appEngineHttpRequest;
}
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
}
public function getCreateTime()
{
return $this->createTime;
}
public function setDispatchCount($dispatchCount)
{
$this->dispatchCount = $dispatchCount;
}
public function getDispatchCount()
{
return $this->dispatchCount;
}
/**
* @param Google_Service_CloudTasks_Attempt
*/
public function setFirstAttempt(Google_Service_CloudTasks_Attempt $firstAttempt)
{
$this->firstAttempt = $firstAttempt;
}
/**
* @return Google_Service_CloudTasks_Attempt
*/
public function getFirstAttempt()
{
return $this->firstAttempt;
}
/**
* @param Google_Service_CloudTasks_Attempt
*/
public function setLastAttempt(Google_Service_CloudTasks_Attempt $lastAttempt)
{
$this->lastAttempt = $lastAttempt;
}
/**
* @return Google_Service_CloudTasks_Attempt
*/
public function getLastAttempt()
{
return $this->lastAttempt;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setResponseCount($responseCount)
{
$this->responseCount = $responseCount;
}
public function getResponseCount()
{
return $this->responseCount;
}
public function setScheduleTime($scheduleTime)
{
$this->scheduleTime = $scheduleTime;
}
public function getScheduleTime()
{
return $this->scheduleTime;
}
public function setView($view)
{
$this->view = $view;
}
public function getView()
{
return $this->view;
}
}
| {
"content_hash": "50de804c8d19ccef0757af8f49b01512",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 111,
"avg_line_length": 23.458715596330276,
"alnum_prop": 0.7008212749315604,
"repo_name": "moometric/GSuiteSignatureManager",
"id": "1735c8e5449f0c275913c6af8e9994fe20cb844a",
"size": "3147",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/google/apiclient-services/src/Google/Service/CloudTasks/Task.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1673"
},
{
"name": "PHP",
"bytes": "18114"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Couargues est
un village
géographiquement positionné dans le département de Cher en Centre. Elle comptait 224 habitants en 2008.</p>
<p>Le nombre d'habitations, à Couargues, était réparti en 2011 en six appartements et 149 maisons soit
un marché plutôt équilibré.</p>
<p>À proximité de Couargues sont situées les villes de
<a href="{{VLROOT}}/immobilier/pouilly-sur-loire_58215/">Pouilly-sur-Loire</a> à 3 km, 1 767 habitants,
<a href="{{VLROOT}}/immobilier/thauvenay_18262/">Thauvenay</a> située à 3 km, 337 habitants,
<a href="{{VLROOT}}/immobilier/saint-bouize_18200/">Saint-Bouize</a> à 2 km, 322 habitants,
<a href="{{VLROOT}}/immobilier/sancerre_18241/">Sancerre</a> à 7 km, 1 789 habitants,
<a href="{{VLROOT}}/immobilier/saint-satur_18233/">Saint-Satur</a> à 7 km, 1 712 habitants,
<a href="{{VLROOT}}/immobilier/saint-andelain_58228/">Saint-Andelain</a> à 3 km, 536 habitants,
entre autres. De plus, Couargues est située à seulement treize km de <a href="{{VLROOT}}/immobilier/cosne-cours-sur-loire_58086/">Cosne-Cours-sur-Loire</a>.</p>
<p>Si vous pensez venir habiter à Couargues, vous pourrez aisément trouver une maison à acheter. </p>
</div>
| {
"content_hash": "3c7ba96ed4750e55b91cfcac2292c04a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 166,
"avg_line_length": 74.3529411764706,
"alnum_prop": 0.7333860759493671,
"repo_name": "donaldinou/frontend",
"id": "1ab743c4a1bacaebcfcf211248f8b718256743ff",
"size": "1289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/18074.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
"""
Save media files.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os
import tarfile
from django.core.management.base import CommandError
from django.core.files.storage import get_storage_class
from ._base import BaseDbBackupCommand, make_option
from ... import utils
from ...storage import get_storage, StorageError
class Command(BaseDbBackupCommand):
help = """Backup media files, gather all in a tarball and encrypt or
compress."""
content_type = "media"
option_list = BaseDbBackupCommand.option_list + (
make_option("-c", "--clean", help="Clean up old backup files", action="store_true",
default=False),
make_option("-s", "--servername",
help="Specify server name to include in backup filename"),
make_option("-z", "--compress", help="Compress the archive", action="store_true",
default=False),
make_option("-e", "--encrypt", help="Encrypt the backup files", action="store_true",
default=False),
make_option("-o", "--output-filename", default=None,
help="Specify filename on storage"),
make_option("-O", "--output-path", default=None,
help="Specify where to store on local filesystem",)
)
@utils.email_uncaught_exception
def handle(self, **options):
self.verbosity = options.get('verbosity')
self.quiet = options.get('quiet')
self._set_logger_level()
self.encrypt = options.get('encrypt', False)
self.compress = options.get('compress', False)
self.servername = options.get('servername')
self.filename = options.get('output_filename')
self.path = options.get('output_path')
try:
self.media_storage = get_storage_class()()
self.storage = get_storage()
self.backup_mediafiles()
if options.get('clean'):
self._cleanup_old_backups(servername=self.servername)
except StorageError as err:
raise CommandError(err)
def _explore_storage(self):
"""Generator of all files contained in media storage."""
path = ''
dirs = [path]
while dirs:
path = dirs.pop()
subdirs, files = self.media_storage.listdir(path)
for media_filename in files:
yield os.path.join(path, media_filename)
dirs.extend([os.path.join(path, subdir) for subdir in subdirs])
def _create_tar(self, name):
"""Create TAR file."""
fileobj = utils.create_spooled_temporary_file()
mode = 'w:gz' if self.compress else 'w'
tar_file = tarfile.open(name=name, fileobj=fileobj, mode=mode)
for media_filename in self._explore_storage():
tarinfo = tarfile.TarInfo(media_filename)
media_file = self.media_storage.open(media_filename)
tarinfo.size = len(media_file)
tar_file.addfile(tarinfo, media_file)
# Close the TAR for writing
tar_file.close()
return fileobj
def backup_mediafiles(self):
"""
Create backup file and write it to storage.
"""
# Check for filename option
if self.filename:
filename = self.filename
else:
extension = "tar%s" % ('.gz' if self.compress else '')
filename = utils.filename_generate(extension,
servername=self.servername,
content_type=self.content_type)
tarball = self._create_tar(filename)
# Apply trans
if self.encrypt:
encrypted_file = utils.encrypt_file(tarball, filename)
tarball, filename = encrypted_file
self.logger.debug("Backup size: %s", utils.handle_size(tarball))
# Store backup
tarball.seek(0)
if self.path is None:
self.write_to_storage(tarball, filename)
else:
self.write_local_file(tarball, self.path)
| {
"content_hash": "7d23474dc9085ecbf6e66ac087a705b0",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 92,
"avg_line_length": 38,
"alnum_prop": 0.5852245292129407,
"repo_name": "django-dbbackup/django-dbbackup",
"id": "542f3ff014e3a254f4898d58cd96c67827a0716d",
"size": "4142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dbbackup/management/commands/mediabackup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "493"
},
{
"name": "Python",
"bytes": "155224"
},
{
"name": "Shell",
"bytes": "2010"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Dave Raskin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.3.0/animate.min.css'>
<link href="http://fonts.googleapis.com/css?family=Martel+Sans:300,400" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.0/angular-material.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-aria.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-local-storage/0.2.1/angular-local-storage.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-animate.js"></script>
<script src="Scripts/app.js"></script>
</head>
<body ng-app="angular" ng-controller="mainController">
<header class="page-header">
<nav ng-if="currentPage != 'home'">
<div class="nav-wrapper deep-orange darken-4">
<a href="#!/" ng-click="changePage('home')" class="brand-logo">Dave Raskin</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li ng-class="activeView('about')"><a ng-click="changePage('about')" href="#!/about">About Me</a></li>
<li ng-class="activeView('projects')"><a ng-click="changePage('projects')" href="#!/projects">Projects</a></li>
<li ng-class="activeView('contact')"><a ng-click="openDialog()" href="#!/contact">Contact</a></li>
</ul>
</div>
</nav>
</header>
<main class="page-main">
<div ng-view></div>
</main>
<footer class="page-footer deep-orange darken-4">
<div class="footer-copyright center-align deep-orange darken-4">
© 2015 Dave Raskin. Cover Photograph by <a id="sutula" href="https://vimeo.com/user5456346">Alex Sutula.</a>
</div>
</footer>
</body>
</html> | {
"content_hash": "cbdbf2123ba1d3e4d1da95173099b4b8",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 121,
"avg_line_length": 55.42857142857143,
"alnum_prop": 0.6851374570446735,
"repo_name": "daveraskin/daveraskin.github.io",
"id": "2ef99da88ad01572cce9692eaa7c5fade4097a90",
"size": "2328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2737"
},
{
"name": "HTML",
"bytes": "11913"
},
{
"name": "JavaScript",
"bytes": "2808"
}
],
"symlink_target": ""
} |
#ifndef _SECTION_CONFIG_H_
#define _SECTION_CONFIG_H_
#include "basic_types.h"
#include "platform_autoconf.h"
#define RAM_VECTOR_TABLE1_SECTION \
SECTION(".ram_vector_table1")
#define RAM_VECTOR_TABLE2_SECTION \
SECTION(".ram_vector_table2")
#define RAM_VECTOR_TABLE3_SECTION \
SECTION(".ram_vector_table3")
//3 //3 Hal Section
#define HAL_ROM_TEXT_SECTION \
SECTION(".hal.rom.text")
#define HAL_ROM_ENTRY_NS_SECTION \
SECTION(".hal.rom.entryns.rodata")
#define SIM_ROM_DATA_SECTION \
SECTION(".sim.rom.rodata")
#define HAL_ROM_DATA_SECTION \
SECTION(".hal.rom.rodata")
#define HAL_ROM_BSS_SECTION \
SECTION(".hal.rom.bss")
#define HAL_ROM_BSS_SECTION_BANK \
SECTION(".hal.rom.bank.bss")
#define BOOT_RAM_TEXT_SECTION \
SECTION(".boot.ram.text")
#define BOOT_RAM_RODATA_SECTION \
SECTION(".boot.rodata")
#define BOOT_RAM_DATA_SECTION \
SECTION(".boot.ram.data")
#define BOOT_RAM_BSS_SECTION \
SECTION(".boot.ram.bss")
#define BOOT_RAM_END_BSS_SECTION \
SECTION(".boot.ram.end.bss")
//3 Shell
#define SHELL_ROM_TEXT_SECTION HAL_ROM_TEXT_SECTION
#define SHELL_ROM_BSS_SECTION HAL_ROM_BSS_SECTION
#define SHELL_ROM_DATA_SECTION HAL_ROM_DATA_SECTION
#define CMD_TABLE_DATA_SECTION \
SECTION(".cmd.table.data")
#define GIT_VER_TABLE_SECTION \
SECTION(".git.ver.data")
//3 Image 1 data
#define IMAGE1_ENTRY_SECTION \
SECTION(".image1.entry.data")
#define IMAGE1_EXPORT_SYMB_SECTION \
SECTION(".image1.export.symb")
#define IMAGE1_VALID_PATTEN_SECTION \
SECTION(".image1.validate.rodata")
#define IMAGE1_DATA_SECTION \
SECTION(".image1.rodata")
#define IMAGE2_VALID_PATTEN_SECTION \
SECTION(".image2.validate.rodata")
//3 SRAM Config Section
#define SRAM_BD_DATA_SECTION \
SECTION(".bdsram.data")
#define SRAM_NOCACHE_DATA_SECTION \
SECTION(".ncsram.data")
#define SRAM_BF_DATA_SECTION \
SECTION(".bfsram.data")
#define IMAGE2_ENTRY_SECTION \
SECTION(".image2.entry.data")
#define IMAGE2_RAM_TEXT_SECTION \
SECTION(".image2.sram.text")
#define IMAGE2_RAM_DATA_SECTION \
SECTION(".image2.sram.data")
#define SDRAM_DATA_SECTION
#if defined (ARM_CORE_CM4)
#define PSRAM_TEXT_SECTION SECTION(".psram.text")
#define PSRAM_DATA_SECTION SECTION(".psram.data")
#define PSRAM_RODATA_SECTION SECTION(".psram.rodata")
#define PSRAM_BSS_SECTION SECTION(".psram.bss")
#define PSRAM_HEAP_SECTION SECTION(".psram.heap")
#elif defined (RSICV_CORE_KR4)
#define PSRAM_TEXT_SECTION
#define PSRAM_DATA_SECTION
#define PSRAM_RODATA_SECTION
#define PSRAM_BSS_SECTION
#define PSRAM_HEAP_SECTION
#endif
#define SBOOT_HEAP_SECTION SECTION(".sboot.heap")
#define IPC_TABLE_DATA_SECTION \
SECTION(".ipc.table.data")
//3 Wlan Section
#define WLAN_ROM_TEXT_SECTION
#define WLAN_ROM_DATA_SECTION
#define WLAN_RAM_MAP_SECTION
#ifdef AMEBAD2_TODO// move wifi code into flash to reduce ram size, revert this when psram or ddr ready
#undef CONFIG_WIFI_CRITICAL_CODE_SECTION
#define CONFIG_WIFI_CRITICAL_CODE_SECTION SECTION(".image2.net.ram.text")
#endif
#define CONFIG_FW_CRITICAL_CODE_SECTION //IMAGE2_RAM_TEXT_SECTION
//3 Apple Section
#define APPLE_ROM_TEXT_SECTION \
SECTION(".apple.rom.text")
#define APPLE_ROM_DATA_SECTION \
SECTION(".apple.rom.rodata")
//3 Libc Section
#define LIBC_ROM_TEXT_SECTION \
SECTION(".libc.rom.text")
#define LIBC_ROM_DATA_SECTION \
SECTION(".libc.rom.rodata")
#define LIBC_HEAP_SECTION \
SECTION(".heap.stdlib")
//3 SSL Section
#define SSL_ROM_TEXT_SECTION \
SECTION(".ssl.rom.text")
#define SSL_ROM_DATA_SECTION \
SECTION(".ssl.rom.rodata")
#define SSL_RAM_MAP_SECTION \
SECTION(".ssl_ram_map")
//OS Section
#define OS_ROM_TEXT_SECTION \
SECTION(".os.rom.text")
#define OS_ROM_DATA_SECTION \
SECTION(".os.rom.rodata")
//FLASH RUN CODE
#define FLASH_BOOT_TEXT_SECTION SECTION(".flashboot.text")
#define IMAGE2_CUSTOM_SIGNATURE SECTION(".img2_custom_signature") /* 32B: for OTA update */
//RDP (read protect area just text)
#define RDP_TEXT_SECTION SECTION(".rdp.ram.text")
#define RDP_DATA_SECTION SECTION(".rdp.ram.data")
#define RETENTION_TEXT_SECTION SECTION(".retention.ram.text")
#define RETENTION_DATA_SECTION SECTION(".retention.ram.data")
#define RETENTION_ENTRY_SECTION SECTION(".retention.entry.data")
/* rom map */
#define ROM_FUNCTION_MAP SECTION(".rommap.data")
//3 FW Section
#define FW_ROM_TEXT_SECTION \
SECTION(".FW.rom.text")
#define FW_ROM_DATA_SECTION \
SECTION(".FW.rom.rodata")
#define FW_ROM_BSS_SECTION \
SECTION(".FW.rom.bss")
/* image3 secure image */
#define IMAGE3_ENTRY_SECTION \
SECTION(".image3.nsc_entry.text")
#if defined(ARM_CORE_CA7)
#undef HAL_ROM_TEXT_SECTION
#undef HAL_ROM_DATA_SECTION
#undef HAL_ROM_BSS_SECTION
#undef LIBC_ROM_TEXT_SECTION
#undef LIBC_ROM_DATA_SECTION
#define HAL_ROM_TEXT_SECTION
#define HAL_ROM_DATA_SECTION
#define HAL_ROM_BSS_SECTION
#define LIBC_ROM_TEXT_SECTION
#define LIBC_ROM_DATA_SECTION
#endif
/*USB_OTG define*/
#define OTG_ROM_TEXT_SECTION
#define START_OTG_RAM_FUN_SECTION
#define START_OTG_RAM_DATA_SECTION
#define OTG_ROM_DATA_SECTION
#endif //_SECTION_CONFIG_H_
| {
"content_hash": "b2197886957d7476993f7e9889b76029",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 103,
"avg_line_length": 28.744075829383885,
"alnum_prop": 0.609563066776587,
"repo_name": "sunghan-chang/TizenRT",
"id": "8d074c045273c129b295239a489402c9ec357c41",
"size": "6311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "os/board/rtl8720e/src/component/soc/amebalite/fwlib/include/section_config.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2051079"
},
{
"name": "Batchfile",
"bytes": "42646"
},
{
"name": "C",
"bytes": "107517969"
},
{
"name": "C++",
"bytes": "813875"
},
{
"name": "CMake",
"bytes": "21368"
},
{
"name": "HTML",
"bytes": "2990"
},
{
"name": "Java",
"bytes": "104053"
},
{
"name": "Makefile",
"bytes": "857981"
},
{
"name": "Perl",
"bytes": "4361"
},
{
"name": "PowerShell",
"bytes": "8511"
},
{
"name": "Python",
"bytes": "296172"
},
{
"name": "Roff",
"bytes": "4401"
},
{
"name": "Shell",
"bytes": "254381"
},
{
"name": "Tcl",
"bytes": "163693"
}
],
"symlink_target": ""
} |
import numpy as np
import theano
import theano.tensor as T
def floatX(arr):
"""Converts data to a numpy array of dtype ``theano.config.floatX``.
Parameters
----------
arr : array_like
The data to be converted.
Returns
-------
numpy ndarray
The input array in the ``floatX`` dtype configured for Theano.
If `arr` is an ndarray of correct dtype, it is returned as is.
"""
return np.asarray(arr, dtype=theano.config.floatX)
def shared_empty(dim=2, dtype=None):
"""Creates empty Theano shared variable.
Shortcut to create an empty Theano shared variable with
the specified number of dimensions.
Parameters
----------
dim : int, optional
The number of dimensions for the empty variable, defaults to 2.
dtype : a numpy data-type, optional
The desired dtype for the variable. Defaults to the Theano
``floatX`` dtype.
Returns
-------
Theano shared variable
An empty Theano shared variable of dtype ``dtype`` with
`dim` dimensions.
"""
if dtype is None:
dtype = theano.config.floatX
shp = tuple([1] * dim)
return theano.shared(np.zeros(shp, dtype=dtype))
def as_theano_expression(input):
"""Wrap as Theano expression.
Wraps the given input as a Theano constant if it is not
a valid Theano expression already. Useful to transparently
handle numpy arrays and Python scalars, for example.
Parameters
----------
input : number, numpy array or Theano expression
Expression to be converted to a Theano constant.
Returns
-------
Theano symbolic constant
Theano constant version of `input`.
"""
if isinstance(input, theano.gof.Variable):
return input
else:
try:
return theano.tensor.constant(input)
except Exception as e:
raise TypeError("Input of type %s is not a Theano expression and "
"cannot be wrapped as a Theano constant (original "
"exception: %s)" % (type(input), e))
def one_hot(x, m=None):
"""One-hot representation of integer vector.
Given a vector of integers from 0 to m-1, returns a matrix
with a one-hot representation, where each row corresponds
to an element of x.
Parameters
----------
x : integer vector
The integer vector to convert to a one-hot representation.
m : int, optional
The number of different columns for the one-hot representation. This
needs to be strictly greater than the maximum value of `x`.
Defaults to ``max(x) + 1``.
Returns
-------
Theano tensor variable
A Theano tensor variable of shape (``n``, `m`), where ``n`` is the
length of `x`, with the one-hot representation of `x`.
Notes
-----
If your integer vector represents target class memberships, and you wish to
compute the cross-entropy between predictions and the target class
memberships, then there is no need to use this function, since the function
:func:`categorical_crossentropy()` can compute the cross-entropy from the
integer vector directly.
"""
if m is None:
m = T.cast(T.max(x) + 1, 'int32')
return T.eye(m)[T.cast(x, 'int32')]
def unique(l):
"""Filters duplicates of iterable.
Create a new list from l with duplicate entries removed,
while preserving the original order.
Parameters
----------
l : iterable
Input iterable to filter of duplicates.
Returns
-------
list
A list of elements of `l` without duplicates and in the same order.
"""
new_list = []
for el in l:
if el not in new_list:
new_list.append(el)
return new_list
def as_tuple(x, N):
"""
Coerce a value to a tuple of length N.
Parameters:
-----------
x : value or iterable
N : integer
length of the desired tuple
Returns:
--------
tuple
``tuple(x)`` if `x` is iterable, ``(x,) * N`` otherwise.
"""
try:
X = tuple(x)
except TypeError:
X = (x,) * N
if len(X) != N:
raise ValueError("input must be a single value "
"or an iterable with length {0}".format(N))
return X
def compute_norms(array, norm_axes=None):
""" Compute incoming weight vector norms.
Parameters
----------
array : ndarray
Weight array.
norm_axes : sequence (list or tuple)
The axes over which to compute the norm. This overrides the
default norm axes defined for the number of dimensions
in `array`. When this is not specified and `array` is a 2D array,
this is set to `(0,)`. If `array` is a 3D, 4D or 5D array, it is
set to a tuple listing all axes but axis 0. The former default is
useful for working with dense layers, the latter is useful for 1D,
2D and 3D convolutional layers.
(Optional)
Returns
-------
norms : 1D array
1D array of incoming weight vector norms.
Examples
--------
>>> array = np.random.randn(100, 200)
>>> norms = compute_norms(array)
>>> norms.shape
(200,)
>>> norms = compute_norms(array, norm_axes=(1,))
>>> norms.shape
(100,)
"""
ndim = array.ndim
if norm_axes is not None:
sum_over = tuple(norm_axes)
elif ndim == 2: # DenseLayer
sum_over = (0,)
elif ndim in [3, 4, 5]: # Conv{1,2,3}DLayer
sum_over = tuple(range(1, ndim))
else:
raise ValueError(
"Unsupported tensor dimensionality {}."
"Must specify `norm_axes`".format(array.ndim)
)
norms = np.sqrt(np.sum(array**2, axis=sum_over))
return norms
def create_param(spec, shape, name=None):
"""
Helper method to create Theano shared variables for layer parameters
and to initialize them.
Parameters
----------
spec : numpy array, Theano shared variable, or callable
Either of the following:
* a numpy array with the initial parameter values
* a Theano shared variable representing the parameters
* a function or callable that takes the desired shape of
the parameter array as its single argument and returns
a numpy array.
shape : iterable of int
a tuple or other iterable of integers representing the desired
shape of the parameter array.
name : string, optional
If a new variable is created, the name to give to the parameter
variable. This is ignored if `spec` is already a Theano shared
variable.
Returns
-------
Theano shared variable
a Theano shared variable representing layer parameters. If a
numpy array was provided, the variable is initialized to
contain this array. If a shared variable was provided, it is
simply returned. If a callable was provided, it is called, and
its output is used to initialize the variable.
Notes
-----
This function is called by :meth:`Layer.add_param()` in the constructor
of most :class:`Layer` subclasses. This enables those layers to
support initialization with numpy arrays, existing Theano shared
variables, and callables for generating initial parameter values.
"""
shape = tuple(shape) # convert to tuple if needed
if any(d <= 0 for d in shape):
raise ValueError((
"Cannot create param with a non-positive shape dimension. "
"Tried to create param with shape=%r, name=%r") % (shape, name))
if isinstance(spec, theano.compile.SharedVariable):
# We cannot check the shape here, the shared variable might not be
# initialized correctly yet. We can check the dimensionality
# though. Note that we cannot assign a name here. We could assign
# to the `name` attribute of the shared variable, but we shouldn't
# because the user may have already named the variable and we don't
# want to override this.
if spec.ndim != len(shape):
raise RuntimeError("shared variable has %d dimensions, "
"should be %d" % (spec.ndim, len(shape)))
return spec
elif isinstance(spec, np.ndarray):
if spec.shape != shape:
raise RuntimeError("parameter array has shape %s, should be "
"%s" % (spec.shape, shape))
return theano.shared(spec, name=name)
elif hasattr(spec, '__call__'):
arr = spec(shape)
try:
arr = floatX(arr)
except Exception:
raise RuntimeError("cannot initialize parameters: the "
"provided callable did not return an "
"array-like value")
if arr.shape != shape:
raise RuntimeError("cannot initialize parameters: the "
"provided callable did not return a value "
"with the correct shape")
return theano.shared(arr, name=name)
else:
raise RuntimeError("cannot initialize parameters: 'spec' is not "
"a numpy array, a Theano shared variable, or a "
"callable")
| {
"content_hash": "a97f8867c1001d11af3c8ba87943db84",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 79,
"avg_line_length": 31.026490066225165,
"alnum_prop": 0.6050160085378868,
"repo_name": "gabortakacs/Lasagne",
"id": "aae5a6a78423ae0ea0ea6775d4e118012dd0beaf",
"size": "9370",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lasagne/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "397561"
}
],
"symlink_target": ""
} |
class Goblin : public Enemy
{
public:
Goblin(Dungeon &dungeon, int x, int y, int score, int exp);
~Goblin();
void levelUp();
};
#endif // RUOEG_GAMEOBJECTS_ENEMIES_GOBLIN_H_ | {
"content_hash": "e1ae8fb5abdd528ebf37f3a565b1e39d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 60,
"avg_line_length": 17.8,
"alnum_prop": 0.6853932584269663,
"repo_name": "SanchezSobrino/Ruoeg",
"id": "4cb6da3934ed578a4558f9a412b62018e955ee24",
"size": "342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/GameObjects/Enemies/Goblin/Goblin.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10921"
},
{
"name": "C++",
"bytes": "139818"
}
],
"symlink_target": ""
} |
package interpreter.interpreter;
import interpreter.ast.Node;
/**
* Created by Thomas on 2-3-2015.
*/
public interface Interpreter {
public void interpret(final Node node);
}
| {
"content_hash": "9bf85508282d1c734c655edb85e78d8b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 43,
"avg_line_length": 15.416666666666666,
"alnum_prop": 0.7243243243243244,
"repo_name": "yakkiesc/lua-interpreter",
"id": "a5887b060c14b50cb867d04c27c74c8c0ef4c792",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/interpreter/interpreter/Interpreter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "64193"
}
],
"symlink_target": ""
} |
void IfSearch::doSimilarity(void)
{
if (ffdBusy)
{
INFO("[SEARCH] ffdBusy");
if (--searchTimeout <= 0)
return searchError("Timeout");
QTimer::singleShot(100, this, SLOT(doSearch()));
return;
}
PROGRESS("[SEARCH] Started for Similarity");
searchResults.clear();
appSettings->setValue("Search/Results", searchResults);
appSettings->setValue("Search/Reason", QString());
appSettings->setValue("Search/Status", "Starting");
if (searchSettings.getPersonMode())
return searchError("Similarity in PersonMode not supported");
searchSimilarity->clear();
QTimer::singleShot(10, this, SLOT(similarityScanDir()));
}
void IfSearch::similarityScanDir(void)
{
NULLPTR(appSettings); NULLPTR(writer);
appSettings->setValue("Search/Status", "Scanning Directory");
QString dirName = appSettings->value("Search/InputDir", "../Search").toString();
if (dirName.isEmpty())
return searchError("Search/InputDir is empty");
searchDir = writer->baseDir();
if ( ! searchDir.cd(dirName))
return searchError(tr("Can't cd to %1").arg(dirName));
searchPending = searchDir.entryList(QDir::Files);
if (searchPending.isEmpty())
return searchError(tr("%1 is empty").arg(dirName));
appSettings->setValue("Search/Status", "Reading Files");
QTimer::singleShot(10, this, SLOT(similarityGrab()));
} // similarityScanDir()
void IfSearch::similarityGrab(void)
{
if (searchPending.isEmpty())
{
QTimer::singleShot(10, this, SLOT(similarityProcess()));
return;
}
QString fileName = searchPending.takeFirst();
EigenFaceTemplate tpl;
DETAIL("Reading %1", searchDir.absoluteFilePath(fileName));
QImage faceImage(searchDir.absoluteFilePath(fileName));
Return rtn = tpl.read(faceImage);
if (rtn.isError())
return searchError(rtn.toString());
QFileInfo fi(searchDir.absoluteFilePath(fileName));
int faceKey = searchSimilarity->insert(tpl, fi.completeBaseName(), faceImage);
searchResults += resultsDelimiter + tr("%1 FK%2 %3 Similarity Face Active")
.arg(searchSimilarity->size())
.arg(faceKey, 6, 10, QChar('0'))
.arg(fi.completeBaseName());
QTimer::singleShot(10, this, SLOT(similarityGrab()));
} // similarityGrab()
void IfSearch::similarityProcess(void)
{
Return rtn;
if (searchSimilarity->size() < 2)
return searchError("Not enough consistent Faces for Similarity");
appSettings->setValue("Search/Status", "Processing");
rtn = searchSimilarity->process(&similarityResultsList);
if (rtn.isError())
return searchError(rtn.toString());
appSettings->setValue("Search/Status", "Writing Results");
QTimer::singleShot(10, this, SLOT(similarityResults()));
} // similarityProcess()
void IfSearch::similarityResults(void)
{
Return rtn;
if (similarityResultsList.isEmpty())
{
QTimer::singleShot(10, this, SLOT(searchFinish()));
return;
}
EigenFaceSimilarityResult result = similarityResultsList.takeFirst();
EigenFaceSimilarityEntry entry = result.first();
searchResults += resultsDelimiter
+ tr("%1. S%2%3 FK%4~FK%5")
.arg(result.getRank(), 2)
.arg(result.getConfidence(), 3, 10, QChar('0'))
.arg(result.getTier().indicator())
.arg(entry.getFaceKey1(), 6, 10, QChar('0'))
.arg(entry.getFaceKey2(), 6, 10, QChar('0'));
if (fwpSimilarity->isActive())
{
QImage topImage(searchSimilarity->image(entry.getFaceKey1()));
QImage botImage(searchSimilarity->image(entry.getFaceKey2()));
ImageMarker topMarker(&topImage);
ImageMarker botMarker(&botImage);
topMarker.title(tr("#%1 %2")
.arg(entry.getFaceKey1())
.arg(entry.getFaceId1()));
topMarker.score(result.getConfidence(), 6,
result.getTier().color());
botMarker.title(tr("#%1 %2")
.arg(entry.getFaceKey2())
.arg(entry.getFaceId2()));
topMarker.end();
botMarker.end();
QImage outImage(qMax(topImage.width(), botImage.width()),
topImage.height() + botImage.height(),
QImage::Format_RGB32);
ImageMarker outMarker(&outImage);
outMarker.drawImage(0, 0, topImage);
outMarker.drawImage(0, topImage.height(), botImage);
outMarker.end();
QString fileName = tr("R%1-S%2%3-FK%4-%5~FK%6-%7")
.arg(result.getRank(), 2, 10, QChar('0'))
.arg(result.getConfidence(), 3, 10, QChar('0'))
.arg(result.getTier().indicator())
.arg(entry.getFaceKey1(), 6, 10, QChar('0'))
.arg(entry.getFaceId1())
.arg(entry.getFaceKey2(), 6, 10, QChar('0'))
.arg(entry.getFaceId2());
fwpSimilarity->write(outImage, fileName);
}
QTimer::singleShot(10, this, SLOT(similarityResults()));
} // similarityResults()
| {
"content_hash": "5caa4556cdbfbf0e1605fb39835afe85",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 84,
"avg_line_length": 35.6875,
"alnum_prop": 0.6137380813387818,
"repo_name": "eirTony/INDI1",
"id": "9008883d883620c91fc29786fa44202415732df4",
"size": "5602",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src4/static/SDK1/IfSearch/IfSearchSimilarity.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2182"
},
{
"name": "C",
"bytes": "987751"
},
{
"name": "C++",
"bytes": "25614243"
},
{
"name": "CMake",
"bytes": "723934"
},
{
"name": "CSS",
"bytes": "175949"
},
{
"name": "Cuda",
"bytes": "311879"
},
{
"name": "HTML",
"bytes": "839417"
},
{
"name": "Java",
"bytes": "127925"
},
{
"name": "JavaScript",
"bytes": "199216"
},
{
"name": "M4",
"bytes": "200"
},
{
"name": "Makefile",
"bytes": "6245411"
},
{
"name": "Mathematica",
"bytes": "284"
},
{
"name": "Objective-C++",
"bytes": "53970"
},
{
"name": "Prolog",
"bytes": "2474"
},
{
"name": "Python",
"bytes": "415039"
},
{
"name": "QMake",
"bytes": "173988"
},
{
"name": "Shell",
"bytes": "3748"
},
{
"name": "TeX",
"bytes": "1530252"
}
],
"symlink_target": ""
} |
import { create } from '@storybook/theming/create';
export default create({
base: 'light',
/*colorPrimary: 'hotpink',
colorSecondary: 'deepskyblue',
// UI
appBg: 'white',
appContentBg: 'silver',
appBorderColor: 'grey',
appBorderRadius: 4,
*/
// Typography
fontBase: '"Open Sans", sans-serif',
fontCode: 'monospace',
// Text colors
textColor: '#031c2d',
headerCommon: { color: 'red' },
brandUrl: null,
/*textInverseColor: 'rgba(255,255,255,0.9)',
// Toolbar default and active colors
barTextColor: 'silver',
barSelectedColor: 'black',
barBg: 'hotpink',
// Form colors
inputBg: 'white',
inputBorder: 'silver',
inputTextColor: 'black',
inputBorderRadius: 4,
brandTitle: 'My custom storybook',
brandUrl: 'https://example.com',
brandImage: 'https://placehold.it/350x150',*/
});
| {
"content_hash": "3b13e92d30b2f75db375813c9402184d",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 51,
"avg_line_length": 21.435897435897434,
"alnum_prop": 0.6614832535885168,
"repo_name": "wfp/ui",
"id": "3e082438a8464e89267c0a83f576ed025b23f329",
"size": "836",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".storybook/theme.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "272839"
},
{
"name": "HTML",
"bytes": "80373"
},
{
"name": "JavaScript",
"bytes": "2864371"
},
{
"name": "Shell",
"bytes": "284"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.activity.HomeActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
</menu>
| {
"content_hash": "6405483e82b783a892d24015996848a7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 40.6,
"alnum_prop": 0.6625615763546798,
"repo_name": "jeremiahespinosa/ToDoList",
"id": "d588a165ef32b704aabb6878c4b9dd8fef56e43b",
"size": "406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobile/src/main/res/menu/menu_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5844"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace SharpGL
{
public partial class OpenGL
{
/// <summary>
/// Determines whether a named extension function is supported.
/// </summary>
/// <param name="extensionFunctionName">Name of the extension function.</param>
/// <returns>
/// <c>true</c> if the extension function is supported; otherwise, <c>false</c>.
/// </returns>
public bool IsExtensionFunctionSupported(string extensionFunctionName)
{
// Try and get the proc address for the function.
IntPtr procAddress = Win32.wglGetProcAddress(extensionFunctionName);
// As long as the pointer is non-zero, we can invoke the extension function.
return procAddress != IntPtr.Zero;
}
/// <summary>
/// Returns a delegate for an extension function. This delegate can be called to execute the extension function.
/// </summary>
/// <typeparam name="T">The extension delegate type.</typeparam>
/// <returns>The delegate that points to the extension function.</returns>
private T GetDelegateFor<T>() where T : class
{
// Get the type of the extension function.
Type delegateType = typeof(T);
// Get the name of the extension function.
string name = delegateType.Name;
// ftlPhysicsGuy - Better way
Delegate del = null;
if (extensionFunctions.TryGetValue(name, out del) == false)
{
IntPtr proc = Win32.wglGetProcAddress(name);
if (proc == IntPtr.Zero)
throw new Exception("Extension function " + name + " not supported");
// Get the delegate for the function pointer.
del = Marshal.GetDelegateForFunctionPointer(proc, delegateType);
// Add to the dictionary.
extensionFunctions.Add(name, del);
}
return del as T;
}
/// <summary>
/// The set of extension functions.
/// </summary>
private Dictionary<string, Delegate> extensionFunctions = new Dictionary<string, Delegate>();
#region OpenGL 1.2
// Methods
public void BlendColor(float red, float green, float blue, float alpha)
{
GetDelegateFor<glBlendColor>()(red, green, blue, alpha);
}
public void BlendEquation(uint mode)
{
GetDelegateFor<glBlendEquation>()(mode);
}
public void DrawRangeElements(uint mode, uint start, uint end, int count, uint type, IntPtr indices)
{
GetDelegateFor<glDrawRangeElements>()(mode, start, end, count, type, indices);
}
public void TexImage3D(uint target, int level, int internalformat, int width, int height, int depth, int border, uint format, uint type, IntPtr pixels)
{
GetDelegateFor<glTexImage3D>()(target, level, internalformat, width, height, depth, border, format, type, pixels);
}
public void TexSubImage3D(uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, uint type, IntPtr pixels)
{
GetDelegateFor<glTexSubImage3D>()(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
}
public void CopyTexSubImage3D(uint target, int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height)
{
GetDelegateFor<glCopyTexSubImage3D>()(target, level, xoffset, yoffset, zoffset, x, y, width, height);
}
// Deprecated Methods
[Obsolete]
public void ColorTable(uint target, uint internalformat, int width, uint format, uint type, IntPtr table)
{
GetDelegateFor<glColorTable>()(target, internalformat, width, format, type, table);
}
[Obsolete]
public void ColorTableParameterfv(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glColorTableParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void ColorTableParameteriv(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glColorTableParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void CopyColorTable(uint target, uint internalformat, int x, int y, int width)
{
GetDelegateFor<glCopyColorTable>()(target, internalformat, x, y, width);
}
[Obsolete]
public void GetColorTable(uint target, uint format, uint type, IntPtr table)
{
GetDelegateFor<glGetColorTable>()(target, format, type, table);
}
[Obsolete]
public void GetColorTableParameter(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetColorTableParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void GetColorTableParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetColorTableParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void ColorSubTable(uint target, int start, int count, uint format, uint type, IntPtr data)
{
GetDelegateFor<glColorSubTable>()(target, start, count, format, type, data);
}
[Obsolete]
public void CopyColorSubTable(uint target, int start, int x, int y, int width)
{
GetDelegateFor<glCopyColorSubTable>()(target, start, x, y, width);
}
[Obsolete]
public void ConvolutionFilter1D(uint target, uint internalformat, int width, uint format, uint type, IntPtr image)
{
GetDelegateFor<glConvolutionFilter1D>()(target, internalformat, width, format, type, image);
}
[Obsolete]
public void ConvolutionFilter2D(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr image)
{
GetDelegateFor<glConvolutionFilter2D>()(target, internalformat, width, height, format, type, image);
}
[Obsolete]
public void ConvolutionParameter(uint target, uint pname, float parameters)
{
GetDelegateFor<glConvolutionParameterf>()(target, pname, parameters);
}
[Obsolete]
public void ConvolutionParameter(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glConvolutionParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void ConvolutionParameter(uint target, uint pname, int parameters)
{
GetDelegateFor<glConvolutionParameteri>()(target, pname, parameters);
}
[Obsolete]
public void ConvolutionParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glConvolutionParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void CopyConvolutionFilter1D(uint target, uint internalformat, int x, int y, int width)
{
GetDelegateFor<glCopyConvolutionFilter1D>()(target, internalformat, x, y, width);
}
[Obsolete]
public void CopyConvolutionFilter2D(uint target, uint internalformat, int x, int y, int width, int height)
{
GetDelegateFor<glCopyConvolutionFilter2D>()(target, internalformat, x, y, width, height);
}
[Obsolete]
public void GetConvolutionFilter(uint target, uint format, uint type, IntPtr image)
{
GetDelegateFor<glGetConvolutionFilter>()(target, format, type, image);
}
[Obsolete]
public void GetConvolutionParameter(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetConvolutionParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void GetConvolutionParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetConvolutionParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void GetSeparableFilter(uint target, uint format, uint type, IntPtr row, IntPtr column, IntPtr span)
{
GetDelegateFor<glGetSeparableFilter>()(target, format, type, row, column, span);
}
[Obsolete]
public void SeparableFilter2D(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr row, IntPtr column)
{
GetDelegateFor<glSeparableFilter2D>()(target, internalformat, width, height, format, type, row, column);
}
[Obsolete]
public void GetHistogram(uint target, bool reset, uint format, uint type, IntPtr values)
{
GetDelegateFor<glGetHistogram>()(target, reset, format, type, values);
}
[Obsolete]
public void GetHistogramParameter(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetHistogramParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void GetHistogramParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetHistogramParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void GetMinmax(uint target, bool reset, uint format, uint type, IntPtr values)
{
GetDelegateFor<glGetMinmax>()(target, reset, format, type, values);
}
[Obsolete]
public void GetMinmaxParameter(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetMinmaxParameterfv>()(target, pname, parameters);
}
[Obsolete]
public void GetMinmaxParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetMinmaxParameteriv>()(target, pname, parameters);
}
[Obsolete]
public void Histogram(uint target, int width, uint internalformat, bool sink)
{
GetDelegateFor<glHistogram>()(target, width, internalformat, sink);
}
[Obsolete]
public void Minmax(uint target, uint internalformat, bool sink)
{
GetDelegateFor<glMinmax>()(target, internalformat, sink);
}
[Obsolete]
public void ResetHistogram(uint target)
{
GetDelegateFor<glResetHistogram>()(target);
}
[Obsolete]
public void ResetMinmax(uint target)
{
GetDelegateFor<glResetMinmax>()(target);
}
// Delegates
private delegate void glBlendColor (float red, float green, float blue, float alpha);
private delegate void glBlendEquation (uint mode);
private delegate void glDrawRangeElements (uint mode, uint start, uint end, int count, uint type, IntPtr indices);
private delegate void glTexImage3D (uint target, int level, int internalformat, int width, int height, int depth, int border, uint format, uint type, IntPtr pixels);
private delegate void glTexSubImage3D (uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, uint type, IntPtr pixels);
private delegate void glCopyTexSubImage3D (uint target, int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height);
private delegate void glColorTable (uint target, uint internalformat, int width, uint format, uint type, IntPtr table);
private delegate void glColorTableParameterfv (uint target, uint pname, float[] parameters);
private delegate void glColorTableParameteriv (uint target, uint pname, int[] parameters);
private delegate void glCopyColorTable (uint target, uint internalformat, int x, int y, int width);
private delegate void glGetColorTable (uint target, uint format, uint type, IntPtr table);
private delegate void glGetColorTableParameterfv (uint target, uint pname, float[] parameters);
private delegate void glGetColorTableParameteriv (uint target, uint pname, int[] parameters);
private delegate void glColorSubTable (uint target, int start, int count, uint format, uint type, IntPtr data);
private delegate void glCopyColorSubTable (uint target, int start, int x, int y, int width);
private delegate void glConvolutionFilter1D (uint target, uint internalformat, int width, uint format, uint type, IntPtr image);
private delegate void glConvolutionFilter2D (uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr image);
private delegate void glConvolutionParameterf (uint target, uint pname, float parameters);
private delegate void glConvolutionParameterfv (uint target, uint pname, float[] parameters);
private delegate void glConvolutionParameteri (uint target, uint pname, int parameters);
private delegate void glConvolutionParameteriv (uint target, uint pname, int[] parameters);
private delegate void glCopyConvolutionFilter1D (uint target, uint internalformat, int x, int y, int width);
private delegate void glCopyConvolutionFilter2D (uint target, uint internalformat, int x, int y, int width, int height);
private delegate void glGetConvolutionFilter (uint target, uint format, uint type, IntPtr image);
private delegate void glGetConvolutionParameterfv (uint target, uint pname, float[] parameters);
private delegate void glGetConvolutionParameteriv (uint target, uint pname, int[] parameters);
private delegate void glGetSeparableFilter (uint target, uint format, uint type, IntPtr row, IntPtr column, IntPtr span);
private delegate void glSeparableFilter2D (uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr row, IntPtr column);
private delegate void glGetHistogram (uint target, bool reset, uint format, uint type, IntPtr values);
private delegate void glGetHistogramParameterfv (uint target, uint pname, float[] parameters);
private delegate void glGetHistogramParameteriv (uint target, uint pname, int[] parameters);
private delegate void glGetMinmax (uint target, bool reset, uint format, uint type, IntPtr values);
private delegate void glGetMinmaxParameterfv (uint target, uint pname, float[] parameters);
private delegate void glGetMinmaxParameteriv (uint target, uint pname, int[] parameters);
private delegate void glHistogram (uint target, int width, uint internalformat, bool sink);
private delegate void glMinmax (uint target, uint internalformat, bool sink);
private delegate void glResetHistogram (uint target);
private delegate void glResetMinmax (uint target);
// Constants
public const uint GL_UNSIGNED_BYTE_3_3_2 = 0x8032;
public const uint GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033;
public const uint GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034;
public const uint GL_UNSIGNED_INT_8_8_8_8 = 0x8035;
public const uint GL_UNSIGNED_INT_10_10_10_2 = 0x8036;
public const uint GL_TEXTURE_BINDING_3D = 0x806A;
public const uint GL_PACK_SKIP_IMAGES = 0x806B;
public const uint GL_PACK_IMAGE_HEIGHT = 0x806C;
public const uint GL_UNPACK_SKIP_IMAGES = 0x806D;
public const uint GL_UNPACK_IMAGE_HEIGHT = 0x806E;
public const uint GL_TEXTURE_3D = 0x806F;
public const uint GL_PROXY_TEXTURE_3D = 0x8070;
public const uint GL_TEXTURE_DEPTH = 0x8071;
public const uint GL_TEXTURE_WRAP_R = 0x8072;
public const uint GL_MAX_3D_TEXTURE_SIZE = 0x8073;
public const uint GL_UNSIGNED_BYTE_2_3_3_REV = 0x8362;
public const uint GL_UNSIGNED_SHORT_5_6_5 = 0x8363;
public const uint GL_UNSIGNED_SHORT_5_6_5_REV = 0x8364;
public const uint GL_UNSIGNED_SHORT_4_4_4_4_REV = 0x8365;
public const uint GL_UNSIGNED_SHORT_1_5_5_5_REV = 0x8366;
public const uint GL_UNSIGNED_INT_8_8_8_8_REV = 0x8367;
public const uint GL_UNSIGNED_INT_2_10_10_10_REV = 0x8368;
public const uint GL_BGR = 0x80E0;
public const uint GL_BGRA = 0x80E1;
public const uint GL_MAX_ELEMENTS_VERTICES = 0x80E8;
public const uint GL_MAX_ELEMENTS_INDICES = 0x80E9;
public const uint GL_CLAMP_TO_EDGE = 0x812F;
public const uint GL_TEXTURE_MIN_LOD = 0x813A;
public const uint GL_TEXTURE_MAX_LOD = 0x813B;
public const uint GL_TEXTURE_BASE_LEVEL = 0x813C;
public const uint GL_TEXTURE_MAX_LEVEL = 0x813D;
public const uint GL_SMOOTH_POINT_SIZE_RANGE = 0x0B12;
public const uint GL_SMOOTH_POINT_SIZE_GRANULARITY = 0x0B13;
public const uint GL_SMOOTH_LINE_WIDTH_RANGE = 0x0B22;
public const uint GL_SMOOTH_LINE_WIDTH_GRANULARITY = 0x0B23;
public const uint GL_ALIASED_LINE_WIDTH_RANGE = 0x846E;
#endregion
#region OpenGL 1.3
// Methods
public void ActiveTexture(uint texture)
{
GetDelegateFor<glActiveTexture>()(texture);
}
public void SampleCoverage(float value, bool invert)
{
GetDelegateFor<glSampleCoverage>()(value, invert);
}
public void CompressedTexImage3D(uint target, int level, uint internalformat, int width, int height, int depth, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage3D>()(target, level, internalformat, width, height, depth, border, imageSize, data);
}
public void CompressedTexImage2D(uint target, int level, uint internalformat, int width, int height, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage2D>()(target, level, internalformat, width, height, border, imageSize, data);
}
public void CompressedTexImage1D(uint target, int level, uint internalformat, int width, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage1D>()(target, level, internalformat, width, border, imageSize, data);
}
public void CompressedTexSubImage3D(uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage3D>()(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
}
public void CompressedTexSubImage2D(uint target, int level, int xoffset, int yoffset, int width, int height, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage2D>()(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
public void CompressedTexSubImage1D(uint target, int level, int xoffset, int width, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage1D>()(target, level, xoffset, width, format, imageSize, data);
}
public void GetCompressedTexImage(uint target, int level, IntPtr img)
{
GetDelegateFor<glGetCompressedTexImage>()(target, level, img);
}
// Deprecated Methods
[Obsolete]
public void ClientActiveTexture(uint texture)
{
GetDelegateFor<glClientActiveTexture>()(texture);
}
[Obsolete]
public void MultiTexCoord1(uint target, double s)
{
GetDelegateFor<glMultiTexCoord1d>()(target, s);
}
[Obsolete]
public void MultiTexCoord1(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord1dv>()(target, v);
}
[Obsolete]
public void MultiTexCoord1(uint target, float s)
{
GetDelegateFor<glMultiTexCoord1f>()(target, s);
}
[Obsolete]
public void MultiTexCoord1(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord1fv>()(target, v);
}
[Obsolete]
public void MultiTexCoord1(uint target, int s)
{
GetDelegateFor<glMultiTexCoord1i>()(target, s);
}
[Obsolete]
public void MultiTexCoord1(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord1iv>()(target, v);
}
[Obsolete]
public void MultiTexCoord1(uint target, short s)
{
GetDelegateFor<glMultiTexCoord1s>()(target, s);
}
[Obsolete]
public void MultiTexCoord1(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord1sv>()(target, v);
}
[Obsolete]
public void MultiTexCoord2(uint target, double s, double t)
{
GetDelegateFor<glMultiTexCoord2d>()(target, s, t);
}
[Obsolete]
public void MultiTexCoord2(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord2dv>()(target, v);
}
[Obsolete]
public void MultiTexCoord2(uint target, float s, float t)
{
GetDelegateFor<glMultiTexCoord2f>()(target, s, t);
}
[Obsolete]
public void MultiTexCoord2(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord2fv>()(target, v);
}
[Obsolete]
public void MultiTexCoord2(uint target, int s, int t)
{
GetDelegateFor<glMultiTexCoord2i>()(target, s, t);
}
[Obsolete]
public void MultiTexCoord2(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord2iv>()(target, v);
}
[Obsolete]
public void MultiTexCoord2(uint target, short s, short t)
{
GetDelegateFor<glMultiTexCoord2s>()(target, s, t);
}
[Obsolete]
public void MultiTexCoord2(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord2sv>()(target, v);
}
[Obsolete]
public void MultiTexCoord3(uint target, double s, double t, double r)
{
GetDelegateFor<glMultiTexCoord3d>()(target, s, t, r);
}
[Obsolete]
public void MultiTexCoord3(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord3dv>()(target, v);
}
[Obsolete]
public void MultiTexCoord3(uint target, float s, float t, float r)
{
GetDelegateFor<glMultiTexCoord3f>()(target, s, t, r);
}
[Obsolete]
public void MultiTexCoord3(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord3fv>()(target, v);
}
[Obsolete]
public void MultiTexCoord3(uint target, int s, int t, int r)
{
GetDelegateFor<glMultiTexCoord3i>()(target, s, t, r);
}
[Obsolete]
public void MultiTexCoord3(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord3iv>()(target, v);
}
[Obsolete]
public void MultiTexCoord3(uint target, short s, short t, short r)
{
GetDelegateFor<glMultiTexCoord3s>()(target, s, t, r);
}
[Obsolete]
public void MultiTexCoord3(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord3sv>()(target, v);
}
[Obsolete]
public void MultiTexCoord4(uint target, double s, double t, double r, double q)
{
GetDelegateFor<glMultiTexCoord4d>()(target, s, t, r, q);
}
[Obsolete]
public void MultiTexCoord4(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord4dv>()(target, v);
}
[Obsolete]
public void MultiTexCoord4(uint target, float s, float t, float r, float q)
{
GetDelegateFor<glMultiTexCoord4f>()(target, s, t, r, q);
}
[Obsolete]
public void MultiTexCoord4(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord4fv>()(target, v);
}
[Obsolete]
public void MultiTexCoord4(uint target, int s, int t, int r, int q)
{
GetDelegateFor<glMultiTexCoord4i>()(target, s, t, r, q);
}
[Obsolete]
public void MultiTexCoord4(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord4iv>()(target, v);
}
[Obsolete]
public void MultiTexCoord4(uint target, short s, short t, short r, short q)
{
GetDelegateFor<glMultiTexCoord4s>()(target, s, t, r, q);
}
[Obsolete]
public void MultiTexCoord4(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord4sv>()(target, v);
}
[Obsolete]
public void LoadTransposeMatrix(float[] m)
{
GetDelegateFor<glLoadTransposeMatrixf>()(m);
}
[Obsolete]
public void LoadTransposeMatrix(double[] m)
{
GetDelegateFor<glLoadTransposeMatrixd>()(m);
}
[Obsolete]
public void MultTransposeMatrix(float[] m)
{
GetDelegateFor<glMultTransposeMatrixf>()(m);
}
[Obsolete]
public void MultTransposeMatrix(double[] m)
{
GetDelegateFor<glMultTransposeMatrixd>()(m);
}
// Delegates
private delegate void glActiveTexture (uint texture);
private delegate void glSampleCoverage (float value, bool invert);
private delegate void glCompressedTexImage3D (uint target, int level, uint internalformat, int width, int height, int depth, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexImage2D (uint target, int level, uint internalformat, int width, int height, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexImage1D (uint target, int level, uint internalformat, int width, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage3D (uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage2D (uint target, int level, int xoffset, int yoffset, int width, int height, uint format, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage1D (uint target, int level, int xoffset, int width, uint format, int imageSize, IntPtr data);
private delegate void glGetCompressedTexImage (uint target, int level, IntPtr img);
private delegate void glClientActiveTexture (uint texture);
private delegate void glMultiTexCoord1d (uint target, double s);
private delegate void glMultiTexCoord1dv (uint target, double[] v);
private delegate void glMultiTexCoord1f (uint target, float s);
private delegate void glMultiTexCoord1fv (uint target, float[] v);
private delegate void glMultiTexCoord1i (uint target, int s);
private delegate void glMultiTexCoord1iv (uint target, int[] v);
private delegate void glMultiTexCoord1s (uint target, short s);
private delegate void glMultiTexCoord1sv (uint target, short[] v);
private delegate void glMultiTexCoord2d (uint target, double s, double t);
private delegate void glMultiTexCoord2dv (uint target, double[] v);
private delegate void glMultiTexCoord2f (uint target, float s, float t);
private delegate void glMultiTexCoord2fv (uint target, float[] v);
private delegate void glMultiTexCoord2i (uint target, int s, int t);
private delegate void glMultiTexCoord2iv (uint target, int[] v);
private delegate void glMultiTexCoord2s (uint target, short s, short t);
private delegate void glMultiTexCoord2sv (uint target, short[] v);
private delegate void glMultiTexCoord3d (uint target, double s, double t, double r);
private delegate void glMultiTexCoord3dv (uint target, double[] v);
private delegate void glMultiTexCoord3f (uint target, float s, float t, float r);
private delegate void glMultiTexCoord3fv (uint target, float[] v);
private delegate void glMultiTexCoord3i (uint target, int s, int t, int r);
private delegate void glMultiTexCoord3iv (uint target, int[] v);
private delegate void glMultiTexCoord3s (uint target, short s, short t, short r);
private delegate void glMultiTexCoord3sv (uint target, short[] v);
private delegate void glMultiTexCoord4d (uint target, double s, double t, double r, double q);
private delegate void glMultiTexCoord4dv (uint target, double[] v);
private delegate void glMultiTexCoord4f (uint target, float s, float t, float r, float q);
private delegate void glMultiTexCoord4fv (uint target, float[] v);
private delegate void glMultiTexCoord4i (uint target, int s, int t, int r, int q);
private delegate void glMultiTexCoord4iv (uint target, int[] v);
private delegate void glMultiTexCoord4s (uint target, short s, short t, short r, short q);
private delegate void glMultiTexCoord4sv (uint target, short[] v);
private delegate void glLoadTransposeMatrixf (float[] m);
private delegate void glLoadTransposeMatrixd (double[] m);
private delegate void glMultTransposeMatrixf (float[] m);
private delegate void glMultTransposeMatrixd (double[] m);
// Constants
public const uint GL_TEXTURE0 = 0x84C0;
public const uint GL_TEXTURE1 = 0x84C1;
public const uint GL_TEXTURE2 = 0x84C2;
public const uint GL_TEXTURE3 = 0x84C3;
public const uint GL_TEXTURE4 = 0x84C4;
public const uint GL_TEXTURE5 = 0x84C5;
public const uint GL_TEXTURE6 = 0x84C6;
public const uint GL_TEXTURE7 = 0x84C7;
public const uint GL_TEXTURE8 = 0x84C8;
public const uint GL_TEXTURE9 = 0x84C9;
public const uint GL_TEXTURE10 = 0x84CA;
public const uint GL_TEXTURE11 = 0x84CB;
public const uint GL_TEXTURE12 = 0x84CC;
public const uint GL_TEXTURE13 = 0x84CD;
public const uint GL_TEXTURE14 = 0x84CE;
public const uint GL_TEXTURE15 = 0x84CF;
public const uint GL_TEXTURE16 = 0x84D0;
public const uint GL_TEXTURE17 = 0x84D1;
public const uint GL_TEXTURE18 = 0x84D2;
public const uint GL_TEXTURE19 = 0x84D3;
public const uint GL_TEXTURE20 = 0x84D4;
public const uint GL_TEXTURE21 = 0x84D5;
public const uint GL_TEXTURE22 = 0x84D6;
public const uint GL_TEXTURE23 = 0x84D7;
public const uint GL_TEXTURE24 = 0x84D8;
public const uint GL_TEXTURE25 = 0x84D9;
public const uint GL_TEXTURE26 = 0x84DA;
public const uint GL_TEXTURE27 = 0x84DB;
public const uint GL_TEXTURE28 = 0x84DC;
public const uint GL_TEXTURE29 = 0x84DD;
public const uint GL_TEXTURE30 = 0x84DE;
public const uint GL_TEXTURE31 = 0x84DF;
public const uint GL_ACTIVE_TEXTURE = 0x84E0;
public const uint GL_MULTISAMPLE = 0x809D;
public const uint GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E;
public const uint GL_SAMPLE_ALPHA_TO_ONE = 0x809F;
public const uint GL_SAMPLE_COVERAGE = 0x80A0;
public const uint GL_SAMPLE_BUFFERS = 0x80A8;
public const uint GL_SAMPLES = 0x80A9;
public const uint GL_SAMPLE_COVERAGE_VALUE = 0x80AA;
public const uint GL_SAMPLE_COVERAGE_INVERT = 0x80AB;
public const uint GL_TEXTURE_CUBE_MAP = 0x8513;
public const uint GL_TEXTURE_BINDING_CUBE_MAP = 0x8514;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A;
public const uint GL_PROXY_TEXTURE_CUBE_MAP = 0x851B;
public const uint GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C;
public const uint GL_COMPRESSED_RGB = 0x84ED;
public const uint GL_COMPRESSED_RGBA = 0x84EE;
public const uint GL_TEXTURE_COMPRESSION_HINT = 0x84EF;
public const uint GL_TEXTURE_COMPRESSED_IMAGE_SIZE = 0x86A0;
public const uint GL_TEXTURE_COMPRESSED = 0x86A1;
public const uint GL_NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2;
public const uint GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3;
public const uint GL_CLAMP_TO_BORDER = 0x812D;
#endregion
#region OpenGL 1.4
// Methods
public void BlendFuncSeparate(uint sfactorRGB, uint dfactorRGB, uint sfactorAlpha, uint dfactorAlpha)
{
GetDelegateFor<glBlendFuncSeparate>()(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
}
public void MultiDrawArrays(uint mode, int[] first, int[] count, int primcount)
{
GetDelegateFor<glMultiDrawArrays>()(mode, first, count, primcount);
}
public void MultiDrawElements(uint mode, int[] count, uint type, IntPtr indices, int primcount)
{
GetDelegateFor<glMultiDrawElements>()(mode, count, type, indices, primcount);
}
public void PointParameter(uint pname, float parameter)
{
GetDelegateFor<glPointParameterf>()(pname, parameter);
}
public void PointParameter(uint pname, float[] parameters)
{
GetDelegateFor<glPointParameterfv>()(pname, parameters);
}
public void PointParameter(uint pname, int parameter)
{
GetDelegateFor<glPointParameteri>()(pname, parameter);
}
public void PointParameter(uint pname, int[] parameters)
{
GetDelegateFor<glPointParameteriv>()(pname, parameters);
}
// Deprecated Methods
[Obsolete]
public void FogCoord(float coord)
{
GetDelegateFor<glFogCoordf>()(coord);
}
[Obsolete]
public void FogCoord(float[] coord)
{
GetDelegateFor<glFogCoordfv>()(coord);
}
[Obsolete]
public void FogCoord(double coord)
{
GetDelegateFor<glFogCoordd>()(coord);
}
[Obsolete]
public void FogCoord(double[] coord)
{
GetDelegateFor<glFogCoorddv>()(coord);
}
[Obsolete]
public void FogCoordPointer(uint type, int stride, IntPtr pointer)
{
GetDelegateFor<glFogCoordPointer>()(type, stride, pointer);
}
[Obsolete]
public void SecondaryColor3(sbyte red, sbyte green, sbyte blue)
{
GetDelegateFor<glSecondaryColor3b>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(sbyte[] v)
{
GetDelegateFor<glSecondaryColor3bv>()(v);
}
[Obsolete]
public void SecondaryColor3(double red, double green, double blue)
{
GetDelegateFor<glSecondaryColor3d>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(double[] v)
{
GetDelegateFor<glSecondaryColor3dv>()(v);
}
[Obsolete]
public void SecondaryColor3(float red, float green, float blue)
{
GetDelegateFor<glSecondaryColor3f>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(float[] v)
{
GetDelegateFor<glSecondaryColor3fv>()(v);
}
[Obsolete]
public void SecondaryColor3(int red, int green, int blue)
{
GetDelegateFor<glSecondaryColor3i>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(int[] v)
{
GetDelegateFor<glSecondaryColor3iv>()(v);
}
[Obsolete]
public void SecondaryColor3(short red, short green, short blue)
{
GetDelegateFor<glSecondaryColor3s>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(short[] v)
{
GetDelegateFor<glSecondaryColor3sv>()(v);
}
[Obsolete]
public void SecondaryColor3(byte red, byte green, byte blue)
{
GetDelegateFor<glSecondaryColor3ub>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(byte[] v)
{
GetDelegateFor<glSecondaryColor3ubv>()(v);
}
[Obsolete]
public void SecondaryColor3(uint red, uint green, uint blue)
{
GetDelegateFor<glSecondaryColor3ui>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(uint[] v)
{
GetDelegateFor<glSecondaryColor3uiv>()(v);
}
[Obsolete]
public void SecondaryColor3(ushort red, ushort green, ushort blue)
{
GetDelegateFor<glSecondaryColor3us>()(red, green, blue);
}
[Obsolete]
public void SecondaryColor3(ushort[] v)
{
GetDelegateFor<glSecondaryColor3usv>()(v);
}
[Obsolete]
public void SecondaryColorPointer(int size, uint type, int stride, IntPtr pointer)
{
GetDelegateFor<glSecondaryColorPointer>()(size, type, stride, pointer);
}
[Obsolete]
public void WindowPos2(double x, double y)
{
GetDelegateFor<glWindowPos2d>()(x, y);
}
[Obsolete]
public void WindowPos2(double[] v)
{
GetDelegateFor<glWindowPos2dv>()(v);
}
[Obsolete]
public void WindowPos2(float x, float y)
{
GetDelegateFor<glWindowPos2f>()(x, y);
}
[Obsolete]
public void WindowPos2(float[] v)
{
GetDelegateFor<glWindowPos2fv>()(v);
}
[Obsolete]
public void WindowPos2(int x, int y)
{
GetDelegateFor<glWindowPos2i>()(x, y);
}
[Obsolete]
public void WindowPos2(int[] v)
{
GetDelegateFor<glWindowPos2iv>()(v);
}
[Obsolete]
public void WindowPos2(short x, short y)
{
GetDelegateFor<glWindowPos2s>()(x, y);
}
[Obsolete]
public void WindowPos2(short[] v)
{
GetDelegateFor<glWindowPos2sv>()(v);
}
[Obsolete]
public void WindowPos3(double x, double y, double z)
{
GetDelegateFor<glWindowPos3d>()(x, y, z);
}
[Obsolete]
public void WindowPos3(double[] v)
{
GetDelegateFor<glWindowPos3dv>()(v);
}
[Obsolete]
public void WindowPos3(float x, float y, float z)
{
GetDelegateFor<glWindowPos3f>()(x, y, z);
}
[Obsolete]
public void WindowPos3(float[] v)
{
GetDelegateFor<glWindowPos3fv>()(v);
}
[Obsolete]
public void WindowPos3(int x, int y, int z)
{
GetDelegateFor<glWindowPos3i>()(x, y, z);
}
[Obsolete]
public void WindowPos3(int[] v)
{
GetDelegateFor<glWindowPos3iv>()(v);
}
[Obsolete]
public void WindowPos3(short x, short y, short z)
{
GetDelegateFor<glWindowPos3s>()(x, y, z);
}
[Obsolete]
public void WindowPos3(short[] v)
{
GetDelegateFor<glWindowPos3sv>()(v);
}
// Delegates
private delegate void glBlendFuncSeparate (uint sfactorRGB, uint dfactorRGB, uint sfactorAlpha, uint dfactorAlpha);
private delegate void glMultiDrawArrays (uint mode, int[] first, int[] count, int primcount);
private delegate void glMultiDrawElements (uint mode, int[] count, uint type, IntPtr indices, int primcount);
private delegate void glPointParameterf (uint pname, float parameter);
private delegate void glPointParameterfv (uint pname, float[] parameters);
private delegate void glPointParameteri (uint pname, int parameter);
private delegate void glPointParameteriv (uint pname, int[] parameters);
private delegate void glFogCoordf (float coord);
private delegate void glFogCoordfv (float[] coord);
private delegate void glFogCoordd (double coord);
private delegate void glFogCoorddv (double[] coord);
private delegate void glFogCoordPointer (uint type, int stride, IntPtr pointer);
private delegate void glSecondaryColor3b (sbyte red, sbyte green, sbyte blue);
private delegate void glSecondaryColor3bv (sbyte[] v);
private delegate void glSecondaryColor3d (double red, double green, double blue);
private delegate void glSecondaryColor3dv (double[] v);
private delegate void glSecondaryColor3f (float red, float green, float blue);
private delegate void glSecondaryColor3fv (float[] v);
private delegate void glSecondaryColor3i (int red, int green, int blue);
private delegate void glSecondaryColor3iv (int[] v);
private delegate void glSecondaryColor3s (short red, short green, short blue);
private delegate void glSecondaryColor3sv (short[] v);
private delegate void glSecondaryColor3ub (byte red, byte green, byte blue);
private delegate void glSecondaryColor3ubv (byte[] v);
private delegate void glSecondaryColor3ui (uint red, uint green, uint blue);
private delegate void glSecondaryColor3uiv (uint[] v);
private delegate void glSecondaryColor3us (ushort red, ushort green, ushort blue);
private delegate void glSecondaryColor3usv (ushort[] v);
private delegate void glSecondaryColorPointer (int size, uint type, int stride, IntPtr pointer);
private delegate void glWindowPos2d (double x, double y);
private delegate void glWindowPos2dv (double[] v);
private delegate void glWindowPos2f (float x, float y);
private delegate void glWindowPos2fv (float[] v);
private delegate void glWindowPos2i (int x, int y);
private delegate void glWindowPos2iv (int[] v);
private delegate void glWindowPos2s (short x, short y);
private delegate void glWindowPos2sv (short[] v);
private delegate void glWindowPos3d (double x, double y, double z);
private delegate void glWindowPos3dv (double[] v);
private delegate void glWindowPos3f (float x, float y, float z);
private delegate void glWindowPos3fv (float[] v);
private delegate void glWindowPos3i (int x, int y, int z);
private delegate void glWindowPos3iv (int[] v);
private delegate void glWindowPos3s (short x, short y, short z);
private delegate void glWindowPos3sv (short[] v);
// Constants
public const uint GL_BLEND_DST_RGB = 0x80C8;
public const uint GL_BLEND_SRC_RGB = 0x80C9;
public const uint GL_BLEND_DST_ALPHA = 0x80CA;
public const uint GL_BLEND_SRC_ALPHA = 0x80CB;
public const uint GL_POINT_FADE_THRESHOLD_SIZE = 0x8128;
public const uint GL_DEPTH_COMPONENT16 = 0x81A5;
public const uint GL_DEPTH_COMPONENT24 = 0x81A6;
public const uint GL_DEPTH_COMPONENT32 = 0x81A7;
public const uint GL_MIRRORED_REPEAT = 0x8370;
public const uint GL_MAX_TEXTURE_LOD_BIAS = 0x84FD;
public const uint GL_TEXTURE_LOD_BIAS = 0x8501;
public const uint GL_INCR_WRAP = 0x8507;
public const uint GL_DECR_WRAP = 0x8508;
public const uint GL_TEXTURE_DEPTH_SIZE = 0x884A;
public const uint GL_TEXTURE_COMPARE_MODE = 0x884C;
public const uint GL_TEXTURE_COMPARE_FUNC = 0x884D;
#endregion
#region OpenGL 1.5
// Methods
public void GenQueries(int n, uint[] ids)
{
GetDelegateFor<glGenQueries>()(n, ids);
}
public void DeleteQueries(int n, uint[] ids)
{
GetDelegateFor<glDeleteQueries>()(n, ids);
}
public bool IsQuery(uint id)
{
return (bool)GetDelegateFor<glIsQuery>()(id);
}
public void BeginQuery(uint target, uint id)
{
GetDelegateFor<glBeginQuery>()(target, id);
}
public void EndQuery(uint target)
{
GetDelegateFor<glEndQuery>()(target);
}
public void GetQuery(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetQueryiv>()(target, pname, parameters);
}
public void GetQueryObject(uint id, uint pname, int[] parameters)
{
GetDelegateFor<glGetQueryObjectiv>()(id, pname, parameters);
}
public void GetQueryObject(uint id, uint pname, uint[] parameters)
{
GetDelegateFor<glGetQueryObjectuiv>()(id, pname, parameters);
}
public void BindBuffer(uint target, uint buffer)
{
GetDelegateFor<glBindBuffer>()(target, buffer);
}
public void DeleteBuffers(int n, uint[] buffers)
{
GetDelegateFor<glDeleteBuffers>()(n, buffers);
}
public void GenBuffers(int n, uint[] buffers)
{
GetDelegateFor<glGenBuffers>()(n, buffers);
}
public bool IsBuffer(uint buffer)
{
return (bool)GetDelegateFor<glIsBuffer>()(buffer);
}
public void BufferData(uint target, int size, IntPtr data, uint usage)
{
GetDelegateFor<glBufferData>()(target, size, data, usage);
}
public void BufferData(uint target, float[] data, uint usage)
{
IntPtr p = Marshal.AllocHGlobal(data.Length * sizeof(float));
Marshal.Copy(data, 0, p, data.Length);
GetDelegateFor<glBufferData>()(target, data.Length * sizeof(float), p, usage);
Marshal.FreeHGlobal(p);
}
public void BufferData(uint target, ushort[] data, uint usage)
{
var dataSize = data.Length * sizeof(ushort);
IntPtr p = Marshal.AllocHGlobal(dataSize);
var shortData = new short[data.Length];
Buffer.BlockCopy(data, 0, shortData, 0, dataSize);
Marshal.Copy(shortData, 0, p, data.Length);
GetDelegateFor<glBufferData>()(target, dataSize, p, usage);
Marshal.FreeHGlobal(p);
}
public void BufferSubData(uint target, int offset, int size, IntPtr data)
{
GetDelegateFor<glBufferSubData>()(target, offset, size, data);
}
public void GetBufferSubData(uint target, int offset, int size, IntPtr data)
{
GetDelegateFor<glGetBufferSubData>()(target, offset, size, data);
}
public IntPtr MapBuffer(uint target, uint access)
{
return (IntPtr)GetDelegateFor<glMapBuffer>()(target, access);
}
public bool UnmapBuffer(uint target)
{
return (bool)GetDelegateFor<glUnmapBuffer>()(target);
}
public void GetBufferParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetBufferParameteriv>()(target, pname, parameters);
}
public void GetBufferPointer(uint target, uint pname, IntPtr[] parameters)
{
GetDelegateFor<glGetBufferPointerv>()(target, pname, parameters);
}
// Delegates
private delegate void glGenQueries (int n, uint[] ids);
private delegate void glDeleteQueries (int n, uint[] ids);
private delegate bool glIsQuery (uint id);
private delegate void glBeginQuery (uint target, uint id);
private delegate void glEndQuery (uint target);
private delegate void glGetQueryiv (uint target, uint pname, int[] parameters);
private delegate void glGetQueryObjectiv (uint id, uint pname, int[] parameters);
private delegate void glGetQueryObjectuiv (uint id, uint pname, uint[] parameters);
private delegate void glBindBuffer (uint target, uint buffer);
private delegate void glDeleteBuffers (int n, uint[] buffers);
private delegate void glGenBuffers (int n, uint[] buffers);
private delegate bool glIsBuffer (uint buffer);
private delegate void glBufferData(uint target, int size, IntPtr data, uint usage);
private delegate void glBufferSubData (uint target, int offset, int size, IntPtr data);
private delegate void glGetBufferSubData (uint target, int offset, int size, IntPtr data);
private delegate IntPtr glMapBuffer (uint target, uint access);
private delegate bool glUnmapBuffer (uint target);
private delegate void glGetBufferParameteriv (uint target, uint pname, int[] parameters);
private delegate void glGetBufferPointerv (uint target, uint pname, IntPtr[] parameters);
// Constants
public const uint GL_BUFFER_SIZE = 0x8764;
public const uint GL_BUFFER_USAGE = 0x8765;
public const uint GL_QUERY_COUNTER_BITS = 0x8864;
public const uint GL_CURRENT_QUERY = 0x8865;
public const uint GL_QUERY_RESULT = 0x8866;
public const uint GL_QUERY_RESULT_AVAILABLE = 0x8867;
public const uint GL_ARRAY_BUFFER = 0x8892;
public const uint GL_ELEMENT_ARRAY_BUFFER = 0x8893;
public const uint GL_ARRAY_BUFFER_BINDING = 0x8894;
public const uint GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
public const uint GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F;
public const uint GL_READ_ONLY = 0x88B8;
public const uint GL_WRITE_ONLY = 0x88B9;
public const uint GL_READ_WRITE = 0x88BA;
public const uint GL_BUFFER_ACCESS = 0x88BB;
public const uint GL_BUFFER_MAPPED = 0x88BC;
public const uint GL_BUFFER_MAP_POINTER = 0x88BD;
public const uint GL_STREAM_DRAW = 0x88E0;
public const uint GL_STREAM_READ = 0x88E1;
public const uint GL_STREAM_COPY = 0x88E2;
public const uint GL_STATIC_DRAW = 0x88E4;
public const uint GL_STATIC_READ = 0x88E5;
public const uint GL_STATIC_COPY = 0x88E6;
public const uint GL_DYNAMIC_DRAW = 0x88E8;
public const uint GL_DYNAMIC_READ = 0x88E9;
public const uint GL_DYNAMIC_COPY = 0x88EA;
public const uint GL_SAMPLES_PASSED = 0x8914;
#endregion
#region OpenGL 2.0
// Methods
public void BlendEquationSeparate (uint modeRGB, uint modeAlpha)
{
GetDelegateFor<glBlendEquationSeparate>()(modeRGB, modeAlpha);
}
public void DrawBuffers (int n, uint[] bufs)
{
GetDelegateFor<glDrawBuffers>()(n, bufs);
}
public void StencilOpSeparate (uint face, uint sfail, uint dpfail, uint dppass)
{
GetDelegateFor<glStencilOpSeparate>()(face, sfail, dpfail, dppass);
}
public void StencilFuncSeparate (uint face, uint func, int reference, uint mask)
{
GetDelegateFor<glStencilFuncSeparate>()(face, func, reference, mask);
}
public void StencilMaskSeparate (uint face, uint mask)
{
GetDelegateFor<glStencilMaskSeparate>()(face, mask);
}
public void AttachShader (uint program, uint shader)
{
GetDelegateFor<glAttachShader>()(program, shader);
}
public void BindAttribLocation (uint program, uint index, string name)
{
GetDelegateFor<glBindAttribLocation>()(program, index, name);
}
/// <summary>
/// Compile a shader object
/// </summary>
/// <param name="shader">Specifies the shader object to be compiled.</param>
public void CompileShader (uint shader)
{
GetDelegateFor<glCompileShader>()(shader);
}
public uint CreateProgram ()
{
return (uint)GetDelegateFor<glCreateProgram>()();
}
/// <summary>
/// Create a shader object
/// </summary>
/// <param name="type">Specifies the type of shader to be created. Must be either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.</param>
/// <returns>This function returns 0 if an error occurs creating the shader object. Otherwise the shader id is returned.</returns>
public uint CreateShader (uint type)
{
return (uint)GetDelegateFor<glCreateShader>()(type);
}
public void DeleteProgram (uint program)
{
GetDelegateFor<glDeleteProgram>()(program);
}
public void DeleteShader (uint shader)
{
GetDelegateFor<glDeleteShader>()(shader);
}
public void DetachShader (uint program, uint shader)
{
GetDelegateFor<glDetachShader>()(program, shader);
}
public void DisableVertexAttribArray (uint index)
{
GetDelegateFor<glDisableVertexAttribArray>()(index);
}
public void EnableVertexAttribArray (uint index)
{
GetDelegateFor<glEnableVertexAttribArray>()(index);
}
/// <summary>
/// Return information about an active attribute variable
/// </summary>
/// <param name="program">Specifies the program object to be queried.</param>
/// <param name="index">Specifies the index of the attribute variable to be queried.</param>
/// <param name="bufSize">Specifies the maximum number of characters OpenGL is allowed to write in the character buffer indicated by <paramref name="name"/>.</param>
/// <param name="length">Returns the number of characters actually written by OpenGL in the string indicated by name (excluding the null terminator) if a value other than NULL is passed.</param>
/// <param name="size">Returns the size of the attribute variable.</param>
/// <param name="type">Returns the data type of the attribute variable.</param>
/// <param name="name">Returns a null terminated string containing the name of the attribute variable.</param>
public void GetActiveAttrib (uint program, uint index, int bufSize, out int length, out int size, out uint type, out string name)
{
var builder = new StringBuilder(bufSize);
GetDelegateFor<glGetActiveAttrib>()(program, index, bufSize, out length, out size, out type, builder);
name = builder.ToString();
}
/// <summary>
/// Return information about an active uniform variable
/// </summary>
/// <param name="program">Specifies the program object to be queried.</param>
/// <param name="index">Specifies the index of the uniform variable to be queried.</param>
/// <param name="bufSize">Specifies the maximum number of characters OpenGL is allowed
/// to write in the character buffer indicated by <paramref name="name"/>.</param>
/// <param name="length">Returns the number of characters actually written by OpenGL in the string indicated by name
/// (excluding the null terminator) if a value other than NULL is passed.</param>
/// <param name="size">Returns the size of the uniform variable.</param>
/// <param name="type">Returns the data type of the uniform variable.</param>
/// <param name="name">Returns a null terminated string containing the name of the uniform variable.</param>
public void GetActiveUniform (uint program, uint index, int bufSize, out int length, out int size, out uint type, out string name)
{
var builder = new StringBuilder(bufSize);
GetDelegateFor<glGetActiveUniform>()(program, index, bufSize, out length, out size, out type, builder);
name = builder.ToString();
}
public void GetAttachedShaders (uint program, int maxCount, int[] count, uint[] obj)
{
GetDelegateFor<glGetAttachedShaders>()(program, maxCount, count, obj);
}
public int GetAttribLocation (uint program, string name)
{
return (int)GetDelegateFor<glGetAttribLocation>()(program, name);
}
public void GetProgram (uint program, uint pname, int[] parameters)
{
GetDelegateFor<glGetProgramiv>()(program, pname, parameters);
}
public void GetProgramInfoLog(uint program, int bufSize, IntPtr length, StringBuilder infoLog)
{
GetDelegateFor<glGetProgramInfoLog>()(program, bufSize, length, infoLog);
}
public void GetShader (uint shader, uint pname, int[] parameters)
{
GetDelegateFor<glGetShaderiv>()(shader, pname, parameters);
}
public void GetShaderInfoLog (uint shader, int bufSize, IntPtr length, StringBuilder infoLog)
{
GetDelegateFor<glGetShaderInfoLog>()(shader, bufSize, length, infoLog);
}
public void GetShaderSource(uint shader, int bufSize, IntPtr length, StringBuilder source)
{
GetDelegateFor<glGetShaderSource>()(shader, bufSize, length, source);
}
/// <summary>
/// Returns an integer that represents the location of a specific uniform variable within a program object. name must be a null terminated string that contains no white space. name must be an active uniform variable name in program that is not a structure, an array of structures, or a subcomponent of a vector or a matrix. This function returns -1 if name does not correspond to an active uniform variable in program, if name starts with the reserved prefix "gl_", or if name is associated with an atomic counter or a named uniform block.
/// </summary>
/// <param name="program">Specifies the program object to be queried.</param>
/// <param name="name">Points to a null terminated string containing the name of the uniform variable whose location is to be queried.</param>
/// <returns></returns>
public int GetUniformLocation (uint program, string name)
{
return (int)GetDelegateFor<glGetUniformLocation>()(program, name);
}
public void GetUniform (uint program, int location, float[] parameters)
{
GetDelegateFor<glGetUniformfv>()(program, location, parameters);
}
public void GetUniform (uint program, int location, int[] parameters)
{
GetDelegateFor<glGetUniformiv>()(program, location, parameters);
}
public void GetVertexAttrib (uint index, uint pname, double[] parameters)
{
GetDelegateFor<glGetVertexAttribdv>()(index, pname, parameters);
}
public void GetVertexAttrib (uint index, uint pname, float[] parameters)
{
GetDelegateFor<glGetVertexAttribfv>()(index, pname, parameters);
}
public void GetVertexAttrib (uint index, uint pname, int[] parameters)
{
GetDelegateFor<glGetVertexAttribiv>()(index, pname, parameters);
}
public void GetVertexAttribPointer(uint index, uint pname, IntPtr pointer)
{
GetDelegateFor<glGetVertexAttribPointerv>()(index, pname, pointer);
}
public bool IsProgram (uint program)
{
return (bool)GetDelegateFor<glIsProgram>()(program);
}
public bool IsShader (uint shader)
{
return (bool)GetDelegateFor<glIsShader>()(shader);
}
public void LinkProgram (uint program)
{
GetDelegateFor<glLinkProgram>()(program);
}
/// <summary>
/// Replace the source code in a shader object
/// </summary>
/// <param name="shader">Specifies the handle of the shader object whose source code is to be replaced.</param>
/// <param name="source">The source.</param>
public void ShaderSource (uint shader, string source)
{
// Remember, the function takes an array of strings but concatenates them, so we should NOT split into lines!
GetDelegateFor<glShaderSource>()(shader, 1, new[] { source }, new[] { source.Length });
}
public static IntPtr StringToPtrAnsi(string str)
{
if (string.IsNullOrEmpty(str))
return IntPtr.Zero;
byte[] bytes = Encoding.ASCII.GetBytes(str + '\0');
IntPtr strPtr = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, strPtr, bytes.Length);
return strPtr;
}
public void UseProgram (uint program)
{
GetDelegateFor<glUseProgram>()(program);
}
public void Uniform1 (int location, float v0)
{
GetDelegateFor<glUniform1f>()(location, v0);
}
public void Uniform2 (int location, float v0, float v1)
{
GetDelegateFor<glUniform2f>()(location, v0, v1);
}
public void Uniform3 (int location, float v0, float v1, float v2)
{
GetDelegateFor<glUniform3f>()(location, v0, v1, v2);
}
public void Uniform4 (int location, float v0, float v1, float v2, float v3)
{
GetDelegateFor<glUniform4f>()(location, v0, v1, v2, v3);
}
public void Uniform1 (int location, int v0)
{
GetDelegateFor<glUniform1i>()(location, v0);
}
public void Uniform2 (int location, int v0, int v1)
{
GetDelegateFor<glUniform2i>()(location, v0, v1);
}
public void Uniform3(int location, int v0, int v1, int v2)
{
GetDelegateFor<glUniform3i>()(location, v0, v1, v2);
}
public void Uniform (int location, int v0, int v1, int v2, int v3)
{
GetDelegateFor<glUniform4i>()(location, v0, v1, v2, v3);
}
public void Uniform1 (int location, int count, float[] value)
{
GetDelegateFor<glUniform1fv>()(location, count, value);
}
public void Uniform2 (int location, int count, float[] value)
{
GetDelegateFor<glUniform2fv>()(location, count, value);
}
public void Uniform3 (int location, int count, float[] value)
{
GetDelegateFor<glUniform3fv>()(location, count, value);
}
public void Uniform4 (int location, int count, float[] value)
{
GetDelegateFor<glUniform4fv>()(location, count, value);
}
public void Uniform1 (int location, int count, int[] value)
{
GetDelegateFor<glUniform1iv>()(location, count, value);
}
public void Uniform2 (int location, int count, int[] value)
{
GetDelegateFor<glUniform2iv>()(location, count, value);
}
public void Uniform3 (int location, int count, int[] value)
{
GetDelegateFor<glUniform3iv>()(location, count, value);
}
public void Uniform4 (int location, int count, int[] value)
{
GetDelegateFor<glUniform4iv>()(location, count, value);
}
public void UniformMatrix2 (int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix2fv>()(location, count, transpose, value);
}
public void UniformMatrix3 (int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix3fv>()(location, count, transpose, value);
}
public void UniformMatrix4 (int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix4fv>()(location, count, transpose, value);
}
public void ValidateProgram (uint program)
{
GetDelegateFor<glValidateProgram>()(program);
}
public void VertexAttrib1 (uint index, double x)
{
GetDelegateFor<glVertexAttrib1d>()(index, x);
}
public void VertexAttrib1 (uint index, double[] v)
{
GetDelegateFor<glVertexAttrib1dv>()(index, v);
}
public void VertexAttrib (uint index, float x)
{
GetDelegateFor<glVertexAttrib1f>()(index, x);
}
public void VertexAttrib1 (uint index, float[] v)
{
GetDelegateFor<glVertexAttrib1fv>()(index, v);
}
public void VertexAttrib (uint index, short x)
{
GetDelegateFor<glVertexAttrib1s>()(index, x);
}
public void VertexAttrib1 (uint index, short[] v)
{
GetDelegateFor<glVertexAttrib1sv>()(index, v);
}
public void VertexAttrib2 (uint index, double x, double y)
{
GetDelegateFor<glVertexAttrib2d>()(index, x, y);
}
public void VertexAttrib2 (uint index, double[] v)
{
GetDelegateFor<glVertexAttrib2dv>()(index, v);
}
public void VertexAttrib2 (uint index, float x, float y)
{
GetDelegateFor<glVertexAttrib2f>()(index, x, y);
}
public void VertexAttrib2 (uint index, float[] v)
{
GetDelegateFor<glVertexAttrib2fv>()(index, v);
}
public void VertexAttrib2 (uint index, short x, short y)
{
GetDelegateFor<glVertexAttrib2s>()(index, x, y);
}
public void VertexAttrib2 (uint index, short[] v)
{
GetDelegateFor<glVertexAttrib2sv>()(index, v);
}
public void VertexAttrib3 (uint index, double x, double y, double z)
{
GetDelegateFor<glVertexAttrib3d>()(index, x, y, z);
}
public void VertexAttrib3 (uint index, double[] v)
{
GetDelegateFor<glVertexAttrib3dv>()(index, v);
}
public void VertexAttrib3 (uint index, float x, float y, float z)
{
GetDelegateFor<glVertexAttrib3f>()(index, x, y, z);
}
public void VertexAttrib3 (uint index, float[] v)
{
GetDelegateFor<glVertexAttrib3fv>()(index, v);
}
public void VertexAttrib3 (uint index, short x, short y, short z)
{
GetDelegateFor<glVertexAttrib3s>()(index, x, y, z);
}
public void VertexAttrib3 (uint index, short[] v)
{
GetDelegateFor<glVertexAttrib3sv>()(index, v);
}
public void VertexAttrib4N (uint index, sbyte[] v)
{
GetDelegateFor<glVertexAttrib4Nbv>()(index, v);
}
public void VertexAttrib4N (uint index, int[] v)
{
GetDelegateFor<glVertexAttrib4Niv>()(index, v);
}
public void VertexAttrib4N (uint index, short[] v)
{
GetDelegateFor<glVertexAttrib4Nsv>()(index, v);
}
public void VertexAttrib4N (uint index, byte x, byte y, byte z, byte w)
{
GetDelegateFor<glVertexAttrib4Nub>()(index, x, y, z, w);
}
public void VertexAttrib4N (uint index, byte[] v)
{
GetDelegateFor<glVertexAttrib4Nubv>()(index, v);
}
public void VertexAttrib4N (uint index, uint[] v)
{
GetDelegateFor<glVertexAttrib4Nuiv>()(index, v);
}
public void VertexAttrib4N (uint index, ushort[] v)
{
GetDelegateFor<glVertexAttrib4Nusv>()(index, v);
}
public void VertexAttrib4 (uint index, sbyte[] v)
{
GetDelegateFor<glVertexAttrib4bv>()(index, v);
}
public void VertexAttrib4 (uint index, double x, double y, double z, double w)
{
GetDelegateFor<glVertexAttrib4d>()(index, x, y, z, w);
}
public void VertexAttrib4 (uint index, double[] v)
{
GetDelegateFor<glVertexAttrib4dv>()(index, v);
}
public void VertexAttrib4 (uint index, float x, float y, float z, float w)
{
GetDelegateFor<glVertexAttrib4f>()(index, x, y, z, w);
}
public void VertexAttrib4 (uint index, float[] v)
{
GetDelegateFor<glVertexAttrib4fv>()(index, v);
}
public void VertexAttrib4 (uint index, int[] v)
{
GetDelegateFor<glVertexAttrib4iv>()(index, v);
}
public void VertexAttrib4 (uint index, short x, short y, short z, short w)
{
GetDelegateFor<glVertexAttrib4s>()(index, x, y, z, w);
}
public void VertexAttrib4 (uint index, short[] v)
{
GetDelegateFor<glVertexAttrib4sv>()(index, v);
}
public void VertexAttrib4 (uint index, byte[] v)
{
GetDelegateFor<glVertexAttrib4ubv>()(index, v);
}
public void VertexAttrib4 (uint index, uint[] v)
{
GetDelegateFor<glVertexAttrib4uiv>()(index, v);
}
public void VertexAttrib4 (uint index, ushort[] v)
{
GetDelegateFor<glVertexAttrib4usv>()(index, v);
}
public void VertexAttribPointer (uint index, int size, uint type, bool normalized, int stride, IntPtr pointer)
{
GetDelegateFor<glVertexAttribPointer>()(index, size, type, normalized, stride, pointer);
}
// Delegates
private delegate void glBlendEquationSeparate (uint modeRGB, uint modeAlpha);
private delegate void glDrawBuffers (int n, uint[] bufs);
private delegate void glStencilOpSeparate (uint face, uint sfail, uint dpfail, uint dppass);
private delegate void glStencilFuncSeparate (uint face, uint func, int reference, uint mask);
private delegate void glStencilMaskSeparate (uint face, uint mask);
private delegate void glAttachShader (uint program, uint shader);
private delegate void glBindAttribLocation (uint program, uint index, string name);
private delegate void glCompileShader (uint shader);
private delegate uint glCreateProgram ();
private delegate uint glCreateShader (uint type);
private delegate void glDeleteProgram (uint program);
private delegate void glDeleteShader (uint shader);
private delegate void glDetachShader (uint program, uint shader);
private delegate void glDisableVertexAttribArray (uint index);
private delegate void glEnableVertexAttribArray (uint index);
private delegate void glGetActiveAttrib (uint program, uint index, int bufSize, out int length, out int size, out uint type, StringBuilder name);
private delegate void glGetActiveUniform (uint program, uint index, int bufSize, out int length, out int size, out uint type, StringBuilder name);
private delegate void glGetAttachedShaders (uint program, int maxCount, int[] count, uint[] obj);
private delegate int glGetAttribLocation (uint program, string name);
private delegate void glGetProgramiv (uint program, uint pname, int[] parameters);
private delegate void glGetProgramInfoLog(uint program, int bufSize, IntPtr length, StringBuilder infoLog);
private delegate void glGetShaderiv (uint shader, uint pname, int[] parameters);
private delegate void glGetShaderInfoLog (uint shader, int bufSize, IntPtr length, StringBuilder infoLog);
private delegate void glGetShaderSource (uint shader, int bufSize, IntPtr length, StringBuilder source);
private delegate int glGetUniformLocation (uint program, string name);
private delegate void glGetUniformfv (uint program, int location, float[] parameters);
private delegate void glGetUniformiv (uint program, int location, int[] parameters);
private delegate void glGetVertexAttribdv (uint index, uint pname, double[] parameters);
private delegate void glGetVertexAttribfv (uint index, uint pname, float[] parameters);
private delegate void glGetVertexAttribiv (uint index, uint pname, int[] parameters);
private delegate void glGetVertexAttribPointerv (uint index, uint pname, IntPtr pointer);
private delegate bool glIsProgram (uint program);
private delegate bool glIsShader (uint shader);
private delegate void glLinkProgram (uint program);
// By specifying 'ThrowOnUnmappableChar' we protect ourselves from inadvertantly using a unicode character
// in the source which the marshaller cannot map. Without this, it maps it to '?' leading to long and pointless
// sessions of trying to find bugs in the shader, which are most often just copied and pasted unicode characters!
// If you're getting exceptions here, remove all unicode crap from your input files (remember, some unicode
// characters you can't even see).
[UnmanagedFunctionPointer(CallingConvention.StdCall, ThrowOnUnmappableChar = true)]
private delegate void glShaderSource (uint shader, int count, string[] source, int[] length);
private delegate void glUseProgram (uint program);
private delegate void glUniform1f (int location, float v0);
private delegate void glUniform2f (int location, float v0, float v1);
private delegate void glUniform3f (int location, float v0, float v1, float v2);
private delegate void glUniform4f (int location, float v0, float v1, float v2, float v3);
private delegate void glUniform1i (int location, int v0);
private delegate void glUniform2i (int location, int v0, int v1);
private delegate void glUniform3i (int location, int v0, int v1, int v2);
private delegate void glUniform4i (int location, int v0, int v1, int v2, int v3);
private delegate void glUniform1fv (int location, int count, float[] value);
private delegate void glUniform2fv (int location, int count, float[] value);
private delegate void glUniform3fv (int location, int count, float[] value);
private delegate void glUniform4fv (int location, int count, float[] value);
private delegate void glUniform1iv (int location, int count, int[] value);
private delegate void glUniform2iv (int location, int count, int[] value);
private delegate void glUniform3iv (int location, int count, int[] value);
private delegate void glUniform4iv (int location, int count, int[] value);
private delegate void glUniformMatrix2fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix3fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix4fv (int location, int count, bool transpose, float[] value);
private delegate void glValidateProgram (uint program);
private delegate void glVertexAttrib1d (uint index, double x);
private delegate void glVertexAttrib1dv (uint index, double[] v);
private delegate void glVertexAttrib1f (uint index, float x);
private delegate void glVertexAttrib1fv (uint index, float[] v);
private delegate void glVertexAttrib1s (uint index, short x);
private delegate void glVertexAttrib1sv (uint index, short[] v);
private delegate void glVertexAttrib2d (uint index, double x, double y);
private delegate void glVertexAttrib2dv (uint index, double[] v);
private delegate void glVertexAttrib2f (uint index, float x, float y);
private delegate void glVertexAttrib2fv (uint index, float[] v);
private delegate void glVertexAttrib2s (uint index, short x, short y);
private delegate void glVertexAttrib2sv (uint index, short[] v);
private delegate void glVertexAttrib3d (uint index, double x, double y, double z);
private delegate void glVertexAttrib3dv (uint index, double[] v);
private delegate void glVertexAttrib3f (uint index, float x, float y, float z);
private delegate void glVertexAttrib3fv (uint index, float[] v);
private delegate void glVertexAttrib3s (uint index, short x, short y, short z);
private delegate void glVertexAttrib3sv (uint index, short[] v);
private delegate void glVertexAttrib4Nbv (uint index, sbyte[] v);
private delegate void glVertexAttrib4Niv (uint index, int[] v);
private delegate void glVertexAttrib4Nsv (uint index, short[] v);
private delegate void glVertexAttrib4Nub (uint index, byte x, byte y, byte z, byte w);
private delegate void glVertexAttrib4Nubv (uint index, byte[] v);
private delegate void glVertexAttrib4Nuiv (uint index, uint[] v);
private delegate void glVertexAttrib4Nusv (uint index, ushort[] v);
private delegate void glVertexAttrib4bv (uint index, sbyte[] v);
private delegate void glVertexAttrib4d (uint index, double x, double y, double z, double w);
private delegate void glVertexAttrib4dv (uint index, double[] v);
private delegate void glVertexAttrib4f (uint index, float x, float y, float z, float w);
private delegate void glVertexAttrib4fv (uint index, float[] v);
private delegate void glVertexAttrib4iv (uint index, int[] v);
private delegate void glVertexAttrib4s (uint index, short x, short y, short z, short w);
private delegate void glVertexAttrib4sv (uint index, short[] v);
private delegate void glVertexAttrib4ubv (uint index, byte[] v);
private delegate void glVertexAttrib4uiv (uint index, uint[] v);
private delegate void glVertexAttrib4usv (uint index, ushort[] v);
private delegate void glVertexAttribPointer (uint index, int size, uint type, bool normalized, int stride, IntPtr pointer);
// Constants
public const uint GL_BLEND_EQUATION_RGB = 0x8009;
public const uint GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
public const uint GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
public const uint GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
public const uint GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
public const uint GL_CURRENT_VERTEX_ATTRIB = 0x8626;
public const uint GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642;
public const uint GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
public const uint GL_STENCIL_BACK_FUNC = 0x8800;
public const uint GL_STENCIL_BACK_FAIL = 0x8801;
public const uint GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
public const uint GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
public const uint GL_MAX_DRAW_BUFFERS = 0x8824;
public const uint GL_DRAW_BUFFER0 = 0x8825;
public const uint GL_DRAW_BUFFER1 = 0x8826;
public const uint GL_DRAW_BUFFER2 = 0x8827;
public const uint GL_DRAW_BUFFER3 = 0x8828;
public const uint GL_DRAW_BUFFER4 = 0x8829;
public const uint GL_DRAW_BUFFER5 = 0x882A;
public const uint GL_DRAW_BUFFER6 = 0x882B;
public const uint GL_DRAW_BUFFER7 = 0x882C;
public const uint GL_DRAW_BUFFER8 = 0x882D;
public const uint GL_DRAW_BUFFER9 = 0x882E;
public const uint GL_DRAW_BUFFER10 = 0x882F;
public const uint GL_DRAW_BUFFER11 = 0x8830;
public const uint GL_DRAW_BUFFER12 = 0x8831;
public const uint GL_DRAW_BUFFER13 = 0x8832;
public const uint GL_DRAW_BUFFER14 = 0x8833;
public const uint GL_DRAW_BUFFER15 = 0x8834;
public const uint GL_BLEND_EQUATION_ALPHA = 0x883D;
public const uint GL_MAX_VERTEX_ATTRIBS = 0x8869;
public const uint GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
public const uint GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872;
public const uint GL_FRAGMENT_SHADER = 0x8B30;
public const uint GL_VERTEX_SHADER = 0x8B31;
public const uint GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49;
public const uint GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A;
public const uint GL_MAX_VARYING_FLOATS = 0x8B4B;
public const uint GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
public const uint GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
public const uint GL_SHADER_TYPE = 0x8B4F;
public const uint GL_FLOAT_VEC2 = 0x8B50;
public const uint GL_FLOAT_VEC3 = 0x8B51;
public const uint GL_FLOAT_VEC4 = 0x8B52;
public const uint GL_INT_VEC2 = 0x8B53;
public const uint GL_INT_VEC3 = 0x8B54;
public const uint GL_INT_VEC4 = 0x8B55;
public const uint GL_BOOL = 0x8B56;
public const uint GL_BOOL_VEC2 = 0x8B57;
public const uint GL_BOOL_VEC3 = 0x8B58;
public const uint GL_BOOL_VEC4 = 0x8B59;
public const uint GL_FLOAT_MAT2 = 0x8B5A;
public const uint GL_FLOAT_MAT3 = 0x8B5B;
public const uint GL_FLOAT_MAT4 = 0x8B5C;
public const uint GL_SAMPLER_1D = 0x8B5D;
public const uint GL_SAMPLER_2D = 0x8B5E;
public const uint GL_SAMPLER_3D = 0x8B5F;
public const uint GL_SAMPLER_CUBE = 0x8B60;
public const uint GL_SAMPLER_1D_SHADOW = 0x8B61;
public const uint GL_SAMPLER_2D_SHADOW = 0x8B62;
public const uint GL_DELETE_STATUS = 0x8B80;
public const uint GL_COMPILE_STATUS = 0x8B81;
public const uint GL_LINK_STATUS = 0x8B82;
public const uint GL_VALIDATE_STATUS = 0x8B83;
public const uint GL_INFO_LOG_LENGTH = 0x8B84;
public const uint GL_ATTACHED_SHADERS = 0x8B85;
public const uint GL_ACTIVE_UNIFORMS = 0x8B86;
public const uint GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87;
public const uint GL_SHADER_SOURCE_LENGTH = 0x8B88;
public const uint GL_ACTIVE_ATTRIBUTES = 0x8B89;
public const uint GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A;
public const uint GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B;
public const uint GL_SHADING_LANGUAGE_VERSION = 0x8B8C;
public const uint GL_CURRENT_PROGRAM = 0x8B8D;
public const uint GL_POINT_SPRITE_COORD_ORIGIN = 0x8CA0;
public const uint GL_LOWER_LEFT = 0x8CA1;
public const uint GL_UPPER_LEFT = 0x8CA2;
public const uint GL_STENCIL_BACK_REF = 0x8CA3;
public const uint GL_STENCIL_BACK_VALUE_MASK = 0x8CA4;
public const uint GL_STENCIL_BACK_WRITEMASK = 0x8CA5;
#endregion
#region OpenGL 2.1
// Methods
public void UniformMatrix2x3(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix2x3fv>()(location, count, transpose, value);
}
public void UniformMatrix3x2(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix3x2fv>()(location, count, transpose, value);
}
public void UniformMatrix2x4(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix2x4fv>()(location, count, transpose, value);
}
public void UniformMatrix4x2(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix4x2fv>()(location, count, transpose, value);
}
public void UniformMatrix3x4(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix3x4fv>()(location, count, transpose, value);
}
public void UniformMatrix4x3(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix4x3fv>()(location, count, transpose, value);
}
// Delegates
private delegate void glUniformMatrix2x3fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix3x2fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix2x4fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix4x2fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix3x4fv (int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix4x3fv (int location, int count, bool transpose, float[] value);
// Constants
public const uint GL_PIXEL_PACK_BUFFER = 0x88EB;
public const uint GL_PIXEL_UNPACK_BUFFER = 0x88EC;
public const uint GL_PIXEL_PACK_BUFFER_BINDING = 0x88ED;
public const uint GL_PIXEL_UNPACK_BUFFER_BINDING = 0x88EF;
public const uint GL_FLOAT_MAT2x3 = 0x8B65;
public const uint GL_FLOAT_MAT2x4 = 0x8B66;
public const uint GL_FLOAT_MAT3x2 = 0x8B67;
public const uint GL_FLOAT_MAT3x4 = 0x8B68;
public const uint GL_FLOAT_MAT4x2 = 0x8B69;
public const uint GL_FLOAT_MAT4x3 = 0x8B6A;
public const uint GL_SRGB = 0x8C40;
public const uint GL_SRGB8 = 0x8C41;
public const uint GL_SRGB_ALPHA = 0x8C42;
public const uint GL_SRGB8_ALPHA8 = 0x8C43;
public const uint GL_COMPRESSED_SRGB = 0x8C48;
public const uint GL_COMPRESSED_SRGB_ALPHA = 0x8C49;
#endregion
#region OpenGL 3.0
// Methods
public void ColorMask(uint index, bool r, bool g, bool b, bool a)
{
GetDelegateFor<glColorMaski>()(index, r, g, b, a);
}
public void GetBoolean(uint target, uint index, bool[] data)
{
GetDelegateFor<glGetBooleani_v>()(target, index, data);
}
public void GetInteger(uint target, uint index, int[] data)
{
GetDelegateFor<glGetIntegeri_v>()(target, index, data);
}
public void Enable(uint target, uint index)
{
GetDelegateFor<glEnablei>()(target, index);
}
public void Disable(uint target, uint index)
{
GetDelegateFor<glDisablei>()(target, index);
}
public bool IsEnabled(uint target, uint index)
{
return (bool)GetDelegateFor<glIsEnabledi>()(target, index);
}
public void BeginTransformFeedback(uint primitiveMode)
{
GetDelegateFor<glBeginTransformFeedback>()(primitiveMode);
}
public void EndTransformFeedback()
{
GetDelegateFor<glEndTransformFeedback>()();
}
public void BindBufferRange(uint target, uint index, uint buffer, int offset, int size)
{
GetDelegateFor<glBindBufferRange>()(target, index, buffer, offset, size);
}
public void BindBufferBase(uint target, uint index, uint buffer)
{
GetDelegateFor<glBindBufferBase>()(target, index, buffer);
}
public void TransformFeedbackVaryings(uint program, int count, string[] varyings, uint bufferMode)
{
GetDelegateFor<glTransformFeedbackVaryings>()(program, count, varyings, bufferMode);
}
public void GetTransformFeedbackVarying(uint program, uint index, int bufSize, int[] length, int[] size, uint[] type, string name)
{
GetDelegateFor<glGetTransformFeedbackVarying>()(program, index, bufSize, length, size, type, name);
}
public void ClampColor(uint target, uint clamp)
{
GetDelegateFor<glClampColor>()(target, clamp);
}
public void BeginConditionalRender(uint id, uint mode)
{
GetDelegateFor<glBeginConditionalRender>()(id, mode);
}
public void EndConditionalRender()
{
GetDelegateFor<glEndConditionalRender>()();
}
public void VertexAttribIPointer(uint index, int size, uint type, int stride, IntPtr pointer)
{
GetDelegateFor<glVertexAttribIPointer>()(index, size, type, stride, pointer);
}
public void GetVertexAttribI(uint index, uint pname, int[] parameters)
{
GetDelegateFor<glGetVertexAttribIiv>()(index, pname, parameters);
}
public void GetVertexAttribI(uint index, uint pname, uint[] parameters)
{
GetDelegateFor<glGetVertexAttribIuiv>()(index, pname, parameters);
}
public void VertexAttribI1(uint index, int x)
{
GetDelegateFor<glVertexAttribI1i>()(index, x);
}
public void VertexAttribI2(uint index, int x, int y)
{
GetDelegateFor<glVertexAttribI2i>()(index, x, y);
}
public void VertexAttribI3(uint index, int x, int y, int z)
{
GetDelegateFor<glVertexAttribI3i>()(index, x, y, z);
}
public void VertexAttribI4(uint index, int x, int y, int z, int w)
{
GetDelegateFor<glVertexAttribI4i>()(index, x, y, z, w);
}
public void VertexAttribI1(uint index, uint x)
{
GetDelegateFor<glVertexAttribI1ui>()(index, x);
}
public void VertexAttribI2(uint index, uint x, uint y)
{
GetDelegateFor<glVertexAttribI2ui>()(index, x, y);
}
public void VertexAttribI3(uint index, uint x, uint y, uint z)
{
GetDelegateFor<glVertexAttribI3ui>()(index, x, y, z);
}
public void VertexAttribI4(uint index, uint x, uint y, uint z, uint w)
{
GetDelegateFor<glVertexAttribI4ui>()(index, x, y, z, w);
}
public void VertexAttribI1(uint index, int[] v)
{
GetDelegateFor<glVertexAttribI1iv>()(index, v);
}
public void VertexAttribI2(uint index, int[] v)
{
GetDelegateFor<glVertexAttribI2iv>()(index, v);
}
public void VertexAttribI3(uint index, int[] v)
{
GetDelegateFor<glVertexAttribI3iv>()(index, v);
}
public void VertexAttribI4(uint index, int[] v)
{
GetDelegateFor<glVertexAttribI4iv>()(index, v);
}
public void VertexAttribI1(uint index, uint[] v)
{
GetDelegateFor<glVertexAttribI1uiv>()(index, v);
}
public void VertexAttribI2(uint index, uint[] v)
{
GetDelegateFor<glVertexAttribI2uiv>()(index, v);
}
public void VertexAttribI3(uint index, uint[] v)
{
GetDelegateFor<glVertexAttribI3uiv>()(index, v);
}
public void VertexAttribI4(uint index, uint[] v)
{
GetDelegateFor<glVertexAttribI4uiv>()(index, v);
}
public void VertexAttribI4(uint index, sbyte[] v)
{
GetDelegateFor<glVertexAttribI4bv>()(index, v);
}
public void VertexAttribI4(uint index, short[] v)
{
GetDelegateFor<glVertexAttribI4sv>()(index, v);
}
public void VertexAttribI4(uint index, byte[] v)
{
GetDelegateFor<glVertexAttribI4ubv>()(index, v);
}
public void VertexAttribI4(uint index, ushort[] v)
{
GetDelegateFor<glVertexAttribI4usv>()(index, v);
}
public void GetUniform(uint program, int location, uint[] parameters)
{
GetDelegateFor<glGetUniformuiv>()(program, location, parameters);
}
public void BindFragDataLocation(uint program, uint color, string name)
{
GetDelegateFor<glBindFragDataLocation>()(program, color, name);
}
public int GetFragDataLocation(uint program, string name)
{
return (int)GetDelegateFor<glGetFragDataLocation>()(program, name);
}
public void Uniform1(int location, uint v0)
{
GetDelegateFor<glUniform1ui>()(location, v0);
}
public void Uniform2(int location, uint v0, uint v1)
{
GetDelegateFor<glUniform2ui>()(location, v0, v1);
}
public void Uniform3(int location, uint v0, uint v1, uint v2)
{
GetDelegateFor<glUniform3ui>()(location, v0, v1, v2);
}
public void Uniform4(int location, uint v0, uint v1, uint v2, uint v3)
{
GetDelegateFor<glUniform4ui>()(location, v0, v1, v2, v3);
}
public void Uniform1(int location, int count, uint[] value)
{
GetDelegateFor<glUniform1uiv>()(location, count, value);
}
public void Uniform2(int location, int count, uint[] value)
{
GetDelegateFor<glUniform2uiv>()(location, count, value);
}
public void Uniform3(int location, int count, uint[] value)
{
GetDelegateFor<glUniform3uiv>()(location, count, value);
}
public void Uniform4(int location, int count, uint[] value)
{
GetDelegateFor<glUniform4uiv>()(location, count, value);
}
public void TexParameterI(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glTexParameterIiv>()(target, pname, parameters);
}
public void TexParameterI(uint target, uint pname, uint[] parameters)
{
GetDelegateFor<glTexParameterIuiv>()(target, pname, parameters);
}
public void GetTexParameterI(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetTexParameterIiv>()(target, pname, parameters);
}
public void GetTexParameterI(uint target, uint pname, uint[] parameters)
{
GetDelegateFor<glGetTexParameterIuiv>()(target, pname, parameters);
}
public void ClearBuffer(uint buffer, int drawbuffer, int[] value)
{
GetDelegateFor<glClearBufferiv>()(buffer, drawbuffer, value);
}
public void ClearBuffer(uint buffer, int drawbuffer, uint[] value)
{
GetDelegateFor<glClearBufferuiv>()(buffer, drawbuffer, value);
}
public void ClearBuffer(uint buffer, int drawbuffer, float[] value)
{
GetDelegateFor<glClearBufferfv>()(buffer, drawbuffer, value);
}
public void ClearBuffer(uint buffer, int drawbuffer, float depth, int stencil)
{
GetDelegateFor<glClearBufferfi>()(buffer, drawbuffer, depth, stencil);
}
public string GetString(uint name, uint index)
{
return (string)GetDelegateFor<glGetStringi>()(name, index);
}
// Delegates
private delegate void glColorMaski (uint index, bool r, bool g, bool b, bool a);
private delegate void glGetBooleani_v (uint target, uint index, bool[] data);
private delegate void glGetIntegeri_v (uint target, uint index, int[] data);
private delegate void glEnablei (uint target, uint index);
private delegate void glDisablei (uint target, uint index);
private delegate bool glIsEnabledi (uint target, uint index);
private delegate void glBeginTransformFeedback (uint primitiveMode);
private delegate void glEndTransformFeedback ();
private delegate void glBindBufferRange (uint target, uint index, uint buffer, int offset, int size);
private delegate void glBindBufferBase (uint target, uint index, uint buffer);
private delegate void glTransformFeedbackVaryings (uint program, int count, string[] varyings, uint bufferMode);
private delegate void glGetTransformFeedbackVarying (uint program, uint index, int bufSize, int[] length, int[] size, uint[] type, string name);
private delegate void glClampColor (uint target, uint clamp);
private delegate void glBeginConditionalRender (uint id, uint mode);
private delegate void glEndConditionalRender ();
private delegate void glVertexAttribIPointer (uint index, int size, uint type, int stride, IntPtr pointer);
private delegate void glGetVertexAttribIiv (uint index, uint pname, int[] parameters);
private delegate void glGetVertexAttribIuiv (uint index, uint pname, uint[] parameters);
private delegate void glVertexAttribI1i (uint index, int x);
private delegate void glVertexAttribI2i (uint index, int x, int y);
private delegate void glVertexAttribI3i (uint index, int x, int y, int z);
private delegate void glVertexAttribI4i (uint index, int x, int y, int z, int w);
private delegate void glVertexAttribI1ui (uint index, uint x);
private delegate void glVertexAttribI2ui (uint index, uint x, uint y);
private delegate void glVertexAttribI3ui (uint index, uint x, uint y, uint z);
private delegate void glVertexAttribI4ui (uint index, uint x, uint y, uint z, uint w);
private delegate void glVertexAttribI1iv (uint index, int[] v);
private delegate void glVertexAttribI2iv (uint index, int[] v);
private delegate void glVertexAttribI3iv (uint index, int[] v);
private delegate void glVertexAttribI4iv (uint index, int[] v);
private delegate void glVertexAttribI1uiv (uint index, uint[] v);
private delegate void glVertexAttribI2uiv (uint index, uint[] v);
private delegate void glVertexAttribI3uiv (uint index, uint[] v);
private delegate void glVertexAttribI4uiv (uint index, uint[] v);
private delegate void glVertexAttribI4bv (uint index, sbyte[] v);
private delegate void glVertexAttribI4sv (uint index, short[] v);
private delegate void glVertexAttribI4ubv (uint index, byte[] v);
private delegate void glVertexAttribI4usv (uint index, ushort[] v);
private delegate void glGetUniformuiv (uint program, int location, uint[] parameters);
private delegate void glBindFragDataLocation (uint program, uint color, string name);
private delegate int glGetFragDataLocation (uint program, string name);
private delegate void glUniform1ui (int location, uint v0);
private delegate void glUniform2ui (int location, uint v0, uint v1);
private delegate void glUniform3ui (int location, uint v0, uint v1, uint v2);
private delegate void glUniform4ui (int location, uint v0, uint v1, uint v2, uint v3);
private delegate void glUniform1uiv (int location, int count, uint[] value);
private delegate void glUniform2uiv (int location, int count, uint[] value);
private delegate void glUniform3uiv (int location, int count, uint[] value);
private delegate void glUniform4uiv (int location, int count, uint[] value);
private delegate void glTexParameterIiv (uint target, uint pname, int[] parameters);
private delegate void glTexParameterIuiv (uint target, uint pname, uint[] parameters);
private delegate void glGetTexParameterIiv (uint target, uint pname, int[] parameters);
private delegate void glGetTexParameterIuiv (uint target, uint pname, uint[] parameters);
private delegate void glClearBufferiv (uint buffer, int drawbuffer, int[] value);
private delegate void glClearBufferuiv (uint buffer, int drawbuffer, uint[] value);
private delegate void glClearBufferfv (uint buffer, int drawbuffer, float[] value);
private delegate void glClearBufferfi (uint buffer, int drawbuffer, float depth, int stencil);
private delegate string glGetStringi (uint name, uint index);
// Constants
public const uint GL_COMPARE_REF_TO_TEXTURE = 0x884E;
public const uint GL_CLIP_DISTANCE0 = 0x3000;
public const uint GL_CLIP_DISTANCE1 = 0x3001;
public const uint GL_CLIP_DISTANCE2 = 0x3002;
public const uint GL_CLIP_DISTANCE3 = 0x3003;
public const uint GL_CLIP_DISTANCE4 = 0x3004;
public const uint GL_CLIP_DISTANCE5 = 0x3005;
public const uint GL_CLIP_DISTANCE6 = 0x3006;
public const uint GL_CLIP_DISTANCE7 = 0x3007;
public const uint GL_MAX_CLIP_DISTANCES = 0x0D32;
public const uint GL_MAJOR_VERSION = 0x821B;
public const uint GL_MINOR_VERSION = 0x821C;
public const uint GL_NUM_EXTENSIONS = 0x821D;
public const uint GL_CONTEXT_FLAGS = 0x821E;
public const uint GL_DEPTH_BUFFER = 0x8223;
public const uint GL_STENCIL_BUFFER = 0x8224;
public const uint GL_COMPRESSED_RED = 0x8225;
public const uint GL_COMPRESSED_RG = 0x8226;
public const uint GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x0001;
public const uint GL_RGBA32F = 0x8814;
public const uint GL_RGB32F = 0x8815;
public const uint GL_RGBA16F = 0x881A;
public const uint GL_RGB16F = 0x881B;
public const uint GL_VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD;
public const uint GL_MAX_ARRAY_TEXTURE_LAYERS = 0x88FF;
public const uint GL_MIN_PROGRAM_TEXEL_OFFSET = 0x8904;
public const uint GL_MAX_PROGRAM_TEXEL_OFFSET = 0x8905;
public const uint GL_CLAMP_READ_COLOR = 0x891C;
public const uint GL_FIXED_ONLY = 0x891D;
public const uint GL_MAX_VARYING_COMPONENTS = 0x8B4B;
public const uint GL_TEXTURE_1D_ARRAY = 0x8C18;
public const uint GL_PROXY_TEXTURE_1D_ARRAY = 0x8C19;
public const uint GL_TEXTURE_2D_ARRAY = 0x8C1A;
public const uint GL_PROXY_TEXTURE_2D_ARRAY = 0x8C1B;
public const uint GL_TEXTURE_BINDING_1D_ARRAY = 0x8C1C;
public const uint GL_TEXTURE_BINDING_2D_ARRAY = 0x8C1D;
public const uint GL_R11F_G11F_B10F = 0x8C3A;
public const uint GL_UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
public const uint GL_RGB9_E5 = 0x8C3D;
public const uint GL_UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
public const uint GL_TEXTURE_SHARED_SIZE = 0x8C3F;
public const uint GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F;
public const uint GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80;
public const uint GL_TRANSFORM_FEEDBACK_VARYINGS = 0x8C83;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85;
public const uint GL_PRIMITIVES_GENERATED = 0x8C87;
public const uint GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88;
public const uint GL_RASTERIZER_DISCARD = 0x8C89;
public const uint GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A;
public const uint GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B;
public const uint GL_INTERLEAVED_ATTRIBS = 0x8C8C;
public const uint GL_SEPARATE_ATTRIBS = 0x8C8D;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER = 0x8C8E;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F;
public const uint GL_RGBA32UI = 0x8D70;
public const uint GL_RGB32UI = 0x8D71;
public const uint GL_RGBA16UI = 0x8D76;
public const uint GL_RGB16UI = 0x8D77;
public const uint GL_RGBA8UI = 0x8D7C;
public const uint GL_RGB8UI = 0x8D7D;
public const uint GL_RGBA32I = 0x8D82;
public const uint GL_RGB32I = 0x8D83;
public const uint GL_RGBA16I = 0x8D88;
public const uint GL_RGB16I = 0x8D89;
public const uint GL_RGBA8I = 0x8D8E;
public const uint GL_RGB8I = 0x8D8F;
public const uint GL_RED_INTEGER = 0x8D94;
public const uint GL_GREEN_INTEGER = 0x8D95;
public const uint GL_BLUE_INTEGER = 0x8D96;
public const uint GL_RGB_INTEGER = 0x8D98;
public const uint GL_RGBA_INTEGER = 0x8D99;
public const uint GL_BGR_INTEGER = 0x8D9A;
public const uint GL_BGRA_INTEGER = 0x8D9B;
public const uint GL_SAMPLER_1D_ARRAY = 0x8DC0;
public const uint GL_SAMPLER_2D_ARRAY = 0x8DC1;
public const uint GL_SAMPLER_1D_ARRAY_SHADOW = 0x8DC3;
public const uint GL_SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;
public const uint GL_SAMPLER_CUBE_SHADOW = 0x8DC5;
public const uint GL_UNSIGNED_INT_VEC2 = 0x8DC6;
public const uint GL_UNSIGNED_INT_VEC3 = 0x8DC7;
public const uint GL_UNSIGNED_INT_VEC4 = 0x8DC8;
public const uint GL_INT_SAMPLER_1D = 0x8DC9;
public const uint GL_INT_SAMPLER_2D = 0x8DCA;
public const uint GL_INT_SAMPLER_3D = 0x8DCB;
public const uint GL_INT_SAMPLER_CUBE = 0x8DCC;
public const uint GL_INT_SAMPLER_1D_ARRAY = 0x8DCE;
public const uint GL_INT_SAMPLER_2D_ARRAY = 0x8DCF;
public const uint GL_UNSIGNED_INT_SAMPLER_1D = 0x8DD1;
public const uint GL_UNSIGNED_INT_SAMPLER_2D = 0x8DD2;
public const uint GL_UNSIGNED_INT_SAMPLER_3D = 0x8DD3;
public const uint GL_UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;
public const uint GL_UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6;
public const uint GL_UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;
public const uint GL_QUERY_WAIT = 0x8E13;
public const uint GL_QUERY_NO_WAIT = 0x8E14;
public const uint GL_QUERY_BY_REGION_WAIT = 0x8E15;
public const uint GL_QUERY_BY_REGION_NO_WAIT = 0x8E16;
public const uint GL_BUFFER_ACCESS_FLAGS = 0x911F;
public const uint GL_BUFFER_MAP_LENGTH = 0x9120;
public const uint GL_BUFFER_MAP_OFFSET = 0x9121;
public const uint GL_R8 = 0x8229;
public const uint GL_R16 = 0x822A;
public const uint GL_RG8 = 0x822B;
public const uint GL_RG16 = 0x822C;
public const uint GL_R16F = 0x822D;
public const uint GL_R32F = 0x822E;
public const uint GL_RG16F = 0x822F;
public const uint GL_RG32F = 0x8230;
public const uint GL_R8I = 0x8231;
public const uint GL_R8UI = 0x8232;
public const uint GL_R16I = 0x8233;
public const uint GL_R16UI = 0x8234;
public const uint GL_R32I = 0x8235;
public const uint GL_R32UI = 0x8236;
public const uint GL_RG8I = 0x8237;
public const uint GL_RG8UI = 0x8238;
public const uint GL_RG16I = 0x8239;
public const uint GL_RG16UI = 0x823A;
public const uint GL_RG32I = 0x823B;
public const uint GL_RG32UI = 0x823C;
public const uint GL_RG = 0x8227;
public const uint GL_RG_INTEGER = 0x8228;
#endregion
#region OpenGL 3.1
// Methods
public void DrawArraysInstanced(uint mode, int first, int count, int primcount)
{
GetDelegateFor<glDrawArraysInstanced>()(mode, first, count, primcount);
}
public void DrawElementsInstanced(uint mode, int count, uint type, IntPtr indices, int primcount)
{
GetDelegateFor<glDrawElementsInstanced>()(mode, count, type, indices, primcount);
}
public void TexBuffer(uint target, uint internalformat, uint buffer)
{
GetDelegateFor<glTexBuffer>()(target, internalformat, buffer);
}
public void PrimitiveRestartIndex(uint index)
{
GetDelegateFor<glPrimitiveRestartIndex>()(index);
}
// Delegates
private delegate void glDrawArraysInstanced (uint mode, int first, int count, int primcount);
private delegate void glDrawElementsInstanced (uint mode, int count, uint type, IntPtr indices, int primcount);
private delegate void glTexBuffer (uint target, uint internalformat, uint buffer);
private delegate void glPrimitiveRestartIndex (uint index);
// Constants
public const uint GL_SAMPLER_2D_RECT = 0x8B63;
public const uint GL_SAMPLER_2D_RECT_SHADOW = 0x8B64;
public const uint GL_SAMPLER_BUFFER = 0x8DC2;
public const uint GL_INT_SAMPLER_2D_RECT = 0x8DCD;
public const uint GL_INT_SAMPLER_BUFFER = 0x8DD0;
public const uint GL_UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5;
public const uint GL_UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8;
public const uint GL_TEXTURE_BUFFER = 0x8C2A;
public const uint GL_MAX_TEXTURE_BUFFER_SIZE = 0x8C2B;
public const uint GL_TEXTURE_BINDING_BUFFER = 0x8C2C;
public const uint GL_TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D;
public const uint GL_TEXTURE_BUFFER_FORMAT = 0x8C2E;
public const uint GL_TEXTURE_RECTANGLE = 0x84F5;
public const uint GL_TEXTURE_BINDING_RECTANGLE = 0x84F6;
public const uint GL_PROXY_TEXTURE_RECTANGLE = 0x84F7;
public const uint GL_MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8;
public const uint GL_RED_SNORM = 0x8F90;
public const uint GL_RG_SNORM = 0x8F91;
public const uint GL_RGB_SNORM = 0x8F92;
public const uint GL_RGBA_SNORM = 0x8F93;
public const uint GL_R8_SNORM = 0x8F94;
public const uint GL_RG8_SNORM = 0x8F95;
public const uint GL_RGB8_SNORM = 0x8F96;
public const uint GL_RGBA8_SNORM = 0x8F97;
public const uint GL_R16_SNORM = 0x8F98;
public const uint GL_RG16_SNORM = 0x8F99;
public const uint GL_RGB16_SNORM = 0x8F9A;
public const uint GL_RGBA16_SNORM = 0x8F9B;
public const uint GL_SIGNED_NORMALIZED = 0x8F9C;
public const uint GL_PRIMITIVE_RESTART = 0x8F9D;
public const uint GL_PRIMITIVE_RESTART_INDEX = 0x8F9E;
#endregion
#region OpenGL 3.2
// Methods
public void GetInteger64(uint target, uint index, Int64[] data)
{
GetDelegateFor<glGetInteger64i_v>()(target, index, data);
}
public void GetBufferParameteri64(uint target, uint pname, Int64[] parameters)
{
GetDelegateFor<glGetBufferParameteri64v>()(target, pname, parameters);
}
public void FramebufferTexture(uint target, uint attachment, uint texture, int level)
{
GetDelegateFor<glFramebufferTexture>()(target, attachment, texture, level);
}
// Delegates
private delegate void glGetInteger64i_v (uint target, uint index, Int64[] data);
private delegate void glGetBufferParameteri64v (uint target, uint pname, Int64[] parameters);
private delegate void glFramebufferTexture (uint target, uint attachment, uint texture, int level);
// Constants
public const uint GL_CONTEXT_CORE_PROFILE_BIT = 0x00000001;
public const uint GL_CONTEXT_COMPATIBILITY_PROFILE_BIT = 0x00000002;
public const uint GL_LINES_ADJACENCY = 0x000A;
public const uint GL_LINE_STRIP_ADJACENCY = 0x000B;
public const uint GL_TRIANGLES_ADJACENCY = 0x000C;
public const uint GL_TRIANGLE_STRIP_ADJACENCY = 0x000D;
public const uint GL_PROGRAM_POINT_SIZE = 0x8642;
public const uint GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29;
public const uint GL_FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7;
public const uint GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8;
public const uint GL_GEOMETRY_SHADER = 0x8DD9;
public const uint GL_GEOMETRY_VERTICES_OUT = 0x8916;
public const uint GL_GEOMETRY_INPUT_TYPE = 0x8917;
public const uint GL_GEOMETRY_OUTPUT_TYPE = 0x8918;
public const uint GL_MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF;
public const uint GL_MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0;
public const uint GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1;
public const uint GL_MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122;
public const uint GL_MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123;
public const uint GL_MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124;
public const uint GL_MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125;
public const uint GL_CONTEXT_PROFILE_MASK = 0x9126;
#endregion
#region OpenGL 3.3
// Methods
public void VertexAttribDivisor(uint index, uint divisor)
{
GetDelegateFor<glVertexAttribDivisor>()(index, divisor);
}
// Delegates
private delegate void glVertexAttribDivisor (uint index, uint divisor);
// Constants
public const uint GL_VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE;
#endregion
#region OpenGL 4.0
// Methods
public void MinSampleShading(float value)
{
GetDelegateFor<glMinSampleShading>()(value);
}
public void BlendEquation(uint buf, uint mode)
{
GetDelegateFor<glBlendEquationi>()(buf, mode);
}
public void BlendEquationSeparate(uint buf, uint modeRGB, uint modeAlpha)
{
GetDelegateFor<glBlendEquationSeparatei>()(buf, modeRGB, modeAlpha);
}
public void BlendFunc(uint buf, uint src, uint dst)
{
GetDelegateFor<glBlendFunci>()(buf, src, dst);
}
public void BlendFuncSeparate(uint buf, uint srcRGB, uint dstRGB, uint srcAlpha, uint dstAlpha)
{
GetDelegateFor<glBlendFuncSeparatei>()(buf, srcRGB, dstRGB, srcAlpha, dstAlpha);
}
// Delegates
private delegate void glMinSampleShading (float value);
private delegate void glBlendEquationi (uint buf, uint mode);
private delegate void glBlendEquationSeparatei (uint buf, uint modeRGB, uint modeAlpha);
private delegate void glBlendFunci (uint buf, uint src, uint dst);
private delegate void glBlendFuncSeparatei (uint buf, uint srcRGB, uint dstRGB, uint srcAlpha, uint dstAlpha);
// Constants
public const uint GL_SAMPLE_SHADING = 0x8C36;
public const uint GL_MIN_SAMPLE_SHADING_VALUE = 0x8C37;
public const uint GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5E;
public const uint GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5F;
public const uint GL_TEXTURE_CUBE_MAP_ARRAY = 0x9009;
public const uint GL_TEXTURE_BINDING_CUBE_MAP_ARRAY = 0x900A;
public const uint GL_PROXY_TEXTURE_CUBE_MAP_ARRAY = 0x900B;
public const uint GL_SAMPLER_CUBE_MAP_ARRAY = 0x900C;
public const uint GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW = 0x900D;
public const uint GL_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900E;
public const uint GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900F;
#endregion
#region GL_EXT_texture3D
/// <summary>
/// Specify a three-dimensional texture subimage.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="level">The level.</param>
/// <param name="internalformat">The internalformat.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="border">The border.</param>
/// <param name="format">The format.</param>
/// <param name="type">The type.</param>
/// <param name="pixels">The pixels.</param>
public void TexImage3DEXT (uint target, int level, uint internalformat, uint width,
uint height, uint depth, int border, uint format, uint type, IntPtr pixels)
{
GetDelegateFor<glTexImage3DEXT>()(target, level, internalformat, width, height, depth, border, format, type, pixels);
}
/// <summary>
/// Texes the sub image3 DEXT.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="level">The level.</param>
/// <param name="xoffset">The xoffset.</param>
/// <param name="yoffset">The yoffset.</param>
/// <param name="zoffset">The zoffset.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="type">The type.</param>
/// <param name="pixels">The pixels.</param>
public void TexSubImage3DEXT(uint target, int level, int xoffset, int yoffset, int zoffset,
uint width, uint height, uint depth, uint format, uint type, IntPtr pixels)
{
GetDelegateFor<glTexSubImage3DEXT>()(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
}
private delegate void glTexImage3DEXT(uint target, int level, uint internalformat, uint width,
uint height, uint depth, int border, uint format, uint type, IntPtr pixels);
private delegate void glTexSubImage3DEXT(uint target, int level, int xoffset, int yoffset, int zoffset,
uint width, uint height, uint depth, uint format, uint type, IntPtr pixels);
#endregion
#region GL_EXT_bgra
public const uint GL_BGR_EXT = 0x80E0;
public const uint GL_BGRA_EXT = 0x80E1;
#endregion
#region GL_EXT_packed_pixels
public const uint GL_UNSIGNED_BYTE_3_3_2_EXT = 0x8032;
public const uint GL_UNSIGNED_SHORT_4_4_4_4_EXT = 0x8033;
public const uint GL_UNSIGNED_SHORT_5_5_5_1_EXT = 0x8034;
public const uint GL_UNSIGNED_INT_8_8_8_8_EXT = 0x8035;
public const uint GL_UNSIGNED_INT_10_10_10_2_EXT = 0x8036;
#endregion
#region GL_EXT_rescale_normal
public const uint GL_RESCALE_NORMAL_EXT = 0x803A;
#endregion
#region GL_EXT_separate_specular_color
public const uint GL_LIGHT_MODEL_COLOR_CONTROL_EXT = 0x81F8;
public const uint GL_SINGLE_COLOR_EXT = 0x81F9;
public const uint GL_SEPARATE_SPECULAR_COLOR_EXT = 0x81FA;
#endregion
#region GL_SGIS_texture_edge_clamp
public const uint GL_CLAMP_TO_EDGE_SGIS = 0x812F;
#endregion
#region GL_SGIS_texture_lod
public const uint GL_TEXTURE_MIN_LOD_SGIS = 0x813A;
public const uint GL_TEXTURE_MAX_LOD_SGIS = 0x813B;
public const uint GL_TEXTURE_BASE_LEVEL_SGIS = 0x813C;
public const uint GL_TEXTURE_MAX_LEVEL_SGIS = 0x813D;
#endregion
#region GL_EXT_draw_range_elements
/// <summary>
/// Render primitives from array data.
/// </summary>
/// <param name="mode">The mode.</param>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="count">The count.</param>
/// <param name="type">The type.</param>
/// <param name="indices">The indices.</param>
public void DrawRangeElementsEXT(uint mode, uint start, uint end, uint count, uint type, IntPtr indices)
{
GetDelegateFor<glDrawRangeElementsEXT>()(mode, start, end, count, type, indices);
}
private delegate void glDrawRangeElementsEXT(uint mode, uint start, uint end, uint count, uint type, IntPtr indices);
public const uint GL_MAX_ELEMENTS_VERTICES_EXT = 0x80E8;
public const uint GL_MAX_ELEMENTS_INDICES_EXT = 0x80E9;
#endregion
#region GL_SGI_color_table
// Delegates
public void ColorTableSGI(uint target, uint internalformat, uint width, uint format, uint type, IntPtr table)
{
GetDelegateFor<glColorTableSGI>()(target, internalformat, width, format, type, table);
}
public void ColorTableParameterSGI(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glColorTableParameterfvSGI>()(target, pname, parameters);
}
public void ColorTableParameterSGI(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glColorTableParameterivSGI>()(target, pname, parameters);
}
public void CopyColorTableSGI(uint target, uint internalformat, int x, int y, uint width)
{
GetDelegateFor<glCopyColorTableSGI>()(target, internalformat, x, y, width);
}
public void GetColorTableSGI(uint target, uint format, uint type, IntPtr table)
{
GetDelegateFor<glGetColorTableSGI>()(target, format, type, table);
}
public void GetColorTableParameterSGI(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetColorTableParameterfvSGI>()(target, pname, parameters);
}
public void GetColorTableParameterSGI(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetColorTableParameterivSGI>()(target, pname, parameters);
}
// Delegates
private delegate void glColorTableSGI(uint target, uint internalformat, uint width, uint format, uint type, IntPtr table);
private delegate void glColorTableParameterfvSGI(uint target, uint pname, float[] parameters);
private delegate void glColorTableParameterivSGI(uint target, uint pname, int[] parameters);
private delegate void glCopyColorTableSGI(uint target, uint internalformat, int x, int y, uint width);
private delegate void glGetColorTableSGI(uint target, uint format, uint type, IntPtr table);
private delegate void glGetColorTableParameterfvSGI(uint target, uint pname, float[] parameters);
private delegate void glGetColorTableParameterivSGI(uint target, uint pname, int[] parameters);
// Constants
public const uint GL_COLOR_TABLE_SGI = 0x80D0;
public const uint GL_POST_CONVOLUTION_COLOR_TABLE_SGI = 0x80D1;
public const uint GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI = 0x80D2;
public const uint GL_PROXY_COLOR_TABLE_SGI = 0x80D3;
public const uint GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI = 0x80D4;
public const uint GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI = 0x80D5;
public const uint GL_COLOR_TABLE_SCALE_SGI = 0x80D6;
public const uint GL_COLOR_TABLE_BIAS_SGI = 0x80D7;
public const uint GL_COLOR_TABLE_FORMAT_SGI = 0x80D8;
public const uint GL_COLOR_TABLE_WIDTH_SGI = 0x80D9;
public const uint GL_COLOR_TABLE_RED_SIZE_SGI = 0x80DA;
public const uint GL_COLOR_TABLE_GREEN_SIZE_SGI = 0x80DB;
public const uint GL_COLOR_TABLE_BLUE_SIZE_SGI = 0x80DC;
public const uint GL_COLOR_TABLE_ALPHA_SIZE_SGI = 0x80DD;
public const uint GL_COLOR_TABLE_LUMINANCE_SIZE_SGI = 0x80DE;
public const uint GL_COLOR_TABLE_INTENSITY_SIZE_SGI = 0x80DF;
#endregion
#region GL_EXT_convolution
// Methods.
public void ConvolutionFilter1DEXT(uint target, uint internalformat, int width, uint format, uint type, IntPtr image)
{
GetDelegateFor<glConvolutionFilter1DEXT>()(target, internalformat, width, format, type, image);
}
public void ConvolutionFilter2DEXT(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr image)
{
GetDelegateFor<glConvolutionFilter2DEXT>()(target, internalformat, width, height, format, type, image);
}
public void ConvolutionParameterEXT(uint target, uint pname, float parameters)
{
GetDelegateFor<glConvolutionParameterfEXT>()(target, pname, parameters);
}
public void ConvolutionParameterEXT(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glConvolutionParameterfvEXT>()(target, pname, parameters);
}
public void ConvolutionParameterEXT(uint target, uint pname, int parameter)
{
GetDelegateFor<glConvolutionParameteriEXT>()(target, pname, parameter);
}
public void ConvolutionParameterEXT(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glConvolutionParameterivEXT>()(target, pname, parameters);
}
public void CopyConvolutionFilter1DEXT(uint target, uint internalformat, int x, int y, int width)
{
GetDelegateFor<glCopyConvolutionFilter1DEXT>()(target, internalformat, x, y, width);
}
public void CopyConvolutionFilter2DEXT(uint target, uint internalformat, int x, int y, int width, int height)
{
GetDelegateFor<glCopyConvolutionFilter2DEXT>()(target, internalformat, x, y, width, height);
}
public void GetConvolutionFilterEXT(uint target, uint format, uint type, IntPtr image)
{
GetDelegateFor<glGetConvolutionFilterEXT>()(target, format, type, image);
}
public void GetConvolutionParameterfvEXT(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetConvolutionParameterfvEXT>()(target, pname, parameters);
}
public void GetConvolutionParameterivEXT(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetConvolutionParameterivEXT>()(target, pname, parameters);
}
public void GetSeparableFilterEXT(uint target, uint format, uint type, IntPtr row, IntPtr column, IntPtr span)
{
GetDelegateFor<glGetSeparableFilterEXT>()(target, format, type, row, column, span);
}
public void SeparableFilter2DEXT(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr row, IntPtr column)
{
GetDelegateFor<glSeparableFilter2DEXT>()(target, internalformat, width, height, format, type, row, column);
}
// Delegates
private delegate void glConvolutionFilter1DEXT(uint target, uint internalformat, int width, uint format, uint type, IntPtr image);
private delegate void glConvolutionFilter2DEXT(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr image);
private delegate void glConvolutionParameterfEXT(uint target, uint pname, float parameters);
private delegate void glConvolutionParameterfvEXT(uint target, uint pname, float[] parameters);
private delegate void glConvolutionParameteriEXT(uint target, uint pname, int parameter);
private delegate void glConvolutionParameterivEXT(uint target, uint pname, int[] parameters);
private delegate void glCopyConvolutionFilter1DEXT(uint target, uint internalformat, int x, int y, int width);
private delegate void glCopyConvolutionFilter2DEXT(uint target, uint internalformat, int x, int y, int width, int height);
private delegate void glGetConvolutionFilterEXT(uint target, uint format, uint type, IntPtr image);
private delegate void glGetConvolutionParameterfvEXT(uint target, uint pname, float[] parameters);
private delegate void glGetConvolutionParameterivEXT(uint target, uint pname, int[] parameters);
private delegate void glGetSeparableFilterEXT(uint target, uint format, uint type, IntPtr row, IntPtr column, IntPtr span);
private delegate void glSeparableFilter2DEXT(uint target, uint internalformat, int width, int height, uint format, uint type, IntPtr row, IntPtr column);
// Constants
public static uint GL_CONVOLUTION_1D_EXT = 0x8010;
public static uint GL_CONVOLUTION_2D_EXT = 0x8011;
public static uint GL_SEPARABLE_2D_EXT = 0x8012;
public static uint GL_CONVOLUTION_BORDER_MODE_EXT = 0x8013;
public static uint GL_CONVOLUTION_FILTER_SCALE_EXT = 0x8014;
public static uint GL_CONVOLUTION_FILTER_BIAS_EXT = 0x8015;
public static uint GL_REDUCE_EXT = 0x8016;
public static uint GL_CONVOLUTION_FORMAT_EXT = 0x8017;
public static uint GL_CONVOLUTION_WIDTH_EXT = 0x8018;
public static uint GL_CONVOLUTION_HEIGHT_EXT = 0x8019;
public static uint GL_MAX_CONVOLUTION_WIDTH_EXT = 0x801A;
public static uint GL_MAX_CONVOLUTION_HEIGHT_EXT = 0x801B;
public static uint GL_POST_CONVOLUTION_RED_SCALE_EXT = 0x801C;
public static uint GL_POST_CONVOLUTION_GREEN_SCALE_EXT = 0x801D;
public static uint GL_POST_CONVOLUTION_BLUE_SCALE_EXT = 0x801E;
public static uint GL_POST_CONVOLUTION_ALPHA_SCALE_EXT = 0x801F;
public static uint GL_POST_CONVOLUTION_RED_BIAS_EXT = 0x8020;
public static uint GL_POST_CONVOLUTION_GREEN_BIAS_EXT = 0x8021;
public static uint GL_POST_CONVOLUTION_BLUE_BIAS_EXT = 0x8022;
public static uint GL_POST_CONVOLUTION_ALPHA_BIAS_EXT = 0x8023;
#endregion
#region GL_SGI_color_matrix
public const uint GL_COLOR_MATRIX_SGI = 0x80B1;
public const uint GL_COLOR_MATRIX_STACK_DEPTH_SGI = 0x80B2;
public const uint GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI = 0x80B3;
public const uint GL_POST_COLOR_MATRIX_RED_SCALE_SGI = 0x80B4;
public const uint GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI = 0x80B5;
public const uint GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI = 0x80B6;
public const uint GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI = 0x80B7;
public const uint GL_POST_COLOR_MATRIX_RED_BIAS_SGI = 0x80B8;
public const uint GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI = 0x80B9;
public const uint GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI = 0x80BA;
public const uint GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI = 0x80BB;
#endregion
#region GL_EXT_histogram
// Methods
public void GetHistogramEXT(uint target, bool reset, uint format, uint type, IntPtr values)
{
GetDelegateFor<glGetHistogramEXT>()(target, reset, format, type, values);
}
public void GetHistogramParameterEXT(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetHistogramParameterfvEXT>()(target, pname, parameters);
}
public void GetHistogramParameterEXT(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetHistogramParameterivEXT>()(target, pname, parameters);
}
public void GetMinmaxEXT(uint target, bool reset, uint format, uint type, IntPtr values)
{
GetDelegateFor<glGetMinmaxEXT>()(target, reset, format, type, values);
}
public void GetMinmaxParameterfvEXT(uint target, uint pname, float[] parameters)
{
GetDelegateFor<glGetMinmaxParameterfvEXT>()(target, pname, parameters);
}
public void GetMinmaxParameterivEXT(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetMinmaxParameterivEXT>()(target, pname, parameters);
}
public void HistogramEXT(uint target, int width, uint internalformat, bool sink)
{
GetDelegateFor<glHistogramEXT>()(target, width, internalformat, sink);
}
public void MinmaxEXT(uint target, uint internalformat, bool sink)
{
GetDelegateFor<glMinmaxEXT>()(target, internalformat, sink);
}
public void ResetHistogramEXT(uint target)
{
GetDelegateFor<glResetHistogramEXT>()(target);
}
public void ResetMinmaxEXT(uint target)
{
GetDelegateFor<glResetMinmaxEXT>()(target);
}
// Delegates
private delegate void glGetHistogramEXT(uint target, bool reset, uint format, uint type, IntPtr values);
private delegate void glGetHistogramParameterfvEXT(uint target, uint pname, float[] parameters);
private delegate void glGetHistogramParameterivEXT(uint target, uint pname, int[] parameters);
private delegate void glGetMinmaxEXT(uint target, bool reset, uint format, uint type, IntPtr values);
private delegate void glGetMinmaxParameterfvEXT(uint target, uint pname, float[] parameters);
private delegate void glGetMinmaxParameterivEXT(uint target, uint pname, int[] parameters);
private delegate void glHistogramEXT(uint target, int width, uint internalformat, bool sink);
private delegate void glMinmaxEXT(uint target, uint internalformat, bool sink);
private delegate void glResetHistogramEXT(uint target);
private delegate void glResetMinmaxEXT(uint target);
// Constants
public const uint GL_HISTOGRAM_EXT = 0x8024;
public const uint GL_PROXY_HISTOGRAM_EXT = 0x8025;
public const uint GL_HISTOGRAM_WIDTH_EXT = 0x8026;
public const uint GL_HISTOGRAM_FORMAT_EXT = 0x8027;
public const uint GL_HISTOGRAM_RED_SIZE_EXT = 0x8028;
public const uint GL_HISTOGRAM_GREEN_SIZE_EXT = 0x8029;
public const uint GL_HISTOGRAM_BLUE_SIZE_EXT = 0x802A;
public const uint GL_HISTOGRAM_ALPHA_SIZE_EXT = 0x802B;
public const uint GL_HISTOGRAM_LUMINANCE_SIZE_EXT = 0x802C;
public const uint GL_HISTOGRAM_SINK_EXT = 0x802D;
public const uint GL_MINMAX_EXT = 0x802E;
public const uint GL_MINMAX_FORMAT_EXT = 0x802F;
public const uint GL_MINMAX_SINK_EXT = 0x8030;
public const uint GL_TABLE_TOO_LARGE_EXT = 0x8031;
#endregion
#region GL_EXT_blend_color
// Methods
public void BlendColorEXT(float red, float green, float blue, float alpha)
{
GetDelegateFor<glBlendColorEXT>()(red, green, blue, alpha);
}
// Delegates
private delegate void glBlendColorEXT(float red, float green, float blue, float alpha);
// Constants
public const uint GL_CONSTANT_COLOR_EXT = 0x8001;
public const uint GL_ONE_MINUS_CONSTANT_COLOR_EXT = 0x8002;
public const uint GL_CONSTANT_ALPHA_EXT = 0x8003;
public const uint GL_ONE_MINUS_CONSTANT_ALPHA_EXT = 0x8004;
public const uint GL_BLEND_COLOR_EXT = 0x8005;
#endregion
#region GL_EXT_blend_minmax
// Methods
public void BlendEquationEXT(uint mode)
{
GetDelegateFor<glBlendEquationEXT>()(mode);
}
// Delegates
private delegate void glBlendEquationEXT(uint mode);
// Constants
public const uint GL_FUNC_ADD_EXT = 0x8006;
public const uint GL_MIN_EXT = 0x8007;
public const uint GL_MAX_EXT = 0x8008;
public const uint GL_FUNC_SUBTRACT_EXT = 0x800A;
public const uint GL_FUNC_REVERSE_SUBTRACT_EXT = 0x800B;
public const uint GL_BLEND_EQUATION_EXT = 0x8009;
#endregion
#region GL_ARB_multitexture
// Methods
[Obsolete("Deprecated from OpenGL version 3.0")]
public void ActiveTextureARB(uint texture)
{
GetDelegateFor<glActiveTextureARB>()(texture);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void ClientActiveTextureARB(uint texture)
{
GetDelegateFor<glClientActiveTextureARB>()(texture);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, double s)
{
GetDelegateFor<glMultiTexCoord1dARB>()(target, s);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord1dvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, float s)
{
GetDelegateFor<glMultiTexCoord1fARB>()(target, s);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord1fvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, int s)
{
GetDelegateFor<glMultiTexCoord1iARB>()(target, s);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord1ivARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, short s)
{
GetDelegateFor<glMultiTexCoord1sARB>()(target, s);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord1ARB(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord1svARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, double s, double t)
{
GetDelegateFor<glMultiTexCoord2dARB>()(target, s, t);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord2dvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, float s, float t)
{
GetDelegateFor<glMultiTexCoord2fARB>()(target, s, t);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord2fvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, int s, int t)
{
GetDelegateFor<glMultiTexCoord2iARB>()(target, s, t);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord2ivARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, short s, short t)
{
GetDelegateFor<glMultiTexCoord2sARB>()(target, s, t);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord2ARB(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord2svARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, double s, double t, double r)
{
GetDelegateFor<glMultiTexCoord3dARB>()(target, s, t, r);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord3dvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, float s, float t, float r)
{
GetDelegateFor<glMultiTexCoord3fARB>()(target, s, t, r);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord3fvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, int s, int t, int r)
{
GetDelegateFor<glMultiTexCoord3iARB>()(target, s, t, r);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord3ivARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, short s, short t, short r)
{
GetDelegateFor<glMultiTexCoord3sARB>()(target, s, t, r);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord3ARB(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord3svARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, double s, double t, double r, double q)
{
GetDelegateFor<glMultiTexCoord4dARB>()(target, s, t, r, q);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, double[] v)
{
GetDelegateFor<glMultiTexCoord4dvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, float s, float t, float r, float q)
{
GetDelegateFor<glMultiTexCoord4fARB>()(target, s, t, r, q);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, float[] v)
{
GetDelegateFor<glMultiTexCoord4fvARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, int s, int t, int r, int q)
{
GetDelegateFor<glMultiTexCoord4iARB>()(target, s, t, r, q);
}
public void MultiTexCoord4ARB(uint target, int[] v)
{
GetDelegateFor<glMultiTexCoord4ivARB>()(target, v);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, short s, short t, short r, short q)
{
GetDelegateFor<glMultiTexCoord4sARB>()(target, s, t, r, q);
}
[Obsolete("Deprecated from OpenGL version 3.0")]
public void MultiTexCoord4ARB(uint target, short[] v)
{
GetDelegateFor<glMultiTexCoord4svARB>()(target, v);
}
// Delegates
private delegate void glActiveTextureARB(uint texture);
private delegate void glClientActiveTextureARB(uint texture);
private delegate void glMultiTexCoord1dARB(uint target, double s);
private delegate void glMultiTexCoord1dvARB(uint target, double[] v);
private delegate void glMultiTexCoord1fARB(uint target, float s);
private delegate void glMultiTexCoord1fvARB(uint target, float[] v);
private delegate void glMultiTexCoord1iARB(uint target, int s);
private delegate void glMultiTexCoord1ivARB(uint target, int[] v);
private delegate void glMultiTexCoord1sARB(uint target, short s);
private delegate void glMultiTexCoord1svARB(uint target, short[] v);
private delegate void glMultiTexCoord2dARB(uint target, double s, double t);
private delegate void glMultiTexCoord2dvARB(uint target, double[] v);
private delegate void glMultiTexCoord2fARB(uint target, float s, float t);
private delegate void glMultiTexCoord2fvARB(uint target, float[] v);
private delegate void glMultiTexCoord2iARB(uint target, int s, int t);
private delegate void glMultiTexCoord2ivARB(uint target, int[] v);
private delegate void glMultiTexCoord2sARB(uint target, short s, short t);
private delegate void glMultiTexCoord2svARB(uint target, short[] v);
private delegate void glMultiTexCoord3dARB(uint target, double s, double t, double r);
private delegate void glMultiTexCoord3dvARB(uint target, double[] v);
private delegate void glMultiTexCoord3fARB(uint target, float s, float t, float r);
private delegate void glMultiTexCoord3fvARB(uint target, float[] v);
private delegate void glMultiTexCoord3iARB(uint target, int s, int t, int r);
private delegate void glMultiTexCoord3ivARB(uint target, int[] v);
private delegate void glMultiTexCoord3sARB(uint target, short s, short t, short r);
private delegate void glMultiTexCoord3svARB(uint target, short[] v);
private delegate void glMultiTexCoord4dARB(uint target, double s, double t, double r, double q);
private delegate void glMultiTexCoord4dvARB(uint target, double[] v);
private delegate void glMultiTexCoord4fARB(uint target, float s, float t, float r, float q);
private delegate void glMultiTexCoord4fvARB(uint target, float[] v);
private delegate void glMultiTexCoord4iARB(uint target, int s, int t, int r, int q);
private delegate void glMultiTexCoord4ivARB(uint target, int[] v);
private delegate void glMultiTexCoord4sARB(uint target, short s, short t, short r, short q);
private delegate void glMultiTexCoord4svARB(uint target, short[] v);
// Constants
public const uint GL_TEXTURE0_ARB = 0x84C0;
public const uint GL_TEXTURE1_ARB = 0x84C1;
public const uint GL_TEXTURE2_ARB = 0x84C2;
public const uint GL_TEXTURE3_ARB = 0x84C3;
public const uint GL_TEXTURE4_ARB = 0x84C4;
public const uint GL_TEXTURE5_ARB = 0x84C5;
public const uint GL_TEXTURE6_ARB = 0x84C6;
public const uint GL_TEXTURE7_ARB = 0x84C7;
public const uint GL_TEXTURE8_ARB = 0x84C8;
public const uint GL_TEXTURE9_ARB = 0x84C9;
public const uint GL_TEXTURE10_ARB = 0x84CA;
public const uint GL_TEXTURE11_ARB = 0x84CB;
public const uint GL_TEXTURE12_ARB = 0x84CC;
public const uint GL_TEXTURE13_ARB = 0x84CD;
public const uint GL_TEXTURE14_ARB = 0x84CE;
public const uint GL_TEXTURE15_ARB = 0x84CF;
public const uint GL_TEXTURE16_ARB = 0x84D0;
public const uint GL_TEXTURE17_ARB = 0x84D1;
public const uint GL_TEXTURE18_ARB = 0x84D2;
public const uint GL_TEXTURE19_ARB = 0x84D3;
public const uint GL_TEXTURE20_ARB = 0x84D4;
public const uint GL_TEXTURE21_ARB = 0x84D5;
public const uint GL_TEXTURE22_ARB = 0x84D6;
public const uint GL_TEXTURE23_ARB = 0x84D7;
public const uint GL_TEXTURE24_ARB = 0x84D8;
public const uint GL_TEXTURE25_ARB = 0x84D9;
public const uint GL_TEXTURE26_ARB = 0x84DA;
public const uint GL_TEXTURE27_ARB = 0x84DB;
public const uint GL_TEXTURE28_ARB = 0x84DC;
public const uint GL_TEXTURE29_ARB = 0x84DD;
public const uint GL_TEXTURE30_ARB = 0x84DE;
public const uint GL_TEXTURE31_ARB = 0x84DF;
public const uint GL_ACTIVE_TEXTURE_ARB = 0x84E0;
public const uint GL_CLIENT_ACTIVE_TEXTURE_ARB = 0x84E1;
public const uint GL_MAX_TEXTURE_UNITS_ARB = 0x84E2;
#endregion
#region GL_ARB_texture_compression
// Methods
public void CompressedTexImage3DARB(uint target, int level, uint internalformat, int width, int height, int depth, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage3DARB>()(target, level, internalformat, width, height, depth, border, imageSize, data);
}
public void CompressedTexImage2DARB(uint target, int level, uint internalformat, int width, int height, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage2DARB>()(target, level, internalformat, width, height, border, imageSize, data);
}
public void CompressedTexImage1DARB(uint target, int level, uint internalformat, int width, int border, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexImage1DARB>()(target, level, internalformat, width, border, imageSize, data);
}
public void CompressedTexSubImage3DARB(uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage3DARB>()(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
}
public void CompressedTexSubImage2DARB(uint target, int level, int xoffset, int yoffset, int width, int height, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage2DARB>()(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
public void CompressedTexSubImage1DARB(uint target, int level, int xoffset, int width, uint format, int imageSize, IntPtr data)
{
GetDelegateFor<glCompressedTexSubImage1DARB>()(target, level, xoffset, width, format, imageSize, data);
}
// Delegates
private delegate void glCompressedTexImage3DARB(uint target, int level, uint internalformat, int width, int height, int depth, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexImage2DARB(uint target, int level, uint internalformat, int width, int height, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexImage1DARB(uint target, int level, uint internalformat, int width, int border, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage3DARB(uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage2DARB(uint target, int level, int xoffset, int yoffset, int width, int height, uint format, int imageSize, IntPtr data);
private delegate void glCompressedTexSubImage1DARB(uint target, int level, int xoffset, int width, uint format, int imageSize, IntPtr data);
private delegate void glGetCompressedTexImageARB(uint target, int level, IntPtr img);
// Constants
public const uint GL_COMPRESSED_ALPHA_ARB = 0x84E9;
public const uint GL_COMPRESSED_LUMINANCE_ARB = 0x84EA;
public const uint GL_COMPRESSED_LUMINANCE_ALPHA_ARB = 0x84EB;
public const uint GL_COMPRESSED_INTENSITY_ARB = 0x84EC;
public const uint GL_COMPRESSED_RGB_ARB = 0x84ED;
public const uint GL_COMPRESSED_RGBA_ARB = 0x84EE;
public const uint GL_TEXTURE_COMPRESSION_HINT_ARB = 0x84EF;
public const uint GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB = 0x86A0;
public const uint GL_TEXTURE_COMPRESSED_ARB = 0x86A1;
public const uint GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB = 0x86A2;
public const uint GL_COMPRESSED_TEXTURE_FORMATS_ARB = 0x86A3;
#endregion
#region GL_EXT_texture_cube_map
// Constants
public const uint GL_NORMAL_MAP_EXT = 0x8511;
public const uint GL_REFLECTION_MAP_EXT = 0x8512;
public const uint GL_TEXTURE_CUBE_MAP_EXT = 0x8513;
public const uint GL_TEXTURE_BINDING_CUBE_MAP_EXT = 0x8514;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT = 0x8515;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT = 0x8516;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT = 0x8517;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT = 0x8518;
public const uint GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT = 0x8519;
public const uint GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT = 0x851A;
public const uint GL_PROXY_TEXTURE_CUBE_MAP_EXT = 0x851B;
public const uint GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT = 0x851C;
#endregion
#region GL_ARB_multisample
// Methods
public void SampleCoverageARB(float value, bool invert)
{
GetDelegateFor<glSampleCoverageARB>()(value, invert);
}
// Delegates
private delegate void glSampleCoverageARB(float value, bool invert);
// Constants
public const uint GL_MULTISAMPLE_ARB = 0x809D;
public const uint GL_SAMPLE_ALPHA_TO_COVERAGE_ARB = 0x809E;
public const uint GL_SAMPLE_ALPHA_TO_ONE_ARB = 0x809F;
public const uint GL_SAMPLE_COVERAGE_ARB = 0x80A0;
public const uint GL_SAMPLE_BUFFERS_ARB = 0x80A8;
public const uint GL_SAMPLES_ARB = 0x80A9;
public const uint GL_SAMPLE_COVERAGE_VALUE_ARB = 0x80AA;
public const uint GL_SAMPLE_COVERAGE_INVERT_ARB = 0x80AB;
public const uint GL_MULTISAMPLE_BIT_ARB = 0x20000000;
#endregion
#region GL_ARB_texture_env_add
// Appears to not have any functionality
#endregion
#region GL_ARB_texture_env_combine
// Constants
public const uint GL_COMBINE_ARB = 0x8570;
public const uint GL_COMBINE_RGB_ARB = 0x8571;
public const uint GL_COMBINE_ALPHA_ARB = 0x8572;
public const uint GL_SOURCE0_RGB_ARB = 0x8580;
public const uint GL_SOURCE1_RGB_ARB = 0x8581;
public const uint GL_SOURCE2_RGB_ARB = 0x8582;
public const uint GL_SOURCE0_ALPHA_ARB = 0x8588;
public const uint GL_SOURCE1_ALPHA_ARB = 0x8589;
public const uint GL_SOURCE2_ALPHA_ARB = 0x858A;
public const uint GL_OPERAND0_RGB_ARB = 0x8590;
public const uint GL_OPERAND1_RGB_ARB = 0x8591;
public const uint GL_OPERAND2_RGB_ARB = 0x8592;
public const uint GL_OPERAND0_ALPHA_ARB = 0x8598;
public const uint GL_OPERAND1_ALPHA_ARB = 0x8599;
public const uint GL_OPERAND2_ALPHA_ARB = 0x859A;
public const uint GL_RGB_SCALE_ARB = 0x8573;
public const uint GL_ADD_SIGNED_ARB = 0x8574;
public const uint GL_INTERPOLATE_ARB = 0x8575;
public const uint GL_SUBTRACT_ARB = 0x84E7;
public const uint GL_CONSTANT_ARB = 0x8576;
public const uint GL_PRIMARY_COLOR_ARB = 0x8577;
public const uint GL_PREVIOUS_ARB = 0x8578;
#endregion
#region GL_ARB_texture_env_dot3
// Constants
public const uint GL_DOT3_RGB_ARB = 0x86AE;
public const uint GL_DOT3_RGBA_ARB = 0x86AF;
#endregion
#region GL_ARB_texture_border_clamp
// Constants
public const uint GL_CLAMP_TO_BORDER_ARB = 0x812D;
#endregion
#region GL_ARB_transpose_matrix
// Methods
public void glLoadTransposeMatrixARB(float[] m)
{
GetDelegateFor<glLoadTransposeMatrixfARB>()(m);
}
public void glLoadTransposeMatrixARB(double[] m)
{
GetDelegateFor<glLoadTransposeMatrixdARB>()(m);
}
public void glMultTransposeMatrixARB(float[] m)
{
GetDelegateFor<glMultTransposeMatrixfARB>()(m);
}
public void glMultTransposeMatrixARB(double[] m)
{
GetDelegateFor<glMultTransposeMatrixdARB>()(m);
}
// Delegates
private delegate void glLoadTransposeMatrixfARB(float[] m);
private delegate void glLoadTransposeMatrixdARB(double[] m);
private delegate void glMultTransposeMatrixfARB(float[] m);
private delegate void glMultTransposeMatrixdARB(double[] m);
// Constants
public const uint GL_TRANSPOSE_MODELVIEW_MATRIX_ARB = 0x84E3;
public const uint GL_TRANSPOSE_PROJECTION_MATRIX_ARB = 0x84E4;
public const uint GL_TRANSPOSE_TEXTURE_MATRIX_ARB = 0x84E5;
public const uint GL_TRANSPOSE_COLOR_MATRIX_ARB = 0x84E6;
#endregion
#region GL_SGIS_generate_mipmap
// Constants
public const uint GL_GENERATE_MIPMAP_SGIS = 0x8191;
public const uint GL_GENERATE_MIPMAP_HINT_SGIS = 0x8192;
#endregion
#region GL_NV_blend_square
// Appears to be empty.
#endregion
#region GL_ARB_depth_texture
// Constants
public const uint GL_DEPTH_COMPONENT16_ARB = 0x81A5;
public const uint GL_DEPTH_COMPONENT24_ARB = 0x81A6;
public const uint GL_DEPTH_COMPONENT32_ARB = 0x81A7;
public const uint GL_TEXTURE_DEPTH_SIZE_ARB = 0x884A;
public const uint GL_DEPTH_TEXTURE_MODE_ARB = 0x884B;
#endregion
#region GL_ARB_shadow
// Constants
public const uint GL_TEXTURE_COMPARE_MODE_ARB = 0x884C;
public const uint GL_TEXTURE_COMPARE_FUNC_ARB = 0x884D;
public const uint GL_COMPARE_R_TO_TEXTURE_ARB = 0x884E;
#endregion
#region GL_EXT_fog_coord
// Methods
public void FogCoordEXT(float coord)
{
GetDelegateFor<glFogCoordfEXT>()(coord);
}
public void FogCoordEXT(float[] coord)
{
GetDelegateFor<glFogCoordfvEXT>()(coord);
}
public void FogCoordEXT(double coord)
{
GetDelegateFor<glFogCoorddEXT>()(coord);
}
public void FogCoordEXT(double[] coord)
{
GetDelegateFor<glFogCoorddvEXT>()(coord);
}
public void FogCoordPointerEXT(uint type, int stride, IntPtr pointer)
{
GetDelegateFor<glFogCoordPointerEXT>()(type, stride, pointer);
}
// Delegates
private delegate void glFogCoordfEXT(float coord);
private delegate void glFogCoordfvEXT(float[] coord);
private delegate void glFogCoorddEXT(double coord);
private delegate void glFogCoorddvEXT(double[] coord);
private delegate void glFogCoordPointerEXT(uint type, int stride, IntPtr pointer);
// Constants
public const uint GL_FOG_COORDINATE_SOURCE_EXT = 0x8450;
public const uint GL_FOG_COORDINATE_EXT = 0x8451;
public const uint GL_FRAGMENT_DEPTH_EXT = 0x8452;
public const uint GL_CURRENT_FOG_COORDINATE_EXT = 0x8453;
public const uint GL_FOG_COORDINATE_ARRAY_TYPE_EXT = 0x8454;
public const uint GL_FOG_COORDINATE_ARRAY_STRIDE_EXT = 0x8455;
public const uint GL_FOG_COORDINATE_ARRAY_POINTER_EXT = 0x8456;
public const uint GL_FOG_COORDINATE_ARRAY_EXT = 0x8457;
#endregion
#region GL_EXT_multi_draw_arrays
// Methods
public void MultiDrawArraysEXT(uint mode, int[] first, int[] count, int primcount)
{
GetDelegateFor<glMultiDrawArraysEXT>()(mode, first, count, primcount);
}
public void MultiDrawElementsEXT(uint mode, int[] count, uint type, IntPtr indices, int primcount)
{
GetDelegateFor<glMultiDrawElementsEXT>()(mode, count, type, indices, primcount);
}
// Delegates
private delegate void glMultiDrawArraysEXT(uint mode, int[] first, int[] count, int primcount);
private delegate void glMultiDrawElementsEXT(uint mode, int[] count, uint type, IntPtr indices, int primcount);
#endregion
#region GL_ARB_point_parameters
// Methods
public void glPointParameterARB(uint pname, float parameter)
{
GetDelegateFor<glPointParameterfARB>()(pname, parameter);
}
public void glPointParameterARB(uint pname, float[] parameters)
{
GetDelegateFor<glPointParameterfvARB>()(pname, parameters);
}
// Delegates
private delegate void glPointParameterfARB(uint pname, float param);
private delegate void glPointParameterfvARB(uint pname, float[] parameters);
// Constants
public const uint GL_POINT_SIZE_MIN_ARB = 0x8126;
public const uint GL_POINT_SIZE_MAX_ARB = 0x8127;
public const uint GL_POINT_FADE_THRESHOLD_SIZE_ARB = 0x8128;
public const uint GL_POINT_DISTANCE_ATTENUATION_ARB = 0x8129;
#endregion
#region GL_EXT_secondary_color
// Methods
public void SecondaryColor3EXT(sbyte red, sbyte green, sbyte blue)
{
GetDelegateFor<glSecondaryColor3bEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(sbyte[] v)
{
GetDelegateFor<glSecondaryColor3bvEXT>()(v);
}
public void SecondaryColor3EXT(double red, double green, double blue)
{
GetDelegateFor<glSecondaryColor3dEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(double[] v)
{
GetDelegateFor<glSecondaryColor3dvEXT>()(v);
}
public void SecondaryColor3EXT(float red, float green, float blue)
{
GetDelegateFor<glSecondaryColor3fEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(float[] v)
{
GetDelegateFor<glSecondaryColor3fvEXT>()(v);
}
public void SecondaryColor3EXT(int red, int green, int blue)
{
GetDelegateFor<glSecondaryColor3iEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(int[] v)
{
GetDelegateFor<glSecondaryColor3ivEXT>()(v);
}
public void SecondaryColor3EXT(short red, short green, short blue)
{
GetDelegateFor<glSecondaryColor3sEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(short[] v)
{
GetDelegateFor<glSecondaryColor3svEXT>()(v);
}
public void SecondaryColor3EXT(byte red, byte green, byte blue)
{
GetDelegateFor<glSecondaryColor3ubEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(byte[] v)
{
GetDelegateFor<glSecondaryColor3ubvEXT>()(v);
}
public void SecondaryColor3EXT(uint red, uint green, uint blue)
{
GetDelegateFor<glSecondaryColor3uiEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(uint[] v)
{
GetDelegateFor<glSecondaryColor3uivEXT>()(v);
}
public void SecondaryColor3EXT(ushort red, ushort green, ushort blue)
{
GetDelegateFor<glSecondaryColor3usEXT>()(red, green, blue);
}
public void SecondaryColor3EXT(ushort[] v)
{
GetDelegateFor<glSecondaryColor3usvEXT>()(v);
}
public void SecondaryColorPointerEXT(int size, uint type, int stride, IntPtr pointer)
{
GetDelegateFor<glSecondaryColorPointerEXT>()(size, type, stride, pointer);
}
// Delegates
private delegate void glSecondaryColor3bEXT(sbyte red, sbyte green, sbyte blue);
private delegate void glSecondaryColor3bvEXT(sbyte[] v);
private delegate void glSecondaryColor3dEXT(double red, double green, double blue);
private delegate void glSecondaryColor3dvEXT(double[] v);
private delegate void glSecondaryColor3fEXT(float red, float green, float blue);
private delegate void glSecondaryColor3fvEXT(float[] v);
private delegate void glSecondaryColor3iEXT(int red, int green, int blue);
private delegate void glSecondaryColor3ivEXT(int[] v);
private delegate void glSecondaryColor3sEXT(short red, short green, short blue);
private delegate void glSecondaryColor3svEXT(short[] v);
private delegate void glSecondaryColor3ubEXT(byte red, byte green, byte blue);
private delegate void glSecondaryColor3ubvEXT(byte[] v);
private delegate void glSecondaryColor3uiEXT(uint red, uint green, uint blue);
private delegate void glSecondaryColor3uivEXT(uint[] v);
private delegate void glSecondaryColor3usEXT(ushort red, ushort green, ushort blue);
private delegate void glSecondaryColor3usvEXT(ushort[] v);
private delegate void glSecondaryColorPointerEXT(int size, uint type, int stride, IntPtr pointer);
// Constants
public const uint GL_COLOR_SUM_EXT = 0x8458;
public const uint GL_CURRENT_SECONDARY_COLOR_EXT = 0x8459;
public const uint GL_SECONDARY_COLOR_ARRAY_SIZE_EXT = 0x845A;
public const uint GL_SECONDARY_COLOR_ARRAY_TYPE_EXT = 0x845B;
public const uint GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT = 0x845C;
public const uint GL_SECONDARY_COLOR_ARRAY_POINTER_EXT = 0x845D;
public const uint GL_SECONDARY_COLOR_ARRAY_EXT = 0x845E;
#endregion
#region GL_EXT_blend_func_separate
// Methods
public void BlendFuncSeparateEXT(uint sfactorRGB, uint dfactorRGB, uint sfactorAlpha, uint dfactorAlpha)
{
GetDelegateFor<glBlendFuncSeparateEXT>()(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
}
// Delegates
private delegate void glBlendFuncSeparateEXT(uint sfactorRGB, uint dfactorRGB, uint sfactorAlpha, uint dfactorAlpha);
// Constants
public const uint GL_BLEND_DST_RGB_EXT = 0x80C8;
public const uint GL_BLEND_SRC_RGB_EXT = 0x80C9;
public const uint GL_BLEND_DST_ALPHA_EXT = 0x80CA;
public const uint GL_BLEND_SRC_ALPHA_EXT = 0x80CB;
#endregion
#region GL_EXT_stencil_wrap
// Constants
public const uint GL_INCR_WRAP_EXT = 0x8507;
public const uint GL_DECR_WRAP_EXT = 0x8508;
#endregion
#region GL_ARB_texture_env_crossbar
// No methods or constants.
#endregion
#region GL_EXT_texture_lod_bias
// Constants
public const uint GL_MAX_TEXTURE_LOD_BIAS_EXT = 0x84FD;
public const uint GL_TEXTURE_FILTER_CONTROL_EXT = 0x8500;
public const uint GL_TEXTURE_LOD_BIAS_EXT = 0x8501;
#endregion
#region GL_ARB_texture_mirrored_repeat
// Constants
public const uint GL_MIRRORED_REPEAT_ARB = 0x8370;
#endregion
#region GL_ARB_window_pos
// Methods
public void WindowPos2ARB(double x, double y)
{
GetDelegateFor<glWindowPos2dARB>()(x, y);
}
public void WindowPos2ARB(double[] v)
{
GetDelegateFor<glWindowPos2dvARB>()(v);
}
public void WindowPos2ARB(float x, float y)
{
GetDelegateFor<glWindowPos2fARB>()(x, y);
}
public void WindowPos2ARB(float[] v)
{
GetDelegateFor<glWindowPos2fvARB>()(v);
}
public void WindowPos2ARB(int x, int y)
{
GetDelegateFor<glWindowPos2iARB>()(x, y);
}
public void WindowPos2ARB(int[] v)
{
GetDelegateFor<glWindowPos2ivARB>()(v);
}
public void WindowPos2ARB(short x, short y)
{
GetDelegateFor<glWindowPos2sARB>()(x, y);
}
public void WindowPos2ARB(short[] v)
{
GetDelegateFor<glWindowPos2svARB>()(v);
}
public void WindowPos3ARB(double x, double y, double z)
{
GetDelegateFor<glWindowPos3dARB>()(x, y, z);
}
public void WindowPos3ARB(double[] v)
{
GetDelegateFor<glWindowPos3dvARB>()(v);
}
public void WindowPos3ARB(float x, float y, float z)
{
GetDelegateFor<glWindowPos3fARB>()(x, y, z);
}
public void WindowPos3ARB(float[] v)
{
GetDelegateFor<glWindowPos3fvARB>()(v);
}
public void WindowPos3ARB(int x, int y, int z)
{
GetDelegateFor<glWindowPos3iARB>()(x, y, z);
}
public void WindowPos3ARB(int[] v)
{
GetDelegateFor<glWindowPos3ivARB>()(v);
}
public void WindowPos3ARB(short x, short y, short z)
{
GetDelegateFor<glWindowPos3sARB>()(x, y, z);
}
public void WindowPos3ARB(short[] v)
{
GetDelegateFor<glWindowPos3svARB>()(v);
}
// Delegates
private delegate void glWindowPos2dARB(double x, double y);
private delegate void glWindowPos2dvARB(double[] v);
private delegate void glWindowPos2fARB(float x, float y);
private delegate void glWindowPos2fvARB(float[] v);
private delegate void glWindowPos2iARB(int x, int y);
private delegate void glWindowPos2ivARB(int[] v);
private delegate void glWindowPos2sARB(short x, short y);
private delegate void glWindowPos2svARB(short[] v);
private delegate void glWindowPos3dARB(double x, double y, double z);
private delegate void glWindowPos3dvARB(double[] v);
private delegate void glWindowPos3fARB(float x, float y, float z);
private delegate void glWindowPos3fvARB(float[] v);
private delegate void glWindowPos3iARB(int x, int y, int z);
private delegate void glWindowPos3ivARB(int[] v);
private delegate void glWindowPos3sARB(short x, short y, short z);
private delegate void glWindowPos3svARB(short[] v);
#endregion
#region GL_ARB_vertex_buffer_object
// Methods
public void BindBufferARB(uint target, uint buffer)
{
GetDelegateFor<glBindBufferARB>()(target, buffer);
}
public void DeleteBuffersARB(int n, uint[] buffers)
{
GetDelegateFor<glDeleteBuffersARB>()(n, buffers);
}
public void GenBuffersARB(int n, uint[] buffers)
{
GetDelegateFor<glGenBuffersARB>()(n, buffers);
}
public bool IsBufferARB(uint buffer)
{
return (bool)GetDelegateFor<glIsBufferARB>()(buffer);
}
public void BufferDataARB(uint target, uint size, IntPtr data, uint usage)
{
GetDelegateFor<glBufferDataARB>()(target, size, data, usage);
}
public void BufferSubDataARB(uint target, uint offset, uint size, IntPtr data)
{
GetDelegateFor<glBufferSubDataARB>()(target, offset, size, data);
}
public void GetBufferSubDataARB(uint target, uint offset, uint size, IntPtr data)
{
GetDelegateFor<glGetBufferSubDataARB>()(target, offset, size, data);
}
public IntPtr MapBufferARB(uint target, uint access)
{
return (IntPtr)GetDelegateFor<glMapBufferARB>()(target, access);
}
public bool UnmapBufferARB(uint target)
{
return (bool)GetDelegateFor<glUnmapBufferARB>()(target);
}
public void GetBufferParameterARB(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetBufferParameterivARB>()(target, pname, parameters);
}
public void GetBufferPointerARB(uint target, uint pname, IntPtr parameters)
{
GetDelegateFor<glGetBufferPointervARB>()(target, pname, parameters);
}
// Delegates
private delegate void glBindBufferARB(uint target, uint buffer);
private delegate void glDeleteBuffersARB(int n, uint[] buffers);
private delegate void glGenBuffersARB(int n, uint[] buffers);
private delegate bool glIsBufferARB(uint buffer);
private delegate void glBufferDataARB(uint target, uint size, IntPtr data, uint usage);
private delegate void glBufferSubDataARB(uint target, uint offset, uint size, IntPtr data);
private delegate void glGetBufferSubDataARB(uint target, uint offset, uint size, IntPtr data);
private delegate IntPtr glMapBufferARB(uint target, uint access);
private delegate bool glUnmapBufferARB(uint target);
private delegate void glGetBufferParameterivARB(uint target, uint pname, int[] parameters);
private delegate void glGetBufferPointervARB(uint target, uint pname, IntPtr parameters);
// Constants
public const uint GL_BUFFER_SIZE_ARB = 0x8764;
public const uint GL_BUFFER_USAGE_ARB = 0x8765;
public const uint GL_ARRAY_BUFFER_ARB = 0x8892;
public const uint GL_ELEMENT_ARRAY_BUFFER_ARB = 0x8893;
public const uint GL_ARRAY_BUFFER_BINDING_ARB = 0x8894;
public const uint GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB = 0x8895;
public const uint GL_VERTEX_ARRAY_BUFFER_BINDING_ARB = 0x8896;
public const uint GL_NORMAL_ARRAY_BUFFER_BINDING_ARB = 0x8897;
public const uint GL_COLOR_ARRAY_BUFFER_BINDING_ARB = 0x8898;
public const uint GL_INDEX_ARRAY_BUFFER_BINDING_ARB = 0x8899;
public const uint GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB = 0x889A;
public const uint GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB = 0x889B;
public const uint GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB = 0x889C;
public const uint GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB = 0x889D;
public const uint GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB = 0x889E;
public const uint GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB = 0x889F;
public const uint GL_READ_ONLY_ARB = 0x88B8;
public const uint GL_WRITE_ONLY_ARB = 0x88B9;
public const uint GL_READ_WRITE_ARB = 0x88BA;
public const uint GL_BUFFER_ACCESS_ARB = 0x88BB;
public const uint GL_BUFFER_MAPPED_ARB = 0x88BC;
public const uint GL_BUFFER_MAP_POINTER_ARB = 0x88BD;
public const uint GL_STREAM_DRAW_ARB = 0x88E0;
public const uint GL_STREAM_READ_ARB = 0x88E1;
public const uint GL_STREAM_COPY_ARB = 0x88E2;
public const uint GL_STATIC_DRAW_ARB = 0x88E4;
public const uint GL_STATIC_READ_ARB = 0x88E5;
public const uint GL_STATIC_COPY_ARB = 0x88E6;
public const uint GL_DYNAMIC_DRAW_ARB = 0x88E8;
public const uint GL_DYNAMIC_READ_ARB = 0x88E9;
public const uint GL_DYNAMIC_COPY_ARB = 0x88EA;
#endregion
#region GL_ARB_occlusion_query
// Methods
public void GenQueriesARB(int n, uint[] ids)
{
GetDelegateFor<glGenQueriesARB>()(n, ids);
}
public void DeleteQueriesARB(int n, uint[] ids)
{
GetDelegateFor<glDeleteQueriesARB>()(n, ids);
}
public bool IsQueryARB(uint id)
{
return (bool)GetDelegateFor<glIsQueryARB>()(id);
}
public void BeginQueryARB(uint target, uint id)
{
GetDelegateFor<glBeginQueryARB>()(target, id);
}
public void EndQueryARB(uint target)
{
GetDelegateFor<glEndQueryARB>()(target);
}
public void GetQueryARB(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetQueryivARB>()(target, pname, parameters);
}
public void GetQueryObjectARB(uint id, uint pname, int[] parameters)
{
GetDelegateFor<glGetQueryObjectivARB>()(id, pname, parameters);
}
public void GetQueryObjectARB(uint id, uint pname, uint[] parameters)
{
GetDelegateFor<glGetQueryObjectuivARB>()(id, pname, parameters);
}
// Delegates
private delegate void glGenQueriesARB(int n, uint[] ids);
private delegate void glDeleteQueriesARB(int n, uint[] ids);
private delegate bool glIsQueryARB(uint id);
private delegate void glBeginQueryARB(uint target, uint id);
private delegate void glEndQueryARB(uint target);
private delegate void glGetQueryivARB(uint target, uint pname, int[] parameters);
private delegate void glGetQueryObjectivARB(uint id, uint pname, int[] parameters);
private delegate void glGetQueryObjectuivARB(uint id, uint pname, uint[] parameters);
// Constants
public const uint GL_QUERY_COUNTER_BITS_ARB = 0x8864;
public const uint GL_CURRENT_QUERY_ARB = 0x8865;
public const uint GL_QUERY_RESULT_ARB = 0x8866;
public const uint GL_QUERY_RESULT_AVAILABLE_ARB = 0x8867;
public const uint GL_SAMPLES_PASSED_ARB = 0x8914;
public const uint GL_ANY_SAMPLES_PASSED = 0x8C2F;
#endregion
#region GL_ARB_shader_objects
// Methods
public void DeleteObjectARB(uint obj)
{
GetDelegateFor<glDeleteObjectARB>()(obj);
}
public uint GetHandleARB(uint pname)
{
return (uint)GetDelegateFor<glGetHandleARB>()(pname);
}
public void DetachObjectARB(uint containerObj, uint attachedObj)
{
GetDelegateFor<glDetachObjectARB>()(containerObj, attachedObj);
}
public uint CreateShaderObjectARB(uint shaderType)
{
return (uint)GetDelegateFor<glCreateShaderObjectARB>()(shaderType);
}
public void ShaderSourceARB(uint shaderObj, int count, string[] source, ref int length)
{
GetDelegateFor<glShaderSourceARB>()(shaderObj, count, source, ref length);
}
public void CompileShaderARB(uint shaderObj)
{
GetDelegateFor<glCompileShaderARB>()(shaderObj);
}
public uint CreateProgramObjectARB()
{
return (uint)GetDelegateFor<glCreateProgramObjectARB>()();
}
public void AttachObjectARB(uint containerObj, uint obj)
{
GetDelegateFor<glAttachObjectARB>()(containerObj, obj);
}
public void LinkProgramARB(uint programObj)
{
GetDelegateFor<glLinkProgramARB>()(programObj);
}
public void UseProgramObjectARB(uint programObj)
{
GetDelegateFor<glUseProgramObjectARB>()(programObj);
}
public void ValidateProgramARB(uint programObj)
{
GetDelegateFor<glValidateProgramARB>()(programObj);
}
public void Uniform1ARB(int location, float v0)
{
GetDelegateFor<glUniform1fARB>()(location, v0);
}
public void Uniform2ARB(int location, float v0, float v1)
{
GetDelegateFor<glUniform2fARB>()(location, v0, v1);
}
public void Uniform3ARB(int location, float v0, float v1, float v2)
{
GetDelegateFor<glUniform3fARB>()(location, v0, v1, v2);
}
public void Uniform4ARB(int location, float v0, float v1, float v2, float v3)
{
GetDelegateFor<glUniform4fARB>()(location, v0, v1, v2, v3);
}
public void Uniform1ARB(int location, int v0)
{
GetDelegateFor<glUniform1iARB>()(location, v0);
}
public void Uniform2ARB(int location, int v0, int v1)
{
GetDelegateFor<glUniform2iARB>()(location, v0, v1);
}
public void Uniform3ARB(int location, int v0, int v1, int v2)
{
GetDelegateFor<glUniform3iARB>()(location, v0, v1, v2);
}
public void Uniform4ARB(int location, int v0, int v1, int v2, int v3)
{
GetDelegateFor<glUniform4iARB>()(location, v0, v1, v2, v3);
}
public void Uniform1ARB(int location, int count, float[] value)
{
GetDelegateFor<glUniform1fvARB>()(location, count, value);
}
public void Uniform2ARB(int location, int count, float[] value)
{
GetDelegateFor<glUniform2fvARB>()(location, count, value);
}
public void Uniform3ARB(int location, int count, float[] value)
{
GetDelegateFor<glUniform3fvARB>()(location, count, value);
}
public void Uniform4ARB(int location, int count, float[] value)
{
GetDelegateFor<glUniform4fvARB>()(location, count, value);
}
public void Uniform1ARB(int location, int count, int[] value)
{
GetDelegateFor<glUniform1ivARB>()(location, count, value);
}
public void Uniform2ARB(int location, int count, int[] value)
{
GetDelegateFor<glUniform2ivARB>()(location, count, value);
}
public void Uniform3ARB(int location, int count, int[] value)
{
GetDelegateFor<glUniform3ivARB>()(location, count, value);
}
public void Uniform4ARB(int location, int count, int[] value)
{
GetDelegateFor<glUniform4ivARB>()(location, count, value);
}
public void UniformMatrix2ARB(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix2fvARB>()(location, count, transpose, value);
}
public void UniformMatrix3ARB(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix3fvARB>()(location, count, transpose, value);
}
public void UniformMatrix4ARB(int location, int count, bool transpose, float[] value)
{
GetDelegateFor<glUniformMatrix4fvARB>()(location, count, transpose, value);
}
public void GetObjectParameterARB(uint obj, uint pname, float[] parameters)
{
GetDelegateFor<glGetObjectParameterfvARB>()(obj, pname, parameters);
}
public void GetObjectParameterARB(uint obj, uint pname, int[] parameters)
{
GetDelegateFor<glGetObjectParameterivARB>()(obj, pname, parameters);
}
public void GetInfoLogARB(uint obj, int maxLength, ref int length, string infoLog)
{
GetDelegateFor<glGetInfoLogARB>()(obj, maxLength, ref length, infoLog);
}
public void GetAttachedObjectsARB(uint containerObj, int maxCount, ref int count, ref uint obj)
{
GetDelegateFor<glGetAttachedObjectsARB>()(containerObj, maxCount, ref count, ref obj);
}
public int GetUniformLocationARB(uint programObj, string name)
{
return (int)GetDelegateFor<glGetUniformLocationARB>()(programObj, name);
}
public void GetActiveUniformARB(uint programObj, uint index, int maxLength, ref int length, ref int size, ref uint type, string name)
{
GetDelegateFor<glGetActiveUniformARB>()(programObj, index, maxLength, ref length, ref size, ref type, name);
}
public void GetUniformARB(uint programObj, int location, float[] parameters)
{
GetDelegateFor<glGetUniformfvARB>()(programObj, location, parameters);
}
public void GetUniformARB(uint programObj, int location, int[] parameters)
{
GetDelegateFor<glGetUniformivARB>()(programObj, location, parameters);
}
public void GetShaderSourceARB(uint obj, int maxLength, ref int length, string source)
{
GetDelegateFor<glGetShaderSourceARB>()(obj, maxLength, ref length, source);
}
// Delegates
private delegate void glDeleteObjectARB(uint obj);
private delegate uint glGetHandleARB(uint pname);
private delegate void glDetachObjectARB(uint containerObj, uint attachedObj);
private delegate uint glCreateShaderObjectARB(uint shaderType);
private delegate void glShaderSourceARB(uint shaderObj, int count, string[] source, ref int length);
private delegate void glCompileShaderARB(uint shaderObj);
private delegate uint glCreateProgramObjectARB();
private delegate void glAttachObjectARB(uint containerObj, uint obj);
private delegate void glLinkProgramARB(uint programObj);
private delegate void glUseProgramObjectARB(uint programObj);
private delegate void glValidateProgramARB(uint programObj);
private delegate void glUniform1fARB(int location, float v0);
private delegate void glUniform2fARB(int location, float v0, float v1);
private delegate void glUniform3fARB(int location, float v0, float v1, float v2);
private delegate void glUniform4fARB(int location, float v0, float v1, float v2, float v3);
private delegate void glUniform1iARB(int location, int v0);
private delegate void glUniform2iARB(int location, int v0, int v1);
private delegate void glUniform3iARB(int location, int v0, int v1, int v2);
private delegate void glUniform4iARB(int location, int v0, int v1, int v2, int v3);
private delegate void glUniform1fvARB(int location, int count, float[] value);
private delegate void glUniform2fvARB(int location, int count, float[] value);
private delegate void glUniform3fvARB(int location, int count, float[] value);
private delegate void glUniform4fvARB(int location, int count, float[] value);
private delegate void glUniform1ivARB(int location, int count, int[] value);
private delegate void glUniform2ivARB(int location, int count, int[] value);
private delegate void glUniform3ivARB(int location, int count, int[] value);
private delegate void glUniform4ivARB(int location, int count, int[] value);
private delegate void glUniformMatrix2fvARB(int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix3fvARB(int location, int count, bool transpose, float[] value);
private delegate void glUniformMatrix4fvARB(int location, int count, bool transpose, float[] value);
private delegate void glGetObjectParameterfvARB(uint obj, uint pname, float[] parameters);
private delegate void glGetObjectParameterivARB(uint obj, uint pname, int[] parameters);
private delegate void glGetInfoLogARB(uint obj, int maxLength, ref int length, string infoLog);
private delegate void glGetAttachedObjectsARB(uint containerObj, int maxCount, ref int count, ref uint obj);
private delegate int glGetUniformLocationARB(uint programObj, string name);
private delegate void glGetActiveUniformARB(uint programObj, uint index, int maxLength, ref int length, ref int size, ref uint type, string name);
private delegate void glGetUniformfvARB(uint programObj, int location, float[] parameters);
private delegate void glGetUniformivARB(uint programObj, int location, int[] parameters);
private delegate void glGetShaderSourceARB(uint obj, int maxLength, ref int length, string source);
// Constants
public const uint GL_PROGRAM_OBJECT_ARB = 0x8B40;
public const uint GL_SHADER_OBJECT_ARB = 0x8B48;
public const uint GL_OBJECT_TYPE_ARB = 0x8B4E;
public const uint GL_OBJECT_SUBTYPE_ARB = 0x8B4F;
public const uint GL_FLOAT_VEC2_ARB = 0x8B50;
public const uint GL_FLOAT_VEC3_ARB = 0x8B51;
public const uint GL_FLOAT_VEC4_ARB = 0x8B52;
public const uint GL_INT_VEC2_ARB = 0x8B53;
public const uint GL_INT_VEC3_ARB = 0x8B54;
public const uint GL_INT_VEC4_ARB = 0x8B55;
public const uint GL_BOOL_ARB = 0x8B56;
public const uint GL_BOOL_VEC2_ARB = 0x8B57;
public const uint GL_BOOL_VEC3_ARB = 0x8B58;
public const uint GL_BOOL_VEC4_ARB = 0x8B59;
public const uint GL_FLOAT_MAT2_ARB = 0x8B5A;
public const uint GL_FLOAT_MAT3_ARB = 0x8B5B;
public const uint GL_FLOAT_MAT4_ARB = 0x8B5C;
public const uint GL_SAMPLER_1D_ARB = 0x8B5D;
public const uint GL_SAMPLER_2D_ARB = 0x8B5E;
public const uint GL_SAMPLER_3D_ARB = 0x8B5F;
public const uint GL_SAMPLER_CUBE_ARB = 0x8B60;
public const uint GL_SAMPLER_1D_SHADOW_ARB = 0x8B61;
public const uint GL_SAMPLER_2D_SHADOW_ARB = 0x8B62;
public const uint GL_SAMPLER_2D_RECT_ARB = 0x8B63;
public const uint GL_SAMPLER_2D_RECT_SHADOW_ARB = 0x8B64;
public const uint GL_OBJECT_DELETE_STATUS_ARB = 0x8B80;
public const uint GL_OBJECT_COMPILE_STATUS_ARB = 0x8B81;
public const uint GL_OBJECT_LINK_STATUS_ARB = 0x8B82;
public const uint GL_OBJECT_VALIDATE_STATUS_ARB = 0x8B83;
public const uint GL_OBJECT_INFO_LOG_LENGTH_ARB = 0x8B84;
public const uint GL_OBJECT_ATTACHED_OBJECTS_ARB = 0x8B85;
public const uint GL_OBJECT_ACTIVE_UNIFORMS_ARB = 0x8B86;
public const uint GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB = 0x8B87;
public const uint GL_OBJECT_SHADER_SOURCE_LENGTH_ARB = 0x8B88;
#endregion
#region GL_ARB_vertex_program
// Methods
public void VertexAttrib1ARB(uint index, double x)
{
GetDelegateFor<glVertexAttrib1dARB>()(index, x);
}
public void VertexAttrib1ARB(uint index, double[] v)
{
GetDelegateFor<glVertexAttrib1dvARB>()(index, v);
}
public void VertexAttrib1ARB(uint index, float x)
{
GetDelegateFor<glVertexAttrib1fARB>()(index, x);
}
public void VertexAttrib1ARB(uint index, float[] v)
{
GetDelegateFor<glVertexAttrib1fvARB>()(index, v);
}
public void VertexAttrib1ARB(uint index, short x)
{
GetDelegateFor<glVertexAttrib1sARB>()(index, x);
}
public void VertexAttrib1ARB(uint index, short[] v)
{
GetDelegateFor<glVertexAttrib1svARB>()(index, v);
}
public void VertexAttrib2ARB(uint index, double x, double y)
{
GetDelegateFor<glVertexAttrib2dARB>()(index, x, y);
}
public void VertexAttrib2ARB(uint index, double[] v)
{
GetDelegateFor<glVertexAttrib2dvARB>()(index, v);
}
public void VertexAttrib2ARB(uint index, float x, float y)
{
GetDelegateFor<glVertexAttrib2fARB>()(index, x, y);
}
public void VertexAttrib2ARB(uint index, float[] v)
{
GetDelegateFor<glVertexAttrib2fvARB>()(index, v);
}
public void VertexAttrib2ARB(uint index, short x, short y)
{
GetDelegateFor<glVertexAttrib2sARB>()(index, x, y);
}
public void VertexAttrib2ARB(uint index, short[] v)
{
GetDelegateFor<glVertexAttrib2svARB>()(index, v);
}
public void VertexAttrib3ARB(uint index, double x, double y, double z)
{
GetDelegateFor<glVertexAttrib3dARB>()(index, x, y, z);
}
public void VertexAttrib3ARB(uint index, double[] v)
{
GetDelegateFor<glVertexAttrib3dvARB>()(index, v);
}
public void VertexAttrib3ARB(uint index, float x, float y, float z)
{
GetDelegateFor<glVertexAttrib3fARB>()(index, x, y, z);
}
public void VertexAttrib3ARB(uint index, float[] v)
{
GetDelegateFor<glVertexAttrib3fvARB>()(index, v);
}
public void VertexAttrib3ARB(uint index, short x, short y, short z)
{
GetDelegateFor<glVertexAttrib3sARB>()(index, x, y, z);
}
public void VertexAttrib3ARB(uint index, short[] v)
{
GetDelegateFor<glVertexAttrib3svARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, sbyte[] v)
{
GetDelegateFor<glVertexAttrib4NbvARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, int[] v)
{
GetDelegateFor<glVertexAttrib4NivARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, short[] v)
{
GetDelegateFor<glVertexAttrib4NsvARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, byte x, byte y, byte z, byte w)
{
GetDelegateFor<glVertexAttrib4NubARB>()(index, x, y, z, w);
}
public void VertexAttrib4NARB(uint index, byte[] v)
{
GetDelegateFor<glVertexAttrib4NubvARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, uint[] v)
{
GetDelegateFor<glVertexAttrib4NuivARB>()(index, v);
}
public void VertexAttrib4NARB(uint index, ushort[] v)
{
GetDelegateFor<glVertexAttrib4NusvARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, sbyte[] v)
{
GetDelegateFor<glVertexAttrib4bvARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, double x, double y, double z, double w)
{
GetDelegateFor<glVertexAttrib4dARB>()(index, x, y, z, w);
}
public void VertexAttrib4ARB(uint index, double[] v)
{
GetDelegateFor<glVertexAttrib4dvARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, float x, float y, float z, float w)
{
GetDelegateFor<glVertexAttrib4fARB>()(index, x, y, z, w);
}
public void VertexAttrib4ARB(uint index, float[] v)
{
GetDelegateFor<glVertexAttrib4fvARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, int[] v)
{
GetDelegateFor<glVertexAttrib4ivARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, short x, short y, short z, short w)
{
GetDelegateFor<glVertexAttrib4sARB>()(index, x, y, z, w);
}
public void VertexAttrib4ARB(uint index, short[] v)
{
GetDelegateFor<glVertexAttrib4svARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, byte[] v)
{
GetDelegateFor<glVertexAttrib4ubvARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, uint[] v)
{
GetDelegateFor<glVertexAttrib4uivARB>()(index, v);
}
public void VertexAttrib4ARB(uint index, ushort[] v)
{
GetDelegateFor<glVertexAttrib4usvARB>()(index, v);
}
public void VertexAttribPointerARB(uint index, int size, uint type, bool normalized, int stride, IntPtr pointer)
{
GetDelegateFor<glVertexAttribPointerARB>()(index, size, type, normalized, stride, pointer);
}
public void EnableVertexAttribArrayARB(uint index)
{
GetDelegateFor<glEnableVertexAttribArrayARB>()(index);
}
public void DisableVertexAttribArrayARB(uint index)
{
GetDelegateFor<glDisableVertexAttribArrayARB>()(index);
}
public void ProgramStringARB(uint target, uint format, int len, IntPtr str)
{
GetDelegateFor<glProgramStringARB>()(target, format, len, str);
}
public void BindProgramARB(uint target, uint program)
{
GetDelegateFor<glBindProgramARB>()(target, program);
}
public void DeleteProgramsARB(int n, uint[] programs)
{
GetDelegateFor<glDeleteProgramsARB>()(n, programs);
}
public void GenProgramsARB(int n, uint[] programs)
{
GetDelegateFor<glGenProgramsARB>()(n, programs);
}
public void ProgramEnvParameter4ARB(uint target, uint index, double x, double y, double z, double w)
{
GetDelegateFor<glProgramEnvParameter4dARB>()(target, index, x, y, z, w);
}
public void ProgramEnvParameter4ARB(uint target, uint index, double[] parameters)
{
GetDelegateFor<glProgramEnvParameter4dvARB>()(target, index, parameters);
}
public void ProgramEnvParameter4ARB(uint target, uint index, float x, float y, float z, float w)
{
GetDelegateFor<glProgramEnvParameter4fARB>()(target, index, x, y, z, w);
}
public void ProgramEnvParameter4ARB(uint target, uint index, float[] parameters)
{
GetDelegateFor<glProgramEnvParameter4fvARB>()(target, index, parameters);
}
public void ProgramLocalParameter4ARB(uint target, uint index, double x, double y, double z, double w)
{
GetDelegateFor<glProgramLocalParameter4dARB>()(target, index, x, y, z, w);
}
public void ProgramLocalParameter4ARB(uint target, uint index, double[] parameters)
{
GetDelegateFor<glProgramLocalParameter4dvARB>()(target, index, parameters);
}
public void ProgramLocalParameter4ARB(uint target, uint index, float x, float y, float z, float w)
{
GetDelegateFor<glProgramLocalParameter4fARB>()(target, index, x, y, z, w);
}
public void ProgramLocalParameter4ARB(uint target, uint index, float[] parameters)
{
GetDelegateFor<glProgramLocalParameter4fvARB>()(target, index, parameters);
}
public void GetProgramEnvParameterdARB(uint target, uint index, double[] parameters)
{
GetDelegateFor<glGetProgramEnvParameterdvARB>()(target, index, parameters);
}
public void GetProgramEnvParameterfARB(uint target, uint index, float[] parameters)
{
GetDelegateFor<glGetProgramEnvParameterfvARB>()(target, index, parameters);
}
public void GetProgramLocalParameterARB(uint target, uint index, double[] parameters)
{
GetDelegateFor<glGetProgramLocalParameterdvARB>()(target, index, parameters);
}
public void GetProgramLocalParameterARB(uint target, uint index, float[] parameters)
{
GetDelegateFor<glGetProgramLocalParameterfvARB>()(target, index, parameters);
}
public void GetProgramARB(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetProgramivARB>()(target, pname, parameters);
}
public void GetProgramStringARB(uint target, uint pname, IntPtr str)
{
GetDelegateFor<glGetProgramStringARB>()(target, pname, str);
}
public void GetVertexAttribARB(uint index, uint pname, double[] parameters)
{
GetDelegateFor<glGetVertexAttribdvARB>()(index, pname, parameters);
}
public void GetVertexAttribARB(uint index, uint pname, float[] parameters)
{
GetDelegateFor<glGetVertexAttribfvARB>()(index, pname, parameters);
}
public void GetVertexAttribARB(uint index, uint pname, int[] parameters)
{
GetDelegateFor<glGetVertexAttribivARB>()(index, pname, parameters);
}
public void GetVertexAttribPointerARB(uint index, uint pname, IntPtr pointer)
{
GetDelegateFor<glGetVertexAttribPointervARB>()(index, pname, pointer);
}
// Delegates
private delegate void glVertexAttrib1dARB(uint index, double x);
private delegate void glVertexAttrib1dvARB(uint index, double[] v);
private delegate void glVertexAttrib1fARB(uint index, float x);
private delegate void glVertexAttrib1fvARB(uint index, float[] v);
private delegate void glVertexAttrib1sARB(uint index, short x);
private delegate void glVertexAttrib1svARB(uint index, short[] v);
private delegate void glVertexAttrib2dARB(uint index, double x, double y);
private delegate void glVertexAttrib2dvARB(uint index, double[] v);
private delegate void glVertexAttrib2fARB(uint index, float x, float y);
private delegate void glVertexAttrib2fvARB(uint index, float[] v);
private delegate void glVertexAttrib2sARB(uint index, short x, short y);
private delegate void glVertexAttrib2svARB(uint index, short[] v);
private delegate void glVertexAttrib3dARB(uint index, double x, double y, double z);
private delegate void glVertexAttrib3dvARB(uint index, double[] v);
private delegate void glVertexAttrib3fARB(uint index, float x, float y, float z);
private delegate void glVertexAttrib3fvARB(uint index, float[] v);
private delegate void glVertexAttrib3sARB(uint index, short x, short y, short z);
private delegate void glVertexAttrib3svARB(uint index, short[] v);
private delegate void glVertexAttrib4NbvARB(uint index, sbyte[] v);
private delegate void glVertexAttrib4NivARB(uint index, int[] v);
private delegate void glVertexAttrib4NsvARB(uint index, short[] v);
private delegate void glVertexAttrib4NubARB(uint index, byte x, byte y, byte z, byte w);
private delegate void glVertexAttrib4NubvARB(uint index, byte[] v);
private delegate void glVertexAttrib4NuivARB(uint index, uint[] v);
private delegate void glVertexAttrib4NusvARB(uint index, ushort[] v);
private delegate void glVertexAttrib4bvARB(uint index, sbyte[] v);
private delegate void glVertexAttrib4dARB(uint index, double x, double y, double z, double w);
private delegate void glVertexAttrib4dvARB(uint index, double[] v);
private delegate void glVertexAttrib4fARB(uint index, float x, float y, float z, float w);
private delegate void glVertexAttrib4fvARB(uint index, float[] v);
private delegate void glVertexAttrib4ivARB(uint index, int[] v);
private delegate void glVertexAttrib4sARB(uint index, short x, short y, short z, short w);
private delegate void glVertexAttrib4svARB(uint index, short[] v);
private delegate void glVertexAttrib4ubvARB(uint index, byte[] v);
private delegate void glVertexAttrib4uivARB(uint index, uint[] v);
private delegate void glVertexAttrib4usvARB(uint index, ushort[] v);
private delegate void glVertexAttribPointerARB(uint index, int size, uint type, bool normalized, int stride, IntPtr pointer);
private delegate void glEnableVertexAttribArrayARB(uint index);
private delegate void glDisableVertexAttribArrayARB(uint index);
private delegate void glProgramStringARB(uint target, uint format, int len, IntPtr str);
private delegate void glBindProgramARB(uint target, uint program);
private delegate void glDeleteProgramsARB(int n, uint[] programs);
private delegate void glGenProgramsARB(int n, uint[] programs);
private delegate void glProgramEnvParameter4dARB(uint target, uint index, double x, double y, double z, double w);
private delegate void glProgramEnvParameter4dvARB(uint target, uint index, double[] parameters);
private delegate void glProgramEnvParameter4fARB(uint target, uint index, float x, float y, float z, float w);
private delegate void glProgramEnvParameter4fvARB(uint target, uint index, float[] parameters);
private delegate void glProgramLocalParameter4dARB(uint target, uint index, double x, double y, double z, double w);
private delegate void glProgramLocalParameter4dvARB(uint target, uint index, double[] parameters);
private delegate void glProgramLocalParameter4fARB(uint target, uint index, float x, float y, float z, float w);
private delegate void glProgramLocalParameter4fvARB(uint target, uint index, float[] parameters);
private delegate void glGetProgramEnvParameterdvARB(uint target, uint index, double[] parameters);
private delegate void glGetProgramEnvParameterfvARB(uint target, uint index, float[] parameters);
private delegate void glGetProgramLocalParameterdvARB(uint target, uint index, double[] parameters);
private delegate void glGetProgramLocalParameterfvARB(uint target, uint index, float[] parameters);
private delegate void glGetProgramivARB(uint target, uint pname, int[] parameters);
private delegate void glGetProgramStringARB(uint target, uint pname, IntPtr str);
private delegate void glGetVertexAttribdvARB(uint index, uint pname, double[] parameters);
private delegate void glGetVertexAttribfvARB(uint index, uint pname, float[] parameters);
private delegate void glGetVertexAttribivARB(uint index, uint pname, int[] parameters);
private delegate void glGetVertexAttribPointervARB(uint index, uint pname, IntPtr pointer);
// Constants
public const uint GL_COLOR_SUM_ARB = 0x8458;
public const uint GL_VERTEX_PROGRAM_ARB = 0x8620;
public const uint GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB = 0x8622;
public const uint GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB = 0x8623;
public const uint GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB = 0x8624;
public const uint GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB = 0x8625;
public const uint GL_CURRENT_VERTEX_ATTRIB_ARB = 0x8626;
public const uint GL_PROGRAM_LENGTH_ARB = 0x8627;
public const uint GL_PROGRAM_STRING_ARB = 0x8628;
public const uint GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB = 0x862E;
public const uint GL_MAX_PROGRAM_MATRICES_ARB = 0x862F;
public const uint GL_CURRENT_MATRIX_STACK_DEPTH_ARB = 0x8640;
public const uint GL_CURRENT_MATRIX_ARB = 0x8641;
public const uint GL_VERTEX_PROGRAM_POINT_SIZE_ARB = 0x8642;
public const uint GL_VERTEX_PROGRAM_TWO_SIDE_ARB = 0x8643;
public const uint GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB = 0x8645;
public const uint GL_PROGRAM_ERROR_POSITION_ARB = 0x864B;
public const uint GL_PROGRAM_BINDING_ARB = 0x8677;
public const uint GL_MAX_VERTEX_ATTRIBS_ARB = 0x8869;
public const uint GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB = 0x886A;
public const uint GL_PROGRAM_ERROR_STRING_ARB = 0x8874;
public const uint GL_PROGRAM_FORMAT_ASCII_ARB = 0x8875;
public const uint GL_PROGRAM_FORMAT_ARB = 0x8876;
public const uint GL_PROGRAM_INSTRUCTIONS_ARB = 0x88A0;
public const uint GL_MAX_PROGRAM_INSTRUCTIONS_ARB = 0x88A1;
public const uint GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB = 0x88A2;
public const uint GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB = 0x88A3;
public const uint GL_PROGRAM_TEMPORARIES_ARB = 0x88A4;
public const uint GL_MAX_PROGRAM_TEMPORARIES_ARB = 0x88A5;
public const uint GL_PROGRAM_NATIVE_TEMPORARIES_ARB = 0x88A6;
public const uint GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB = 0x88A7;
public const uint GL_PROGRAM_PARAMETERS_ARB = 0x88A8;
public const uint GL_MAX_PROGRAM_PARAMETERS_ARB = 0x88A9;
public const uint GL_PROGRAM_NATIVE_PARAMETERS_ARB = 0x88AA;
public const uint GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB = 0x88AB;
public const uint GL_PROGRAM_ATTRIBS_ARB = 0x88AC;
public const uint GL_MAX_PROGRAM_ATTRIBS_ARB = 0x88AD;
public const uint GL_PROGRAM_NATIVE_ATTRIBS_ARB = 0x88AE;
public const uint GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB = 0x88AF;
public const uint GL_PROGRAM_ADDRESS_REGISTERS_ARB = 0x88B0;
public const uint GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB = 0x88B1;
public const uint GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB = 0x88B2;
public const uint GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB = 0x88B3;
public const uint GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB = 0x88B4;
public const uint GL_MAX_PROGRAM_ENV_PARAMETERS_ARB = 0x88B5;
public const uint GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB = 0x88B6;
public const uint GL_TRANSPOSE_CURRENT_MATRIX_ARB = 0x88B7;
public const uint GL_MATRIX0_ARB = 0x88C0;
public const uint GL_MATRIX1_ARB = 0x88C1;
public const uint GL_MATRIX2_ARB = 0x88C2;
public const uint GL_MATRIX3_ARB = 0x88C3;
public const uint GL_MATRIX4_ARB = 0x88C4;
public const uint GL_MATRIX5_ARB = 0x88C5;
public const uint GL_MATRIX6_ARB = 0x88C6;
public const uint GL_MATRIX7_ARB = 0x88C7;
public const uint GL_MATRIX8_ARB = 0x88C8;
public const uint GL_MATRIX9_ARB = 0x88C9;
public const uint GL_MATRIX10_ARB = 0x88CA;
public const uint GL_MATRIX11_ARB = 0x88CB;
public const uint GL_MATRIX12_ARB = 0x88CC;
public const uint GL_MATRIX13_ARB = 0x88CD;
public const uint GL_MATRIX14_ARB = 0x88CE;
public const uint GL_MATRIX15_ARB = 0x88CF;
public const uint GL_MATRIX16_ARB = 0x88D0;
public const uint GL_MATRIX17_ARB = 0x88D1;
public const uint GL_MATRIX18_ARB = 0x88D2;
public const uint GL_MATRIX19_ARB = 0x88D3;
public const uint GL_MATRIX20_ARB = 0x88D4;
public const uint GL_MATRIX21_ARB = 0x88D5;
public const uint GL_MATRIX22_ARB = 0x88D6;
public const uint GL_MATRIX23_ARB = 0x88D7;
public const uint GL_MATRIX24_ARB = 0x88D8;
public const uint GL_MATRIX25_ARB = 0x88D9;
public const uint GL_MATRIX26_ARB = 0x88DA;
public const uint GL_MATRIX27_ARB = 0x88DB;
public const uint GL_MATRIX28_ARB = 0x88DC;
public const uint GL_MATRIX29_ARB = 0x88DD;
public const uint GL_MATRIX30_ARB = 0x88DE;
public const uint GL_MATRIX31_ARB = 0x88DF;
#endregion
#region GL_ARB_vertex_shader
// Methods
public void BindAttribLocationARB(uint programObj, uint index, string name)
{
GetDelegateFor<glBindAttribLocationARB>()(programObj, index, name);
}
public void GetActiveAttribARB(uint programObj, uint index, int maxLength, int[] length, int[] size, uint[] type, string name)
{
GetDelegateFor<glGetActiveAttribARB>()(programObj, index, maxLength, length, size, type, name);
}
public uint GetAttribLocationARB(uint programObj, string name)
{
return (uint)GetDelegateFor<glGetAttribLocationARB>()(programObj, name);
}
// Delegates
private delegate void glBindAttribLocationARB(uint programObj, uint index, string name);
private delegate void glGetActiveAttribARB(uint programObj, uint index, int maxLength, int[] length, int[] size, uint[] type, string name);
private delegate uint glGetAttribLocationARB(uint programObj, string name);
// Constants
public const uint GL_VERTEX_SHADER_ARB = 0x8B31;
public const uint GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB = 0x8B4A;
public const uint GL_MAX_VARYING_FLOATS_ARB = 0x8B4B;
public const uint GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB = 0x8B4C;
public const uint GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB = 0x8B4D;
public const uint GL_OBJECT_ACTIVE_ATTRIBUTES_ARB = 0x8B89;
public const uint GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB = 0x8B8A;
#endregion
#region GL_ARB_fragment_shader
public const uint GL_FRAGMENT_SHADER_ARB = 0x8B30;
public const uint GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB = 0x8B49;
public const uint GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB = 0x8B8B;
#endregion
#region GL_ARB_draw_buffers
// Methods
public void DrawBuffersARB(int n, uint[] bufs)
{
GetDelegateFor<glDrawBuffersARB>()(n, bufs);
}
// Delegates
private delegate void glDrawBuffersARB(int n, uint[] bufs);
// Constants
public const uint GL_MAX_DRAW_BUFFERS_ARB = 0x8824;
public const uint GL_DRAW_BUFFER0_ARB = 0x8825;
public const uint GL_DRAW_BUFFER1_ARB = 0x8826;
public const uint GL_DRAW_BUFFER2_ARB = 0x8827;
public const uint GL_DRAW_BUFFER3_ARB = 0x8828;
public const uint GL_DRAW_BUFFER4_ARB = 0x8829;
public const uint GL_DRAW_BUFFER5_ARB = 0x882A;
public const uint GL_DRAW_BUFFER6_ARB = 0x882B;
public const uint GL_DRAW_BUFFER7_ARB = 0x882C;
public const uint GL_DRAW_BUFFER8_ARB = 0x882D;
public const uint GL_DRAW_BUFFER9_ARB = 0x882E;
public const uint GL_DRAW_BUFFER10_ARB = 0x882F;
public const uint GL_DRAW_BUFFER11_ARB = 0x8830;
public const uint GL_DRAW_BUFFER12_ARB = 0x8831;
public const uint GL_DRAW_BUFFER13_ARB = 0x8832;
public const uint GL_DRAW_BUFFER14_ARB = 0x8833;
public const uint GL_DRAW_BUFFER15_ARB = 0x8834;
#endregion
#region GL_ARB_texture_non_power_of_two
// No methods or constants
#endregion
#region GL_ARB_texture_rectangle
// Constants
public const uint GL_TEXTURE_RECTANGLE_ARB = 0x84F5;
public const uint GL_TEXTURE_BINDING_RECTANGLE_ARB = 0x84F6;
public const uint GL_PROXY_TEXTURE_RECTANGLE_ARB = 0x84F7;
public const uint GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB = 0x84F8;
#endregion
#region GL_ARB_point_sprite
// Constants
public const uint GL_POINT_SPRITE_ARB = 0x8861;
public const uint GL_COORD_REPLACE_ARB = 0x8862;
#endregion
#region GL_ARB_texture_float
// Constants
public const uint GL_TEXTURE_RED_TYPE_ARB = 0x8C10;
public const uint GL_TEXTURE_GREEN_TYPE_ARB = 0x8C11;
public const uint GL_TEXTURE_BLUE_TYPE_ARB = 0x8C12;
public const uint GL_TEXTURE_ALPHA_TYPE_ARB = 0x8C13;
public const uint GL_TEXTURE_LUMINANCE_TYPE_ARB = 0x8C14;
public const uint GL_TEXTURE_INTENSITY_TYPE_ARB = 0x8C15;
public const uint GL_TEXTURE_DEPTH_TYPE_ARB = 0x8C16;
public const uint GL_UNSIGNED_NORMALIZED_ARB = 0x8C17;
public const uint GL_RGBA32F_ARB = 0x8814;
public const uint GL_RGB32F_ARB = 0x8815;
public const uint GL_ALPHA32F_ARB = 0x8816;
public const uint GL_INTENSITY32F_ARB = 0x8817;
public const uint GL_LUMINANCE32F_ARB = 0x8818;
public const uint GL_LUMINANCE_ALPHA32F_ARB = 0x8819;
public const uint GL_RGBA16F_ARB = 0x881A;
public const uint GL_RGB16F_ARB = 0x881B;
public const uint GL_ALPHA16F_ARB = 0x881C;
public const uint GL_INTENSITY16F_ARB = 0x881D;
public const uint GL_LUMINANCE16F_ARB = 0x881E;
public const uint GL_LUMINANCE_ALPHA16F_ARB = 0x881F;
#endregion
#region GL_EXT_blend_equation_separate
// Methods
public void BlendEquationSeparateEXT(uint modeRGB, uint modeAlpha)
{
// GetDelegateFor<glBlendEquationEXT>()(modeRGB, modeAlpha);
GetDelegateFor<glBlendEquationEXT>()(modeRGB);
}
// Delegates
private delegate void glBlendEquationSeparateEXT(uint modeRGB, uint modeAlpha);
// Constants
public const uint GL_BLEND_EQUATION_RGB_EXT = 0x8009;
public const uint GL_BLEND_EQUATION_ALPHA_EXT = 0x883D;
#endregion
#region GL_EXT_stencil_two_side
// Methods
public void ActiveStencilFaceEXT(uint face)
{
GetDelegateFor<glActiveStencilFaceEXT>()(face);
}
// Delegates
private delegate void glActiveStencilFaceEXT(uint face);
// Constants
public const uint GL_STENCIL_TEST_TWO_SIDE_EXT = 0x8009;
public const uint GL_ACTIVE_STENCIL_FACE_EXT = 0x883D;
#endregion
#region GL_ARB_pixel_buffer_object
public const uint GL_PIXEL_PACK_BUFFER_ARB = 0x88EB;
public const uint GL_PIXEL_UNPACK_BUFFER_ARB = 0x88EC;
public const uint GL_PIXEL_PACK_BUFFER_BINDING_ARB = 0x88ED;
public const uint GL_PIXEL_UNPACK_BUFFER_BINDING_ARB = 0x88EF;
#endregion
#region GL_EXT_texture_sRGB
public const uint GL_SRGB_EXT = 0x8C40;
public const uint GL_SRGB8_EXT = 0x8C41;
public const uint GL_SRGB_ALPHA_EXT = 0x8C42;
public const uint GL_SRGB8_ALPHA8_EXT = 0x8C43;
public const uint GL_SLUMINANCE_ALPHA_EXT = 0x8C44;
public const uint GL_SLUMINANCE8_ALPHA8_EXT = 0x8C45;
public const uint GL_SLUMINANCE_EXT = 0x8C46;
public const uint GL_SLUMINANCE8_EXT = 0x8C47;
public const uint GL_COMPRESSED_SRGB_EXT = 0x8C48;
public const uint GL_COMPRESSED_SRGB_ALPHA_EXT = 0x8C49;
public const uint GL_COMPRESSED_SLUMINANCE_EXT = 0x8C4A;
public const uint GL_COMPRESSED_SLUMINANCE_ALPHA_EXT = 0x8C4B;
public const uint GL_COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C;
public const uint GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D;
public const uint GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E;
public const uint GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F;
#endregion
#region GL_EXT_framebuffer_object
// Methods
public bool IsRenderbufferEXT(uint renderbuffer)
{
return (bool)GetDelegateFor<glIsRenderbufferEXT>()(renderbuffer);
}
public void BindRenderbufferEXT(uint target, uint renderbuffer)
{
GetDelegateFor<glBindRenderbufferEXT>()(target, renderbuffer);
}
public void DeleteRenderbuffersEXT(uint n, uint[] renderbuffers)
{
GetDelegateFor<glDeleteRenderbuffersEXT>()(n, renderbuffers);
}
public void GenRenderbuffersEXT(uint n, uint[] renderbuffers)
{
GetDelegateFor<glGenRenderbuffersEXT>()(n, renderbuffers);
}
public void RenderbufferStorageEXT(uint target, uint internalformat, int width, int height)
{
GetDelegateFor<glRenderbufferStorageEXT>()(target, internalformat, width, height);
}
public void GetRenderbufferParameterivEXT(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetRenderbufferParameterivEXT>()(target, pname, parameters);
}
public bool IsFramebufferEXT(uint framebuffer)
{
return (bool)GetDelegateFor<glIsFramebufferEXT>()(framebuffer);
}
public void BindFramebufferEXT(uint target, uint framebuffer)
{
GetDelegateFor<glBindFramebufferEXT>()(target, framebuffer);
}
public void DeleteFramebuffersEXT(uint n, uint[] framebuffers)
{
GetDelegateFor<glDeleteFramebuffersEXT>()(n, framebuffers);
}
public void GenFramebuffersEXT(uint n, uint[] framebuffers)
{
GetDelegateFor<glGenFramebuffersEXT>()(n, framebuffers);
}
public uint CheckFramebufferStatusEXT(uint target)
{
return (uint)GetDelegateFor<glCheckFramebufferStatusEXT>()(target);
}
public void FramebufferTexture1DEXT(uint target, uint attachment, uint textarget, uint texture, int level)
{
GetDelegateFor<glFramebufferTexture1DEXT>()(target, attachment, textarget, texture, level);
}
public void FramebufferTexture2DEXT(uint target, uint attachment, uint textarget, uint texture, int level)
{
GetDelegateFor<glFramebufferTexture2DEXT>()(target, attachment, textarget, texture, level);
}
public void FramebufferTexture3DEXT(uint target, uint attachment, uint textarget, uint texture, int level, int zoffset)
{
GetDelegateFor<glFramebufferTexture3DEXT>()(target, attachment, textarget, texture, level, zoffset);
}
public void FramebufferRenderbufferEXT(uint target, uint attachment, uint renderbuffertarget, uint renderbuffer)
{
GetDelegateFor<glFramebufferRenderbufferEXT>()(target, attachment, renderbuffertarget, renderbuffer);
}
public void GetFramebufferAttachmentParameterivEXT(uint target, uint attachment, uint pname, int[] parameters)
{
GetDelegateFor<glGetFramebufferAttachmentParameterivEXT>()(target, attachment, pname, parameters);
}
public void GenerateMipmapEXT(uint target)
{
GetDelegateFor<glGenerateMipmapEXT>()(target);
}
// Delegates
private delegate bool glIsRenderbufferEXT(uint renderbuffer);
private delegate void glBindRenderbufferEXT(uint target, uint renderbuffer);
private delegate void glDeleteRenderbuffersEXT(uint n, uint[] renderbuffers);
private delegate void glGenRenderbuffersEXT(uint n, uint[] renderbuffers);
private delegate void glRenderbufferStorageEXT(uint target, uint internalformat, int width, int height);
private delegate void glGetRenderbufferParameterivEXT(uint target, uint pname, int[] parameters);
private delegate bool glIsFramebufferEXT(uint framebuffer);
private delegate void glBindFramebufferEXT(uint target, uint framebuffer);
private delegate void glDeleteFramebuffersEXT(uint n, uint[] framebuffers);
private delegate void glGenFramebuffersEXT(uint n, uint[] framebuffers);
private delegate uint glCheckFramebufferStatusEXT(uint target);
private delegate void glFramebufferTexture1DEXT(uint target, uint attachment, uint textarget, uint texture, int level);
private delegate void glFramebufferTexture2DEXT(uint target, uint attachment, uint textarget, uint texture, int level);
private delegate void glFramebufferTexture3DEXT(uint target, uint attachment, uint textarget, uint texture, int level, int zoffset);
private delegate void glFramebufferRenderbufferEXT(uint target, uint attachment, uint renderbuffertarget, uint renderbuffer);
private delegate void glGetFramebufferAttachmentParameterivEXT(uint target, uint attachment, uint pname, int[] parameters);
private delegate void glGenerateMipmapEXT(uint target);
// Constants
public const uint GL_INVALID_FRAMEBUFFER_OPERATION_EXT = 0x0506;
public const uint GL_MAX_RENDERBUFFER_SIZE_EXT = 0x84E8;
public const uint GL_FRAMEBUFFER_BINDING_EXT = 0x8CA6;
public const uint GL_RENDERBUFFER_BINDING_EXT = 0x8CA7;
public const uint GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT = 0x8CD0;
public const uint GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT = 0x8CD1;
public const uint GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT = 0x8CD2;
public const uint GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT = 0x8CD3;
public const uint GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT = 0x8CD4;
public const uint GL_FRAMEBUFFER_COMPLETE_EXT = 0x8CD5;
public const uint GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT = 0x8CD6;
public const uint GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT = 0x8CD7;
public const uint GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT = 0x8CD9;
public const uint GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT = 0x8CDA;
public const uint GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT = 0x8CDB;
public const uint GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT = 0x8CDC;
public const uint GL_FRAMEBUFFER_UNSUPPORTED_EXT = 0x8CDD;
public const uint GL_MAX_COLOR_ATTACHMENTS_EXT = 0x8CDF;
public const uint GL_COLOR_ATTACHMENT0_EXT = 0x8CE0;
public const uint GL_COLOR_ATTACHMENT1_EXT = 0x8CE1;
public const uint GL_COLOR_ATTACHMENT2_EXT = 0x8CE2;
public const uint GL_COLOR_ATTACHMENT3_EXT = 0x8CE3;
public const uint GL_COLOR_ATTACHMENT4_EXT = 0x8CE4;
public const uint GL_COLOR_ATTACHMENT5_EXT = 0x8CE5;
public const uint GL_COLOR_ATTACHMENT6_EXT = 0x8CE6;
public const uint GL_COLOR_ATTACHMENT7_EXT = 0x8CE7;
public const uint GL_COLOR_ATTACHMENT8_EXT = 0x8CE8;
public const uint GL_COLOR_ATTACHMENT9_EXT = 0x8CE9;
public const uint GL_COLOR_ATTACHMENT10_EXT = 0x8CEA;
public const uint GL_COLOR_ATTACHMENT11_EXT = 0x8CEB;
public const uint GL_COLOR_ATTACHMENT12_EXT = 0x8CEC;
public const uint GL_COLOR_ATTACHMENT13_EXT = 0x8CED;
public const uint GL_COLOR_ATTACHMENT14_EXT = 0x8CEE;
public const uint GL_COLOR_ATTACHMENT15_EXT = 0x8CEF;
public const uint GL_DEPTH_ATTACHMENT_EXT = 0x8D00;
public const uint GL_STENCIL_ATTACHMENT_EXT = 0x8D20;
public const uint GL_FRAMEBUFFER_EXT = 0x8D40;
public const uint GL_RENDERBUFFER_EXT = 0x8D41;
public const uint GL_RENDERBUFFER_WIDTH_EXT = 0x8D42;
public const uint GL_RENDERBUFFER_HEIGHT_EXT = 0x8D43;
public const uint GL_RENDERBUFFER_INTERNAL_FORMAT_EXT = 0x8D44;
public const uint GL_STENCIL_INDEX1_EXT = 0x8D46;
public const uint GL_STENCIL_INDEX4_EXT = 0x8D47;
public const uint GL_STENCIL_INDEX8_EXT = 0x8D48;
public const uint GL_STENCIL_INDEX16_EXT = 0x8D49;
public const uint GL_RENDERBUFFER_RED_SIZE_EXT = 0x8D50;
public const uint GL_RENDERBUFFER_GREEN_SIZE_EXT = 0x8D51;
public const uint GL_RENDERBUFFER_BLUE_SIZE_EXT = 0x8D52;
public const uint GL_RENDERBUFFER_ALPHA_SIZE_EXT = 0x8D53;
public const uint GL_RENDERBUFFER_DEPTH_SIZE_EXT = 0x8D54;
public const uint GL_RENDERBUFFER_STENCIL_SIZE_EXT = 0x8D55;
#endregion
#region GL_EXT_framebuffer_multisample
// Methods
public void RenderbufferStorageMultisampleEXT(uint target, int samples, uint internalformat, int width, int height)
{
GetDelegateFor<glRenderbufferStorageMultisampleEXT>()(target, samples, internalformat, width, height);
}
// Delegates
private delegate void glRenderbufferStorageMultisampleEXT(uint target, int samples, uint internalformat, int width, int height);
// Constants
public const uint GL_RENDERBUFFER_SAMPLES_EXT = 0x8CAB;
public const uint GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8D56;
public const uint GL_MAX_SAMPLES_EXT = 0x8D57;
#endregion
#region GL_EXT_draw_instanced
// Methods
public void DrawArraysInstancedEXT(uint mode, int start, int count, int primcount)
{
GetDelegateFor<glDrawArraysInstancedEXT>()(mode, start, count, primcount);
}
public void DrawElementsInstancedEXT(uint mode, int count, uint type, IntPtr indices, int primcount)
{
GetDelegateFor<glDrawElementsInstancedEXT>()(mode, count, type, indices, primcount);
}
// Delegates
private delegate void glDrawArraysInstancedEXT(uint mode, int start, int count, int primcount);
private delegate void glDrawElementsInstancedEXT(uint mode, int count, uint type, IntPtr indices, int primcount);
#endregion
#region GL_ARB_vertex_array_object
// Methods
public void BindVertexArray(uint array)
{
GetDelegateFor<glBindVertexArray>()(array);
}
public void DeleteVertexArrays(int n, uint[] arrays)
{
GetDelegateFor<glDeleteVertexArrays>()(n, arrays);
}
public void GenVertexArrays(int n, uint[] arrays)
{
GetDelegateFor<glGenVertexArrays>()(n, arrays);
}
public bool IsVertexArray(uint array)
{
return (bool)GetDelegateFor<glIsVertexArray>()(array);
}
// Delegates
private delegate void glBindVertexArray(uint array);
private delegate void glDeleteVertexArrays(int n, uint[] arrays);
private delegate void glGenVertexArrays(int n, uint[] arrays);
private delegate bool glIsVertexArray(uint array);
// Constants
public const uint GL_VERTEX_ARRAY_BINDING = 0x85B5;
#endregion
#region GL_EXT_framebuffer_sRGB
// Constants
public const uint GL_FRAMEBUFFER_SRGB_EXT = 0x8DB9;
public const uint GL_FRAMEBUFFER_SRGB_CAPABLE_EXT = 0x8DBA;
#endregion
#region GGL_EXT_transform_feedback
// Methods
public void BeginTransformFeedbackEXT(uint primitiveMode)
{
GetDelegateFor<glBeginTransformFeedbackEXT>()(primitiveMode);
}
public void EndTransformFeedbackEXT()
{
GetDelegateFor<glEndTransformFeedbackEXT>()();
}
public void BindBufferRangeEXT(uint target, uint index, uint buffer, int offset, int size)
{
GetDelegateFor<glBindBufferRangeEXT>()(target, index, buffer, offset, size);
}
public void BindBufferOffsetEXT(uint target, uint index, uint buffer, int offset)
{
GetDelegateFor<glBindBufferOffsetEXT>()(target, index, buffer, offset);
}
public void BindBufferBaseEXT(uint target, uint index, uint buffer)
{
GetDelegateFor<glBindBufferBaseEXT>()(target, index, buffer);
}
public void TransformFeedbackVaryingsEXT(uint program, int count, string[] varyings, uint bufferMode)
{
GetDelegateFor<glTransformFeedbackVaryingsEXT>()(program, count, varyings, bufferMode);
}
public void GetTransformFeedbackVaryingEXT(uint program, uint index, int bufSize, int[] length, int[] size, uint[] type, string name)
{
GetDelegateFor<glGetTransformFeedbackVaryingEXT>()(program, index, bufSize, length, size, type, name);
}
// Delegates
private delegate void glBeginTransformFeedbackEXT(uint primitiveMode);
private delegate void glEndTransformFeedbackEXT ();
private delegate void glBindBufferRangeEXT (uint target, uint index, uint buffer, int offset, int size);
private delegate void glBindBufferOffsetEXT (uint target, uint index, uint buffer, int offset);
private delegate void glBindBufferBaseEXT (uint target, uint index, uint buffer);
private delegate void glTransformFeedbackVaryingsEXT (uint program, int count, string[] varyings, uint bufferMode);
private delegate void glGetTransformFeedbackVaryingEXT (uint program, uint index, int bufSize, int[] length, int[] size, uint[] type, string name);
// Constants
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_EXT = 0x8C8E;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT = 0x8C84;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT = 0x8C85;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT = 0x8C8F;
public const uint GL_INTERLEAVED_ATTRIBS_EXT = 0x8C8C;
public const uint GL_SEPARATE_ATTRIBS_EXT = 0x8C8D;
public const uint GL_PRIMITIVES_GENERATED_EXT = 0x8C87;
public const uint GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT = 0x8C88;
public const uint GL_RASTERIZER_DISCARD_EXT = 0x8C89;
public const uint GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT = 0x8C8A;
public const uint GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT = 0x8C8B;
public const uint GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT = 0x8C80;
public const uint GL_TRANSFORM_FEEDBACK_VARYINGS_EXT = 0x8C83;
public const uint GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT = 0x8C7F;
public const uint GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT = 0x8C76;
#endregion
#region WGL_ARB_extensions_string
/// <summary>
/// Gets the ARB extensions string.
/// </summary>
public string GetExtensionsStringARB()
{
return (string)GetDelegateFor<wglGetExtensionsStringARB>()(RenderContextProvider.DeviceContextHandle);
}
// Delegates
private delegate string wglGetExtensionsStringARB(IntPtr hdc);
#endregion
#region WGL_ARB_create_context
// Methods
/// <summary>
/// Creates a render context with the specified attributes.
/// </summary>
/// <param name="hShareContext">
/// If is not null, then all shareable data (excluding
/// OpenGL texture objects named 0) will be shared by <hshareContext>,
/// all other contexts <hshareContext> already shares with, and the
/// newly created context. An arbitrary number of contexts can share
/// data in this fashion.</param>
/// <param name="attribList">
/// specifies a list of attributes for the context. The
/// list consists of a sequence of <name,value> pairs terminated by the
/// value 0. If an attribute is not specified in <attribList>, then the
/// default value specified below is used instead. If an attribute is
/// specified more than once, then the last value specified is used.
/// </param>
public IntPtr CreateContextAttribsARB(IntPtr hShareContext, int[] attribList)
{
return (IntPtr)GetDelegateFor<wglCreateContextAttribsARB>()(RenderContextProvider.DeviceContextHandle, hShareContext, attribList);
}
// Delegates
private delegate IntPtr wglCreateContextAttribsARB(IntPtr hDC, IntPtr hShareContext, int[] attribList);
// Constants
public const int WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
public const int WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
public const int WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093;
public const int WGL_CONTEXT_FLAGS_ARB = 0x2094;
public const int WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
public const int WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001;
public const int WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
public const int WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
public const int WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
public const int ERROR_INVALID_VERSION_ARB = 0x2095;
public const int ERROR_INVALID_PROFILE_ARB = 0x2096;
#endregion
#region GL_ARB_explicit_uniform_location
// Constants
/// <summary>
/// The number of available pre-assigned uniform locations to that can default be
/// allocated in the default uniform block.
/// </summary>
public const int GL_MAX_UNIFORM_LOCATIONS = 0x826E;
#endregion
#region GL_ARB_clear_buffer_object
/// <summary>
/// Fill a buffer object's data store with a fixed value
/// </summary>
/// <param name="target">Specifies the target buffer object. The symbolic constant must be GL_ARRAY_BUFFER, GL_ATOMIC_COUNTER_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_DRAW_INDIRECT_BUFFER, GL_DISPATCH_INDIRECT_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_QUERY_BUFFER, GL_SHADER_STORAGE_BUFFER, GL_TEXTURE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER.</param>
/// <param name="internalformat">The sized internal format with which the data will be stored in the buffer object.</param>
/// <param name="format">Specifies the format of the pixel data. For transfers of depth, stencil, or depth/stencil data, you must use GL_DEPTH_COMPONENT, GL_STENCIL_INDEX, or GL_DEPTH_STENCIL, where appropriate. For transfers of normalized integer or floating-point color image data, you must use one of the following: GL_RED, GL_GREEN, GL_BLUE, GL_RG, GL_RGB, GL_BGR, GL_RGBA, and GL_BGRA. For transfers of non-normalized integer data, you must use one of the following: GL_RED_INTEGER, GL_GREEN_INTEGER, GL_BLUE_INTEGER, GL_RG_INTEGER, GL_RGB_INTEGER, GL_BGR_INTEGER, GL_RGBA_INTEGER, and GL_BGRA_INTEGER.</param>
/// <param name="type">Specifies the data type of the pixel data. The following symbolic values are accepted: GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, GL_INT, GL_FLOAT, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, and GL_UNSIGNED_INT_2_10_10_10_REV.</param>
/// <param name="data">Specifies a pointer to a single pixel of data to upload. This parameter may not be NULL.</param>
public void ClearBufferData(uint target, uint internalformat, uint format, uint type, IntPtr data)
{
GetDelegateFor<glClearBufferData>()(target, internalformat, format, type, data);
}
/// <summary>
/// Fill all or part of buffer object's data store with a fixed value
/// </summary>
/// <param name="target">Specifies the target buffer object. The symbolic constant must be GL_ARRAY_BUFFER, GL_ATOMIC_COUNTER_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_DRAW_INDIRECT_BUFFER, GL_DISPATCH_INDIRECT_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_QUERY_BUFFER, GL_SHADER_STORAGE_BUFFER, GL_TEXTURE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER.</param>
/// <param name="internalformat">The sized internal format with which the data will be stored in the buffer object.</param>
/// <param name="offset">The offset, in basic machine units into the buffer object's data store at which to start filling.</param>
/// <param name="size">The size, in basic machine units of the range of the data store to fill.</param>
/// <param name="format">Specifies the format of the pixel data. For transfers of depth, stencil, or depth/stencil data, you must use GL_DEPTH_COMPONENT, GL_STENCIL_INDEX, or GL_DEPTH_STENCIL, where appropriate. For transfers of normalized integer or floating-point color image data, you must use one of the following: GL_RED, GL_GREEN, GL_BLUE, GL_RG, GL_RGB, GL_BGR, GL_RGBA, and GL_BGRA. For transfers of non-normalized integer data, you must use one of the following: GL_RED_INTEGER, GL_GREEN_INTEGER, GL_BLUE_INTEGER, GL_RG_INTEGER, GL_RGB_INTEGER, GL_BGR_INTEGER, GL_RGBA_INTEGER, and GL_BGRA_INTEGER.</param>
/// <param name="type">Specifies the data type of the pixel data. The following symbolic values are accepted: GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, GL_INT, GL_FLOAT, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, and GL_UNSIGNED_INT_2_10_10_10_REV.</param>
/// <param name="data">Specifies a pointer to a single pixel of data to upload. This parameter may not be NULL.</param>
public void ClearBufferSubData(uint target, uint internalformat, IntPtr offset, uint size, uint format, uint type, IntPtr data)
{
GetDelegateFor<glClearBufferSubData>()(target, internalformat, offset, size, format, type, data);
}
public void ClearNamedBufferDataEXT(uint buffer, uint internalformat, uint format, uint type, IntPtr data)
{
GetDelegateFor<glClearNamedBufferDataEXT>()(buffer, internalformat, format, type, data);
}
public void ClearNamedBufferSubDataEXT(uint buffer, uint internalformat, IntPtr offset, uint size, uint format, uint type, IntPtr data)
{
GetDelegateFor<glClearNamedBufferSubDataEXT>()(buffer, internalformat, offset, size, format, type, data);
}
// Delegates
private delegate void glClearBufferData(uint target, uint internalformat, uint format, uint type, IntPtr data);
private delegate void glClearBufferSubData(uint target, uint internalformat, IntPtr offset, uint size, uint format, uint type, IntPtr data);
private delegate void glClearNamedBufferDataEXT(uint buffer, uint internalformat, uint format, uint type, IntPtr data);
private delegate void glClearNamedBufferSubDataEXT(uint buffer, uint internalformat, IntPtr offset, uint size, uint format, uint type, IntPtr data);
#endregion
#region GL_ARB_compute_shader
/// <summary>
/// Launch one or more compute work groups
/// </summary>
/// <param name="num_groups_x">The number of work groups to be launched in the X dimension.</param>
/// <param name="num_groups_y">The number of work groups to be launched in the Y dimension.</param>
/// <param name="num_groups_z">The number of work groups to be launched in the Z dimension.</param>
public void DispatchCompute(uint num_groups_x, uint num_groups_y, uint num_groups_z)
{
GetDelegateFor<glDispatchCompute>()(num_groups_x, num_groups_y, num_groups_z);
}
/// <summary>
/// Launch one or more compute work groups using parameters stored in a buffer
/// </summary>
/// <param name="indirect">The offset into the buffer object currently bound to the GL_DISPATCH_INDIRECT_BUFFER buffer target at which the dispatch parameters are stored.</param>
public void DispatchComputeIndirect(IntPtr indirect)
{
GetDelegateFor<glDispatchComputeIndirect>()(indirect);
}
// Delegates
private delegate void glDispatchCompute(uint num_groups_x, uint num_groups_y, uint num_groups_z);
private delegate void glDispatchComputeIndirect(IntPtr indirect);
// Constants
public const uint GL_COMPUTE_SHADER = 0x91B9;
public const uint GL_MAX_COMPUTE_UNIFORM_BLOCKS = 0x91BB;
public const uint GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS = 0x91BC;
public const uint GL_MAX_COMPUTE_IMAGE_UNIFORMS = 0x91BD;
public const uint GL_MAX_COMPUTE_SHARED_MEMORY_SIZE = 0x8262;
public const uint GL_MAX_COMPUTE_UNIFORM_COMPONENTS = 0x8263;
public const uint GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS = 0x8264;
public const uint GL_MAX_COMPUTE_ATOMIC_COUNTERS = 0x8265;
public const uint GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS = 0x8266;
public const uint GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 0x90EB;
public const uint GL_MAX_COMPUTE_WORK_GROUP_COUNT = 0x91BE;
public const uint GL_MAX_COMPUTE_WORK_GROUP_SIZE = 0x91BF;
public const uint GL_COMPUTE_WORK_GROUP_SIZE = 0x8267;
public const uint GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER = 0x90EC;
public const uint GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER = 0x90ED;
public const uint GL_DISPATCH_INDIRECT_BUFFER = 0x90EE;
public const uint GL_DISPATCH_INDIRECT_BUFFER_BINDING = 0x90EF;
public const uint GL_COMPUTE_SHADER_BIT = 0x00000020;
#endregion
#region GL_ARB_copy_image
/// <summary>
/// Perform a raw data copy between two images
/// </summary>
/// <param name="srcName">The name of a texture or renderbuffer object from which to copy.</param>
/// <param name="srcTarget">The target representing the namespace of the source name srcName.</param>
/// <param name="srcLevel">The mipmap level to read from the source.</param>
/// <param name="srcX">The X coordinate of the left edge of the souce region to copy.</param>
/// <param name="srcY">The Y coordinate of the top edge of the souce region to copy.</param>
/// <param name="srcZ">The Z coordinate of the near edge of the souce region to copy.</param>
/// <param name="dstName">The name of a texture or renderbuffer object to which to copy.</param>
/// <param name="dstTarget">The target representing the namespace of the destination name dstName.</param>
/// <param name="dstLevel">The desination mipmap level.</param>
/// <param name="dstX">The X coordinate of the left edge of the destination region.</param>
/// <param name="dstY">The Y coordinate of the top edge of the destination region.</param>
/// <param name="dstZ">The Z coordinate of the near edge of the destination region.</param>
/// <param name="srcWidth">The width of the region to be copied.</param>
/// <param name="srcHeight">The height of the region to be copied.</param>
/// <param name="srcDepth">The depth of the region to be copied.</param>
public void CopyImageSubData(uint srcName, uint srcTarget, int srcLevel, int srcX, int srcY, int srcZ, uint dstName,
uint dstTarget, int dstLevel, int dstX, int dstY, int dstZ, uint srcWidth, uint srcHeight, uint srcDepth)
{
GetDelegateFor<glCopyImageSubData>()(srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstName,
dstTarget, dstLevel, dstX, dstY, dstZ, srcWidth, srcHeight, srcDepth);
}
// Delegates
private delegate void glCopyImageSubData(uint srcName, uint srcTarget, int srcLevel, int srcX, int srcY, int srcZ, uint dstName,
uint dstTarget, int dstLevel, int dstX, int dstY, int dstZ, uint srcWidth, uint srcHeight, uint srcDepth);
#endregion
#region GL_ARB_ES3_compatibility
public const uint GL_COMPRESSED_RGB8_ETC2 = 0x9274;
public const uint GL_COMPRESSED_SRGB8_ETC2 = 0x9275;
public const uint GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276;
public const uint GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277;
public const uint GL_COMPRESSED_RGBA8_ETC2_EAC = 0x9278;
public const uint GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279;
public const uint GL_COMPRESSED_R11_EAC = 0x9270;
public const uint GL_COMPRESSED_SIGNED_R11_EAC = 0x9271;
public const uint GL_COMPRESSED_RG11_EAC = 0x9272;
public const uint GL_COMPRESSED_SIGNED_RG11_EAC = 0x9273;
public const uint GL_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69;
public const uint GL_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A;
public const uint GL_MAX_ELEMENT_INDEX = 0x8D6B;
public const uint GL_TEXTURE_IMMUTABLE_LEVELS = 0x82DF;
#endregion
#region GL_ARB_framebuffer_no_attachments
// Methods
/// <summary>
/// Set a named parameter of a framebuffer.
/// </summary>
/// <param name="target">The target of the operation, which must be GL_READ_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER or GL_FRAMEBUFFER.</param>
/// <param name="pname">A token indicating the parameter to be modified.</param>
/// <param name="param">The new value for the parameter named pname.</param>
public void FramebufferParameter(uint target, uint pname, int param)
{
GetDelegateFor<glFramebufferParameteri>()(target, pname, param);
}
/// <summary>
/// Retrieve a named parameter from a framebuffer
/// </summary>
/// <param name="target">The target of the operation, which must be GL_READ_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER or GL_FRAMEBUFFER.</param>
/// <param name="pname">A token indicating the parameter to be retrieved.</param>
/// <param name="parameters">The address of a variable to receive the value of the parameter named pname.</param>
public void GetFramebufferParameter(uint target, uint pname, int[] parameters)
{
GetDelegateFor<glGetFramebufferParameteriv>()(target, pname, parameters);
}
public void NamedFramebufferParameterEXT(uint framebuffer, uint pname, int param)
{
GetDelegateFor<glNamedFramebufferParameteriEXT>()(framebuffer, pname, param);
}
public void GetNamedFramebufferParameterEXT(uint framebuffer, uint pname, int[] parameters)
{
GetDelegateFor<glGetNamedFramebufferParameterivEXT>()(framebuffer, pname, parameters);
}
// Delegates
private delegate void glFramebufferParameteri(uint target, uint pname, int param);
private delegate void glGetFramebufferParameteriv(uint target, uint pname, int[] parameters);
private delegate void glNamedFramebufferParameteriEXT(uint framebuffer, uint pname, int param);
private delegate void glGetNamedFramebufferParameterivEXT(uint framebuffer, uint pname, int[] parameters);
#endregion
#region GL_ARB_internalformat_query2
/// <summary>
/// Retrieve information about implementation-dependent support for internal formats
/// </summary>
/// <param name="target">Indicates the usage of the internal format. target must be GL_TEXTURE_1D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BUFFER, GL_RENDERBUFFER, GL_TEXTURE_2D_MULTISAMPLE or GL_TEXTURE_2D_MULTISAMPLE_ARRAY.</param>
/// <param name="internalformat">Specifies the internal format about which to retrieve information.</param>
/// <param name="pname">Specifies the type of information to query.</param>
/// <param name="bufSize">Specifies the maximum number of basic machine units that may be written to params by the function.</param>
/// <param name="parameters">Specifies the address of a variable into which to write the retrieved information.</param>
public void GetInternalformat(uint target, uint internalformat, uint pname, uint bufSize, int[] parameters)
{
GetDelegateFor<glGetInternalformativ>()(target, internalformat, pname, bufSize, parameters);
}
/// <summary>
/// Retrieve information about implementation-dependent support for internal formats
/// </summary>
/// <param name="target">Indicates the usage of the internal format. target must be GL_TEXTURE_1D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BUFFER, GL_RENDERBUFFER, GL_TEXTURE_2D_MULTISAMPLE or GL_TEXTURE_2D_MULTISAMPLE_ARRAY.</param>
/// <param name="internalformat">Specifies the internal format about which to retrieve information.</param>
/// <param name="pname">Specifies the type of information to query.</param>
/// <param name="bufSize">Specifies the maximum number of basic machine units that may be written to params by the function.</param>
/// <param name="parameters">Specifies the address of a variable into which to write the retrieved information.</param>
public void GetInternalformat(uint target, uint internalformat, uint pname, uint bufSize, Int64[] parameters)
{
GetDelegateFor<glGetInternalformati64v>()(target, internalformat, pname, bufSize, parameters);
}
// Delegates
private delegate void glGetInternalformativ(uint target, uint internalformat, uint pname, uint bufSize, int[] parameters);
private delegate void glGetInternalformati64v(uint target, uint internalformat, uint pname, uint bufSize, Int64[] parameters);
// Constants
public const uint GL_RENDERBUFFER = 0x8D41;
public const uint GL_TEXTURE_2D_MULTISAMPLE = 0x9100;
public const uint GL_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102;
public const uint GL_NUM_SAMPLE_COUNTS = 0x9380;
public const uint GL_INTERNALFORMAT_SUPPORTED = 0x826F;
public const uint GL_INTERNALFORMAT_PREFERRED = 0x8270;
public const uint GL_INTERNALFORMAT_RED_SIZE = 0x8271;
public const uint GL_INTERNALFORMAT_GREEN_SIZE = 0x8272;
public const uint GL_INTERNALFORMAT_BLUE_SIZE = 0x8273;
public const uint GL_INTERNALFORMAT_ALPHA_SIZE = 0x8274;
public const uint GL_INTERNALFORMAT_DEPTH_SIZE = 0x8275;
public const uint GL_INTERNALFORMAT_STENCIL_SIZE = 0x8276;
public const uint GL_INTERNALFORMAT_SHARED_SIZE = 0x8277;
public const uint GL_INTERNALFORMAT_RED_TYPE = 0x8278;
public const uint GL_INTERNALFORMAT_GREEN_TYPE = 0x8279;
public const uint GL_INTERNALFORMAT_BLUE_TYPE = 0x827A;
public const uint GL_INTERNALFORMAT_ALPHA_TYPE = 0x827B;
public const uint GL_INTERNALFORMAT_DEPTH_TYPE = 0x827C;
public const uint GL_INTERNALFORMAT_STENCIL_TYPE = 0x827D;
public const uint GL_MAX_WIDTH = 0x827E;
public const uint GL_MAX_HEIGHT = 0x827F;
public const uint GL_MAX_DEPTH = 0x8280;
public const uint GL_MAX_LAYERS = 0x8281;
public const uint GL_MAX_COMBINED_DIMENSIONS = 0x8282;
public const uint GL_COLOR_COMPONENTS = 0x8283;
public const uint GL_DEPTH_COMPONENTS = 0x8284;
public const uint GL_STENCIL_COMPONENTS = 0x8285;
public const uint GL_COLOR_RENDERABLE = 0x8286;
public const uint GL_DEPTH_RENDERABLE = 0x8287;
public const uint GL_STENCIL_RENDERABLE = 0x8288;
public const uint GL_FRAMEBUFFER_RENDERABLE = 0x8289;
public const uint GL_FRAMEBUFFER_RENDERABLE_LAYERED = 0x828A;
public const uint GL_FRAMEBUFFER_BLEND = 0x828B;
public const uint GL_READ_PIXELS = 0x828C;
public const uint GL_READ_PIXELS_FORMAT = 0x828D;
public const uint GL_READ_PIXELS_TYPE = 0x828E;
public const uint GL_TEXTURE_IMAGE_FORMAT = 0x828F;
public const uint GL_TEXTURE_IMAGE_TYPE = 0x8290;
public const uint GL_GET_TEXTURE_IMAGE_FORMAT = 0x8291;
public const uint GL_GET_TEXTURE_IMAGE_TYPE = 0x8292;
public const uint GL_MIPMAP = 0x8293;
public const uint GL_MANUAL_GENERATE_MIPMAP = 0x8294;
public const uint GL_AUTO_GENERATE_MIPMAP = 0x8295;
public const uint GL_COLOR_ENCODING = 0x8296;
public const uint GL_SRGB_READ = 0x8297;
public const uint GL_SRGB_WRITE = 0x8298;
public const uint GL_SRGB_DECODE_ARB = 0x8299;
public const uint GL_FILTER = 0x829A;
public const uint GL_VERTEX_TEXTURE = 0x829B;
public const uint GL_TESS_CONTROL_TEXTURE = 0x829C;
public const uint GL_TESS_EVALUATION_TEXTURE = 0x829D;
public const uint GL_GEOMETRY_TEXTURE = 0x829E;
public const uint GL_FRAGMENT_TEXTURE = 0x829F;
public const uint GL_COMPUTE_TEXTURE = 0x82A0;
public const uint GL_TEXTURE_SHADOW = 0x82A1;
public const uint GL_TEXTURE_GATHER = 0x82A2;
public const uint GL_TEXTURE_GATHER_SHADOW = 0x82A3;
public const uint GL_SHADER_IMAGE_LOAD = 0x82A4;
public const uint GL_SHADER_IMAGE_STORE = 0x82A5;
public const uint GL_SHADER_IMAGE_ATOMIC = 0x82A6;
public const uint GL_IMAGE_TEXEL_SIZE = 0x82A7;
public const uint GL_IMAGE_COMPATIBILITY_CLASS = 0x82A8;
public const uint GL_IMAGE_PIXEL_FORMAT = 0x82A9;
public const uint GL_IMAGE_PIXEL_TYPE = 0x82AA;
public const uint GL_IMAGE_FORMAT_COMPATIBILITY_TYPE = 0x90C7;
public const uint GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST = 0x82AC;
public const uint GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST = 0x82AD;
public const uint GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE = 0x82AE;
public const uint GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE = 0x82AF;
public const uint GL_TEXTURE_COMPRESSED_BLOCK_WIDTH = 0x82B1;
public const uint GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT = 0x82B2;
public const uint GL_TEXTURE_COMPRESSED_BLOCK_SIZE = 0x82B3;
public const uint GL_CLEAR_BUFFER = 0x82B4;
public const uint GL_TEXTURE_VIEW = 0x82B5;
public const uint GL_VIEW_COMPATIBILITY_CLASS = 0x82B6;
public const uint GL_FULL_SUPPORT = 0x82B7;
public const uint GL_CAVEAT_SUPPORT = 0x82B8;
public const uint GL_IMAGE_CLASS_4_X_32 = 0x82B9;
public const uint GL_IMAGE_CLASS_2_X_32 = 0x82BA;
public const uint GL_IMAGE_CLASS_1_X_32 = 0x82BB;
public const uint GL_IMAGE_CLASS_4_X_16 = 0x82BC;
public const uint GL_IMAGE_CLASS_2_X_16 = 0x82BD;
public const uint GL_IMAGE_CLASS_1_X_16 = 0x82BE;
public const uint GL_IMAGE_CLASS_4_X_8 = 0x82BF;
public const uint GL_IMAGE_CLASS_2_X_8 = 0x82C0;
public const uint GL_IMAGE_CLASS_1_X_8 = 0x82C1;
public const uint GL_IMAGE_CLASS_11_11_10 = 0x82C2;
public const uint GL_IMAGE_CLASS_10_10_10_2 = 0x82C3;
public const uint GL_VIEW_CLASS_128_BITS = 0x82C4;
public const uint GL_VIEW_CLASS_96_BITS = 0x82C5;
public const uint GL_VIEW_CLASS_64_BITS = 0x82C6;
public const uint GL_VIEW_CLASS_48_BITS = 0x82C7;
public const uint GL_VIEW_CLASS_32_BITS = 0x82C8;
public const uint GL_VIEW_CLASS_24_BITS = 0x82C9;
public const uint GL_VIEW_CLASS_16_BITS = 0x82CA;
public const uint GL_VIEW_CLASS_8_BITS = 0x82CB;
public const uint GL_VIEW_CLASS_S3TC_DXT1_RGB = 0x82CC;
public const uint GL_VIEW_CLASS_S3TC_DXT1_RGBA = 0x82CD;
public const uint GL_VIEW_CLASS_S3TC_DXT3_RGBA = 0x82CE;
public const uint GL_VIEW_CLASS_S3TC_DXT5_RGBA = 0x82CF;
public const uint GL_VIEW_CLASS_RGTC1_RED = 0x82D0;
public const uint GL_VIEW_CLASS_RGTC2_RG = 0x82D1;
public const uint GL_VIEW_CLASS_BPTC_UNORM = 0x82D2;
public const uint GL_VIEW_CLASS_BPTC_FLOAT = 0x82D3;
#endregion
#region GL_ARB_invalidate_subdata
/// <summary>
/// Invalidate a region of a texture image
/// </summary>
/// <param name="texture">The name of a texture object a subregion of which to invalidate.</param>
/// <param name="level">The level of detail of the texture object within which the region resides.</param>
/// <param name="xoffset">The X offset of the region to be invalidated.</param>
/// <param name="yoffset">The Y offset of the region to be invalidated.</param>
/// <param name="zoffset">The Z offset of the region to be invalidated.</param>
/// <param name="width">The width of the region to be invalidated.</param>
/// <param name="height">The height of the region to be invalidated.</param>
/// <param name="depth">The depth of the region to be invalidated.</param>
public void InvalidateTexSubImage(uint texture, int level, int xoffset, int yoffset, int zoffset,
uint width, uint height, uint depth)
{
GetDelegateFor<glInvalidateTexSubImage>()(texture, level, xoffset, yoffset, zoffset, width, height, depth);
}
/// <summary>
/// Invalidate the entirety a texture image
/// </summary>
/// <param name="texture">The name of a texture object to invalidate.</param>
/// <param name="level">The level of detail of the texture object to invalidate.</param>
public void InvalidateTexImage(uint texture, int level)
{
GetDelegateFor<glInvalidateTexImage>()(texture, level);
}
/// <summary>
/// Invalidate a region of a buffer object's data store
/// </summary>
/// <param name="buffer">The name of a buffer object, a subrange of whose data store to invalidate.</param>
/// <param name="offset">The offset within the buffer's data store of the start of the range to be invalidated.</param>
/// <param name="length">The length of the range within the buffer's data store to be invalidated.</param>
public void InvalidateBufferSubData(uint buffer, IntPtr offset, IntPtr length)
{
GetDelegateFor<glInvalidateBufferSubData>()(buffer, offset, length);
}
/// <summary>
/// Invalidate the content of a buffer object's data store
/// </summary>
/// <param name="buffer">The name of a buffer object whose data store to invalidate.</param>
public void InvalidateBufferData(uint buffer)
{
GetDelegateFor<glInvalidateBufferData>()(buffer);
}
/// <summary>
/// Invalidate the content some or all of a framebuffer object's attachments
/// </summary>
/// <param name="target">The target to which the framebuffer is attached. target must be GL_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER, or GL_READ_FRAMEBUFFER.</param>
/// <param name="numAttachments">The number of entries in the attachments array.</param>
/// <param name="attachments">The address of an array identifying the attachments to be invalidated.</param>
public void InvalidateFramebuffer(uint target, uint numAttachments, uint[] attachments)
{
GetDelegateFor<glInvalidateFramebuffer>()(target, numAttachments, attachments);
}
/// <summary>
/// Invalidate the content of a region of some or all of a framebuffer object's attachments
/// </summary>
/// <param name="target">The target to which the framebuffer is attached. target must be GL_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER, or GL_READ_FRAMEBUFFER.</param>
/// <param name="numAttachments">The number of entries in the attachments array.</param>
/// <param name="attachments">The address of an array identifying the attachments to be invalidated.</param>
/// <param name="x">The X offset of the region to be invalidated.</param>
/// <param name="y">The Y offset of the region to be invalidated.</param>
/// <param name="width">The width of the region to be invalidated.</param>
/// <param name="height">The height of the region to be invalidated.</param>
public void InvalidateSubFramebuffer(uint target, uint numAttachments, uint[] attachments,
int x, int y, uint width, uint height)
{
GetDelegateFor<glInvalidateSubFramebuffer>()(target, numAttachments, attachments, x, y, width, height);
}
// Delegates
private delegate void glInvalidateTexSubImage(uint texture, int level, int xoffset,
int yoffset, int zoffset, uint width, uint height, uint depth);
private delegate void glInvalidateTexImage(uint texture, int level);
private delegate void glInvalidateBufferSubData(uint buffer, IntPtr offset, IntPtr length);
private delegate void glInvalidateBufferData(uint buffer);
private delegate void glInvalidateFramebuffer(uint target, uint numAttachments, uint[] attachments);
private delegate void glInvalidateSubFramebuffer(uint target, uint numAttachments, uint[] attachments,
int x, int y, uint width, uint height);
#endregion
#region ARB_multi_draw_indirect
/// <summary>
/// Render multiple sets of primitives from array data, taking parameters from memory
/// </summary>
/// <param name="mode">Specifies what kind of primitives to render. Symbolic constants GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, GL_LINE_STRIP_ADJACENCY, GL_LINES_ADJACENCY, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLES, GL_TRIANGLE_STRIP_ADJACENCY, GL_TRIANGLES_ADJACENCY, and GL_PATCHES are accepted.</param>
/// <param name="indirect">Specifies the address of an array of structures containing the draw parameters.</param>
/// <param name="primcount">Specifies the the number of elements in the array of draw parameter structures.</param>
/// <param name="stride">Specifies the distance in basic machine units between elements of the draw parameter array.</param>
public void MultiDrawArraysIndirect(uint mode, IntPtr indirect, uint primcount, uint stride)
{
GetDelegateFor<glMultiDrawArraysIndirect>()(mode, indirect, primcount, stride);
}
/// <summary>
/// Render indexed primitives from array data, taking parameters from memory
/// </summary>
/// <param name="mode">Specifies what kind of primitives to render. Symbolic constants GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, GL_LINE_STRIP_ADJACENCY, GL_LINES_ADJACENCY, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLES, GL_TRIANGLE_STRIP_ADJACENCY, GL_TRIANGLES_ADJACENCY, and GL_PATCHES are accepted.</param>
/// <param name="type">Specifies the type of data in the buffer bound to the GL_ELEMENT_ARRAY_BUFFER binding.</param>
/// <param name="indirect">Specifies a byte offset (cast to a pointer type) into the buffer bound to GL_DRAW_INDIRECT_BUFFER, which designates the starting point of the structure containing the draw parameters.</param>
/// <param name="primcount">Specifies the number of elements in the array addressed by indirect.</param>
/// <param name="stride">Specifies the distance in basic machine units between elements of the draw parameter array.</param>
public void MultiDrawElementsIndirect(uint mode, uint type, IntPtr indirect, uint primcount, uint stride)
{
GetDelegateFor<glMultiDrawElementsIndirect>()(mode, type, indirect, primcount, stride);
}
private delegate void glMultiDrawArraysIndirect(uint mode, IntPtr indirect, uint primcount, uint stride);
private delegate void glMultiDrawElementsIndirect(uint mode, uint type, IntPtr indirect, uint primcount, uint stride);
#endregion
#region GL_ARB_program_interface_query
/// <summary>
/// Query a property of an interface in a program
/// </summary>
/// <param name="program">The name of a program object whose interface to query.</param>
/// <param name="programInterface">A token identifying the interface within program to query.</param>
/// <param name="pname">The name of the parameter within programInterface to query.</param>
/// <param name="parameters">The address of a variable to retrieve the value of pname for the program interface..</param>
public void GetProgramInterface(uint program, uint programInterface, uint pname, int[] parameters)
{
GetDelegateFor<glGetProgramInterfaceiv>()(program, programInterface, pname, parameters);
}
/// <summary>
/// Query the index of a named resource within a program
/// </summary>
/// <param name="program">The name of a program object whose resources to query.</param>
/// <param name="programInterface">A token identifying the interface within program containing the resource named name.</param>
/// <param name="name">The name of the resource to query the index of.</param>
public void GetProgramResourceIndex(uint program, uint programInterface, string name)
{
GetDelegateFor<glGetProgramResourceIndex>()(program, programInterface, name);
}
/// <summary>
/// Query the name of an indexed resource within a program
/// </summary>
/// <param name="program">The name of a program object whose resources to query.</param>
/// <param name="programInterface">A token identifying the interface within program containing the indexed resource.</param>
/// <param name="index">The index of the resource within programInterface of program.</param>
/// <param name="bufSize">The size of the character array whose address is given by name.</param>
/// <param name="length">The address of a variable which will receive the length of the resource name.</param>
/// <param name="name">The address of a character array into which will be written the name of the resource.</param>
public void GetProgramResourceName(uint program, uint programInterface, uint index, uint bufSize, out uint length, out string name)
{
var lengthParameter = new uint[1];
var nameParameter = new string[1];
GetDelegateFor<glGetProgramResourceName>()(program, programInterface, index, bufSize, lengthParameter, nameParameter);
length = lengthParameter[0];
name = nameParameter[0];
}
/// <summary>
/// Retrieve values for multiple properties of a single active resource within a program object
/// </summary>
/// <param name="program">The name of a program object whose resources to query.</param>
/// <param name="programInterface">A token identifying the interface within program containing the resource named name.</param>
/// <param name="index">The index within the programInterface to query information about.</param>
/// <param name="propCount">The number of properties being queried.</param>
/// <param name="props">An array of properties of length propCount to query.</param>
/// <param name="bufSize">The number of GLint values in the params array.</param>
/// <param name="length">If not NULL, then this value will be filled in with the number of actual parameters written to params.</param>
/// <param name="parameters">The output array of parameters to write.</param>
public void GetProgramResource(uint program, uint programInterface, uint index, uint propCount, uint[] props, uint bufSize, out uint length, out int[] parameters)
{
var lengthParameter = new uint[1];
var parametersParameter = new int[bufSize];
GetDelegateFor<glGetProgramResourceiv>()(program, programInterface, index, propCount, props, bufSize, lengthParameter, parametersParameter);
length = lengthParameter[0];
parameters = parametersParameter;
}
/// <summary>
/// Query the location of a named resource within a program.
/// </summary>
/// <param name="program">The name of a program object whose resources to query.</param>
/// <param name="programInterface">A token identifying the interface within program containing the resource named name.</param>
/// <param name="name">The name of the resource to query the location of.</param>
public void GetProgramResourceLocation(uint program, uint programInterface, string name)
{
GetDelegateFor<glGetProgramResourceLocation>()(program, programInterface, name);
}
/// <summary>
/// Query the fragment color index of a named variable within a program.
/// </summary>
/// <param name="program">The name of a program object whose resources to query.</param>
/// <param name="programInterface">A token identifying the interface within program containing the resource named name.</param>
/// <param name="name">The name of the resource to query the location of.</param>
public void GetProgramResourceLocationIndex(uint program, uint programInterface, string name)
{
GetDelegateFor<glGetProgramResourceLocationIndex>()(program, programInterface, name);
}
private delegate void glGetProgramInterfaceiv(uint program, uint programInterface, uint pname, int[] parameters);
private delegate uint glGetProgramResourceIndex(uint program, uint programInterface, string name);
private delegate void glGetProgramResourceName(uint program, uint programInterface, uint index, uint bufSize, uint[] length, string[] name);
private delegate void glGetProgramResourceiv(uint program, uint programInterface, uint index, uint propCount, uint[] props, uint bufSize, uint[] length, int[] parameters);
private delegate int glGetProgramResourceLocation(uint program, uint programInterface, string name);
private delegate int glGetProgramResourceLocationIndex(uint program, uint programInterface, string name);
#endregion
#region GL_ARB_shader_storage_buffer_object
/// <summary>
/// Change an active shader storage block binding.
/// </summary>
/// <param name="program">The name of the program containing the block whose binding to change.</param>
/// <param name="storageBlockIndex">The index storage block within the program.</param>
/// <param name="storageBlockBinding">The index storage block binding to associate with the specified storage block.</param>
public void ShaderStorageBlockBinding(uint program, uint storageBlockIndex, uint storageBlockBinding)
{
GetDelegateFor<glShaderStorageBlockBinding>()(program, storageBlockIndex, storageBlockBinding);
}
private delegate void glShaderStorageBlockBinding(uint program, uint storageBlockIndex, uint storageBlockBinding);
// Constants
public const uint GL_SHADER_STORAGE_BUFFER = 0x90D2;
public const uint GL_SHADER_STORAGE_BUFFER_BINDING = 0x90D3;
public const uint GL_SHADER_STORAGE_BUFFER_START = 0x90D4;
public const uint GL_SHADER_STORAGE_BUFFER_SIZE = 0x90D5;
public const uint GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS = 0x90D6;
public const uint GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS = 0x90D7;
public const uint GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS = 0x90D8;
public const uint GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS = 0x90D9;
public const uint GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS = 0x90DA;
public const uint GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS = 0x90DB;
public const uint GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS = 0x90DC;
public const uint GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS = 0x90DD;
public const uint GL_MAX_SHADER_STORAGE_BLOCK_SIZE = 0x90DE;
public const uint GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT = 0x90DF;
public const uint GL_SHADER_STORAGE_BARRIER_BIT = 0x2000;
public const uint GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES = 0x8F39;
#endregion
#region GL_ARB_stencil_texturing
// Constants
public const uint GL_DEPTH_STENCIL_TEXTURE_MODE = 0x90EA;
#endregion
#region GL_ARB_texture_buffer_range
/// <summary>
/// Bind a range of a buffer's data store to a buffer texture
/// </summary>
/// <param name="target">Specifies the target of the operation and must be GL_TEXTURE_BUFFER.</param>
/// <param name="internalformat">Specifies the internal format of the data in the store belonging to buffer.</param>
/// <param name="buffer">Specifies the name of the buffer object whose storage to attach to the active buffer texture.</param>
/// <param name="offset">Specifies the offset of the start of the range of the buffer's data store to attach.</param>
/// <param name="size">Specifies the size of the range of the buffer's data store to attach.</param>
public void TexBufferRange(uint target, uint internalformat, uint buffer, IntPtr offset, IntPtr size)
{
GetDelegateFor<glTexBufferRange>()(target, internalformat, buffer, offset, size);
}
/// <summary>
/// Bind a range of a buffer's data store to a buffer texture
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="target">Specifies the target of the operation and must be GL_TEXTURE_BUFFER.</param>
/// <param name="internalformat">Specifies the internal format of the data in the store belonging to buffer.</param>
/// <param name="buffer">Specifies the name of the buffer object whose storage to attach to the active buffer texture.</param>
/// <param name="offset">Specifies the offset of the start of the range of the buffer's data store to attach.</param>
/// <param name="size">Specifies the size of the range of the buffer's data store to attach.</param>
public void TextureBufferRangeEXT(uint texture, uint target, uint internalformat, uint buffer, IntPtr offset, IntPtr size)
{
GetDelegateFor<glTextureBufferRangeEXT>()(texture, target, internalformat, buffer, offset, size);
}
private delegate void glTexBufferRange(uint target, uint internalformat, uint buffer, IntPtr offset, IntPtr size);
private delegate void glTextureBufferRangeEXT(uint texture, uint target, uint internalformat, uint buffer, IntPtr offset, IntPtr size);
#endregion
#region GL_ARB_texture_storage_multisample
/// <summary>
/// Specify storage for a two-dimensional multisample texture.
/// </summary>
/// <param name="target">Specify the target of the operation. target must be GL_TEXTURE_2D_MULTISAMPLE or GL_PROXY_TEXTURE_2D_MULTISAMPLE.</param>
/// <param name="samples">Specify the number of samples in the texture.</param>
/// <param name="internalformat">Specifies the sized internal format to be used to store texture image data.</param>
/// <param name="width">Specifies the width of the texture, in texels.</param>
/// <param name="height">Specifies the height of the texture, in texels.</param>
/// <param name="fixedsamplelocations">Specifies whether the image will use identical sample locations and the same number of samples for all texels in the image, and the sample locations will not depend on the internal format or size of the image.</param>
public void TexStorage2DMultisample(uint target, uint samples, uint internalformat, uint width, uint height, bool fixedsamplelocations)
{
GetDelegateFor<glTexStorage2DMultisample>()(target, samples, internalformat, width, height, fixedsamplelocations);
}
/// <summary>
/// Specify storage for a three-dimensional multisample array texture
/// </summary>
/// <param name="target">Specify the target of the operation. target must be GL_TEXTURE_3D_MULTISAMPLE_ARRAY or GL_PROXY_TEXTURE_3D_MULTISAMPLE_ARRAY.</param>
/// <param name="samples">Specify the number of samples in the texture.</param>
/// <param name="internalformat">Specifies the sized internal format to be used to store texture image data.</param>
/// <param name="width">Specifies the width of the texture, in texels.</param>
/// <param name="height">Specifies the height of the texture, in texels.</param>
/// <param name="depth">Specifies the depth of the texture, in layers.</param>
/// <param name="fixedsamplelocations">Specifies the depth of the texture, in layers.</param>
public void TexStorage3DMultisample(uint target, uint samples, uint internalformat, uint width, uint height, uint depth, bool fixedsamplelocations)
{
GetDelegateFor<glTexStorage3DMultisample>()(target, samples, internalformat, width, height, depth, fixedsamplelocations);
}
/// <summary>
/// Specify storage for a two-dimensional multisample texture.
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="target">Specify the target of the operation. target must be GL_TEXTURE_2D_MULTISAMPLE or GL_PROXY_TEXTURE_2D_MULTISAMPLE.</param>
/// <param name="samples">Specify the number of samples in the texture.</param>
/// <param name="internalformat">Specifies the sized internal format to be used to store texture image data.</param>
/// <param name="width">Specifies the width of the texture, in texels.</param>
/// <param name="height">Specifies the height of the texture, in texels.</param>
/// <param name="fixedsamplelocations">Specifies whether the image will use identical sample locations and the same number of samples for all texels in the image, and the sample locations will not depend on the internal format or size of the image.</param>
public void TexStorage2DMultisampleEXT(uint texture, uint target, uint samples, uint internalformat, uint width, uint height, bool fixedsamplelocations)
{
GetDelegateFor<glTexStorage2DMultisampleEXT>()(texture, target, samples, internalformat, width, height, fixedsamplelocations);
}
/// <summary>
/// Specify storage for a three-dimensional multisample array texture
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="target">Specify the target of the operation. target must be GL_TEXTURE_3D_MULTISAMPLE_ARRAY or GL_PROXY_TEXTURE_3D_MULTISAMPLE_ARRAY.</param>
/// <param name="samples">Specify the number of samples in the texture.</param>
/// <param name="internalformat">Specifies the sized internal format to be used to store texture image data.</param>
/// <param name="width">Specifies the width of the texture, in texels.</param>
/// <param name="height">Specifies the height of the texture, in texels.</param>
/// <param name="depth">Specifies the depth of the texture, in layers.</param>
/// <param name="fixedsamplelocations">Specifies the depth of the texture, in layers.</param>
public void TexStorage3DMultisampleEXT(uint texture, uint target, uint samples, uint internalformat, uint width, uint height, uint depth, bool fixedsamplelocations)
{
GetDelegateFor<glTexStorage3DMultisampleEXT>()(texture, target, samples, internalformat, width, height, depth, fixedsamplelocations);
}
// Delegates
private delegate void glTexStorage2DMultisample(uint target, uint samples, uint internalformat, uint width, uint height, bool fixedsamplelocations);
private delegate void glTexStorage3DMultisample(uint target, uint samples, uint internalformat, uint width, uint height, uint depth, bool fixedsamplelocations);
private delegate void glTexStorage2DMultisampleEXT(uint texture, uint target, uint samples, uint internalformat, uint width, uint height, bool fixedsamplelocations);
private delegate void glTexStorage3DMultisampleEXT(uint texture, uint target, uint samples, uint internalformat, uint width, uint height, uint depth, bool fixedsamplelocations);
#endregion
#region GL_ARB_texture_view
/// <summary>
/// Initialize a texture as a data alias of another texture's data store.
/// </summary>
/// <param name="texture">Specifies the texture object to be initialized as a view.</param>
/// <param name="target">Specifies the target to be used for the newly initialized texture.</param>
/// <param name="origtexture">Specifies the name of a texture object of which to make a view.</param>
/// <param name="internalformat">Specifies the internal format for the newly created view.</param>
/// <param name="minlevel">Specifies lowest level of detail of the view.</param>
/// <param name="numlevels">Specifies the number of levels of detail to include in the view.</param>
/// <param name="minlayer">Specifies the index of the first layer to include in the view.</param>
/// <param name="numlayers">Specifies the number of layers to include in the view.</param>
public void TextureView(uint texture, uint target, uint origtexture, uint internalformat, uint minlevel, uint numlevels, uint minlayer, uint numlayers)
{
GetDelegateFor<glTextureView>()(texture, target, origtexture, internalformat, minlevel, numlevels, minlayer, numlayers);
}
// Delegates
private delegate void glTextureView(uint texture, uint target, uint origtexture, uint internalformat, uint minlevel, uint numlevels, uint minlayer, uint numlayers);
// Constants
public const uint GL_TEXTURE_VIEW_MIN_LEVEL = 0x82DB;
public const uint GL_TEXTURE_VIEW_NUM_LEVELS = 0x82DC;
public const uint GL_TEXTURE_VIEW_MIN_LAYER = 0x82DD;
public const uint GL_TEXTURE_VIEW_NUM_LAYERS = 0x82DE;
#endregion
#region GL_ARB_vertex_attrib_binding
/// <summary>
/// Bind a buffer to a vertex buffer bind point.
/// </summary>
/// <param name="bindingindex">The index of the vertex buffer binding point to which to bind the buffer.</param>
/// <param name="buffer">The name of an existing buffer to bind to the vertex buffer binding point.</param>
/// <param name="offset">The offset of the first element of the buffer.</param>
/// <param name="stride">The distance between elements within the buffer.</param>
public void BindVertexBuffer(uint bindingindex, uint buffer, IntPtr offset, uint stride)
{
GetDelegateFor<glBindVertexBuffer>()(bindingindex, buffer, offset, stride);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// </summary>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="normalized">GL_TRUE if the parameter represents a normalized integer (type must be an integer type). GL_FALSE otherwise.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexAttribFormat(uint attribindex, int size, uint type, bool normalized, uint relativeoffset)
{
GetDelegateFor<glVertexAttribFormat>()(attribindex, size, type, normalized, relativeoffset);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// </summary>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexAttribIFormat(uint attribindex, int size, uint type, uint relativeoffset)
{
GetDelegateFor<glVertexAttribIFormat>()(attribindex, size, type, relativeoffset);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// </summary>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexAttribLFormat(uint attribindex, int size, uint type, uint relativeoffset)
{
GetDelegateFor<glVertexAttribLFormat>()(attribindex, size, type, relativeoffset);
}
/// <summary>
/// Associate a vertex attribute and a vertex buffer binding.
/// </summary>
/// <param name="attribindex">The index of the attribute to associate with a vertex buffer binding.</param>
/// <param name="bindingindex">The index of the vertex buffer binding with which to associate the generic vertex attribute.</param>
public void VertexAttribBinding(uint attribindex, uint bindingindex)
{
GetDelegateFor<glVertexAttribBinding>()(attribindex, bindingindex);
}
/// <summary>
/// Modify the rate at which generic vertex attributes advance.
/// </summary>
/// <param name="bindingindex">The index of the binding whose divisor to modify.</param>
/// <param name="divisor">The new value for the instance step rate to apply.</param>
public void VertexBindingDivisor(uint bindingindex, uint divisor)
{
GetDelegateFor<glVertexBindingDivisor>()(bindingindex, divisor);
}
/// <summary>
/// Bind a buffer to a vertex buffer bind point.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="bindingindex">The index of the vertex buffer binding point to which to bind the buffer.</param>
/// <param name="buffer">The name of an existing buffer to bind to the vertex buffer binding point.</param>
/// <param name="offset">The offset of the first element of the buffer.</param>
/// <param name="stride">The distance between elements within the buffer.</param>
public void VertexArrayBindVertexBufferEXT(uint vaobj, uint bindingindex, uint buffer, IntPtr offset, uint stride)
{
GetDelegateFor<glVertexArrayBindVertexBufferEXT>()(vaobj, bindingindex, buffer, offset, stride);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="normalized">GL_TRUE if the parameter represents a normalized integer (type must be an integer type). GL_FALSE otherwise.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexArrayVertexAttribFormatEXT(uint vaobj, uint attribindex, int size, uint type, bool normalized, uint relativeoffset)
{
GetDelegateFor<glVertexArrayVertexAttribFormatEXT>()(vaobj, attribindex, size, type, normalized, relativeoffset);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexArrayVertexAttribIFormatEXT(uint vaobj, uint attribindex, int size, uint type, uint relativeoffset)
{
GetDelegateFor<glVertexArrayVertexAttribIFormatEXT>()(vaobj, attribindex, size, type, relativeoffset);
}
/// <summary>
/// Specify the organization of vertex arrays.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="attribindex">The generic vertex attribute array being described.</param>
/// <param name="size">The number of values per vertex that are stored in the array.</param>
/// <param name="type">The type of the data stored in the array.</param>
/// <param name="relativeoffset">The offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from.</param>
public void VertexArrayVertexAttribLFormatEXT(uint vaobj, uint attribindex, int size, uint type, uint relativeoffset)
{
GetDelegateFor<glVertexArrayVertexAttribLFormatEXT>()(vaobj, attribindex, size, type, relativeoffset);
}
/// <summary>
/// Associate a vertex attribute and a vertex buffer binding.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="attribindex">The index of the attribute to associate with a vertex buffer binding.</param>
/// <param name="bindingindex">The index of the vertex buffer binding with which to associate the generic vertex attribute.</param>
public void VertexArrayVertexAttribBindingEXT(uint vaobj, uint attribindex, uint bindingindex)
{
GetDelegateFor<glVertexArrayVertexAttribBindingEXT>()(vaobj, attribindex, bindingindex);
}
/// <summary>
/// Modify the rate at which generic vertex attributes advance.
/// Available only when When EXT_direct_state_access is present.
/// </summary>
/// <param name="vaobj">The vertex array object.</param>
/// <param name="bindingindex">The index of the binding whose divisor to modify.</param>
/// <param name="divisor">The new value for the instance step rate to apply.</param>
public void VertexArrayVertexBindingDivisorEXT(uint vaobj, uint bindingindex, uint divisor)
{
GetDelegateFor<glVertexArrayVertexBindingDivisorEXT>()(vaobj, bindingindex, divisor);
}
// Delegates
private delegate void glBindVertexBuffer(uint bindingindex, uint buffer, IntPtr offset, uint stride);
private delegate void glVertexAttribFormat(uint attribindex, int size, uint type, bool normalized, uint relativeoffset);
private delegate void glVertexAttribIFormat(uint attribindex, int size, uint type, uint relativeoffset);
private delegate void glVertexAttribLFormat(uint attribindex, int size, uint type, uint relativeoffset);
private delegate void glVertexAttribBinding(uint attribindex, uint bindingindex);
private delegate void glVertexBindingDivisor(uint bindingindex, uint divisor);
private delegate void glVertexArrayBindVertexBufferEXT(uint vaobj, uint bindingindex, uint buffer, IntPtr offset, uint stride);
private delegate void glVertexArrayVertexAttribFormatEXT(uint vaobj, uint attribindex, int size, uint type, bool normalized, uint relativeoffset);
private delegate void glVertexArrayVertexAttribIFormatEXT(uint vaobj, uint attribindex, int size, uint type, uint relativeoffset);
private delegate void glVertexArrayVertexAttribLFormatEXT(uint vaobj, uint attribindex, int size, uint type, uint relativeoffset);
private delegate void glVertexArrayVertexAttribBindingEXT(uint vaobj, uint attribindex, uint bindingindex);
private delegate void glVertexArrayVertexBindingDivisorEXT(uint vaobj, uint bindingindex, uint divisor);
// Constants
public const uint GL_VERTEX_ATTRIB_BINDING = 0x82D4;
public const uint GL_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D5;
public const uint GL_VERTEX_BINDING_DIVISOR = 0x82D6;
public const uint GL_VERTEX_BINDING_OFFSET = 0x82D7;
public const uint GL_VERTEX_BINDING_STRIDE = 0x82D8;
public const uint GL_VERTEX_BINDING_BUFFER = 0x8F4F;
public const uint GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D9;
public const uint GL_MAX_VERTEX_ATTRIB_BINDINGS = 0x82DA;
#endregion
#region WGL_NV_DX_interop / WGL_NV_DX_interop2
public bool DXSetResourceShareHandleNV(IntPtr dxObject, IntPtr shareHandle)
{
return (bool)GetDelegateFor<wglDXSetResourceShareHandleNV>()(dxObject, shareHandle);
}
public IntPtr DXOpenDeviceNV(IntPtr dxDevice)
{
return (IntPtr)GetDelegateFor<wglDXOpenDeviceNV>()(dxDevice);
}
public bool DXCloseDeviceNV(IntPtr hDevice)
{
return (bool)GetDelegateFor<wglDXCloseDeviceNV>()(hDevice);
}
public IntPtr DXRegisterObjectNV(IntPtr hDevice, IntPtr dxObject, uint name, uint type, uint access)
{
return (IntPtr)GetDelegateFor<wglDXRegisterObjectNV>()(hDevice, dxObject, name, type, access);
}
public bool DXUnregisterObjectNV(IntPtr hDevice, IntPtr hObject)
{
return (bool)GetDelegateFor<wglDXUnregisterObjectNV>()(hDevice, hObject);
}
public bool DXObjectAccessNV(IntPtr hObject, uint access)
{
return (bool)GetDelegateFor<wglDXObjectAccessNV>()(hObject, access);
}
public bool DXLockObjectsNV(IntPtr hDevice, IntPtr[] hObjects)
{
unsafe
{
void** objects = stackalloc void*[hObjects.Length];
for (int i = 0; i<hObjects.Length; i++)
{
objects[i] = hObjects[i].ToPointer();
}
return (bool)GetDelegateFor<wglDXLockObjectsNV>()(hDevice, hObjects.Length, objects);
}
}
public bool DXUnlockObjectsNV(IntPtr hDevice, IntPtr[] hObjects)
{
unsafe
{
void** objects = stackalloc void*[hObjects.Length];
for (int i = 0; i<hObjects.Length; i++)
{
objects[i] = hObjects[i].ToPointer();
}
return (bool)GetDelegateFor<wglDXUnlockObjectsNV>()(hDevice, hObjects.Length, objects);
}
}
private delegate bool wglDXSetResourceShareHandleNV(IntPtr dxObject, IntPtr shareHandle);
private delegate IntPtr wglDXOpenDeviceNV(IntPtr dxDevice);
private delegate bool wglDXCloseDeviceNV(IntPtr hDevice);
private delegate IntPtr wglDXRegisterObjectNV(IntPtr hDevice, IntPtr dxObject, uint name, uint type, uint access);
private delegate bool wglDXUnregisterObjectNV(IntPtr hDevice, IntPtr hObject);
private delegate bool wglDXObjectAccessNV(IntPtr hObject, uint access);
private unsafe delegate bool wglDXLockObjectsNV(IntPtr hDevice, int count, void** hObjects);
private unsafe delegate bool wglDXUnlockObjectsNV(IntPtr hDevice, int count, void** hObjects);
public const uint WGL_ACCESS_READ_ONLY_NV = 0x0000;
public const uint WGL_ACCESS_READ_WRITE_NV = 0x0001;
public const uint WGL_ACCESS_WRITE_DISCARD_NV = 0x0002;
#endregion
}
}
| {
"content_hash": "a28076559ca76fe41fdcd5ef9b3cda4f",
"timestamp": "",
"source": "github",
"line_count": 5918,
"max_line_length": 642,
"avg_line_length": 53.117945251774245,
"alnum_prop": 0.6182146129180027,
"repo_name": "LittleFox94/sharpgl",
"id": "542f0cb4621616528564f8fbedb413fa7498d5cf",
"size": "314796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/SharpGL/Core/SharpGL/OpenGLExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1860080"
},
{
"name": "GLSL",
"bytes": "8580"
},
{
"name": "PowerShell",
"bytes": "23407"
}
],
"symlink_target": ""
} |
package com.java110.report.bmo.reportFeeMonthStatistics;
import com.java110.po.reportFeeMonthStatistics.ReportFeeMonthStatisticsPo;
import org.springframework.http.ResponseEntity;
public interface IDeleteReportFeeMonthStatisticsBMO {
/**
* 修改费用月统计
* add by wuxw
* @param reportFeeMonthStatisticsPo
* @return
*/
ResponseEntity<String> delete(ReportFeeMonthStatisticsPo reportFeeMonthStatisticsPo);
}
| {
"content_hash": "b5c3317bf80dd274ecfa5beebc0f06aa",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 89,
"avg_line_length": 25.705882352941178,
"alnum_prop": 0.7780320366132724,
"repo_name": "java110/MicroCommunity",
"id": "2ab5ae9c6811bb29670d4ca6b79f293e01197173",
"size": "451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "service-report/src/main/java/com/java110/report/bmo/reportFeeMonthStatistics/IDeleteReportFeeMonthStatisticsBMO.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "737"
},
{
"name": "HTML",
"bytes": "12981"
},
{
"name": "Java",
"bytes": "19654092"
},
{
"name": "JavaScript",
"bytes": "19296"
},
{
"name": "Shell",
"bytes": "1121"
}
],
"symlink_target": ""
} |
The package provides probability distributions.
## [Documentation][doc]
[doc]: http://godoc.org/github.com/ready-steady/probability/distribution
| {
"content_hash": "480a6af0e477c289c0cd527b4ffc083b",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 72,
"avg_line_length": 29.4,
"alnum_prop": 0.7891156462585034,
"repo_name": "ready-steady/probability",
"id": "4a79120db360dd84d7262fcce6cdc6dd4cd06c41",
"size": "163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "distribution/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "12493"
}
],
"symlink_target": ""
} |
/**
* @file
* IIR filter interface
*/
#ifndef AVCODEC_IIRFILTER_H
#define AVCODEC_IIRFILTER_H
#include "avcodec.h"
struct FFIIRFilterCoeffs;
struct FFIIRFilterState;
enum IIRFilterType{
FF_FILTER_TYPE_BESSEL,
FF_FILTER_TYPE_BIQUAD,
FF_FILTER_TYPE_BUTTERWORTH,
FF_FILTER_TYPE_CHEBYSHEV,
FF_FILTER_TYPE_ELLIPTIC,
};
enum IIRFilterMode{
FF_FILTER_MODE_LOWPASS,
FF_FILTER_MODE_HIGHPASS,
FF_FILTER_MODE_BANDPASS,
FF_FILTER_MODE_BANDSTOP,
};
/**
* Initialize filter coefficients.
*
* @param avc a pointer to an arbitrary struct of which the first
* field is a pointer to an AVClass struct
* @param filt_type filter type (e.g. Butterworth)
* @param filt_mode filter mode (e.g. lowpass)
* @param order filter order
* @param cutoff_ratio cutoff to input frequency ratio
* @param stopband stopband to input frequency ratio (used by bandpass and bandstop filter modes)
* @param ripple ripple factor (used only in Chebyshev filters)
*
* @return pointer to filter coefficients structure or NULL if filter cannot be created
*/
struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(void *avc,
enum IIRFilterType filt_type,
enum IIRFilterMode filt_mode,
int order, float cutoff_ratio,
float stopband, float ripple);
/**
* Create new filter state.
*
* @param order filter order
*
* @return pointer to new filter state or NULL if state creation fails
*/
struct FFIIRFilterState* ff_iir_filter_init_state(int order);
/**
* Free filter coefficients.
*
* @param coeffs pointer allocated with ff_iir_filter_init_coeffs()
*/
void ff_iir_filter_free_coeffs(struct FFIIRFilterCoeffs *coeffs);
/**
* Free filter state.
*
* @param state pointer allocated with ff_iir_filter_init_state()
*/
void ff_iir_filter_free_state(struct FFIIRFilterState *state);
/**
* Perform IIR filtering on signed 16-bit input samples.
*
* @param coeffs pointer to filter coefficients
* @param state pointer to filter state
* @param size input length
* @param src source samples
* @param sstep source stride
* @param dst filtered samples (destination may be the same as input)
* @param dstep destination stride
*/
void ff_iir_filter(const struct FFIIRFilterCoeffs *coeffs, struct FFIIRFilterState *state,
int size, const int16_t *src, int sstep, int16_t *dst, int dstep);
/**
* Perform IIR filtering on floating-point input samples.
*
* @param coeffs pointer to filter coefficients
* @param state pointer to filter state
* @param size input length
* @param src source samples
* @param sstep source stride
* @param dst filtered samples (destination may be the same as input)
* @param dstep destination stride
*/
void ff_iir_filter_flt(const struct FFIIRFilterCoeffs *coeffs,
struct FFIIRFilterState *state, int size,
const float *src, int sstep, float *dst, int dstep);
#endif /* AVCODEC_IIRFILTER_H */
| {
"content_hash": "54e091afc7cb76a5887193aa910fcf41",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 101,
"avg_line_length": 30.883495145631066,
"alnum_prop": 0.6598553913863565,
"repo_name": "fillest/rtmp_load",
"id": "bc65a96b59bd67782c0799024f4bee207066cc38",
"size": "3998",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/libav/libavcodec/iirfilter.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1170180"
},
{
"name": "C",
"bytes": "21402746"
},
{
"name": "C++",
"bytes": "756318"
},
{
"name": "CSS",
"bytes": "8089"
},
{
"name": "Lua",
"bytes": "353492"
},
{
"name": "Objective-C",
"bytes": "60159"
},
{
"name": "Perl",
"bytes": "12139"
},
{
"name": "Python",
"bytes": "9473"
},
{
"name": "Shell",
"bytes": "44483"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/asdlfjei"
tools:context=".ui.activity.MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="@+id/text" />
<com.psuwgipgf.myapplication.ui.view.CircleImageView
android:id="@+id/circleImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_below="@+id/image"
app:civ_border_width="2dp"
app:civ_border_color="#FFffffff">
</com.psuwgipgf.myapplication.ui.view.CircleImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我" />
</LinearLayout>
</RelativeLayout>
| {
"content_hash": "72ae9df3e4c54c6b35d61b857a9b03df",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 74,
"avg_line_length": 33,
"alnum_prop": 0.6106346483704974,
"repo_name": "psuwgipgf/BaseAndroid",
"id": "3d634462a7ef7196c761512150c3da93f0b39b82",
"size": "1757",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BaseAndroid/app/res/layout/activity_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "104923"
},
{
"name": "Kotlin",
"bytes": "325"
}
],
"symlink_target": ""
} |
package org.apache.maven.repository.metadata;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.inject.Inject;
import org.apache.maven.artifact.ArtifactScopeEnum;
import org.codehaus.plexus.testing.PlexusTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
*
* @author <a href="mailto:oleg@codehaus.org">Oleg Gusakov</a>
*
*/
@PlexusTest
public class DefaultGraphConflictResolverTest {
@Inject
GraphConflictResolver resolver;
MetadataGraph graph;
MetadataGraphVertex v1;
MetadataGraphVertex v2;
MetadataGraphVertex v3;
MetadataGraphVertex v4;
// ------------------------------------------------------------------------------------------
@BeforeEach
public void setUp() throws Exception {
/*
* v2
* v1<
* v3-v4
*
*/
graph = new MetadataGraph(4, 3);
v1 = graph.addVertex(new ArtifactMetadata("g", "a1", "1.0"));
graph.setEntry(v1);
v2 = graph.addVertex(new ArtifactMetadata("g", "a2", "1.0"));
v3 = graph.addVertex(new ArtifactMetadata("g", "a3", "1.0"));
v4 = graph.addVertex(new ArtifactMetadata("g", "a4", "1.0"));
// v1-->v2
graph.addEdge(v1, v2, new MetadataGraphEdge("1.1", true, null, null, 2, 1));
graph.addEdge(v1, v2, new MetadataGraphEdge("1.2", true, null, null, 2, 2));
// v1-->v3
graph.addEdge(v1, v3, new MetadataGraphEdge("1.1", true, null, null, 2, 1));
graph.addEdge(v1, v3, new MetadataGraphEdge("1.2", true, null, null, 4, 2));
// v3-->v4
graph.addEdge(v3, v4, new MetadataGraphEdge("1.1", true, ArtifactScopeEnum.runtime, null, 2, 1));
graph.addEdge(v3, v4, new MetadataGraphEdge("1.2", true, ArtifactScopeEnum.provided, null, 2, 2));
}
// ------------------------------------------------------------------------------------------
@Test
public void testCompileResolution() throws Exception {
MetadataGraph res;
res = resolver.resolveConflicts(graph, ArtifactScopeEnum.compile);
assertNotNull(res, "null graph after resolver");
assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver");
assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver");
assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver");
assertEquals(
2,
res.getExcidentEdges(v1).size(),
"wrong # of excident edges in the resulting graph entry after resolver");
assertEquals(
1,
res.getIncidentEdges(v2).size(),
"wrong # of v2 incident edges in the resulting graph after resolver");
assertEquals(
"1.2",
res.getIncidentEdges(v2).get(0).getVersion(),
"wrong edge v1-v2 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver");
assertEquals(
"1.1",
res.getIncidentEdges(v3).get(0).getVersion(),
"wrong edge v1-v3 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver");
assertEquals(
"1.2",
res.getIncidentEdges(v4).get(0).getVersion(),
"wrong edge v3-v4 in the resulting graph after resolver");
}
// ------------------------------------------------------------------------------------------
@Test
public void testRuntimeResolution() throws Exception {
MetadataGraph res;
res = resolver.resolveConflicts(graph, ArtifactScopeEnum.runtime);
assertNotNull(res, "null graph after resolver");
assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver");
assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver");
assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver");
assertEquals(
2,
res.getExcidentEdges(v1).size(),
"wrong # of excident edges in the resulting graph entry after resolver");
assertEquals(
1,
res.getIncidentEdges(v2).size(),
"wrong # of v2 incident edges in the resulting graph after resolver");
assertEquals(
"1.2",
res.getIncidentEdges(v2).get(0).getVersion(),
"wrong edge v1-v2 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver");
assertEquals(
"1.1",
res.getIncidentEdges(v3).get(0).getVersion(),
"wrong edge v1-v3 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver");
assertEquals(
"1.1",
res.getIncidentEdges(v4).get(0).getVersion(),
"wrong edge v3-v4 in the resulting graph after resolver");
}
// ------------------------------------------------------------------------------------------
@Test
public void testTestResolution() throws Exception {
MetadataGraph res;
res = resolver.resolveConflicts(graph, ArtifactScopeEnum.test);
assertNotNull(res, "null graph after resolver");
assertNotNull(res.getVertices(), "no vertices in the resulting graph after resolver");
assertNotNull(res.getExcidentEdges(v1), "no edges in the resulting graph after resolver");
assertEquals(4, res.getVertices().size(), "wrong # of vertices in the resulting graph after resolver");
assertEquals(
2,
res.getExcidentEdges(v1).size(),
"wrong # of excident edges in the resulting graph entry after resolver");
assertEquals(
1,
res.getIncidentEdges(v2).size(),
"wrong # of v2 incident edges in the resulting graph after resolver");
assertEquals(
"1.2",
res.getIncidentEdges(v2).get(0).getVersion(),
"wrong edge v1-v2 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v3).size(), "wrong # of edges v1-v3 in the resulting graph after resolver");
assertEquals(
"1.1",
res.getIncidentEdges(v3).get(0).getVersion(),
"wrong edge v1-v3 in the resulting graph after resolver");
assertEquals(
1, res.getIncidentEdges(v4).size(), "wrong # of edges v3-v4 in the resulting graph after resolver");
assertEquals(
"1.2",
res.getIncidentEdges(v4).get(0).getVersion(),
"wrong edge v3-v4 in the resulting graph after resolver");
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
}
| {
"content_hash": "c6fa8632d22ccd179643b772cd26c0cb",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 116,
"avg_line_length": 42.144444444444446,
"alnum_prop": 0.5557606116530451,
"repo_name": "apache/maven",
"id": "536b4bb552ec132eaa19445c4eca0e8c69e346a1",
"size": "8393",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "maven-compat/src/test/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolverTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8860"
},
{
"name": "HTML",
"bytes": "2379"
},
{
"name": "Java",
"bytes": "5615236"
},
{
"name": "Shell",
"bytes": "5741"
}
],
"symlink_target": ""
} |
class sACNListener;
class sACNSentUniverse;
enum StreamingACNProtocolVersion
{
sACNProtocolUnknown = 0,
sACNProtocolDraft,
sACNProtocolRelease,
};
class sACNSource : public QObject
{
Q_OBJECT
public:
explicit sACNSource();
CID src_cid;
bool src_valid;
quint8 lastseq;
ttimer active; //If this expires, we haven't received any data in over a second
//The per-channel priority alternate start code policy requires we detect the source only after
//a STARTCODE_PRIORITY packet was received or 1.5 seconds have expired
bool waited_for_dd;
bool doing_dmx; //if true, we are processing dmx data from this source
bool doing_per_channel; //If true, we are tracking per-channel priority messages for this source
bool isPreview;
ttimer priority_wait; //if !initially_notified, used to track if a source is finally detected
//(either by receiving priority or timeout). If doing_per_channel,
//used to time out the 0xdd packets to see if we lost per-channel priority
quint16 universe;
quint8 level_array[DMX_SLOT_MAX];
quint16 slot_count; // Number of slots actually received
quint8 priority_array[DMX_SLOT_MAX];
quint8 last_level_array[DMX_SLOT_MAX];
quint8 last_priority_array[DMX_SLOT_MAX];
bool dirty_array[DMX_SLOT_MAX]; // Set if an individual level or priority has changed
bool source_params_change; // Set if any parameter of the source changes between packets
bool source_levels_change;
quint8 priority;
quint16 synchronization;
QString name;
QString cid_string();
QHostAddress ip;
fpsCounter fpscounter;
// The number of sequence errors from this source
int seqErr;
// The number of jumps (increments by anything other than 1) of this source
int jumps;
// Protocol Version
StreamingACNProtocolVersion protocol_version;
public slots:
void resetSeqErr() {
seqErr = 0;
}
void resetJumps() {
jumps = 0;
}
};
// The sACNManager class is a singleton that manages the lifespan of sACNTransmitters and sACNListeners.
class sACNManager : public QObject
{
Q_OBJECT
public:
static sACNManager *getInstance();
typedef QSharedPointer<sACNListener> tListener;
typedef QSharedPointer<sACNSentUniverse> tSender;
public slots:
void listenerDelete(QObject *obj = Q_NULLPTR);
void senderDelete(QObject *obj = Q_NULLPTR);
private:
sACNManager();
static sACNManager *m_instance;
QMutex sACNManager_mutex;
QHash<QObject*, quint16> m_objToUniverse;
QHash<QObject*, CID> m_objToCid;
QHash<quint16, QWeakPointer<sACNListener>> m_listenerHash;
QHash<quint16, QThread *> m_listenerThreads;
tSender createSender(CID cid, quint16 universe);
QHash<CID, QHash<quint16, QWeakPointer<sACNSentUniverse>> > m_senderHash;
public:
tListener getListener(quint16 universe);
const decltype(m_listenerHash) getListenerList() { return m_listenerHash; }
tSender getSender(quint16 universe, CID cid = CID::CreateCid());
const decltype(m_senderHash) getSenderList() { return m_senderHash; }
signals:
void newSender();
private slots:
void senderUniverseChanged();
void senderCIDChanged();
private:
};
#endif // STREAMINGACN_H
| {
"content_hash": "e5db6b968a3230a90ffc17694cf6f32b",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 108,
"avg_line_length": 30.623853211009173,
"alnum_prop": 0.7043139604553625,
"repo_name": "marcusbirkin/sacnview",
"id": "54571416540185aef2a563a5e763d65288553ae0",
"size": "4816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sacn/streamingacn.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "1998"
},
{
"name": "C",
"bytes": "267341"
},
{
"name": "C++",
"bytes": "570236"
},
{
"name": "CSS",
"bytes": "9239"
},
{
"name": "HTML",
"bytes": "195"
},
{
"name": "JavaScript",
"bytes": "3422"
},
{
"name": "Makefile",
"bytes": "3583"
},
{
"name": "NSIS",
"bytes": "17370"
},
{
"name": "Objective-C",
"bytes": "12700"
},
{
"name": "Python",
"bytes": "6491"
},
{
"name": "QMake",
"bytes": "17002"
},
{
"name": "Ruby",
"bytes": "516"
},
{
"name": "Shell",
"bytes": "8705"
}
],
"symlink_target": ""
} |
public class Test {
public static void main(String[] args) {
System.out.println("Hi!");
}
}
| {
"content_hash": "8d78761c32b36ba0a9c69d4b8668beff",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 44,
"avg_line_length": 21.6,
"alnum_prop": 0.5833333333333334,
"repo_name": "dcos-labs/dcos-maven-plugin",
"id": "c35ad141f6ab7664e05c0df648cf6f29caa01466",
"size": "109",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "samples/simple-pod-sample/src/main/java/Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "15511"
}
],
"symlink_target": ""
} |
FactoryBot.define do
factory :part_payment do
application
expires_at { rand(3..7).days.from_now }
factory :part_payment_part_outcome do
outcome { 'part' }
end
factory :part_payment_none_outcome do
outcome { 'none' }
end
factory :part_payment_return_outcome do
outcome { 'return' }
end
factory :part_payment_incorrect do
correct { false }
incorrect_reason { 'SOME REASON' }
outcome { 'none' }
end
trait :completed do
completed_at { Time.zone.yesterday }
association :completed_by, factory: :user
end
end
end
| {
"content_hash": "fa3e40b2d465f5ec0eca033a3d5f853f",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 47,
"avg_line_length": 21.103448275862068,
"alnum_prop": 0.6209150326797386,
"repo_name": "ministryofjustice/fr-staffapp",
"id": "da8915c2f0abe9a454f88231ba4c257f8df02beb",
"size": "612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/factories/part_payments.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "12502"
},
{
"name": "Dockerfile",
"bytes": "2640"
},
{
"name": "Gherkin",
"bytes": "71762"
},
{
"name": "HTML",
"bytes": "9288"
},
{
"name": "JavaScript",
"bytes": "18196"
},
{
"name": "Ruby",
"bytes": "1440239"
},
{
"name": "SCSS",
"bytes": "42727"
},
{
"name": "Scala",
"bytes": "4251"
},
{
"name": "Shell",
"bytes": "3858"
},
{
"name": "Slim",
"bytes": "250532"
}
],
"symlink_target": ""
} |
The following instructions apply to
the
[Raspberry Pi 2 Model B v1.2](https://www.raspberrypi.org/products/raspberry-pi-2-model-b/).
Other models may work just fine but YMMV.
## Preparing the Raspberry Pi
You will need:
* 4GB or bigger microSD card
* USB drive adapter or other way to flash microSD
* (Optional) 802.11 USB WiFi nano module - [recommended model](https://www.adafruit.com/product/814)
Either of the flash instructions below will make a bootable microSD card.
### Flashing via GUI
1. Download [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/)
2. Download [Etcher](https://etcher.io/) for your OS
3. Plug in the microSD card
4. Run Etcher, select the Raspbian zipfile and the microSD card, click Flash
5. Make a coffee
### Flashing via commandline
TODO(mfoltz): Write a script
### Logging in and configuring WiFi
TODO(mfoltz): Figure this out
## Compiling for Raspberry Pi
[TODO](https://bugs.chromium.org/p/openscreen/issues/detail?id=18)
## Deploying and Running OSP
[TODO](https://bugs.chromium.org/p/openscreen/issues/detail?id=18)
| {
"content_hash": "5a3a80455535a4d14d7c22ae298176b4",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 100,
"avg_line_length": 28.36842105263158,
"alnum_prop": 0.7541743970315399,
"repo_name": "endlessm/chromium-browser",
"id": "d19af05f5d222baa496678cb8a8f882964a41d61",
"size": "1094",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "third_party/openscreen/src/osp/docs/pi.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
title: "Gradle Sync task is not incremental"
date: 2016-09-21 12:09
classes: wide
categories: dev
---
While this may seem obvious to some it came as a surprise to learn that Gradle's
[Sync](https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Sync.html) task
will copy the entire source even if only one file has changed.
For example, with this task in our `build.gradle`
task syncToTarget(type: Sync) {
from "sourceDir"
into new File("targetSync/destDir")
eachFile { details ->
println "Syncing file: ${details.name}"
}
}
and the following project layout
.
├── build.gradle
├── sourceDir
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
└── targetSync
running **the first `Sync`** task produces the following output
:syncToTarget
Syncing file: file1.txt
Syncing file: file2.txt
Syncing file: file3.txt
BUILD SUCCESSFUL
Total time: 2.531 secs
and then **the next sync** with no changes works as expected
:syncToTarget UP-TO-DATE
BUILD SUCCESSFUL
Total time: 2.119 secs
If we then **add a single file** to the source directory
$ echo $RANDOM > sourceDir/file4.txt
And re-run the Sync task we'll see that all files are copied again
:syncToTarget
Syncing file: file1.txt
Syncing file: file2.txt
Syncing file: file3.txt
Syncing file: file4.txt
BUILD SUCCESSFUL
Total time: 2.927 secs
Checking the time stamps confirms that all files have been copied again.
Thus, in conclusion, **the Gradle Sync task is not an rsync replacement**.
| {
"content_hash": "c40f43ddb645e7c3c5db29f9196c04f2",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 80,
"avg_line_length": 23.791044776119403,
"alnum_prop": 0.6800501882057717,
"repo_name": "ftclausen/ftclausen.github.io",
"id": "67216f0837dc32a099743bb0e37423f4543cd441",
"size": "1646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-09-21-gradle_sync_task_is_not_incremental.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "5067"
},
{
"name": "JavaScript",
"bytes": "4776"
},
{
"name": "Ruby",
"bytes": "3342"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-fingroup: 1 m 47 s</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.11.2 / mathcomp-fingroup - 1.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-fingroup
<small>
1.9.0
<span class="label label-success">1 m 47 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-17 11:46:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-17 11:46:38 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.2 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.0 Official release 4.10.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
name: "coq-mathcomp-fingroup"
version: "1.9.0"
maintainer: "Mathematical Components <mathcomp-dev@sympa.inria.fr>"
homepage: "https://math-comp.github.io/"
bug-reports: "https://github.com/math-comp/math-comp/issues"
dev-repo: "git+https://github.com/math-comp/math-comp.git"
license: "CeCILL-B"
build: [ make "-C" "mathcomp/fingroup" "-j" "%{jobs}%" ]
install: [ make "-C" "mathcomp/fingroup" "install" ]
depends: [ "coq-mathcomp-ssreflect" { = "1.9.0" } ]
tags: [ "keyword:finite groups" "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" "mathcomp.fingroup" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "Mathematical Components Library on finite groups"
description: """
This library contains definitions and theorems about finite groups,
group quotients, group morphisms, group presentation, group action...
"""
url {
src: "http://github.com/math-comp/math-comp/archive/mathcomp-1.9.0.tar.gz"
checksum: "sha256=fe3d157a4db7e96f39212f76e701a7fc1e3f125c54b8c38f06a6a387eda61c96"
}
</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-mathcomp-fingroup.1.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-mathcomp-fingroup.1.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 26 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-mathcomp-fingroup.1.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 47 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 7 M</p>
<ul>
<li>914 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/action.glob</code></li>
<li>851 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/fingroup.glob</code></li>
<li>841 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/action.vo</code></li>
<li>711 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/gproduct.vo</code></li>
<li>642 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/fingroup.vo</code></li>
<li>594 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/gproduct.glob</code></li>
<li>527 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/morphism.glob</code></li>
<li>452 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/morphism.vo</code></li>
<li>310 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/quotient.glob</code></li>
<li>252 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/quotient.vo</code></li>
<li>225 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/perm.vo</code></li>
<li>165 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/perm.glob</code></li>
<li>163 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/automorphism.vo</code></li>
<li>131 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/automorphism.glob</code></li>
<li>111 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/fingroup.v</code></li>
<li>98 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/action.v</code></li>
<li>92 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/presentation.vo</code></li>
<li>62 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/gproduct.v</code></li>
<li>52 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/morphism.v</code></li>
<li>40 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/presentation.glob</code></li>
<li>34 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/quotient.v</code></li>
<li>29 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/all_fingroup.vo</code></li>
<li>24 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/perm.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/automorphism.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/presentation.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/all_fingroup.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/mathcomp/fingroup/all_fingroup.v</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-mathcomp-fingroup.1.9.0</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">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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": "d394b2d36c2525f5fe2c984415c8dee5",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 554,
"avg_line_length": 58.3551912568306,
"alnum_prop": 0.5862908512032962,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ee7ffd36faf961c1211290f19e2485e9f0501c6f",
"size": "10682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.0-2.0.6/released/8.11.2/mathcomp-fingroup/1.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fragment_container" >
</LinearLayout> | {
"content_hash": "ea8896cde2b29a0e5ec59270972c5092",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 72,
"avg_line_length": 37.375,
"alnum_prop": 0.7324414715719063,
"repo_name": "india-rose/old-indiarose",
"id": "7a2d6d787dccf9ec795998d4f896eb1660893f31",
"size": "299",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "EclipseWS/IndiaRoseLibrary/res/layout/activity_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "4207949"
}
],
"symlink_target": ""
} |
/* * * This file was autogenerated by Styler at 02:02 on 02/15/2003 * * */
/***********************************************************
* SCRIPT-SUPPORTING STYLES
***********************************************************/
/* Defines the userData cache persistence mechanism. */
.userDataStyle
{
behavior: url(#default#userData);
}
/* Used to save the scroll bar position when navigating away from a page. */
div.saveHistory
{
behavior: url(#default#savehistory);
}
/* Formats the expand/collapse images for all collapsible regions. */
img.toggle
{
border: 0;
margin-right: 5;
}
/* Formats the Collapse All/Expand All images. */
img#toggleAllImage
{
margin-left: 0;
vertical-align: middle;
}
/* Supports XLinks */
MSHelp\:link
{
text-decoration: underline;
color: #0000ff;
hoverColor: #3366ff;
filterString: ;
}
/***********************************************************
* CONTENT PRESENTATION STYLES
***********************************************************/
body
{
background: #FFFFFF;
color: #000000;
font-family: Verdana;
font-size: medium;
font-style: normal;
font-weight: normal;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
margin-right: 0;
width: 100%;
}
dl
{
margin-top: 15;
margin-bottom:5;
padding-left: 1;
}
dl.authored dt {
font-style: bold;
margin-top: 2;
}
dd {
margin-left: 0;
}
ul
{
margin-top:0;
margin-bottom:0;
margin-left: 17;
list-style-type: disc;
}
ul ul
{
margin-bottom: 4;
margin-left: 17;
margin-top: 3;
list-style-type: disc;
}
ol {
margin-top:0;
margin-bottom:0;
margin-left: 28;
list-style-type: decimal;
}
ol ol {
margin-bottom: 4;
margin-left: 28;
margin-top: 3;
list-style-type: lower-alpha;
}
li {
margin-top: 5;
margin-bottom: 5;
}
p {
margin-top: 10;
margin-bottom: 5;
}
a:link {
color: #0000FF;
}
a:visited {
color: #DD7C3B;
}
a:hover {
color: #3366FF;
}
div#header a, div#mainSectionMHS a {
text-decoration: underline;
}
code
{
font-family: Monospace, Courier New, Courier;
font-size: 105%;
color: #000066;
}
span.parameter {
font-style: italic;
}
span.italic {
font-style: italic;
}
span.selflink {
font-weight: bold;
}
span.nolink {
font-weight: bold;
}
/***********************************************************
* STRUCTURE PRESENTATION STYLES
***********************************************************/
/* Applies to everything below the non-scrolling header region. */
div#mainSection
{
font-size: 62.5%;
width: 100%;
}
div#mainSectionMHS
{
font-family: Verdana;
font-size: 81%;
width: 100%;
}
html>body #mainSection, html>body #mainSectionMHS
{
font-size:73%;
width: 100%;
}
/* Applies to everything below the non-scrolling header region, minus the footer. */
div#mainBody
{
font-size: 100%;
margin-left: 15;
margin-top: 10;
/*padding-bottom: 20;*/
}
html>body #mainBody
{
font-size: 93%;
margin-left: 15;
margin-top: 10;
padding-bottom: 20;
}
/* Adds right padding for all blocks in mainBody */
div#mainBody p, div#mainBody ol, div#mainBody ul, div#mainBody dl
{
padding-right: 5;
}
/*------------------------------ Begin Non-scrolling Header Region Styles -------------------------------*/
/* Applies to the entire non-scrolling header region. */
div#header
{
font-family: Verdana;
background-color: #FFFFFF;
padding-top: 0;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
width: 100%;
}
/* Applies to both tables in the non-scrolling header region. */
div#header table
{
width: 100%;
}
/* Applies to cells in both tables in the non-scrolling header region. */
div#header table td
{
color: #0000FF;
font-size: 70%;
margin-top: 0;
margin-bottom: 0;
padding-right: 20;
}
/* Applies to second row in the upper table of the non-scrolling header region. */
div#header table tr#headerTableRow2 td
{
padding-left: 13px;
}
/* Applies to the last row in the upper table of the non-scrolling header region. Text
in this row includes See Also, Constructors, Methods, and Properties. */
div#header table tr#headerTableRow3 td
{
padding-top: 2px;
padding-left: 15;
}
/* Applies to the lower table in the non-scrolling header region. Text in this table
includes Collapse All/Expand All, Language Filter, and Members Options. */
div#header table#bottomTable
{
border-top-color: #FFFFFF;
border-top-style: solid;
border-top-width: 1;
text-align: left;
padding-left: 15;
padding-top: 5px;
padding-bottom: 5px;
}
/* Formats the first column--the one that displays icons--in mref list tables (such as Public Constructors,
Protected Constructors, Public Properties, Protected Properties, and so on). */
div#mainSection table td.imageCell, div#mainSectionMHS table td.imageCell
{
white-space: nowrap;
}
/*------------------------------ End General Table Styles -------------------------------*/
/*------------------------------ Begin General Table Styles -------------------------------*/
div#mainBody div.alert, div#mainBody div.code, div#mainBody div.tableSection
{
width:98.9%;
}
div#mainBody div.section div.alert, div#mainBody div.section div.code,
div#mainBody div.section div.tableSection
{
width:100%;
}
div#mainBody div.section ul div.alert, div#mainBody div.section ul div.code,
div#mainBody div.section ul div.tableSection, div#mainBody div.section ol div.alert,
div#mainBody div.section ol div.code, div#mainBody div.section ol div.tableSection
{
width:100%;
}
div.alert p, div.code p
{
margin-top:5;
margin-bottom:8;
}
dd p
{
margin-top:2;
margin-bottom:8;
}
div.tableSection p
{
margin-top:1;
margin-bottom:4;
}
li p
{
margin-top:2;
margin-bottom:2;
}
div.seeAlsoNoToggleSection dl
{
margin-top:8;
margin-bottom:1;
padding-left:1;
}
div.seeAlsoNoToggleSection dd p
{
margin-top:2;
margin-bottom:8;
}
div.section dl
{
margin-top:8;
margin-bottom:1;
padding-left:1;
}
div.section dd p
{
margin-top:2;
margin-bottom:8;
}
/*------------------------------ End General Table Styles -------------------------------*/
/*------------------------------ Begin Syntax and Snipper Code Block Styles -------------------------------*/
div.code table
{
border: 0;
font-size: 95%;
margin-bottom: 5;
margin-top:-.4em;
width: 100%
}
div.code table th
{
background: #EFEFF7;
border-bottom-color: #C8CDDE;
border-bottom-style: solid;
border-bottom-width: 1;
color: #000066;
font-weight: bold;
padding-left: 5;
padding-right: 5;
}
div.code table td
{
background: #F7F7FF;
border-top-color: #FFFFFF;
border-top-style: solid;
border-top-width: 1;
padding-left: 5;
padding-right: 5;
padding-top: 5;
}
/* Applies to the running header text in the first row of the upper table in the
non-scrolling header region. */
span#runningHeaderText
{
color: #8C8C8C;
font-size: 90%;
padding-left: 13;
}
/* Applies to the topic title in the second row of the upper table in the
non-scrolling header region. */
span#nsrTitle
{
color: #000000;
font-size: 160%;
font-weight: 400;
font-family: arial;
}
/*------------------------------ End Non-scrolling Header Region Styles -------------------------------*/
/* Formats the footer. Currently, the transforms pass in two parameters to the
footer SSC, but the default footer SSC doesn't use either parameter.
TODO: Investigate whether the default footer SSC has any impact on doc spec. */
div#footer
{
font-size: 80%;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
margin-right: 0;
padding-top: 8;
padding-bottom: 6;
padding-left: 1;
padding-right: 1;
width: 100%;
}
html>body div#footer
{
font-size: 80%;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
margin-right: 0;
padding-top: 2;
padding-bottom: 6;
padding-left: 1;
padding-right: 1;
width: 98%;
}
/* Unable to find this style in the transforms. The default footer SSC adds a plain horizontal rule.
TODO: Determine whether this style is required by the doc spec. */
/*
hr#footerHR
{
border-bottom-color: #EEEEFF;
border-bottom-style: solid;
border-bottom-width: 1;
border-top-color: C8CDDE;
border-top-style: solid;
border-top-width: 1;
height: 3;
color: #D4DFFF;
}
*/
/********************************************************************************************************************
Collapsible Section Structure
<h1 class="heading"> // Format of the collapsible section text
<span onclick="ExpandCollapse(xxxToggle)"> // Defines the onclick procedure for the expand/collapse section
<img id="xxxToggle"> // Expand/collapse image
</img>
</span>
</h1>
<div id="xxxSection" class="section"> // The body of the collapsible section; hidden by default
</div>
The ExpandCollapse() function is responsible for toggling the expand/collapse image, and for
displaying/hiding the body of the collapsible section.
********************************************************************************************************************/
/* Applies to the body of a collapsible section */
div.seeAlsoNoToggleSection
{
margin-left:0;
padding-top: 2;
padding-bottom: 2;
padding-left: 0;
padding-right: 15;
width: 100%;
}
div.section
{
margin-left:0;
padding-top: 0;
padding-bottom: 0;
padding-left: 16;
padding-right: 15;
width: 100%;
}
html>body div.section
{
margin-left:0;
padding-top: 2;
padding-bottom: 2;
padding-left: 16;
padding-right: 15;
width: 97%;
}
div.seeSection
{
margin-left:0;
padding-top: 0;
padding-bottom: 2;
padding-left: 16;
padding-right: 15;
width: 100%;
}
/*------------------------------ Begin Heading Styles -------------------------------*/
/* As far as I can tell, only <h1> tags use this class.
TODO: Decide whether to roll these attributes into the h1.heading style */
.heading
{
font-weight: bold;
margin-top: 18;
margin-bottom: 8;
}
/* All <h1> headings. */
h1.heading
{
font-family: Verdana;
color: #000000;
font-size: 130%;
}
/* Applies to table titles and subsection titles. */
.subHeading
{
font-weight: bold;
margin-bottom: 4;
}
.procedureSubHeading
{
font-weight: bold;
margin-bottom: 4;
}
/* Formats the titles of author-generated tables. */
h3.subHeading
{
font-family: Verdana;
color: #000000;
font-size: 120%;
font-weight:800;
}
h3.procedureSubHeading
{
font-family: Verdana;
color: #000000;
font-size: 120%;
}
/* Formats the titles of all subsections. */
h4.subHeading
{
font-family: Verdana;
color: #000000;
font-size: 110%;
font-weight:800;
}
span.labelheading, div.labelheading
{
font-size:100%;
color:#003399;
}
/*------------------------------ End Heading Styles -------------------------------*/
/*------------------------------ Begin Image Styles -------------------------------*/
img.copyCodeImage
{
border: 0;
margin: 1;
margin-right: 3;
}
img.downloadCodeImage
{
border: 0;
margin-right: 3;
}
img.viewCodeImage
{
border: 0;
margin-right: 3;
}
img.note
{
border: 0;
margin-right: 3;
}
/*------------------------------ End Image Styles -------------------------------*/
/*------------------------------ Begin General Table Styles -------------------------------*/
div#mainSection table, div#mainSectionMHS table
{
border: 0;
font-size: 100%;
width: 98.9%;
margin-top: 5px;
margin-bottom: 5px;
}
div#mainSection table tr, div#mainSectionMHS table tr
{
vertical-align: top;
}
div#mainSection table th, div#mainSectionMHS table th
{
background-color: #EFEFF7;
border-bottom: 1px solid #C8CDDE;
border-left: 1px none #D5D5D3;
color: #000066;
padding-left: 5px;
padding-right: 5px;
text-align: left;
}
div#mainSection table td, div#mainSectionMHS table td
{
background-color: #F7F7FF;
border-bottom: 1px solid #D5D5D3;
border-left: 1px none #D5D5D3;
padding-left: 5px;
padding-right: 5px;
}
/* Formats the first column--the one that displays icons--in mref list tables (such as Public Constructors,
Protected Constructors, Public Properties, Protected Properties, and so on). */
div#mainSection table td.imageCell, div#mainSectionMHS table td.imageCell
{
white-space: nowrap;
}
/*------------------------------ End General Table Styles -------------------------------*/
/*------------------------------ Begin Syntax and Snipper Code Block Styles -------------------------------*/
div.code table
{
border: 0;
font-size: 95%;
margin-bottom: 5;
width: 100%
}
div.code table th
{
background: #EFEFF7;
border-bottom-color: #C8CDDE;
border-bottom-style: solid;
border-bottom-width: 1;
color: #000066;
font-weight: bold;
padding-left: 5;
padding-right: 5;
}
div.code table td
{
background: #F7F7FF;
border-top-color: #FFFFFF;
border-top-style: solid;
border-top-width: 1;
padding-left: 5;
padding-right: 5;
padding-top: 5;
}
/*------------------------------ End Syntax and Snipper Code Block Styles -------------------------------*/
/*------------------------------ Begin Note Styles -------------------------------*/
div.alert table
{
border: 0;
font-size: 100%;
width: 100%;
}
div.alert table th
{
background: #EFEFF7;
border-bottom-width: 0;
color: #000066;
padding-left: 5;
padding-right: 5;
}
div.alert table td
{
background: #F7F7FF;
border-top-color: #FFFFFF;
border-top-style: solid;
border-top-width: 1;
padding-left: 5;
padding-right: 5;
}
/*------------------------------ End Note Styles -------------------------------*/
/* Applies to the copy code text and image. */
span.copyCode
{
color: #0000ff;
font-size: 90%;
font-weight: normal;
cursor: pointer;
float: right;
display: inline;
text-align: right;
text-decoration: underline;
}
span.copyCodeOnHover
{
color: #E85F17;
font-size:xx-small;
font-weight: normal;
cursor: pointer;
float: right;
display: inline;
text-align: right;
text-decoration: underline;
}
.downloadCode
{
color: #0000ff;
font-size: 90%;
font-weight: normal;
cursor: pointer;
}
.viewCode
{
color: #0000ff;
font-size: 90%;
font-weight: normal;
cursor: pointer;
}
/* Formats the code in syntax and usage blocks, and the code in non-snipper code blocks. */
div.code pre
{
font-family: Monospace, Courier New, Courier;
font-size: 105%;
color: #000066;
word-wrap: break-word;
background: #F7F7FF;
}
/* Formats parameter tooltips. */
.tip
{
color: #0000FF;
font-style: italic;
cursor: pointer;
text-decoration:underline;
}
/* Applies to text styled as math. This text is passed as a parameter to the italics SSC definition */
.math
{
font-family: Times New Roman;
font-size: 125%
}
/* The sourceCodeList class doesn't appear in the transforms.
TODO: Find out whether this style is needed for the doc spec. */
/*
.sourceCodeList
{
font-family: Verdana;
font-size: 90%;
}
*/
/* The viewCode class doesn't appear in the transforms.
TODO: Find out whether this style is needed for the doc spec. */
/*
pre.viewCode
{
width: 100%;
overflow: auto;
}
*/
/* Dropdown areas */
#devlangsMenu {
position: absolute;
visibility: hidden;
border-style: solid;
border-width: 1px;
border-color: #f3cbb5;
background: #FCECE4;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 4px;
padding-right:8px;
font-size: 70%;
}
div.OH_outerContent #devlangsMenu {
font-size: 91%;
}
#memberOptionsMenu {
position: absolute;
visibility: hidden;
border-style: solid;
border-width: 1px;
border-color: #f3cbb5;
background: #FCECE4;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 4px;
padding-right:8px;
font-size: 70%;
}
div.OH_outerContent #memberOptionsMenu {
font-size: 91%;
}
#memberFrameworksMenu {
position: absolute;
visibility: hidden;
border-style: solid;
border-width: 1px;
border-color: #f3cbb5;
background: #FCECE4;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 4px;
padding-right:8px;
font-size: 70%;
}
div.OH_outerContent #memberFrameworksMenu {
font-size: 91%;
}
/* Applies to the checkbox labels in the filter drop-downs for devlang, member options, and member platforms. */
.checkboxLabel
{
color: #0000FF;
cursor: pointer;
text-decoration:underline;
padding-bottom:4;
font-size:90%;
}
img#devlangsDropdownImage
{
border: 0;
margin-left: 0;
vertical-align: middle;
}
/* Formats the Members Options filter drop-down image. */
img#memberOptionsDropdownImage
{
border: 0;
margin-left: 0;
vertical-align: middle;
}
/* Formats the Members Platforms filter drop-down image. */
img#memberFrameworksDropdownImage
{
border: 0;
margin-left: 0;
vertical-align: middle;
}
/* Line seperating footer from main body */
div.footerLine {
margin: 0;
width: 100%;
padding-top: 8;
padding-bottom: 6;
/*padding-left: 5;
padding-right: 2;*/
}
div.hr1 {
margin: 0;
width: 100%;
height: 1px;
padding: 0;
background: #C8CDDE;
font-size: 1px;
}
div.hr2 {
margin: 0;
width: 100%;
height: 1px;
padding: 0;
background: #D4DFFF;
font-size: 1px;
}
div.hr3 {
margin: 0;
width: 100%;
height: 1px;
padding: 0;
background: #EEEEFF;
font-size: 1px;
}
span.cs {
display: none;
}
span.vb {
display: none;
}
span.cpp {
display: none;
}
span.nu {
display: inline;
}
span.fs
{
display: none;
}
span.code {
font-family: Monospace, Courier New, Courier;
font-size: 105%;
color: #000066;
}
span.ui {
font-weight: bold;
}
span.math {
font-style: italic;
}
span.input {
font-weight: bold;
}
span.term {
font-style: italic;
}
span.label
{
font-weight: bold;
}
span.foreignPhrase {
font-style: italic;
}
span.placeholder {
font-style: italic;
}
span.keyword
{
font-weight: bold;
}
span.typeparameter
{
font-style:italic;
}
div.caption
{
font-weight: bold;
font-size:100%;
color:#003399;
}
/* syntax styles */
div.code span.identifier
{
/*font-weight: bold;*/
}
div.code span.keyword
{
/*color: green;*/
color: #871F78;
}
div.code span.parameter
{
font-style: italic;
/*color: purple;*/
}
div.code span.literal
{
/*color: purple;*/
color:#8B0000;
}
div.code span.comment
{
/*color: red;*/
color: #006400;
}
span.syntaxLabel
{
color:#0481DA;
font-weight:bold;
}
span.introStyle
{
color:DarkGray;
}
div.seeAlsoStyle
{
padding-top:5px;
}
td.nsrBottom
{
height: 0.6em;
width: 100%;
}
/* end of syntax styles */
/* Glossary */
SPAN.clsGlossary {cursor: default; color: #509950; font-weight: bold;}
DIV.clsTooltip {border: 1px solid black; padding: 2px; position: absolute; top: 0; left: 0; display: none; background-color: #FFFFAA; color: black; font-size: 8pt; font-family: Arial;}
/* FB STYLES */
span.feedbackcss
{
font-size: 110%;
width:100%;
margin-left: 15px;
/*
border-width: 1px 1px 1px 1px;
border-style: solid;
border-color:#C8CDDE;
*/
}
div#feedbackarea table
{
margin-bottom:0px;
margin-top:0px;
margin-left: 0;
width:300;
border-width: 0px 0px 0px 0px;
}
div#feedbackarea table td
{
/*background-color: #D4DFFF;*/
font-family:Verdana;
font-size:100%;
text-align:center;
/*color: #003399;*/
border-bottom:0px;
}
div#feedbackarea p
{
font-size:100%;
/*background-color: #D4DFFF;*/
width: 100%;
margin-bottom: 0;
margin-top: 0;
margin-left: 6;
margin-right: 5;
}
div#feedbackarea H5
{
margin-top:0px;
margin-bottom:0.7em;
font-size:10pt;
margin-left: 6;
}
p.feedbackarea
{
width:expression(document.body.clientWidth-27);
font-size:100%;
background-color: #D4DFFF;
}
input#submitFeedback
{
font-size:100%;
text-align:center;
/*background-color:#D4DFFF; */
}
span#feedbackarea
{
/*
background-color: #D4DFFF;
color: #003399;
border-color:#C8CDDE;
*/
width:100%;
}
div#feedbackarea
{
/*background-color: #D4DFFF;
color: #003399;*/
width:100%;
}
span.filterOnHover
{
color: #E85F17;
}
span.filter
{
color: #0000FF;
}
| {
"content_hash": "a2857892c8e0820afa673ed5eec42c75",
"timestamp": "",
"source": "github",
"line_count": 1115,
"max_line_length": 184,
"avg_line_length": 18.60627802690583,
"alnum_prop": 0.5983804106815772,
"repo_name": "jozefizso/sandcastle-presentation",
"id": "79834734dd1e99dbd9b8b82a35ec5612ea9832e5",
"size": "20748",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Sandcastle/Presentation/vs2005/Styles/Presentation.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "27152"
},
{
"name": "C#",
"bytes": "13344193"
},
{
"name": "CSS",
"bytes": "234581"
},
{
"name": "HTML",
"bytes": "2768"
},
{
"name": "Java",
"bytes": "95540"
},
{
"name": "JavaScript",
"bytes": "247291"
},
{
"name": "PowerShell",
"bytes": "52706"
},
{
"name": "Shell",
"bytes": "35601"
},
{
"name": "XSLT",
"bytes": "1916792"
}
],
"symlink_target": ""
} |
class TamlJSONReader
{
public:
TamlJSONReader( Taml* pTaml ) :
mpTaml( pTaml )
{}
virtual ~TamlJSONReader() {}
/// Read.
SimObject* read( FileStream& stream );
private:
Taml* mpTaml;
typedef HashMap<SimObjectId, SimObject*> typeObjectReferenceHash;
typeObjectReferenceHash mObjectReferenceMap;
private:
void resetParse( void );
SimObject* parseType( const rapidjson::Value::ConstMemberIterator& memberItr );
inline void parseField( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject );
inline void parseChild( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject );
inline void parseCustom( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject, const char* pCustomNodeName, TamlCustomNodes& customNodes );
inline void parseCustomNode( rapidjson::Value::ConstMemberIterator& memberItr, TamlCustomNode* pCustomNode );
inline StringTableEntry getDemangledName( const char* pMangledName );
inline bool parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName );
inline U32 getTamlRefId( const rapidjson::Value& value );
inline U32 getTamlRefToId( const rapidjson::Value& value );
inline const char* getTamlObjectName( const rapidjson::Value& value );
};
#endif // _TAML_JSONREADER_H_ | {
"content_hash": "aa92f8ae7e605bec0414f34d4b2d551d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 162,
"avg_line_length": 39.42857142857143,
"alnum_prop": 0.7427536231884058,
"repo_name": "RichardRanft/Torque2D",
"id": "bf201a0d09ae1eba2c354688d6931b0699c3a218",
"size": "3043",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "engine/source/persistence/taml/json/tamlJSONReader.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "22202"
},
{
"name": "Batchfile",
"bytes": "1170"
},
{
"name": "C",
"bytes": "1521981"
},
{
"name": "C#",
"bytes": "516720"
},
{
"name": "C++",
"bytes": "12790552"
},
{
"name": "CMake",
"bytes": "62780"
},
{
"name": "CSS",
"bytes": "2384"
},
{
"name": "HTML",
"bytes": "329097"
},
{
"name": "Java",
"bytes": "27086"
},
{
"name": "JavaScript",
"bytes": "2047"
},
{
"name": "Lex",
"bytes": "15855"
},
{
"name": "Lua",
"bytes": "3594"
},
{
"name": "M4",
"bytes": "19093"
},
{
"name": "Makefile",
"bytes": "106799"
},
{
"name": "Objective-C",
"bytes": "307353"
},
{
"name": "Objective-C++",
"bytes": "611476"
},
{
"name": "Python",
"bytes": "183962"
},
{
"name": "Ruby",
"bytes": "2275"
},
{
"name": "Shell",
"bytes": "302718"
},
{
"name": "Yacc",
"bytes": "16053"
}
],
"symlink_target": ""
} |
package framework
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"text/tabwriter"
"time"
"github.com/golang/glog"
"golang.org/x/crypto/ssh"
"golang.org/x/net/websocket"
"google.golang.org/api/googleapi"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
gomegatypes "github.com/onsi/gomega/types"
apps "k8s.io/api/apps/v1"
batch "k8s.io/api/batch/v1"
"k8s.io/api/core/v1"
extensions "k8s.io/api/extensions/v1beta1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
utilfeature "k8s.io/apiserver/pkg/util/feature"
clientset "k8s.io/client-go/kubernetes"
scaleclient "k8s.io/client-go/scale"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/api/testapi"
podutil "k8s.io/kubernetes/pkg/api/v1/pod"
appsinternal "k8s.io/kubernetes/pkg/apis/apps"
batchinternal "k8s.io/kubernetes/pkg/apis/batch"
api "k8s.io/kubernetes/pkg/apis/core"
extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"k8s.io/kubernetes/pkg/client/conditions"
"k8s.io/kubernetes/pkg/cloudprovider/providers/azure"
gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce"
"k8s.io/kubernetes/pkg/controller"
nodectlr "k8s.io/kubernetes/pkg/controller/nodelifecycle"
"k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/kubectl"
kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis"
"k8s.io/kubernetes/pkg/kubelet/util/format"
"k8s.io/kubernetes/pkg/master/ports"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
"k8s.io/kubernetes/pkg/scheduler/schedulercache"
sshutil "k8s.io/kubernetes/pkg/ssh"
"k8s.io/kubernetes/pkg/util/system"
taintutils "k8s.io/kubernetes/pkg/util/taints"
utilversion "k8s.io/kubernetes/pkg/util/version"
"k8s.io/kubernetes/test/e2e/framework/ginkgowrapper"
testutils "k8s.io/kubernetes/test/utils"
imageutils "k8s.io/kubernetes/test/utils/image"
uexec "k8s.io/utils/exec"
)
const (
// How long to wait for the pod to be listable
PodListTimeout = time.Minute
// Initial pod start can be delayed O(minutes) by slow docker pulls
// TODO: Make this 30 seconds once #4566 is resolved.
PodStartTimeout = 5 * time.Minute
// If there are any orphaned namespaces to clean up, this test is running
// on a long lived cluster. A long wait here is preferably to spurious test
// failures caused by leaked resources from a previous test run.
NamespaceCleanupTimeout = 15 * time.Minute
// Some pods can take much longer to get ready due to volume attach/detach latency.
slowPodStartTimeout = 15 * time.Minute
// How long to wait for a service endpoint to be resolvable.
ServiceStartTimeout = 1 * time.Minute
// How often to Poll pods, nodes and claims.
Poll = 2 * time.Second
pollShortTimeout = 1 * time.Minute
pollLongTimeout = 5 * time.Minute
// service accounts are provisioned after namespace creation
// a service account is required to support pod creation in a namespace as part of admission control
ServiceAccountProvisionTimeout = 2 * time.Minute
// How long to try single API calls (like 'get' or 'list'). Used to prevent
// transient failures from failing tests.
// TODO: client should not apply this timeout to Watch calls. Increased from 30s until that is fixed.
SingleCallTimeout = 5 * time.Minute
// How long nodes have to be "ready" when a test begins. They should already
// be "ready" before the test starts, so this is small.
NodeReadyInitialTimeout = 20 * time.Second
// How long pods have to be "ready" when a test begins.
PodReadyBeforeTimeout = 5 * time.Minute
// How long pods have to become scheduled onto nodes
podScheduledBeforeTimeout = PodListTimeout + (20 * time.Second)
podRespondingTimeout = 15 * time.Minute
ServiceRespondingTimeout = 2 * time.Minute
EndpointRegisterTimeout = time.Minute
// How long claims have to become dynamically provisioned
ClaimProvisionTimeout = 5 * time.Minute
// How long claims have to become bound
ClaimBindingTimeout = 3 * time.Minute
// How long claims have to become deleted
ClaimDeletingTimeout = 3 * time.Minute
// How long PVs have to beome reclaimed
PVReclaimingTimeout = 3 * time.Minute
// How long PVs have to become bound
PVBindingTimeout = 3 * time.Minute
// How long PVs have to become deleted
PVDeletingTimeout = 3 * time.Minute
// How long a node is allowed to become "Ready" after it is restarted before
// the test is considered failed.
RestartNodeReadyAgainTimeout = 5 * time.Minute
// How long a pod is allowed to become "running" and "ready" after a node
// restart before test is considered failed.
RestartPodReadyAgainTimeout = 5 * time.Minute
// Number of objects that gc can delete in a second.
// GC issues 2 requestes for single delete.
gcThroughput = 10
// Minimal number of nodes for the cluster to be considered large.
largeClusterThreshold = 100
// TODO(justinsb): Avoid hardcoding this.
awsMasterIP = "172.20.0.9"
// ssh port
sshPort = "22"
// ImagePrePullingTimeout is the time we wait for the e2e-image-puller
// static pods to pull the list of seeded images. If they don't pull
// images within this time we simply log their output and carry on
// with the tests.
ImagePrePullingTimeout = 5 * time.Minute
)
var (
BusyBoxImage = "busybox"
// Label allocated to the image puller static pod that runs on each node
// before e2es.
ImagePullerLabels = map[string]string{"name": "e2e-image-puller"}
// For parsing Kubectl version for version-skewed testing.
gitVersionRegexp = regexp.MustCompile("GitVersion:\"(v.+?)\"")
// Slice of regexps for names of pods that have to be running to consider a Node "healthy"
requiredPerNodePods = []*regexp.Regexp{
regexp.MustCompile(".*kube-proxy.*"),
regexp.MustCompile(".*fluentd-elasticsearch.*"),
regexp.MustCompile(".*node-problem-detector.*"),
}
// Serve hostname image name
ServeHostnameImage = imageutils.GetE2EImage(imageutils.ServeHostname)
)
type Address struct {
internalIP string
externalIP string
hostname string
}
// GetServerArchitecture fetches the architecture of the cluster's apiserver.
func GetServerArchitecture(c clientset.Interface) string {
arch := ""
sVer, err := c.Discovery().ServerVersion()
if err != nil || sVer.Platform == "" {
// If we failed to get the server version for some reason, default to amd64.
arch = "amd64"
} else {
// Split the platform string into OS and Arch separately.
// The platform string may for example be "linux/amd64", "linux/arm" or "windows/amd64".
osArchArray := strings.Split(sVer.Platform, "/")
arch = osArchArray[1]
}
return arch
}
// GetPauseImageName fetches the pause image name for the same architecture as the apiserver.
func GetPauseImageName(c clientset.Interface) string {
return imageutils.GetE2EImageWithArch(imageutils.Pause, GetServerArchitecture(c))
}
func GetServicesProxyRequest(c clientset.Interface, request *restclient.Request) (*restclient.Request, error) {
return request.Resource("services").SubResource("proxy"), nil
}
// unique identifier of the e2e run
var RunId = uuid.NewUUID()
type CreateTestingNSFn func(baseName string, c clientset.Interface, labels map[string]string) (*v1.Namespace, error)
type ContainerFailures struct {
status *v1.ContainerStateTerminated
Restarts int
}
func GetMasterHost() string {
masterUrl, err := url.Parse(TestContext.Host)
ExpectNoError(err)
return masterUrl.Host
}
func nowStamp() string {
return time.Now().Format(time.StampMilli)
}
func log(level string, format string, args ...interface{}) {
fmt.Fprintf(GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...)
}
func Logf(format string, args ...interface{}) {
log("INFO", format, args...)
}
func Failf(format string, args ...interface{}) {
FailfWithOffset(1, format, args...)
}
// FailfWithOffset calls "Fail" and logs the error at "offset" levels above its caller
// (for example, for call chain f -> g -> FailfWithOffset(1, ...) error would be logged for "f").
func FailfWithOffset(offset int, format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
log("INFO", msg)
ginkgowrapper.Fail(nowStamp()+": "+msg, 1+offset)
}
func Skipf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
log("INFO", msg)
ginkgowrapper.Skip(nowStamp() + ": " + msg)
}
func SkipUnlessNodeCountIsAtLeast(minNodeCount int) {
if TestContext.CloudConfig.NumNodes < minNodeCount {
Skipf("Requires at least %d nodes (not %d)", minNodeCount, TestContext.CloudConfig.NumNodes)
}
}
func SkipUnlessNodeCountIsAtMost(maxNodeCount int) {
if TestContext.CloudConfig.NumNodes > maxNodeCount {
Skipf("Requires at most %d nodes (not %d)", maxNodeCount, TestContext.CloudConfig.NumNodes)
}
}
func SkipUnlessAtLeast(value int, minValue int, message string) {
if value < minValue {
Skipf(message)
}
}
func SkipIfProviderIs(unsupportedProviders ...string) {
if ProviderIs(unsupportedProviders...) {
Skipf("Not supported for providers %v (found %s)", unsupportedProviders, TestContext.Provider)
}
}
func SkipUnlessLocalEphemeralStorageEnabled() {
if !utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
Skipf("Only supported when %v feature is enabled", features.LocalStorageCapacityIsolation)
}
}
func SkipUnlessSSHKeyPresent() {
if _, err := GetSigner(TestContext.Provider); err != nil {
Skipf("No SSH Key for provider %s: '%v'", TestContext.Provider, err)
}
}
func SkipUnlessProviderIs(supportedProviders ...string) {
if !ProviderIs(supportedProviders...) {
Skipf("Only supported for providers %v (not %s)", supportedProviders, TestContext.Provider)
}
}
func SkipUnlessMultizone(c clientset.Interface) {
zones, err := GetClusterZones(c)
if err != nil {
Skipf("Error listing cluster zones")
}
if zones.Len() <= 1 {
Skipf("Requires more than one zone")
}
}
func SkipIfMultizone(c clientset.Interface) {
zones, err := GetClusterZones(c)
if err != nil {
Skipf("Error listing cluster zones")
}
if zones.Len() > 1 {
Skipf("Requires more than one zone")
}
}
func SkipUnlessClusterMonitoringModeIs(supportedMonitoring ...string) {
if !ClusterMonitoringModeIs(supportedMonitoring...) {
Skipf("Only next monitoring modes are supported %v (not %s)", supportedMonitoring, TestContext.ClusterMonitoringMode)
}
}
func SkipUnlessMasterOSDistroIs(supportedMasterOsDistros ...string) {
if !MasterOSDistroIs(supportedMasterOsDistros...) {
Skipf("Only supported for master OS distro %v (not %s)", supportedMasterOsDistros, TestContext.MasterOSDistro)
}
}
func SkipUnlessNodeOSDistroIs(supportedNodeOsDistros ...string) {
if !NodeOSDistroIs(supportedNodeOsDistros...) {
Skipf("Only supported for node OS distro %v (not %s)", supportedNodeOsDistros, TestContext.NodeOSDistro)
}
}
func SkipIfContainerRuntimeIs(runtimes ...string) {
for _, runtime := range runtimes {
if runtime == TestContext.ContainerRuntime {
Skipf("Not supported under container runtime %s", runtime)
}
}
}
func RunIfContainerRuntimeIs(runtimes ...string) {
for _, runtime := range runtimes {
if runtime == TestContext.ContainerRuntime {
return
}
}
Skipf("Skipped because container runtime %q is not in %s", TestContext.ContainerRuntime, runtimes)
}
func RunIfSystemSpecNameIs(names ...string) {
for _, name := range names {
if name == TestContext.SystemSpecName {
return
}
}
Skipf("Skipped because system spec name %q is not in %v", TestContext.SystemSpecName, names)
}
func ProviderIs(providers ...string) bool {
for _, provider := range providers {
if strings.ToLower(provider) == strings.ToLower(TestContext.Provider) {
return true
}
}
return false
}
func ClusterMonitoringModeIs(monitoringModes ...string) bool {
for _, mode := range monitoringModes {
if strings.ToLower(mode) == strings.ToLower(TestContext.ClusterMonitoringMode) {
return true
}
}
return false
}
func MasterOSDistroIs(supportedMasterOsDistros ...string) bool {
for _, distro := range supportedMasterOsDistros {
if strings.ToLower(distro) == strings.ToLower(TestContext.MasterOSDistro) {
return true
}
}
return false
}
func NodeOSDistroIs(supportedNodeOsDistros ...string) bool {
for _, distro := range supportedNodeOsDistros {
if strings.ToLower(distro) == strings.ToLower(TestContext.NodeOSDistro) {
return true
}
}
return false
}
func ProxyMode(f *Framework) (string, error) {
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-proxy-mode-detector",
Namespace: f.Namespace.Name,
},
Spec: v1.PodSpec{
HostNetwork: true,
Containers: []v1.Container{
{
Name: "detector",
Image: imageutils.GetE2EImage(imageutils.Net),
Command: []string{"/bin/sleep", "3600"},
},
},
},
}
f.PodClient().CreateSync(pod)
defer f.PodClient().DeleteSync(pod.Name, &metav1.DeleteOptions{}, DefaultPodDeletionTimeout)
cmd := "curl -q -s --connect-timeout 1 http://localhost:10249/proxyMode"
stdout, err := RunHostCmd(pod.Namespace, pod.Name, cmd)
if err != nil {
return "", err
}
Logf("ProxyMode: %s", stdout)
return stdout, nil
}
func SkipUnlessServerVersionGTE(v *utilversion.Version, c discovery.ServerVersionInterface) {
gte, err := ServerVersionGTE(v, c)
if err != nil {
Failf("Failed to get server version: %v", err)
}
if !gte {
Skipf("Not supported for server versions before %q", v)
}
}
func SkipIfMissingResource(clientPool dynamic.ClientPool, gvr schema.GroupVersionResource, namespace string) {
dynamicClient, err := clientPool.ClientForGroupVersionResource(gvr)
if err != nil {
Failf("Unexpected error getting dynamic client for %v: %v", gvr.GroupVersion(), err)
}
apiResource := metav1.APIResource{Name: gvr.Resource, Namespaced: true}
_, err = dynamicClient.Resource(&apiResource, namespace).List(metav1.ListOptions{})
if err != nil {
// not all resources support list, so we ignore those
if apierrs.IsMethodNotSupported(err) || apierrs.IsNotFound(err) || apierrs.IsForbidden(err) {
Skipf("Could not find %s resource, skipping test: %#v", gvr, err)
}
Failf("Unexpected error getting %v: %v", gvr, err)
}
}
// ProvidersWithSSH are those providers where each node is accessible with SSH
var ProvidersWithSSH = []string{"gce", "gke", "aws", "local"}
type podCondition func(pod *v1.Pod) (bool, error)
// logPodStates logs basic info of provided pods for debugging.
func logPodStates(pods []v1.Pod) {
// Find maximum widths for pod, node, and phase strings for column printing.
maxPodW, maxNodeW, maxPhaseW, maxGraceW := len("POD"), len("NODE"), len("PHASE"), len("GRACE")
for i := range pods {
pod := &pods[i]
if len(pod.ObjectMeta.Name) > maxPodW {
maxPodW = len(pod.ObjectMeta.Name)
}
if len(pod.Spec.NodeName) > maxNodeW {
maxNodeW = len(pod.Spec.NodeName)
}
if len(pod.Status.Phase) > maxPhaseW {
maxPhaseW = len(pod.Status.Phase)
}
}
// Increase widths by one to separate by a single space.
maxPodW++
maxNodeW++
maxPhaseW++
maxGraceW++
// Log pod info. * does space padding, - makes them left-aligned.
Logf("%-[1]*[2]s %-[3]*[4]s %-[5]*[6]s %-[7]*[8]s %[9]s",
maxPodW, "POD", maxNodeW, "NODE", maxPhaseW, "PHASE", maxGraceW, "GRACE", "CONDITIONS")
for _, pod := range pods {
grace := ""
if pod.DeletionGracePeriodSeconds != nil {
grace = fmt.Sprintf("%ds", *pod.DeletionGracePeriodSeconds)
}
Logf("%-[1]*[2]s %-[3]*[4]s %-[5]*[6]s %-[7]*[8]s %[9]s",
maxPodW, pod.ObjectMeta.Name, maxNodeW, pod.Spec.NodeName, maxPhaseW, pod.Status.Phase, maxGraceW, grace, pod.Status.Conditions)
}
Logf("") // Final empty line helps for readability.
}
// errorBadPodsStates create error message of basic info of bad pods for debugging.
func errorBadPodsStates(badPods []v1.Pod, desiredPods int, ns, desiredState string, timeout time.Duration) string {
errStr := fmt.Sprintf("%d / %d pods in namespace %q are NOT in %s state in %v\n", len(badPods), desiredPods, ns, desiredState, timeout)
// Print bad pods info only if there are fewer than 10 bad pods
if len(badPods) > 10 {
return errStr + "There are too many bad pods. Please check log for details."
}
buf := bytes.NewBuffer(nil)
w := tabwriter.NewWriter(buf, 0, 0, 1, ' ', 0)
fmt.Fprintln(w, "POD\tNODE\tPHASE\tGRACE\tCONDITIONS")
for _, badPod := range badPods {
grace := ""
if badPod.DeletionGracePeriodSeconds != nil {
grace = fmt.Sprintf("%ds", *badPod.DeletionGracePeriodSeconds)
}
podInfo := fmt.Sprintf("%s\t%s\t%s\t%s\t%+v",
badPod.ObjectMeta.Name, badPod.Spec.NodeName, badPod.Status.Phase, grace, badPod.Status.Conditions)
fmt.Fprintln(w, podInfo)
}
w.Flush()
return errStr + buf.String()
}
// WaitForPodsSuccess waits till all labels matching the given selector enter
// the Success state. The caller is expected to only invoke this method once the
// pods have been created.
func WaitForPodsSuccess(c clientset.Interface, ns string, successPodLabels map[string]string, timeout time.Duration) error {
successPodSelector := labels.SelectorFromSet(successPodLabels)
start, badPods, desiredPods := time.Now(), []v1.Pod{}, 0
if wait.PollImmediate(30*time.Second, timeout, func() (bool, error) {
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{LabelSelector: successPodSelector.String()})
if err != nil {
Logf("Error getting pods in namespace %q: %v", ns, err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
if len(podList.Items) == 0 {
Logf("Waiting for pods to enter Success, but no pods in %q match label %v", ns, successPodLabels)
return true, nil
}
badPods = []v1.Pod{}
desiredPods = len(podList.Items)
for _, pod := range podList.Items {
if pod.Status.Phase != v1.PodSucceeded {
badPods = append(badPods, pod)
}
}
successPods := len(podList.Items) - len(badPods)
Logf("%d / %d pods in namespace %q are in Success state (%d seconds elapsed)",
successPods, len(podList.Items), ns, int(time.Since(start).Seconds()))
if len(badPods) == 0 {
return true, nil
}
return false, nil
}) != nil {
logPodStates(badPods)
LogPodsWithLabels(c, ns, successPodLabels, Logf)
return errors.New(errorBadPodsStates(badPods, desiredPods, ns, "SUCCESS", timeout))
}
return nil
}
// WaitForPodsRunningReady waits up to timeout to ensure that all pods in
// namespace ns are either running and ready, or failed but controlled by a
// controller. Also, it ensures that at least minPods are running and
// ready. It has separate behavior from other 'wait for' pods functions in
// that it requests the list of pods on every iteration. This is useful, for
// example, in cluster startup, because the number of pods increases while
// waiting. All pods that are in SUCCESS state are not counted.
//
// If ignoreLabels is not empty, pods matching this selector are ignored.
func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods, allowedNotReadyPods int32, timeout time.Duration, ignoreLabels map[string]string) error {
ignoreSelector := labels.SelectorFromSet(ignoreLabels)
start := time.Now()
Logf("Waiting up to %v for all pods (need at least %d) in namespace '%s' to be running and ready",
timeout, minPods, ns)
wg := sync.WaitGroup{}
wg.Add(1)
var ignoreNotReady bool
badPods := []v1.Pod{}
desiredPods := 0
notReady := int32(0)
if wait.PollImmediate(Poll, timeout, func() (bool, error) {
// We get the new list of pods, replication controllers, and
// replica sets in every iteration because more pods come
// online during startup and we want to ensure they are also
// checked.
replicas, replicaOk := int32(0), int32(0)
rcList, err := c.CoreV1().ReplicationControllers(ns).List(metav1.ListOptions{})
if err != nil {
Logf("Error getting replication controllers in namespace '%s': %v", ns, err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
for _, rc := range rcList.Items {
replicas += *rc.Spec.Replicas
replicaOk += rc.Status.ReadyReplicas
}
rsList, err := c.ExtensionsV1beta1().ReplicaSets(ns).List(metav1.ListOptions{})
if err != nil {
Logf("Error getting replication sets in namespace %q: %v", ns, err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
for _, rs := range rsList.Items {
replicas += *rs.Spec.Replicas
replicaOk += rs.Status.ReadyReplicas
}
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{})
if err != nil {
Logf("Error getting pods in namespace '%s': %v", ns, err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
nOk := int32(0)
notReady = int32(0)
badPods = []v1.Pod{}
desiredPods = len(podList.Items)
for _, pod := range podList.Items {
if len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(pod.Labels)) {
continue
}
res, err := testutils.PodRunningReady(&pod)
switch {
case res && err == nil:
nOk++
case pod.Status.Phase == v1.PodSucceeded:
Logf("The status of Pod %s is Succeeded which is unexpected", pod.ObjectMeta.Name)
badPods = append(badPods, pod)
// it doesn't make sense to wait for this pod
return false, errors.New("unexpected Succeeded pod state")
case pod.Status.Phase != v1.PodFailed:
Logf("The status of Pod %s is %s (Ready = false), waiting for it to be either Running (with Ready = true) or Failed", pod.ObjectMeta.Name, pod.Status.Phase)
notReady++
badPods = append(badPods, pod)
default:
if metav1.GetControllerOf(&pod) == nil {
Logf("Pod %s is Failed, but it's not controlled by a controller", pod.ObjectMeta.Name)
badPods = append(badPods, pod)
}
//ignore failed pods that are controlled by some controller
}
}
Logf("%d / %d pods in namespace '%s' are running and ready (%d seconds elapsed)",
nOk, len(podList.Items), ns, int(time.Since(start).Seconds()))
Logf("expected %d pod replicas in namespace '%s', %d are Running and Ready.", replicas, ns, replicaOk)
if replicaOk == replicas && nOk >= minPods && len(badPods) == 0 {
return true, nil
}
ignoreNotReady = (notReady <= allowedNotReadyPods)
logPodStates(badPods)
return false, nil
}) != nil {
if !ignoreNotReady {
return errors.New(errorBadPodsStates(badPods, desiredPods, ns, "RUNNING and READY", timeout))
}
Logf("Number of not-ready pods (%d) is below the allowed threshold (%d).", notReady, allowedNotReadyPods)
}
return nil
}
func kubectlLogPod(c clientset.Interface, pod v1.Pod, containerNameSubstr string, logFunc func(ftm string, args ...interface{})) {
for _, container := range pod.Spec.Containers {
if strings.Contains(container.Name, containerNameSubstr) {
// Contains() matches all strings if substr is empty
logs, err := GetPodLogs(c, pod.Namespace, pod.Name, container.Name)
if err != nil {
logs, err = getPreviousPodLogs(c, pod.Namespace, pod.Name, container.Name)
if err != nil {
logFunc("Failed to get logs of pod %v, container %v, err: %v", pod.Name, container.Name, err)
}
}
logFunc("Logs of %v/%v:%v on node %v", pod.Namespace, pod.Name, container.Name, pod.Spec.NodeName)
logFunc("%s : STARTLOG\n%s\nENDLOG for container %v:%v:%v", containerNameSubstr, logs, pod.Namespace, pod.Name, container.Name)
}
}
}
func LogFailedContainers(c clientset.Interface, ns string, logFunc func(ftm string, args ...interface{})) {
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{})
if err != nil {
logFunc("Error getting pods in namespace '%s': %v", ns, err)
return
}
logFunc("Running kubectl logs on non-ready containers in %v", ns)
for _, pod := range podList.Items {
if res, err := testutils.PodRunningReady(&pod); !res || err != nil {
kubectlLogPod(c, pod, "", Logf)
}
}
}
func LogPodsWithLabels(c clientset.Interface, ns string, match map[string]string, logFunc func(ftm string, args ...interface{})) {
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{LabelSelector: labels.SelectorFromSet(match).String()})
if err != nil {
logFunc("Error getting pods in namespace %q: %v", ns, err)
return
}
logFunc("Running kubectl logs on pods with labels %v in %v", match, ns)
for _, pod := range podList.Items {
kubectlLogPod(c, pod, "", logFunc)
}
}
func LogContainersInPodsWithLabels(c clientset.Interface, ns string, match map[string]string, containerSubstr string, logFunc func(ftm string, args ...interface{})) {
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{LabelSelector: labels.SelectorFromSet(match).String()})
if err != nil {
Logf("Error getting pods in namespace %q: %v", ns, err)
return
}
for _, pod := range podList.Items {
kubectlLogPod(c, pod, containerSubstr, logFunc)
}
}
// DeleteNamespaces deletes all namespaces that match the given delete and skip filters.
// Filter is by simple strings.Contains; first skip filter, then delete filter.
// Returns the list of deleted namespaces or an error.
func DeleteNamespaces(c clientset.Interface, deleteFilter, skipFilter []string) ([]string, error) {
By("Deleting namespaces")
nsList, err := c.CoreV1().Namespaces().List(metav1.ListOptions{})
Expect(err).NotTo(HaveOccurred())
var deleted []string
var wg sync.WaitGroup
OUTER:
for _, item := range nsList.Items {
if skipFilter != nil {
for _, pattern := range skipFilter {
if strings.Contains(item.Name, pattern) {
continue OUTER
}
}
}
if deleteFilter != nil {
var shouldDelete bool
for _, pattern := range deleteFilter {
if strings.Contains(item.Name, pattern) {
shouldDelete = true
break
}
}
if !shouldDelete {
continue OUTER
}
}
wg.Add(1)
deleted = append(deleted, item.Name)
go func(nsName string) {
defer wg.Done()
defer GinkgoRecover()
Expect(c.CoreV1().Namespaces().Delete(nsName, nil)).To(Succeed())
Logf("namespace : %v api call to delete is complete ", nsName)
}(item.Name)
}
wg.Wait()
return deleted, nil
}
func WaitForNamespacesDeleted(c clientset.Interface, namespaces []string, timeout time.Duration) error {
By("Waiting for namespaces to vanish")
nsMap := map[string]bool{}
for _, ns := range namespaces {
nsMap[ns] = true
}
//Now POLL until all namespaces have been eradicated.
return wait.Poll(2*time.Second, timeout,
func() (bool, error) {
nsList, err := c.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
return false, err
}
for _, item := range nsList.Items {
if _, ok := nsMap[item.Name]; ok {
return false, nil
}
}
return true, nil
})
}
func waitForServiceAccountInNamespace(c clientset.Interface, ns, serviceAccountName string, timeout time.Duration) error {
w, err := c.CoreV1().ServiceAccounts(ns).Watch(metav1.SingleObject(metav1.ObjectMeta{Name: serviceAccountName}))
if err != nil {
return err
}
_, err = watch.Until(timeout, w, conditions.ServiceAccountHasSecrets)
return err
}
func WaitForPodCondition(c clientset.Interface, ns, podName, desc string, timeout time.Duration, condition podCondition) error {
Logf("Waiting up to %v for pod %q in namespace %q to be %q", timeout, podName, ns, desc)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
pod, err := c.CoreV1().Pods(ns).Get(podName, metav1.GetOptions{})
if err != nil {
if apierrs.IsNotFound(err) {
Logf("Pod %q in namespace %q not found. Error: %v", podName, ns, err)
return err
}
Logf("Get pod %q in namespace %q failed, ignoring for %v. Error: %v", podName, ns, Poll, err)
continue
}
// log now so that current pod info is reported before calling `condition()`
Logf("Pod %q: Phase=%q, Reason=%q, readiness=%t. Elapsed: %v",
podName, pod.Status.Phase, pod.Status.Reason, podutil.IsPodReady(pod), time.Since(start))
if done, err := condition(pod); done {
if err == nil {
Logf("Pod %q satisfied condition %q", podName, desc)
}
return err
}
}
return fmt.Errorf("Gave up after waiting %v for pod %q to be %q", timeout, podName, desc)
}
// WaitForMatchPodsCondition finds match pods based on the input ListOptions.
// waits and checks if all match pods are in the given podCondition
func WaitForMatchPodsCondition(c clientset.Interface, opts metav1.ListOptions, desc string, timeout time.Duration, condition podCondition) error {
Logf("Waiting up to %v for matching pods' status to be %s", timeout, desc)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
pods, err := c.CoreV1().Pods(metav1.NamespaceAll).List(opts)
if err != nil {
return err
}
conditionNotMatch := []string{}
for _, pod := range pods.Items {
done, err := condition(&pod)
if done && err != nil {
return fmt.Errorf("Unexpected error: %v", err)
}
if !done {
conditionNotMatch = append(conditionNotMatch, format.Pod(&pod))
}
}
if len(conditionNotMatch) <= 0 {
return err
}
Logf("%d pods are not %s: %v", len(conditionNotMatch), desc, conditionNotMatch)
}
return fmt.Errorf("gave up waiting for matching pods to be '%s' after %v", desc, timeout)
}
// WaitForDefaultServiceAccountInNamespace waits for the default service account to be provisioned
// the default service account is what is associated with pods when they do not specify a service account
// as a result, pods are not able to be provisioned in a namespace until the service account is provisioned
func WaitForDefaultServiceAccountInNamespace(c clientset.Interface, namespace string) error {
return waitForServiceAccountInNamespace(c, namespace, "default", ServiceAccountProvisionTimeout)
}
// WaitForPersistentVolumePhase waits for a PersistentVolume to be in a specific phase or until timeout occurs, whichever comes first.
func WaitForPersistentVolumePhase(phase v1.PersistentVolumePhase, c clientset.Interface, pvName string, Poll, timeout time.Duration) error {
Logf("Waiting up to %v for PersistentVolume %s to have phase %s", timeout, pvName, phase)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
pv, err := c.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{})
if err != nil {
Logf("Get persistent volume %s in failed, ignoring for %v: %v", pvName, Poll, err)
continue
} else {
if pv.Status.Phase == phase {
Logf("PersistentVolume %s found and phase=%s (%v)", pvName, phase, time.Since(start))
return nil
} else {
Logf("PersistentVolume %s found but phase is %s instead of %s.", pvName, pv.Status.Phase, phase)
}
}
}
return fmt.Errorf("PersistentVolume %s not in phase %s within %v", pvName, phase, timeout)
}
// WaitForStatefulSetReplicasReady waits for all replicas of a StatefulSet to become ready or until timeout occurs, whichever comes first.
func WaitForStatefulSetReplicasReady(statefulSetName, ns string, c clientset.Interface, Poll, timeout time.Duration) error {
Logf("Waiting up to %v for StatefulSet %s to have all replicas ready", timeout, statefulSetName)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
sts, err := c.AppsV1().StatefulSets(ns).Get(statefulSetName, metav1.GetOptions{})
if err != nil {
Logf("Get StatefulSet %s failed, ignoring for %v: %v", statefulSetName, Poll, err)
continue
} else {
if sts.Status.ReadyReplicas == *sts.Spec.Replicas {
Logf("All %d replicas of StatefulSet %s are ready. (%v)", sts.Status.ReadyReplicas, statefulSetName, time.Since(start))
return nil
} else {
Logf("StatefulSet %s found but there are %d ready replicas and %d total replicas.", statefulSetName, sts.Status.ReadyReplicas, *sts.Spec.Replicas)
}
}
}
return fmt.Errorf("StatefulSet %s still has unready pods within %v", statefulSetName, timeout)
}
// WaitForPersistentVolumeDeleted waits for a PersistentVolume to get deleted or until timeout occurs, whichever comes first.
func WaitForPersistentVolumeDeleted(c clientset.Interface, pvName string, Poll, timeout time.Duration) error {
Logf("Waiting up to %v for PersistentVolume %s to get deleted", timeout, pvName)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
pv, err := c.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{})
if err == nil {
Logf("PersistentVolume %s found and phase=%s (%v)", pvName, pv.Status.Phase, time.Since(start))
continue
} else {
if apierrs.IsNotFound(err) {
Logf("PersistentVolume %s was removed", pvName)
return nil
} else {
Logf("Get persistent volume %s in failed, ignoring for %v: %v", pvName, Poll, err)
}
}
}
return fmt.Errorf("PersistentVolume %s still exists within %v", pvName, timeout)
}
// WaitForPersistentVolumeClaimPhase waits for a PersistentVolumeClaim to be in a specific phase or until timeout occurs, whichever comes first.
func WaitForPersistentVolumeClaimPhase(phase v1.PersistentVolumeClaimPhase, c clientset.Interface, ns string, pvcName string, Poll, timeout time.Duration) error {
Logf("Waiting up to %v for PersistentVolumeClaim %s to have phase %s", timeout, pvcName, phase)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
pvc, err := c.CoreV1().PersistentVolumeClaims(ns).Get(pvcName, metav1.GetOptions{})
if err != nil {
Logf("Failed to get claim %q, retrying in %v. Error: %v", pvcName, Poll, err)
continue
} else {
if pvc.Status.Phase == phase {
Logf("PersistentVolumeClaim %s found and phase=%s (%v)", pvcName, phase, time.Since(start))
return nil
} else {
Logf("PersistentVolumeClaim %s found but phase is %s instead of %s.", pvcName, pvc.Status.Phase, phase)
}
}
}
return fmt.Errorf("PersistentVolumeClaim %s not in phase %s within %v", pvcName, phase, timeout)
}
// CreateTestingNS should be used by every test, note that we append a common prefix to the provided test name.
// Please see NewFramework instead of using this directly.
func CreateTestingNS(baseName string, c clientset.Interface, labels map[string]string) (*v1.Namespace, error) {
if labels == nil {
labels = map[string]string{}
}
labels["e2e-run"] = string(RunId)
namespaceObj := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
GenerateName: fmt.Sprintf("e2e-tests-%v-", baseName),
Namespace: "",
Labels: labels,
},
Status: v1.NamespaceStatus{},
}
// Be robust about making the namespace creation call.
var got *v1.Namespace
if err := wait.PollImmediate(Poll, 30*time.Second, func() (bool, error) {
var err error
got, err = c.CoreV1().Namespaces().Create(namespaceObj)
if err != nil {
Logf("Unexpected error while creating namespace: %v", err)
return false, nil
}
return true, nil
}); err != nil {
return nil, err
}
if TestContext.VerifyServiceAccount {
if err := WaitForDefaultServiceAccountInNamespace(c, got.Name); err != nil {
// Even if we fail to create serviceAccount in the namespace,
// we have successfully create a namespace.
// So, return the created namespace.
return got, err
}
}
return got, nil
}
// CheckTestingNSDeletedExcept checks whether all e2e based existing namespaces are in the Terminating state
// and waits until they are finally deleted. It ignores namespace skip.
func CheckTestingNSDeletedExcept(c clientset.Interface, skip string) error {
// TODO: Since we don't have support for bulk resource deletion in the API,
// while deleting a namespace we are deleting all objects from that namespace
// one by one (one deletion == one API call). This basically exposes us to
// throttling - currently controller-manager has a limit of max 20 QPS.
// Once #10217 is implemented and used in namespace-controller, deleting all
// object from a given namespace should be much faster and we will be able
// to lower this timeout.
// However, now Density test is producing ~26000 events and Load capacity test
// is producing ~35000 events, thus assuming there are no other requests it will
// take ~30 minutes to fully delete the namespace. Thus I'm setting it to 60
// minutes to avoid any timeouts here.
timeout := 60 * time.Minute
Logf("Waiting for terminating namespaces to be deleted...")
for start := time.Now(); time.Since(start) < timeout; time.Sleep(15 * time.Second) {
namespaces, err := c.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
Logf("Listing namespaces failed: %v", err)
continue
}
terminating := 0
for _, ns := range namespaces.Items {
if strings.HasPrefix(ns.ObjectMeta.Name, "e2e-tests-") && ns.ObjectMeta.Name != skip {
if ns.Status.Phase == v1.NamespaceActive {
return fmt.Errorf("Namespace %s is active", ns.ObjectMeta.Name)
}
terminating++
}
}
if terminating == 0 {
return nil
}
}
return fmt.Errorf("Waiting for terminating namespaces to be deleted timed out")
}
// deleteNS deletes the provided namespace, waits for it to be completely deleted, and then checks
// whether there are any pods remaining in a non-terminating state.
func deleteNS(c clientset.Interface, clientPool dynamic.ClientPool, namespace string, timeout time.Duration) error {
startTime := time.Now()
if err := c.CoreV1().Namespaces().Delete(namespace, nil); err != nil {
return err
}
// wait for namespace to delete or timeout.
err := wait.PollImmediate(2*time.Second, timeout, func() (bool, error) {
if _, err := c.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{}); err != nil {
if apierrs.IsNotFound(err) {
return true, nil
}
Logf("Error while waiting for namespace to be terminated: %v", err)
return false, nil
}
return false, nil
})
// verify there is no more remaining content in the namespace
remainingContent, cerr := hasRemainingContent(c, clientPool, namespace)
if cerr != nil {
return cerr
}
// if content remains, let's dump information about the namespace, and system for flake debugging.
remainingPods := 0
missingTimestamp := 0
if remainingContent {
// log information about namespace, and set of namespaces in api server to help flake detection
logNamespace(c, namespace)
logNamespaces(c, namespace)
// if we can, check if there were pods remaining with no timestamp.
remainingPods, missingTimestamp, _ = countRemainingPods(c, namespace)
}
// a timeout waiting for namespace deletion happened!
if err != nil {
// some content remains in the namespace
if remainingContent {
// pods remain
if remainingPods > 0 {
if missingTimestamp != 0 {
// pods remained, but were not undergoing deletion (namespace controller is probably culprit)
return fmt.Errorf("namespace %v was not deleted with limit: %v, pods remaining: %v, pods missing deletion timestamp: %v", namespace, err, remainingPods, missingTimestamp)
}
// but they were all undergoing deletion (kubelet is probably culprit, check NodeLost)
return fmt.Errorf("namespace %v was not deleted with limit: %v, pods remaining: %v", namespace, err, remainingPods)
}
// other content remains (namespace controller is probably screwed up)
return fmt.Errorf("namespace %v was not deleted with limit: %v, namespaced content other than pods remain", namespace, err)
}
// no remaining content, but namespace was not deleted (namespace controller is probably wedged)
return fmt.Errorf("namespace %v was not deleted with limit: %v, namespace is empty but is not yet removed", namespace, err)
}
Logf("namespace %v deletion completed in %s", namespace, time.Now().Sub(startTime))
return nil
}
// logNamespaces logs the number of namespaces by phase
// namespace is the namespace the test was operating against that failed to delete so it can be grepped in logs
func logNamespaces(c clientset.Interface, namespace string) {
namespaceList, err := c.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
Logf("namespace: %v, unable to list namespaces: %v", namespace, err)
return
}
numActive := 0
numTerminating := 0
for _, namespace := range namespaceList.Items {
if namespace.Status.Phase == v1.NamespaceActive {
numActive++
} else {
numTerminating++
}
}
Logf("namespace: %v, total namespaces: %v, active: %v, terminating: %v", namespace, len(namespaceList.Items), numActive, numTerminating)
}
// logNamespace logs detail about a namespace
func logNamespace(c clientset.Interface, namespace string) {
ns, err := c.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
if err != nil {
if apierrs.IsNotFound(err) {
Logf("namespace: %v no longer exists", namespace)
return
}
Logf("namespace: %v, unable to get namespace due to error: %v", namespace, err)
return
}
Logf("namespace: %v, DeletionTimetamp: %v, Finalizers: %v, Phase: %v", ns.Name, ns.DeletionTimestamp, ns.Spec.Finalizers, ns.Status.Phase)
}
// countRemainingPods queries the server to count number of remaining pods, and number of pods that had a missing deletion timestamp.
func countRemainingPods(c clientset.Interface, namespace string) (int, int, error) {
// check for remaining pods
pods, err := c.CoreV1().Pods(namespace).List(metav1.ListOptions{})
if err != nil {
return 0, 0, err
}
// nothing remains!
if len(pods.Items) == 0 {
return 0, 0, nil
}
// stuff remains, log about it
logPodStates(pods.Items)
// check if there were any pods with missing deletion timestamp
numPods := len(pods.Items)
missingTimestamp := 0
for _, pod := range pods.Items {
if pod.DeletionTimestamp == nil {
missingTimestamp++
}
}
return numPods, missingTimestamp, nil
}
// isDynamicDiscoveryError returns true if the error is a group discovery error
// only for groups expected to be created/deleted dynamically during e2e tests
func isDynamicDiscoveryError(err error) bool {
if !discovery.IsGroupDiscoveryFailedError(err) {
return false
}
discoveryErr := err.(*discovery.ErrGroupDiscoveryFailed)
for gv := range discoveryErr.Groups {
switch gv.Group {
case "mygroup.example.com":
// custom_resource_definition
// garbage_collector
case "wardle.k8s.io":
// aggregator
default:
Logf("discovery error for unexpected group: %#v", gv)
return false
}
}
return true
}
// hasRemainingContent checks if there is remaining content in the namespace via API discovery
func hasRemainingContent(c clientset.Interface, clientPool dynamic.ClientPool, namespace string) (bool, error) {
// some tests generate their own framework.Client rather than the default
// TODO: ensure every test call has a configured clientPool
if clientPool == nil {
return false, nil
}
// find out what content is supported on the server
// Since extension apiserver is not always available, e.g. metrics server sometimes goes down,
// add retry here.
resources, err := waitForServerPreferredNamespacedResources(c.Discovery(), 30*time.Second)
if err != nil {
return false, err
}
groupVersionResources, err := discovery.GroupVersionResources(resources)
if err != nil {
return false, err
}
// TODO: temporary hack for https://github.com/kubernetes/kubernetes/issues/31798
ignoredResources := sets.NewString("bindings")
contentRemaining := false
// dump how many of resource type is on the server in a log.
for gvr := range groupVersionResources {
// get a client for this group version...
dynamicClient, err := clientPool.ClientForGroupVersionResource(gvr)
if err != nil {
// not all resource types support list, so some errors here are normal depending on the resource type.
Logf("namespace: %s, unable to get client - gvr: %v, error: %v", namespace, gvr, err)
continue
}
// get the api resource
apiResource := metav1.APIResource{Name: gvr.Resource, Namespaced: true}
// TODO: temporary hack for https://github.com/kubernetes/kubernetes/issues/31798
if ignoredResources.Has(apiResource.Name) {
Logf("namespace: %s, resource: %s, ignored listing per whitelist", namespace, apiResource.Name)
continue
}
obj, err := dynamicClient.Resource(&apiResource, namespace).List(metav1.ListOptions{})
if err != nil {
// not all resources support list, so we ignore those
if apierrs.IsMethodNotSupported(err) || apierrs.IsNotFound(err) || apierrs.IsForbidden(err) {
continue
}
// skip unavailable servers
if apierrs.IsServiceUnavailable(err) {
continue
}
return false, err
}
unstructuredList, ok := obj.(*unstructured.UnstructuredList)
if !ok {
return false, fmt.Errorf("namespace: %s, resource: %s, expected *unstructured.UnstructuredList, got %#v", namespace, apiResource.Name, obj)
}
if len(unstructuredList.Items) > 0 {
Logf("namespace: %s, resource: %s, items remaining: %v", namespace, apiResource.Name, len(unstructuredList.Items))
contentRemaining = true
}
}
return contentRemaining, nil
}
func ContainerInitInvariant(older, newer runtime.Object) error {
oldPod := older.(*v1.Pod)
newPod := newer.(*v1.Pod)
if len(oldPod.Spec.InitContainers) == 0 {
return nil
}
if len(oldPod.Spec.InitContainers) != len(newPod.Spec.InitContainers) {
return fmt.Errorf("init container list changed")
}
if oldPod.UID != newPod.UID {
return fmt.Errorf("two different pods exist in the condition: %s vs %s", oldPod.UID, newPod.UID)
}
if err := initContainersInvariants(oldPod); err != nil {
return err
}
if err := initContainersInvariants(newPod); err != nil {
return err
}
oldInit, _, _ := podInitialized(oldPod)
newInit, _, _ := podInitialized(newPod)
if oldInit && !newInit {
// TODO: we may in the future enable resetting PodInitialized = false if the kubelet needs to restart it
// from scratch
return fmt.Errorf("pod cannot be initialized and then regress to not being initialized")
}
return nil
}
func podInitialized(pod *v1.Pod) (ok bool, failed bool, err error) {
allInit := true
initFailed := false
for _, s := range pod.Status.InitContainerStatuses {
switch {
case initFailed && s.State.Waiting == nil:
return allInit, initFailed, fmt.Errorf("container %s is after a failed container but isn't waiting", s.Name)
case allInit && s.State.Waiting == nil:
return allInit, initFailed, fmt.Errorf("container %s is after an initializing container but isn't waiting", s.Name)
case s.State.Terminated == nil:
allInit = false
case s.State.Terminated.ExitCode != 0:
allInit = false
initFailed = true
case !s.Ready:
return allInit, initFailed, fmt.Errorf("container %s initialized but isn't marked as ready", s.Name)
}
}
return allInit, initFailed, nil
}
func initContainersInvariants(pod *v1.Pod) error {
allInit, initFailed, err := podInitialized(pod)
if err != nil {
return err
}
if !allInit || initFailed {
for _, s := range pod.Status.ContainerStatuses {
if s.State.Waiting == nil || s.RestartCount != 0 {
return fmt.Errorf("container %s is not waiting but initialization not complete", s.Name)
}
if s.State.Waiting.Reason != "PodInitializing" {
return fmt.Errorf("container %s should have reason PodInitializing: %s", s.Name, s.State.Waiting.Reason)
}
}
}
_, c := podutil.GetPodCondition(&pod.Status, v1.PodInitialized)
if c == nil {
return fmt.Errorf("pod does not have initialized condition")
}
if c.LastTransitionTime.IsZero() {
return fmt.Errorf("PodInitialized condition should always have a transition time")
}
switch {
case c.Status == v1.ConditionUnknown:
return fmt.Errorf("PodInitialized condition should never be Unknown")
case c.Status == v1.ConditionTrue && (initFailed || !allInit):
return fmt.Errorf("PodInitialized condition was True but all not all containers initialized")
case c.Status == v1.ConditionFalse && (!initFailed && allInit):
return fmt.Errorf("PodInitialized condition was False but all containers initialized")
}
return nil
}
type InvariantFunc func(older, newer runtime.Object) error
func CheckInvariants(events []watch.Event, fns ...InvariantFunc) error {
errs := sets.NewString()
for i := range events {
j := i + 1
if j >= len(events) {
continue
}
for _, fn := range fns {
if err := fn(events[i].Object, events[j].Object); err != nil {
errs.Insert(err.Error())
}
}
}
if errs.Len() > 0 {
return fmt.Errorf("invariants violated:\n* %s", strings.Join(errs.List(), "\n* "))
}
return nil
}
// Waits default amount of time (PodStartTimeout) for the specified pod to become running.
// Returns an error if timeout occurs first, or pod goes in to failed state.
func WaitForPodRunningInNamespace(c clientset.Interface, pod *v1.Pod) error {
if pod.Status.Phase == v1.PodRunning {
return nil
}
return WaitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace, PodStartTimeout)
}
// Waits default amount of time (PodStartTimeout) for the specified pod to become running.
// Returns an error if timeout occurs first, or pod goes in to failed state.
func WaitForPodNameRunningInNamespace(c clientset.Interface, podName, namespace string) error {
return WaitTimeoutForPodRunningInNamespace(c, podName, namespace, PodStartTimeout)
}
// Waits an extended amount of time (slowPodStartTimeout) for the specified pod to become running.
// The resourceVersion is used when Watching object changes, it tells since when we care
// about changes to the pod. Returns an error if timeout occurs first, or pod goes in to failed state.
func waitForPodRunningInNamespaceSlow(c clientset.Interface, podName, namespace string) error {
return WaitTimeoutForPodRunningInNamespace(c, podName, namespace, slowPodStartTimeout)
}
func WaitTimeoutForPodRunningInNamespace(c clientset.Interface, podName, namespace string, timeout time.Duration) error {
return wait.PollImmediate(Poll, timeout, podRunning(c, podName, namespace))
}
func podRunning(c clientset.Interface, podName, namespace string) wait.ConditionFunc {
return func() (bool, error) {
pod, err := c.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{})
if err != nil {
return false, err
}
switch pod.Status.Phase {
case v1.PodRunning:
return true, nil
case v1.PodFailed, v1.PodSucceeded:
return false, conditions.ErrPodCompleted
}
return false, nil
}
}
// Waits default amount of time (DefaultPodDeletionTimeout) for the specified pod to stop running.
// Returns an error if timeout occurs first.
func WaitForPodNoLongerRunningInNamespace(c clientset.Interface, podName, namespace string) error {
return WaitTimeoutForPodNoLongerRunningInNamespace(c, podName, namespace, DefaultPodDeletionTimeout)
}
func WaitTimeoutForPodNoLongerRunningInNamespace(c clientset.Interface, podName, namespace string, timeout time.Duration) error {
return wait.PollImmediate(Poll, timeout, podCompleted(c, podName, namespace))
}
func podCompleted(c clientset.Interface, podName, namespace string) wait.ConditionFunc {
return func() (bool, error) {
pod, err := c.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{})
if err != nil {
return false, err
}
switch pod.Status.Phase {
case v1.PodFailed, v1.PodSucceeded:
return true, nil
}
return false, nil
}
}
func waitTimeoutForPodReadyInNamespace(c clientset.Interface, podName, namespace string, timeout time.Duration) error {
return wait.PollImmediate(Poll, timeout, podRunningAndReady(c, podName, namespace))
}
func podRunningAndReady(c clientset.Interface, podName, namespace string) wait.ConditionFunc {
return func() (bool, error) {
pod, err := c.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{})
if err != nil {
return false, err
}
switch pod.Status.Phase {
case v1.PodFailed, v1.PodSucceeded:
return false, conditions.ErrPodCompleted
case v1.PodRunning:
return podutil.IsPodReady(pod), nil
}
return false, nil
}
}
// WaitForPodNotPending returns an error if it took too long for the pod to go out of pending state.
// The resourceVersion is used when Watching object changes, it tells since when we care
// about changes to the pod.
func WaitForPodNotPending(c clientset.Interface, ns, podName string) error {
return wait.PollImmediate(Poll, PodStartTimeout, podNotPending(c, podName, ns))
}
func podNotPending(c clientset.Interface, podName, namespace string) wait.ConditionFunc {
return func() (bool, error) {
pod, err := c.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{})
if err != nil {
return false, err
}
switch pod.Status.Phase {
case v1.PodPending:
return false, nil
default:
return true, nil
}
}
}
// waitForPodTerminatedInNamespace returns an error if it takes too long for the pod to terminate,
// if the pod Get api returns an error (IsNotFound or other), or if the pod failed (and thus did not
// terminate) with an unexpected reason. Typically called to test that the passed-in pod is fully
// terminated (reason==""), but may be called to detect if a pod did *not* terminate according to
// the supplied reason.
func waitForPodTerminatedInNamespace(c clientset.Interface, podName, reason, namespace string) error {
return WaitForPodCondition(c, namespace, podName, "terminated due to deadline exceeded", PodStartTimeout, func(pod *v1.Pod) (bool, error) {
// Only consider Failed pods. Successful pods will be deleted and detected in
// waitForPodCondition's Get call returning `IsNotFound`
if pod.Status.Phase == v1.PodFailed {
if pod.Status.Reason == reason { // short-circuit waitForPodCondition's loop
return true, nil
} else {
return true, fmt.Errorf("Expected pod %q in namespace %q to be terminated with reason %q, got reason: %q", podName, namespace, reason, pod.Status.Reason)
}
}
return false, nil
})
}
// waitForPodNotFoundInNamespace returns an error if it takes too long for the pod to fully terminate.
// Unlike `waitForPodTerminatedInNamespace`, the pod's Phase and Reason are ignored. If the pod Get
// api returns IsNotFound then the wait stops and nil is returned. If the Get api returns an error other
// than "not found" then that error is returned and the wait stops.
func waitForPodNotFoundInNamespace(c clientset.Interface, podName, ns string, timeout time.Duration) error {
return wait.PollImmediate(Poll, timeout, func() (bool, error) {
_, err := c.CoreV1().Pods(ns).Get(podName, metav1.GetOptions{})
if apierrs.IsNotFound(err) {
return true, nil // done
}
if err != nil {
return true, err // stop wait with error
}
return false, nil
})
}
// waitForPodSuccessInNamespaceTimeout returns nil if the pod reached state success, or an error if it reached failure or ran too long.
func waitForPodSuccessInNamespaceTimeout(c clientset.Interface, podName string, namespace string, timeout time.Duration) error {
return WaitForPodCondition(c, namespace, podName, "success or failure", timeout, func(pod *v1.Pod) (bool, error) {
if pod.Spec.RestartPolicy == v1.RestartPolicyAlways {
return true, fmt.Errorf("pod %q will never terminate with a succeeded state since its restart policy is Always", podName)
}
switch pod.Status.Phase {
case v1.PodSucceeded:
By("Saw pod success")
return true, nil
case v1.PodFailed:
return true, fmt.Errorf("pod %q failed with status: %+v", podName, pod.Status)
default:
return false, nil
}
})
}
// WaitForPodSuccessInNamespace returns nil if the pod reached state success, or an error if it reached failure or until podStartupTimeout.
func WaitForPodSuccessInNamespace(c clientset.Interface, podName string, namespace string) error {
return waitForPodSuccessInNamespaceTimeout(c, podName, namespace, PodStartTimeout)
}
// WaitForPodSuccessInNamespaceSlow returns nil if the pod reached state success, or an error if it reached failure or until slowPodStartupTimeout.
func WaitForPodSuccessInNamespaceSlow(c clientset.Interface, podName string, namespace string) error {
return waitForPodSuccessInNamespaceTimeout(c, podName, namespace, slowPodStartTimeout)
}
// WaitForRCToStabilize waits till the RC has a matching generation/replica count between spec and status.
func WaitForRCToStabilize(c clientset.Interface, ns, name string, timeout time.Duration) error {
options := metav1.ListOptions{FieldSelector: fields.Set{
"metadata.name": name,
"metadata.namespace": ns,
}.AsSelector().String()}
w, err := c.CoreV1().ReplicationControllers(ns).Watch(options)
if err != nil {
return err
}
_, err = watch.Until(timeout, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Deleted:
return false, apierrs.NewNotFound(schema.GroupResource{Resource: "replicationcontrollers"}, "")
}
switch rc := event.Object.(type) {
case *v1.ReplicationController:
if rc.Name == name && rc.Namespace == ns &&
rc.Generation <= rc.Status.ObservedGeneration &&
*(rc.Spec.Replicas) == rc.Status.Replicas {
return true, nil
}
Logf("Waiting for rc %s to stabilize, generation %v observed generation %v spec.replicas %d status.replicas %d",
name, rc.Generation, rc.Status.ObservedGeneration, *(rc.Spec.Replicas), rc.Status.Replicas)
}
return false, nil
})
return err
}
func WaitForPodToDisappear(c clientset.Interface, ns, podName string, label labels.Selector, interval, timeout time.Duration) error {
return wait.PollImmediate(interval, timeout, func() (bool, error) {
Logf("Waiting for pod %s to disappear", podName)
options := metav1.ListOptions{LabelSelector: label.String()}
pods, err := c.CoreV1().Pods(ns).List(options)
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
found := false
for _, pod := range pods.Items {
if pod.Name == podName {
Logf("Pod %s still exists", podName)
found = true
break
}
}
if !found {
Logf("Pod %s no longer exists", podName)
return true, nil
}
return false, nil
})
}
// WaitForPodNameUnschedulableInNamespace returns an error if it takes too long for the pod to become Pending
// and have condition Status equal to Unschedulable,
// if the pod Get api returns an error (IsNotFound or other), or if the pod failed with an unexpected reason.
// Typically called to test that the passed-in pod is Pending and Unschedulable.
func WaitForPodNameUnschedulableInNamespace(c clientset.Interface, podName, namespace string) error {
return WaitForPodCondition(c, namespace, podName, "Unschedulable", PodStartTimeout, func(pod *v1.Pod) (bool, error) {
// Only consider Failed pods. Successful pods will be deleted and detected in
// waitForPodCondition's Get call returning `IsNotFound`
if pod.Status.Phase == v1.PodPending {
for _, cond := range pod.Status.Conditions {
if cond.Type == v1.PodScheduled && cond.Status == v1.ConditionFalse && cond.Reason == "Unschedulable" {
return true, nil
}
}
}
if pod.Status.Phase == v1.PodRunning || pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed {
return true, fmt.Errorf("Expected pod %q in namespace %q to be in phase Pending, but got phase: %v", podName, namespace, pod.Status.Phase)
}
return false, nil
})
}
// WaitForService waits until the service appears (exist == true), or disappears (exist == false)
func WaitForService(c clientset.Interface, namespace, name string, exist bool, interval, timeout time.Duration) error {
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
_, err := c.CoreV1().Services(namespace).Get(name, metav1.GetOptions{})
switch {
case err == nil:
Logf("Service %s in namespace %s found.", name, namespace)
return exist, nil
case apierrs.IsNotFound(err):
Logf("Service %s in namespace %s disappeared.", name, namespace)
return !exist, nil
case !testutils.IsRetryableAPIError(err):
Logf("Non-retryable failure while getting service.")
return false, err
default:
Logf("Get service %s in namespace %s failed: %v", name, namespace, err)
return false, nil
}
})
if err != nil {
stateMsg := map[bool]string{true: "to appear", false: "to disappear"}
return fmt.Errorf("error waiting for service %s/%s %s: %v", namespace, name, stateMsg[exist], err)
}
return nil
}
// WaitForServiceWithSelector waits until any service with given selector appears (exist == true), or disappears (exist == false)
func WaitForServiceWithSelector(c clientset.Interface, namespace string, selector labels.Selector, exist bool, interval,
timeout time.Duration) error {
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
services, err := c.CoreV1().Services(namespace).List(metav1.ListOptions{LabelSelector: selector.String()})
switch {
case len(services.Items) != 0:
Logf("Service with %s in namespace %s found.", selector.String(), namespace)
return exist, nil
case len(services.Items) == 0:
Logf("Service with %s in namespace %s disappeared.", selector.String(), namespace)
return !exist, nil
case !testutils.IsRetryableAPIError(err):
Logf("Non-retryable failure while listing service.")
return false, err
default:
Logf("List service with %s in namespace %s failed: %v", selector.String(), namespace, err)
return false, nil
}
})
if err != nil {
stateMsg := map[bool]string{true: "to appear", false: "to disappear"}
return fmt.Errorf("error waiting for service with %s in namespace %s %s: %v", selector.String(), namespace, stateMsg[exist], err)
}
return nil
}
//WaitForServiceEndpointsNum waits until the amount of endpoints that implement service to expectNum.
func WaitForServiceEndpointsNum(c clientset.Interface, namespace, serviceName string, expectNum int, interval, timeout time.Duration) error {
return wait.Poll(interval, timeout, func() (bool, error) {
Logf("Waiting for amount of service:%s endpoints to be %d", serviceName, expectNum)
list, err := c.CoreV1().Endpoints(namespace).List(metav1.ListOptions{})
if err != nil {
return false, err
}
for _, e := range list.Items {
if e.Name == serviceName && countEndpointsNum(&e) == expectNum {
return true, nil
}
}
return false, nil
})
}
func countEndpointsNum(e *v1.Endpoints) int {
num := 0
for _, sub := range e.Subsets {
num += len(sub.Addresses)
}
return num
}
func WaitForEndpoint(c clientset.Interface, ns, name string) error {
for t := time.Now(); time.Since(t) < EndpointRegisterTimeout; time.Sleep(Poll) {
endpoint, err := c.CoreV1().Endpoints(ns).Get(name, metav1.GetOptions{})
if apierrs.IsNotFound(err) {
Logf("Endpoint %s/%s is not ready yet", ns, name)
continue
}
Expect(err).NotTo(HaveOccurred())
if len(endpoint.Subsets) == 0 || len(endpoint.Subsets[0].Addresses) == 0 {
Logf("Endpoint %s/%s is not ready yet", ns, name)
continue
} else {
return nil
}
}
return fmt.Errorf("Failed to get endpoints for %s/%s", ns, name)
}
// Context for checking pods responses by issuing GETs to them (via the API
// proxy) and verifying that they answer with there own pod name.
type podProxyResponseChecker struct {
c clientset.Interface
ns string
label labels.Selector
controllerName string
respondName bool // Whether the pod should respond with its own name.
pods *v1.PodList
}
func PodProxyResponseChecker(c clientset.Interface, ns string, label labels.Selector, controllerName string, respondName bool, pods *v1.PodList) podProxyResponseChecker {
return podProxyResponseChecker{c, ns, label, controllerName, respondName, pods}
}
// CheckAllResponses issues GETs to all pods in the context and verify they
// reply with their own pod name.
func (r podProxyResponseChecker) CheckAllResponses() (done bool, err error) {
successes := 0
options := metav1.ListOptions{LabelSelector: r.label.String()}
currentPods, err := r.c.CoreV1().Pods(r.ns).List(options)
Expect(err).NotTo(HaveOccurred())
for i, pod := range r.pods.Items {
// Check that the replica list remains unchanged, otherwise we have problems.
if !isElementOf(pod.UID, currentPods) {
return false, fmt.Errorf("pod with UID %s is no longer a member of the replica set. Must have been restarted for some reason. Current replica set: %v", pod.UID, currentPods)
}
ctx, cancel := context.WithTimeout(context.Background(), SingleCallTimeout)
defer cancel()
body, err := r.c.CoreV1().RESTClient().Get().
Context(ctx).
Namespace(r.ns).
Resource("pods").
SubResource("proxy").
Name(string(pod.Name)).
Do().
Raw()
if err != nil {
if ctx.Err() != nil {
// We may encounter errors here because of a race between the pod readiness and apiserver
// proxy. So, we log the error and retry if this occurs.
Logf("Controller %s: Failed to Get from replica %d [%s]: %v\n pod status: %#v", r.controllerName, i+1, pod.Name, err, pod.Status)
return false, nil
}
Logf("Controller %s: Failed to GET from replica %d [%s]: %v\npod status: %#v", r.controllerName, i+1, pod.Name, err, pod.Status)
continue
}
// The response checker expects the pod's name unless !respondName, in
// which case it just checks for a non-empty response.
got := string(body)
what := ""
if r.respondName {
what = "expected"
want := pod.Name
if got != want {
Logf("Controller %s: Replica %d [%s] expected response %q but got %q",
r.controllerName, i+1, pod.Name, want, got)
continue
}
} else {
what = "non-empty"
if len(got) == 0 {
Logf("Controller %s: Replica %d [%s] expected non-empty response",
r.controllerName, i+1, pod.Name)
continue
}
}
successes++
Logf("Controller %s: Got %s result from replica %d [%s]: %q, %d of %d required successes so far",
r.controllerName, what, i+1, pod.Name, got, successes, len(r.pods.Items))
}
if successes < len(r.pods.Items) {
return false, nil
}
return true, nil
}
// ServerVersionGTE returns true if v is greater than or equal to the server
// version.
//
// TODO(18726): This should be incorporated into client.VersionInterface.
func ServerVersionGTE(v *utilversion.Version, c discovery.ServerVersionInterface) (bool, error) {
serverVersion, err := c.ServerVersion()
if err != nil {
return false, fmt.Errorf("Unable to get server version: %v", err)
}
sv, err := utilversion.ParseSemantic(serverVersion.GitVersion)
if err != nil {
return false, fmt.Errorf("Unable to parse server version %q: %v", serverVersion.GitVersion, err)
}
return sv.AtLeast(v), nil
}
func SkipUnlessKubectlVersionGTE(v *utilversion.Version) {
gte, err := KubectlVersionGTE(v)
if err != nil {
Failf("Failed to get kubectl version: %v", err)
}
if !gte {
Skipf("Not supported for kubectl versions before %q", v)
}
}
// KubectlVersionGTE returns true if the kubectl version is greater than or
// equal to v.
func KubectlVersionGTE(v *utilversion.Version) (bool, error) {
kv, err := KubectlVersion()
if err != nil {
return false, err
}
return kv.AtLeast(v), nil
}
// KubectlVersion gets the version of kubectl that's currently being used (see
// --kubectl-path in e2e.go to use an alternate kubectl).
func KubectlVersion() (*utilversion.Version, error) {
output := RunKubectlOrDie("version", "--client")
matches := gitVersionRegexp.FindStringSubmatch(output)
if len(matches) != 2 {
return nil, fmt.Errorf("Could not find kubectl version in output %v", output)
}
// Don't use the full match, as it contains "GitVersion:\"" and a
// trailing "\"". Just use the submatch.
return utilversion.ParseSemantic(matches[1])
}
func PodsResponding(c clientset.Interface, ns, name string, wantName bool, pods *v1.PodList) error {
By("trying to dial each unique pod")
label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
return wait.PollImmediate(Poll, podRespondingTimeout, PodProxyResponseChecker(c, ns, label, name, wantName, pods).CheckAllResponses)
}
func PodsCreated(c clientset.Interface, ns, name string, replicas int32) (*v1.PodList, error) {
label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
return PodsCreatedByLabel(c, ns, name, replicas, label)
}
func PodsCreatedByLabel(c clientset.Interface, ns, name string, replicas int32, label labels.Selector) (*v1.PodList, error) {
timeout := 2 * time.Minute
for start := time.Now(); time.Since(start) < timeout; time.Sleep(5 * time.Second) {
options := metav1.ListOptions{LabelSelector: label.String()}
// List the pods, making sure we observe all the replicas.
pods, err := c.CoreV1().Pods(ns).List(options)
if err != nil {
return nil, err
}
created := []v1.Pod{}
for _, pod := range pods.Items {
if pod.DeletionTimestamp != nil {
continue
}
created = append(created, pod)
}
Logf("Pod name %s: Found %d pods out of %d", name, len(created), replicas)
if int32(len(created)) == replicas {
pods.Items = created
return pods, nil
}
}
return nil, fmt.Errorf("Pod name %s: Gave up waiting %v for %d pods to come up", name, timeout, replicas)
}
func podsRunning(c clientset.Interface, pods *v1.PodList) []error {
// Wait for the pods to enter the running state. Waiting loops until the pods
// are running so non-running pods cause a timeout for this test.
By("ensuring each pod is running")
e := []error{}
error_chan := make(chan error)
for _, pod := range pods.Items {
go func(p v1.Pod) {
error_chan <- WaitForPodRunningInNamespace(c, &p)
}(pod)
}
for range pods.Items {
err := <-error_chan
if err != nil {
e = append(e, err)
}
}
return e
}
func VerifyPods(c clientset.Interface, ns, name string, wantName bool, replicas int32) error {
return podRunningMaybeResponding(c, ns, name, wantName, replicas, true)
}
func VerifyPodsRunning(c clientset.Interface, ns, name string, wantName bool, replicas int32) error {
return podRunningMaybeResponding(c, ns, name, wantName, replicas, false)
}
func podRunningMaybeResponding(c clientset.Interface, ns, name string, wantName bool, replicas int32, checkResponding bool) error {
pods, err := PodsCreated(c, ns, name, replicas)
if err != nil {
return err
}
e := podsRunning(c, pods)
if len(e) > 0 {
return fmt.Errorf("failed to wait for pods running: %v", e)
}
if checkResponding {
err = PodsResponding(c, ns, name, wantName, pods)
if err != nil {
return fmt.Errorf("failed to wait for pods responding: %v", err)
}
}
return nil
}
func ServiceResponding(c clientset.Interface, ns, name string) error {
By(fmt.Sprintf("trying to dial the service %s.%s via the proxy", ns, name))
return wait.PollImmediate(Poll, ServiceRespondingTimeout, func() (done bool, err error) {
proxyRequest, errProxy := GetServicesProxyRequest(c, c.CoreV1().RESTClient().Get())
if errProxy != nil {
Logf("Failed to get services proxy request: %v:", errProxy)
return false, nil
}
ctx, cancel := context.WithTimeout(context.Background(), SingleCallTimeout)
defer cancel()
body, err := proxyRequest.Namespace(ns).
Context(ctx).
Name(name).
Do().
Raw()
if err != nil {
if ctx.Err() != nil {
Failf("Failed to GET from service %s: %v", name, err)
return true, err
}
Logf("Failed to GET from service %s: %v:", name, err)
return false, nil
}
got := string(body)
if len(got) == 0 {
Logf("Service %s: expected non-empty response", name)
return false, err // stop polling
}
Logf("Service %s: found nonempty answer: %s", name, got)
return true, nil
})
}
func RestclientConfig(kubeContext string) (*clientcmdapi.Config, error) {
Logf(">>> kubeConfig: %s", TestContext.KubeConfig)
if TestContext.KubeConfig == "" {
return nil, fmt.Errorf("KubeConfig must be specified to load client config")
}
c, err := clientcmd.LoadFromFile(TestContext.KubeConfig)
if err != nil {
return nil, fmt.Errorf("error loading KubeConfig: %v", err.Error())
}
if kubeContext != "" {
Logf(">>> kubeContext: %s", kubeContext)
c.CurrentContext = kubeContext
}
return c, nil
}
type ClientConfigGetter func() (*restclient.Config, error)
func LoadConfig() (*restclient.Config, error) {
if TestContext.NodeE2E {
// This is a node e2e test, apply the node e2e configuration
return &restclient.Config{Host: TestContext.Host}, nil
}
c, err := RestclientConfig(TestContext.KubeContext)
if err != nil {
if TestContext.KubeConfig == "" {
return restclient.InClusterConfig()
} else {
return nil, err
}
}
return clientcmd.NewDefaultClientConfig(*c, &clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: TestContext.Host}}).ClientConfig()
}
func LoadInternalClientset() (*internalclientset.Clientset, error) {
config, err := LoadConfig()
if err != nil {
return nil, fmt.Errorf("error creating client: %v", err.Error())
}
return internalclientset.NewForConfig(config)
}
func LoadClientset() (*clientset.Clientset, error) {
config, err := LoadConfig()
if err != nil {
return nil, fmt.Errorf("error creating client: %v", err.Error())
}
return clientset.NewForConfig(config)
}
// randomSuffix provides a random string to append to pods,services,rcs.
// TODO: Allow service names to have the same form as names
// for pods and replication controllers so we don't
// need to use such a function and can instead
// use the UUID utility function.
func randomSuffix() string {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return strconv.Itoa(r.Int() % 10000)
}
func ExpectNoError(err error, explain ...interface{}) {
ExpectNoErrorWithOffset(1, err, explain...)
}
// ExpectNoErrorWithOffset checks if "err" is set, and if so, fails assertion while logging the error at "offset" levels above its caller
// (for example, for call chain f -> g -> ExpectNoErrorWithOffset(1, ...) error would be logged for "f").
func ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {
if err != nil {
Logf("Unexpected error occurred: %v", err)
}
ExpectWithOffset(1+offset, err).NotTo(HaveOccurred(), explain...)
}
func ExpectNoErrorWithRetries(fn func() error, maxRetries int, explain ...interface{}) {
var err error
for i := 0; i < maxRetries; i++ {
err = fn()
if err == nil {
return
}
Logf("(Attempt %d of %d) Unexpected error occurred: %v", i+1, maxRetries, err)
}
ExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)
}
// Stops everything from filePath from namespace ns and checks if everything matching selectors from the given namespace is correctly stopped.
func Cleanup(filePath, ns string, selectors ...string) {
By("using delete to clean up resources")
var nsArg string
if ns != "" {
nsArg = fmt.Sprintf("--namespace=%s", ns)
}
RunKubectlOrDie("delete", "--grace-period=0", "-f", filePath, nsArg)
AssertCleanup(ns, selectors...)
}
// Asserts that cleanup of a namespace wrt selectors occurred.
func AssertCleanup(ns string, selectors ...string) {
var nsArg string
if ns != "" {
nsArg = fmt.Sprintf("--namespace=%s", ns)
}
backoff := wait.Backoff{
Duration: 5 * time.Second,
Factor: 2,
Steps: 3,
}
var e error
verifyCleanupFunc := func() (bool, error) {
e = nil
for _, selector := range selectors {
resources := RunKubectlOrDie("get", "rc,svc", "-l", selector, "--no-headers", nsArg)
if resources != "" {
e = fmt.Errorf("Resources left running after stop:\n%s", resources)
return false, nil
}
pods := RunKubectlOrDie("get", "pods", "-l", selector, nsArg, "-o", "go-template={{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}{{ \"\\n\" }}{{ end }}{{ end }}")
if pods != "" {
e = fmt.Errorf("Pods left unterminated after stop:\n%s", pods)
return false, nil
}
}
return true, nil
}
err := wait.ExponentialBackoff(backoff, verifyCleanupFunc)
if err != nil {
Failf(e.Error())
}
}
// KubectlCmd runs the kubectl executable through the wrapper script.
func KubectlCmd(args ...string) *exec.Cmd {
defaultArgs := []string{}
// Reference a --server option so tests can run anywhere.
if TestContext.Host != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.FlagAPIServer+"="+TestContext.Host)
}
if TestContext.KubeConfig != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.RecommendedConfigPathFlag+"="+TestContext.KubeConfig)
// Reference the KubeContext
if TestContext.KubeContext != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.FlagContext+"="+TestContext.KubeContext)
}
} else {
if TestContext.CertDir != "" {
defaultArgs = append(defaultArgs,
fmt.Sprintf("--certificate-authority=%s", filepath.Join(TestContext.CertDir, "ca.crt")),
fmt.Sprintf("--client-certificate=%s", filepath.Join(TestContext.CertDir, "kubecfg.crt")),
fmt.Sprintf("--client-key=%s", filepath.Join(TestContext.CertDir, "kubecfg.key")))
}
}
kubectlArgs := append(defaultArgs, args...)
//We allow users to specify path to kubectl, so you can test either "kubectl" or "cluster/kubectl.sh"
//and so on.
cmd := exec.Command(TestContext.KubectlPath, kubectlArgs...)
//caller will invoke this and wait on it.
return cmd
}
// kubectlBuilder is used to build, customize and execute a kubectl Command.
// Add more functions to customize the builder as needed.
type kubectlBuilder struct {
cmd *exec.Cmd
timeout <-chan time.Time
}
func NewKubectlCommand(args ...string) *kubectlBuilder {
b := new(kubectlBuilder)
b.cmd = KubectlCmd(args...)
return b
}
func (b *kubectlBuilder) WithEnv(env []string) *kubectlBuilder {
b.cmd.Env = env
return b
}
func (b *kubectlBuilder) WithTimeout(t <-chan time.Time) *kubectlBuilder {
b.timeout = t
return b
}
func (b kubectlBuilder) WithStdinData(data string) *kubectlBuilder {
b.cmd.Stdin = strings.NewReader(data)
return &b
}
func (b kubectlBuilder) WithStdinReader(reader io.Reader) *kubectlBuilder {
b.cmd.Stdin = reader
return &b
}
func (b kubectlBuilder) ExecOrDie() string {
str, err := b.Exec()
// In case of i/o timeout error, try talking to the apiserver again after 2s before dying.
// Note that we're still dying after retrying so that we can get visibility to triage it further.
if isTimeout(err) {
Logf("Hit i/o timeout error, talking to the server 2s later to see if it's temporary.")
time.Sleep(2 * time.Second)
retryStr, retryErr := RunKubectl("version")
Logf("stdout: %q", retryStr)
Logf("err: %v", retryErr)
}
Expect(err).NotTo(HaveOccurred())
return str
}
func isTimeout(err error) bool {
switch err := err.(type) {
case net.Error:
if err.Timeout() {
return true
}
case *url.Error:
if err, ok := err.Err.(net.Error); ok && err.Timeout() {
return true
}
}
return false
}
func (b kubectlBuilder) Exec() (string, error) {
var stdout, stderr bytes.Buffer
cmd := b.cmd
cmd.Stdout, cmd.Stderr = &stdout, &stderr
Logf("Running '%s %s'", cmd.Path, strings.Join(cmd.Args[1:], " ")) // skip arg[0] as it is printed separately
if err := cmd.Start(); err != nil {
return "", fmt.Errorf("error starting %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v\n", cmd, cmd.Stdout, cmd.Stderr, err)
}
errCh := make(chan error, 1)
go func() {
errCh <- cmd.Wait()
}()
select {
case err := <-errCh:
if err != nil {
var rc int = 127
if ee, ok := err.(*exec.ExitError); ok {
rc = int(ee.Sys().(syscall.WaitStatus).ExitStatus())
Logf("rc: %d", rc)
}
return "", uexec.CodeExitError{
Err: fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v\n", cmd, cmd.Stdout, cmd.Stderr, err),
Code: rc,
}
}
case <-b.timeout:
b.cmd.Process.Kill()
return "", fmt.Errorf("timed out waiting for command %v:\nCommand stdout:\n%v\nstderr:\n%v\n", cmd, cmd.Stdout, cmd.Stderr)
}
Logf("stderr: %q", stderr.String())
Logf("stdout: %q", stdout.String())
return stdout.String(), nil
}
// RunKubectlOrDie is a convenience wrapper over kubectlBuilder
func RunKubectlOrDie(args ...string) string {
return NewKubectlCommand(args...).ExecOrDie()
}
// RunKubectl is a convenience wrapper over kubectlBuilder
func RunKubectl(args ...string) (string, error) {
return NewKubectlCommand(args...).Exec()
}
// RunKubectlOrDieInput is a convenience wrapper over kubectlBuilder that takes input to stdin
func RunKubectlOrDieInput(data string, args ...string) string {
return NewKubectlCommand(args...).WithStdinData(data).ExecOrDie()
}
// RunKubemciWithKubeconfig is a convenience wrapper over RunKubemciCmd
func RunKubemciWithKubeconfig(args ...string) (string, error) {
if TestContext.KubeConfig != "" {
args = append(args, "--"+clientcmd.RecommendedConfigPathFlag+"="+TestContext.KubeConfig)
}
return RunKubemciCmd(args...)
}
// RunKubemciCmd is a convenience wrapper over kubectlBuilder to run kubemci.
// It assumes that kubemci exists in PATH.
func RunKubemciCmd(args ...string) (string, error) {
// kubemci is assumed to be in PATH.
kubemci := "kubemci"
b := new(kubectlBuilder)
args = append(args, "--gcp-project="+TestContext.CloudConfig.ProjectID)
b.cmd = exec.Command(kubemci, args...)
return b.Exec()
}
func StartCmdAndStreamOutput(cmd *exec.Cmd) (stdout, stderr io.ReadCloser, err error) {
stdout, err = cmd.StdoutPipe()
if err != nil {
return
}
stderr, err = cmd.StderrPipe()
if err != nil {
return
}
Logf("Asynchronously running '%s %s'", cmd.Path, strings.Join(cmd.Args, " "))
err = cmd.Start()
return
}
// Rough equivalent of ctrl+c for cleaning up processes. Intended to be run in defer.
func TryKill(cmd *exec.Cmd) {
if err := cmd.Process.Kill(); err != nil {
Logf("ERROR failed to kill command %v! The process may leak", cmd)
}
}
// testContainerOutputMatcher runs the given pod in the given namespace and waits
// for all of the containers in the podSpec to move into the 'Success' status, and tests
// the specified container log against the given expected output using the given matcher.
func (f *Framework) testContainerOutputMatcher(scenarioName string,
pod *v1.Pod,
containerIndex int,
expectedOutput []string,
matcher func(string, ...interface{}) gomegatypes.GomegaMatcher) {
By(fmt.Sprintf("Creating a pod to test %v", scenarioName))
if containerIndex < 0 || containerIndex >= len(pod.Spec.Containers) {
Failf("Invalid container index: %d", containerIndex)
}
ExpectNoError(f.MatchContainerOutput(pod, pod.Spec.Containers[containerIndex].Name, expectedOutput, matcher))
}
// MatchContainerOutput creates a pod and waits for all it's containers to exit with success.
// It then tests that the matcher with each expectedOutput matches the output of the specified container.
func (f *Framework) MatchContainerOutput(
pod *v1.Pod,
containerName string,
expectedOutput []string,
matcher func(string, ...interface{}) gomegatypes.GomegaMatcher) error {
ns := pod.ObjectMeta.Namespace
if ns == "" {
ns = f.Namespace.Name
}
podClient := f.PodClientNS(ns)
createdPod := podClient.Create(pod)
defer func() {
By("delete the pod")
podClient.DeleteSync(createdPod.Name, &metav1.DeleteOptions{}, DefaultPodDeletionTimeout)
}()
// Wait for client pod to complete.
podErr := WaitForPodSuccessInNamespace(f.ClientSet, createdPod.Name, ns)
// Grab its logs. Get host first.
podStatus, err := podClient.Get(createdPod.Name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get pod status: %v", err)
}
if podErr != nil {
// Pod failed. Dump all logs from all containers to see what's wrong
for _, container := range podStatus.Spec.Containers {
logs, err := GetPodLogs(f.ClientSet, ns, podStatus.Name, container.Name)
if err != nil {
Logf("Failed to get logs from node %q pod %q container %q: %v",
podStatus.Spec.NodeName, podStatus.Name, container.Name, err)
continue
}
Logf("Output of node %q pod %q container %q: %s", podStatus.Spec.NodeName, podStatus.Name, container.Name, logs)
}
return fmt.Errorf("expected pod %q success: %v", createdPod.Name, podErr)
}
Logf("Trying to get logs from node %s pod %s container %s: %v",
podStatus.Spec.NodeName, podStatus.Name, containerName, err)
// Sometimes the actual containers take a second to get started, try to get logs for 60s
logs, err := GetPodLogs(f.ClientSet, ns, podStatus.Name, containerName)
if err != nil {
Logf("Failed to get logs from node %q pod %q container %q. %v",
podStatus.Spec.NodeName, podStatus.Name, containerName, err)
return fmt.Errorf("failed to get logs from %s for %s: %v", podStatus.Name, containerName, err)
}
for _, expected := range expectedOutput {
m := matcher(expected)
matches, err := m.Match(logs)
if err != nil {
return fmt.Errorf("expected %q in container output: %v", expected, err)
} else if !matches {
return fmt.Errorf("expected %q in container output: %s", expected, m.FailureMessage(logs))
}
}
return nil
}
type EventsLister func(opts metav1.ListOptions, ns string) (*v1.EventList, error)
func DumpEventsInNamespace(eventsLister EventsLister, namespace string) {
By(fmt.Sprintf("Collecting events from namespace %q.", namespace))
events, err := eventsLister(metav1.ListOptions{}, namespace)
Expect(err).NotTo(HaveOccurred())
By(fmt.Sprintf("Found %d events.", len(events.Items)))
// Sort events by their first timestamp
sortedEvents := events.Items
if len(sortedEvents) > 1 {
sort.Sort(byFirstTimestamp(sortedEvents))
}
for _, e := range sortedEvents {
Logf("At %v - event for %v: %v %v: %v", e.FirstTimestamp, e.InvolvedObject.Name, e.Source, e.Reason, e.Message)
}
// Note that we don't wait for any Cleanup to propagate, which means
// that if you delete a bunch of pods right before ending your test,
// you may or may not see the killing/deletion/Cleanup events.
}
func DumpAllNamespaceInfo(c clientset.Interface, namespace string) {
DumpEventsInNamespace(func(opts metav1.ListOptions, ns string) (*v1.EventList, error) {
return c.CoreV1().Events(ns).List(opts)
}, namespace)
// If cluster is large, then the following logs are basically useless, because:
// 1. it takes tens of minutes or hours to grab all of them
// 2. there are so many of them that working with them are mostly impossible
// So we dump them only if the cluster is relatively small.
maxNodesForDump := 20
if nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{}); err == nil {
if len(nodes.Items) <= maxNodesForDump {
dumpAllPodInfo(c)
dumpAllNodeInfo(c)
} else {
Logf("skipping dumping cluster info - cluster too large")
}
} else {
Logf("unable to fetch node list: %v", err)
}
}
// byFirstTimestamp sorts a slice of events by first timestamp, using their involvedObject's name as a tie breaker.
type byFirstTimestamp []v1.Event
func (o byFirstTimestamp) Len() int { return len(o) }
func (o byFirstTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o byFirstTimestamp) Less(i, j int) bool {
if o[i].FirstTimestamp.Equal(&o[j].FirstTimestamp) {
return o[i].InvolvedObject.Name < o[j].InvolvedObject.Name
}
return o[i].FirstTimestamp.Before(&o[j].FirstTimestamp)
}
func dumpAllPodInfo(c clientset.Interface) {
pods, err := c.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
Logf("unable to fetch pod debug info: %v", err)
}
logPodStates(pods.Items)
}
func dumpAllNodeInfo(c clientset.Interface) {
// It should be OK to list unschedulable Nodes here.
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
Logf("unable to fetch node list: %v", err)
return
}
names := make([]string, len(nodes.Items))
for ix := range nodes.Items {
names[ix] = nodes.Items[ix].Name
}
DumpNodeDebugInfo(c, names, Logf)
}
func DumpNodeDebugInfo(c clientset.Interface, nodeNames []string, logFunc func(fmt string, args ...interface{})) {
for _, n := range nodeNames {
logFunc("\nLogging node info for node %v", n)
node, err := c.CoreV1().Nodes().Get(n, metav1.GetOptions{})
if err != nil {
logFunc("Error getting node info %v", err)
}
logFunc("Node Info: %v", node)
logFunc("\nLogging kubelet events for node %v", n)
for _, e := range getNodeEvents(c, n) {
logFunc("source %v type %v message %v reason %v first ts %v last ts %v, involved obj %+v",
e.Source, e.Type, e.Message, e.Reason, e.FirstTimestamp, e.LastTimestamp, e.InvolvedObject)
}
logFunc("\nLogging pods the kubelet thinks is on node %v", n)
podList, err := GetKubeletPods(c, n)
if err != nil {
logFunc("Unable to retrieve kubelet pods for node %v: %v", n, err)
continue
}
for _, p := range podList.Items {
logFunc("%v started at %v (%d+%d container statuses recorded)", p.Name, p.Status.StartTime, len(p.Status.InitContainerStatuses), len(p.Status.ContainerStatuses))
for _, c := range p.Status.InitContainerStatuses {
logFunc("\tInit container %v ready: %v, restart count %v",
c.Name, c.Ready, c.RestartCount)
}
for _, c := range p.Status.ContainerStatuses {
logFunc("\tContainer %v ready: %v, restart count %v",
c.Name, c.Ready, c.RestartCount)
}
}
HighLatencyKubeletOperations(c, 10*time.Second, n, logFunc)
// TODO: Log node resource info
}
}
// logNodeEvents logs kubelet events from the given node. This includes kubelet
// restart and node unhealthy events. Note that listing events like this will mess
// with latency metrics, beware of calling it during a test.
func getNodeEvents(c clientset.Interface, nodeName string) []v1.Event {
selector := fields.Set{
"involvedObject.kind": "Node",
"involvedObject.name": nodeName,
"involvedObject.namespace": metav1.NamespaceAll,
"source": "kubelet",
}.AsSelector().String()
options := metav1.ListOptions{FieldSelector: selector}
events, err := c.CoreV1().Events(metav1.NamespaceSystem).List(options)
if err != nil {
Logf("Unexpected error retrieving node events %v", err)
return []v1.Event{}
}
return events.Items
}
// waitListSchedulableNodes is a wrapper around listing nodes supporting retries.
func waitListSchedulableNodes(c clientset.Interface) (*v1.NodeList, error) {
var nodes *v1.NodeList
var err error
if wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) {
nodes, err = c.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
return true, nil
}) != nil {
return nodes, err
}
return nodes, nil
}
// waitListSchedulableNodesOrDie is a wrapper around listing nodes supporting retries.
func waitListSchedulableNodesOrDie(c clientset.Interface) *v1.NodeList {
nodes, err := waitListSchedulableNodes(c)
if err != nil {
ExpectNoError(err, "Non-retryable failure or timed out while listing nodes for e2e cluster.")
}
return nodes
}
// Node is schedulable if:
// 1) doesn't have "unschedulable" field set
// 2) it's Ready condition is set to true
// 3) doesn't have NetworkUnavailable condition set to true
func isNodeSchedulable(node *v1.Node) bool {
nodeReady := IsNodeConditionSetAsExpected(node, v1.NodeReady, true)
networkReady := IsNodeConditionUnset(node, v1.NodeNetworkUnavailable) ||
IsNodeConditionSetAsExpectedSilent(node, v1.NodeNetworkUnavailable, false)
return !node.Spec.Unschedulable && nodeReady && networkReady
}
// Test whether a fake pod can be scheduled on "node", given its current taints.
func isNodeUntainted(node *v1.Node) bool {
fakePod := &v1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: testapi.Groups[v1.GroupName].GroupVersion().String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "fake-not-scheduled",
Namespace: "fake-not-scheduled",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "fake-not-scheduled",
Image: "fake-not-scheduled",
},
},
},
}
nodeInfo := schedulercache.NewNodeInfo()
nodeInfo.SetNode(node)
fit, _, err := predicates.PodToleratesNodeTaints(fakePod, nil, nodeInfo)
if err != nil {
Failf("Can't test predicates for node %s: %v", node.Name, err)
return false
}
return fit
}
// GetReadySchedulableNodesOrDie addresses the common use case of getting nodes you can do work on.
// 1) Needs to be schedulable.
// 2) Needs to be ready.
// If EITHER 1 or 2 is not true, most tests will want to ignore the node entirely.
func GetReadySchedulableNodesOrDie(c clientset.Interface) (nodes *v1.NodeList) {
nodes = waitListSchedulableNodesOrDie(c)
// previous tests may have cause failures of some nodes. Let's skip
// 'Not Ready' nodes, just in case (there is no need to fail the test).
FilterNodes(nodes, func(node v1.Node) bool {
return isNodeSchedulable(&node) && isNodeUntainted(&node)
})
return nodes
}
func WaitForAllNodesSchedulable(c clientset.Interface, timeout time.Duration) error {
Logf("Waiting up to %v for all (but %d) nodes to be schedulable", timeout, TestContext.AllowedNotReadyNodes)
var notSchedulable []*v1.Node
attempt := 0
return wait.PollImmediate(30*time.Second, timeout, func() (bool, error) {
attempt++
notSchedulable = nil
opts := metav1.ListOptions{
ResourceVersion: "0",
FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector().String(),
}
nodes, err := c.CoreV1().Nodes().List(opts)
if err != nil {
Logf("Unexpected error listing nodes: %v", err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
for i := range nodes.Items {
node := &nodes.Items[i]
if !isNodeSchedulable(node) {
notSchedulable = append(notSchedulable, node)
}
}
// Framework allows for <TestContext.AllowedNotReadyNodes> nodes to be non-ready,
// to make it possible e.g. for incorrect deployment of some small percentage
// of nodes (which we allow in cluster validation). Some nodes that are not
// provisioned correctly at startup will never become ready (e.g. when something
// won't install correctly), so we can't expect them to be ready at any point.
//
// However, we only allow non-ready nodes with some specific reasons.
if len(notSchedulable) > 0 {
// In large clusters, log them only every 10th pass.
if len(nodes.Items) >= largeClusterThreshold && attempt%10 == 0 {
Logf("Unschedulable nodes:")
for i := range notSchedulable {
Logf("-> %s Ready=%t Network=%t",
notSchedulable[i].Name,
IsNodeConditionSetAsExpectedSilent(notSchedulable[i], v1.NodeReady, true),
IsNodeConditionSetAsExpectedSilent(notSchedulable[i], v1.NodeNetworkUnavailable, false))
}
Logf("================================")
}
}
return len(notSchedulable) <= TestContext.AllowedNotReadyNodes, nil
})
}
func GetPodSecretUpdateTimeout(c clientset.Interface) time.Duration {
// With SecretManager(ConfigMapManager), we may have to wait up to full sync period +
// TTL of secret(configmap) to elapse before the Kubelet projects the update into the
// volume and the container picks it up.
// So this timeout is based on default Kubelet sync period (1 minute) + maximum TTL for
// secret(configmap) that's based on cluster size + additional time as a fudge factor.
secretTTL, err := GetNodeTTLAnnotationValue(c)
if err != nil {
Logf("Couldn't get node TTL annotation (using default value of 0): %v", err)
}
podLogTimeout := 240*time.Second + secretTTL
return podLogTimeout
}
func GetNodeTTLAnnotationValue(c clientset.Interface) (time.Duration, error) {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil || len(nodes.Items) == 0 {
return time.Duration(0), fmt.Errorf("Couldn't list any nodes to get TTL annotation: %v", err)
}
// Since TTL the kubelet is using is stored in node object, for the timeout
// purpose we take it from the first node (all of them should be the same).
node := &nodes.Items[0]
if node.Annotations == nil {
return time.Duration(0), fmt.Errorf("No annotations found on the node")
}
value, ok := node.Annotations[v1.ObjectTTLAnnotationKey]
if !ok {
return time.Duration(0), fmt.Errorf("No TTL annotation found on the node")
}
intValue, err := strconv.Atoi(value)
if err != nil {
return time.Duration(0), fmt.Errorf("Cannot convert TTL annotation from %#v to int", *node)
}
return time.Duration(intValue) * time.Second, nil
}
func AddOrUpdateLabelOnNode(c clientset.Interface, nodeName string, labelKey, labelValue string) {
ExpectNoError(testutils.AddLabelsToNode(c, nodeName, map[string]string{labelKey: labelValue}))
}
func AddOrUpdateLabelOnNodeAndReturnOldValue(c clientset.Interface, nodeName string, labelKey, labelValue string) string {
var oldValue string
node, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
ExpectNoError(err)
oldValue = node.Labels[labelKey]
ExpectNoError(testutils.AddLabelsToNode(c, nodeName, map[string]string{labelKey: labelValue}))
return oldValue
}
func ExpectNodeHasLabel(c clientset.Interface, nodeName string, labelKey string, labelValue string) {
By("verifying the node has the label " + labelKey + " " + labelValue)
node, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
ExpectNoError(err)
Expect(node.Labels[labelKey]).To(Equal(labelValue))
}
func RemoveTaintOffNode(c clientset.Interface, nodeName string, taint v1.Taint) {
ExpectNoError(controller.RemoveTaintOffNode(c, nodeName, nil, &taint))
VerifyThatTaintIsGone(c, nodeName, &taint)
}
func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taint v1.Taint) {
ExpectNoError(controller.AddOrUpdateTaintOnNode(c, nodeName, &taint))
}
// RemoveLabelOffNode is for cleaning up labels temporarily added to node,
// won't fail if target label doesn't exist or has been removed.
func RemoveLabelOffNode(c clientset.Interface, nodeName string, labelKey string) {
By("removing the label " + labelKey + " off the node " + nodeName)
ExpectNoError(testutils.RemoveLabelOffNode(c, nodeName, []string{labelKey}))
By("verifying the node doesn't have the label " + labelKey)
ExpectNoError(testutils.VerifyLabelsRemoved(c, nodeName, []string{labelKey}))
}
func VerifyThatTaintIsGone(c clientset.Interface, nodeName string, taint *v1.Taint) {
By("verifying the node doesn't have the taint " + taint.ToString())
nodeUpdated, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
ExpectNoError(err)
if taintutils.TaintExists(nodeUpdated.Spec.Taints, taint) {
Failf("Failed removing taint " + taint.ToString() + " of the node " + nodeName)
}
}
func ExpectNodeHasTaint(c clientset.Interface, nodeName string, taint *v1.Taint) {
By("verifying the node has the taint " + taint.ToString())
if has, err := NodeHasTaint(c, nodeName, taint); !has {
ExpectNoError(err)
Failf("Failed to find taint %s on node %s", taint.ToString(), nodeName)
}
}
func NodeHasTaint(c clientset.Interface, nodeName string, taint *v1.Taint) (bool, error) {
node, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err != nil {
return false, err
}
nodeTaints := node.Spec.Taints
if len(nodeTaints) == 0 || !taintutils.TaintExists(nodeTaints, taint) {
return false, nil
}
return true, nil
}
//AddOrUpdateAvoidPodOnNode adds avoidPods annotations to node, will override if it exists
func AddOrUpdateAvoidPodOnNode(c clientset.Interface, nodeName string, avoidPods v1.AvoidPods) {
err := wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) {
node, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
taintsData, err := json.Marshal(avoidPods)
ExpectNoError(err)
if node.Annotations == nil {
node.Annotations = make(map[string]string)
}
node.Annotations[v1.PreferAvoidPodsAnnotationKey] = string(taintsData)
_, err = c.CoreV1().Nodes().Update(node)
if err != nil {
if !apierrs.IsConflict(err) {
ExpectNoError(err)
} else {
Logf("Conflict when trying to add/update avoidPonds %v to %v", avoidPods, nodeName)
}
}
return true, nil
})
ExpectNoError(err)
}
//RemoveAnnotationOffNode removes AvoidPods annotations from the node. It does not fail if no such annotation exists.
func RemoveAvoidPodsOffNode(c clientset.Interface, nodeName string) {
err := wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) {
node, err := c.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
if node.Annotations == nil {
return true, nil
}
delete(node.Annotations, v1.PreferAvoidPodsAnnotationKey)
_, err = c.CoreV1().Nodes().Update(node)
if err != nil {
if !apierrs.IsConflict(err) {
ExpectNoError(err)
} else {
Logf("Conflict when trying to remove avoidPods to %v", nodeName)
}
}
return true, nil
})
ExpectNoError(err)
}
func ScaleResource(
clientset clientset.Interface,
internalClientset internalclientset.Interface,
scalesGetter scaleclient.ScalesGetter,
ns, name string,
size uint,
wait bool,
kind schema.GroupKind,
gr schema.GroupResource,
) error {
By(fmt.Sprintf("Scaling %v %s in namespace %s to %d", kind, name, ns, size))
scaler := kubectl.ScalerFor(kind, internalClientset.Batch(), scalesGetter, gr)
if err := testutils.ScaleResourceWithRetries(scaler, ns, name, size); err != nil {
return fmt.Errorf("error while scaling RC %s to %d replicas: %v", name, size, err)
}
if !wait {
return nil
}
return WaitForControlledPodsRunning(clientset, ns, name, kind)
}
// Wait up to 10 minutes for pods to become Running.
func WaitForControlledPodsRunning(c clientset.Interface, ns, name string, kind schema.GroupKind) error {
rtObject, err := getRuntimeObjectForKind(c, kind, ns, name)
if err != nil {
return err
}
selector, err := getSelectorFromRuntimeObject(rtObject)
if err != nil {
return err
}
replicas, err := getReplicasFromRuntimeObject(rtObject)
if err != nil {
return err
}
err = testutils.WaitForEnoughPodsWithLabelRunning(c, ns, selector, int(replicas))
if err != nil {
return fmt.Errorf("Error while waiting for replication controller %s pods to be running: %v", name, err)
}
return nil
}
// Wait up to PodListTimeout for getting pods of the specified controller name and return them.
func WaitForControlledPods(c clientset.Interface, ns, name string, kind schema.GroupKind) (pods *v1.PodList, err error) {
rtObject, err := getRuntimeObjectForKind(c, kind, ns, name)
if err != nil {
return nil, err
}
selector, err := getSelectorFromRuntimeObject(rtObject)
if err != nil {
return nil, err
}
return WaitForPodsWithLabel(c, ns, selector)
}
// Returns true if all the specified pods are scheduled, else returns false.
func podsWithLabelScheduled(c clientset.Interface, ns string, label labels.Selector) (bool, error) {
PodStore := testutils.NewPodStore(c, ns, label, fields.Everything())
defer PodStore.Stop()
pods := PodStore.List()
if len(pods) == 0 {
return false, nil
}
for _, pod := range pods {
if pod.Spec.NodeName == "" {
return false, nil
}
}
return true, nil
}
// Wait for all matching pods to become scheduled and at least one
// matching pod exists. Return the list of matching pods.
func WaitForPodsWithLabelScheduled(c clientset.Interface, ns string, label labels.Selector) (pods *v1.PodList, err error) {
err = wait.PollImmediate(Poll, podScheduledBeforeTimeout,
func() (bool, error) {
pods, err = WaitForPodsWithLabel(c, ns, label)
if err != nil {
return false, err
}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
return false, nil
}
}
return true, nil
})
return pods, err
}
// Wait up to PodListTimeout for getting pods with certain label
func WaitForPodsWithLabel(c clientset.Interface, ns string, label labels.Selector) (pods *v1.PodList, err error) {
for t := time.Now(); time.Since(t) < PodListTimeout; time.Sleep(Poll) {
options := metav1.ListOptions{LabelSelector: label.String()}
pods, err = c.CoreV1().Pods(ns).List(options)
if err != nil {
if testutils.IsRetryableAPIError(err) {
continue
}
return
}
if len(pods.Items) > 0 {
break
}
}
if pods == nil || len(pods.Items) == 0 {
err = fmt.Errorf("Timeout while waiting for pods with label %v", label)
}
return
}
// Wait for exact amount of matching pods to become running and ready.
// Return the list of matching pods.
func WaitForPodsWithLabelRunningReady(c clientset.Interface, ns string, label labels.Selector, num int, timeout time.Duration) (pods *v1.PodList, err error) {
var current int
err = wait.Poll(Poll, timeout,
func() (bool, error) {
pods, err := WaitForPodsWithLabel(c, ns, label)
if err != nil {
Logf("Failed to list pods: %v", err)
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
current = 0
for _, pod := range pods.Items {
if flag, err := testutils.PodRunningReady(&pod); err == nil && flag == true {
current++
}
}
if current != num {
Logf("Got %v pods running and ready, expect: %v", current, num)
return false, nil
}
return true, nil
})
return pods, err
}
func getRuntimeObjectForKind(c clientset.Interface, kind schema.GroupKind, ns, name string) (runtime.Object, error) {
switch kind {
case api.Kind("ReplicationController"):
return c.CoreV1().ReplicationControllers(ns).Get(name, metav1.GetOptions{})
case extensionsinternal.Kind("ReplicaSet"), appsinternal.Kind("ReplicaSet"):
return c.ExtensionsV1beta1().ReplicaSets(ns).Get(name, metav1.GetOptions{})
case extensionsinternal.Kind("Deployment"), appsinternal.Kind("Deployment"):
return c.ExtensionsV1beta1().Deployments(ns).Get(name, metav1.GetOptions{})
case extensionsinternal.Kind("DaemonSet"):
return c.ExtensionsV1beta1().DaemonSets(ns).Get(name, metav1.GetOptions{})
case batchinternal.Kind("Job"):
return c.BatchV1().Jobs(ns).Get(name, metav1.GetOptions{})
default:
return nil, fmt.Errorf("Unsupported kind when getting runtime object: %v", kind)
}
}
func getSelectorFromRuntimeObject(obj runtime.Object) (labels.Selector, error) {
switch typed := obj.(type) {
case *v1.ReplicationController:
return labels.SelectorFromSet(typed.Spec.Selector), nil
case *extensions.ReplicaSet:
return metav1.LabelSelectorAsSelector(typed.Spec.Selector)
case *extensions.Deployment:
return metav1.LabelSelectorAsSelector(typed.Spec.Selector)
case *extensions.DaemonSet:
return metav1.LabelSelectorAsSelector(typed.Spec.Selector)
case *batch.Job:
return metav1.LabelSelectorAsSelector(typed.Spec.Selector)
default:
return nil, fmt.Errorf("Unsupported kind when getting selector: %v", obj)
}
}
func getReplicasFromRuntimeObject(obj runtime.Object) (int32, error) {
switch typed := obj.(type) {
case *v1.ReplicationController:
if typed.Spec.Replicas != nil {
return *typed.Spec.Replicas, nil
}
return 0, nil
case *extensions.ReplicaSet:
if typed.Spec.Replicas != nil {
return *typed.Spec.Replicas, nil
}
return 0, nil
case *extensions.Deployment:
if typed.Spec.Replicas != nil {
return *typed.Spec.Replicas, nil
}
return 0, nil
case *batch.Job:
// TODO: currently we use pause pods so that's OK. When we'll want to switch to Pods
// that actually finish we need a better way to do this.
if typed.Spec.Parallelism != nil {
return *typed.Spec.Parallelism, nil
}
return 0, nil
default:
return -1, fmt.Errorf("Unsupported kind when getting number of replicas: %v", obj)
}
}
// DeleteResourceAndPods deletes a given resource and all pods it spawned
func DeleteResourceAndPods(clientset clientset.Interface, internalClientset internalclientset.Interface, scaleClient scaleclient.ScalesGetter, kind schema.GroupKind, ns, name string) error {
By(fmt.Sprintf("deleting %v %s in namespace %s", kind, name, ns))
rtObject, err := getRuntimeObjectForKind(clientset, kind, ns, name)
if err != nil {
if apierrs.IsNotFound(err) {
Logf("%v %s not found: %v", kind, name, err)
return nil
}
return err
}
selector, err := getSelectorFromRuntimeObject(rtObject)
if err != nil {
return err
}
ps, err := podStoreForSelector(clientset, ns, selector)
if err != nil {
return err
}
defer ps.Stop()
startTime := time.Now()
if err := testutils.DeleteResourceUsingReaperWithRetries(internalClientset, kind, ns, name, nil, scaleClient); err != nil {
return fmt.Errorf("error while stopping %v: %s: %v", kind, name, err)
}
deleteTime := time.Now().Sub(startTime)
Logf("Deleting %v %s took: %v", kind, name, deleteTime)
err = waitForPodsInactive(ps, 100*time.Millisecond, 10*time.Minute)
if err != nil {
return fmt.Errorf("error while waiting for pods to become inactive %s: %v", name, err)
}
terminatePodTime := time.Now().Sub(startTime) - deleteTime
Logf("Terminating %v %s pods took: %v", kind, name, terminatePodTime)
// this is to relieve namespace controller's pressure when deleting the
// namespace after a test.
err = waitForPodsGone(ps, 100*time.Millisecond, 10*time.Minute)
if err != nil {
return fmt.Errorf("error while waiting for pods gone %s: %v", name, err)
}
gcPodTime := time.Now().Sub(startTime) - terminatePodTime
Logf("Garbage collecting %v %s pods took: %v", kind, name, gcPodTime)
return nil
}
// DeleteResourceAndWaitForGC deletes only given resource and waits for GC to delete the pods.
func DeleteResourceAndWaitForGC(c clientset.Interface, kind schema.GroupKind, ns, name string) error {
By(fmt.Sprintf("deleting %v %s in namespace %s, will wait for the garbage collector to delete the pods", kind, name, ns))
rtObject, err := getRuntimeObjectForKind(c, kind, ns, name)
if err != nil {
if apierrs.IsNotFound(err) {
Logf("%v %s not found: %v", kind, name, err)
return nil
}
return err
}
selector, err := getSelectorFromRuntimeObject(rtObject)
if err != nil {
return err
}
replicas, err := getReplicasFromRuntimeObject(rtObject)
if err != nil {
return err
}
ps, err := podStoreForSelector(c, ns, selector)
if err != nil {
return err
}
defer ps.Stop()
falseVar := false
deleteOption := &metav1.DeleteOptions{OrphanDependents: &falseVar}
startTime := time.Now()
if err := testutils.DeleteResourceWithRetries(c, kind, ns, name, deleteOption); err != nil {
return err
}
deleteTime := time.Now().Sub(startTime)
Logf("Deleting %v %s took: %v", kind, name, deleteTime)
var interval, timeout time.Duration
switch {
case replicas < 100:
interval = 100 * time.Millisecond
case replicas < 1000:
interval = 1 * time.Second
default:
interval = 10 * time.Second
}
if replicas < 5000 {
timeout = 10 * time.Minute
} else {
timeout = time.Duration(replicas/gcThroughput) * time.Second
// gcThroughput is pretty strict now, add a bit more to it
timeout = timeout + 3*time.Minute
}
err = waitForPodsInactive(ps, interval, timeout)
if err != nil {
return fmt.Errorf("error while waiting for pods to become inactive %s: %v", name, err)
}
terminatePodTime := time.Now().Sub(startTime) - deleteTime
Logf("Terminating %v %s pods took: %v", kind, name, terminatePodTime)
err = waitForPodsGone(ps, interval, 10*time.Minute)
if err != nil {
return fmt.Errorf("error while waiting for pods gone %s: %v", name, err)
}
return nil
}
// podStoreForSelector creates a PodStore that monitors pods from given namespace matching given selector.
// It waits until the reflector does a List() before returning.
func podStoreForSelector(c clientset.Interface, ns string, selector labels.Selector) (*testutils.PodStore, error) {
ps := testutils.NewPodStore(c, ns, selector, fields.Everything())
err := wait.Poll(100*time.Millisecond, 2*time.Minute, func() (bool, error) {
if len(ps.Reflector.LastSyncResourceVersion()) != 0 {
return true, nil
}
return false, nil
})
return ps, err
}
// waitForPodsInactive waits until there are no active pods left in the PodStore.
// This is to make a fair comparison of deletion time between DeleteRCAndPods
// and DeleteRCAndWaitForGC, because the RC controller decreases status.replicas
// when the pod is inactvie.
func waitForPodsInactive(ps *testutils.PodStore, interval, timeout time.Duration) error {
return wait.PollImmediate(interval, timeout, func() (bool, error) {
pods := ps.List()
for _, pod := range pods {
if controller.IsPodActive(pod) {
return false, nil
}
}
return true, nil
})
}
// waitForPodsGone waits until there are no pods left in the PodStore.
func waitForPodsGone(ps *testutils.PodStore, interval, timeout time.Duration) error {
return wait.PollImmediate(interval, timeout, func() (bool, error) {
if pods := ps.List(); len(pods) == 0 {
return true, nil
}
return false, nil
})
}
func WaitForPodsReady(c clientset.Interface, ns, name string, minReadySeconds int) error {
label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
options := metav1.ListOptions{LabelSelector: label.String()}
return wait.Poll(Poll, 5*time.Minute, func() (bool, error) {
pods, err := c.CoreV1().Pods(ns).List(options)
if err != nil {
return false, nil
}
for _, pod := range pods.Items {
if !podutil.IsPodAvailable(&pod, int32(minReadySeconds), metav1.Now()) {
return false, nil
}
}
return true, nil
})
}
// Waits for the number of events on the given object to reach a desired count.
func WaitForEvents(c clientset.Interface, ns string, objOrRef runtime.Object, desiredEventsCount int) error {
return wait.Poll(Poll, 5*time.Minute, func() (bool, error) {
events, err := c.CoreV1().Events(ns).Search(legacyscheme.Scheme, objOrRef)
if err != nil {
return false, fmt.Errorf("error in listing events: %s", err)
}
eventsCount := len(events.Items)
if eventsCount == desiredEventsCount {
return true, nil
}
if eventsCount < desiredEventsCount {
return false, nil
}
// Number of events has exceeded the desired count.
return false, fmt.Errorf("number of events has exceeded the desired count, eventsCount: %d, desiredCount: %d", eventsCount, desiredEventsCount)
})
}
// Waits for the number of events on the given object to be at least a desired count.
func WaitForPartialEvents(c clientset.Interface, ns string, objOrRef runtime.Object, atLeastEventsCount int) error {
return wait.Poll(Poll, 5*time.Minute, func() (bool, error) {
events, err := c.CoreV1().Events(ns).Search(legacyscheme.Scheme, objOrRef)
if err != nil {
return false, fmt.Errorf("error in listing events: %s", err)
}
eventsCount := len(events.Items)
if eventsCount >= atLeastEventsCount {
return true, nil
}
return false, nil
})
}
type updateDSFunc func(*apps.DaemonSet)
func UpdateDaemonSetWithRetries(c clientset.Interface, namespace, name string, applyUpdate updateDSFunc) (ds *apps.DaemonSet, err error) {
daemonsets := c.AppsV1().DaemonSets(namespace)
var updateErr error
pollErr := wait.PollImmediate(10*time.Millisecond, 1*time.Minute, func() (bool, error) {
if ds, err = daemonsets.Get(name, metav1.GetOptions{}); err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
// Apply the update, then attempt to push it to the apiserver.
applyUpdate(ds)
if ds, err = daemonsets.Update(ds); err == nil {
Logf("Updating DaemonSet %s", name)
return true, nil
}
updateErr = err
return false, nil
})
if pollErr == wait.ErrWaitTimeout {
pollErr = fmt.Errorf("couldn't apply the provided updated to DaemonSet %q: %v", name, updateErr)
}
return ds, pollErr
}
// NodeAddresses returns the first address of the given type of each node.
func NodeAddresses(nodelist *v1.NodeList, addrType v1.NodeAddressType) []string {
hosts := []string{}
for _, n := range nodelist.Items {
for _, addr := range n.Status.Addresses {
// Use the first external IP address we find on the node, and
// use at most one per node.
// TODO(roberthbailey): Use the "preferred" address for the node, once
// such a thing is defined (#2462).
if addr.Type == addrType {
hosts = append(hosts, addr.Address)
break
}
}
}
return hosts
}
// NodeSSHHosts returns SSH-able host names for all schedulable nodes - this excludes master node.
// It returns an error if it can't find an external IP for every node, though it still returns all
// hosts that it found in that case.
func NodeSSHHosts(c clientset.Interface) ([]string, error) {
nodelist := waitListSchedulableNodesOrDie(c)
// TODO(roberthbailey): Use the "preferred" address for the node, once such a thing is defined (#2462).
hosts := NodeAddresses(nodelist, v1.NodeExternalIP)
// Error if any node didn't have an external IP.
if len(hosts) != len(nodelist.Items) {
return hosts, fmt.Errorf(
"only found %d external IPs on nodes, but found %d nodes. Nodelist: %v",
len(hosts), len(nodelist.Items), nodelist)
}
sshHosts := make([]string, 0, len(hosts))
for _, h := range hosts {
sshHosts = append(sshHosts, net.JoinHostPort(h, sshPort))
}
return sshHosts, nil
}
type SSHResult struct {
User string
Host string
Cmd string
Stdout string
Stderr string
Code int
}
// NodeExec execs the given cmd on node via SSH. Note that the nodeName is an sshable name,
// eg: the name returned by framework.GetMasterHost(). This is also not guaranteed to work across
// cloud providers since it involves ssh.
func NodeExec(nodeName, cmd string) (SSHResult, error) {
return SSH(cmd, net.JoinHostPort(nodeName, sshPort), TestContext.Provider)
}
// SSH synchronously SSHs to a node running on provider and runs cmd. If there
// is no error performing the SSH, the stdout, stderr, and exit code are
// returned.
func SSH(cmd, host, provider string) (SSHResult, error) {
result := SSHResult{Host: host, Cmd: cmd}
// Get a signer for the provider.
signer, err := GetSigner(provider)
if err != nil {
return result, fmt.Errorf("error getting signer for provider %s: '%v'", provider, err)
}
// RunSSHCommand will default to Getenv("USER") if user == "", but we're
// defaulting here as well for logging clarity.
result.User = os.Getenv("KUBE_SSH_USER")
if result.User == "" {
result.User = os.Getenv("USER")
}
stdout, stderr, code, err := sshutil.RunSSHCommand(cmd, result.User, host, signer)
result.Stdout = stdout
result.Stderr = stderr
result.Code = code
return result, err
}
func LogSSHResult(result SSHResult) {
remote := fmt.Sprintf("%s@%s", result.User, result.Host)
Logf("ssh %s: command: %s", remote, result.Cmd)
Logf("ssh %s: stdout: %q", remote, result.Stdout)
Logf("ssh %s: stderr: %q", remote, result.Stderr)
Logf("ssh %s: exit code: %d", remote, result.Code)
}
func IssueSSHCommandWithResult(cmd, provider string, node *v1.Node) (*SSHResult, error) {
Logf("Getting external IP address for %s", node.Name)
host := ""
for _, a := range node.Status.Addresses {
if a.Type == v1.NodeExternalIP {
host = net.JoinHostPort(a.Address, sshPort)
break
}
}
if host == "" {
// No external IPs were found, let's try to use internal as plan B
for _, a := range node.Status.Addresses {
if a.Type == v1.NodeInternalIP {
host = net.JoinHostPort(a.Address, sshPort)
break
}
}
}
if host == "" {
return nil, fmt.Errorf("couldn't find any IP address for node %s", node.Name)
}
Logf("SSH %q on %s(%s)", cmd, node.Name, host)
result, err := SSH(cmd, host, provider)
LogSSHResult(result)
if result.Code != 0 || err != nil {
return nil, fmt.Errorf("failed running %q: %v (exit code %d)",
cmd, err, result.Code)
}
return &result, nil
}
func IssueSSHCommand(cmd, provider string, node *v1.Node) error {
_, err := IssueSSHCommandWithResult(cmd, provider, node)
if err != nil {
return err
}
return nil
}
// NewHostExecPodSpec returns the pod spec of hostexec pod
func NewHostExecPodSpec(ns, name string) *v1.Pod {
immediate := int64(0)
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "hostexec",
Image: imageutils.GetE2EImage(imageutils.Hostexec),
ImagePullPolicy: v1.PullIfNotPresent,
},
},
HostNetwork: true,
SecurityContext: &v1.PodSecurityContext{},
TerminationGracePeriodSeconds: &immediate,
},
}
return pod
}
// RunHostCmd runs the given cmd in the context of the given pod using `kubectl exec`
// inside of a shell.
func RunHostCmd(ns, name, cmd string) (string, error) {
return RunKubectl("exec", fmt.Sprintf("--namespace=%v", ns), name, "--", "/bin/sh", "-c", cmd)
}
// RunHostCmdOrDie calls RunHostCmd and dies on error.
func RunHostCmdOrDie(ns, name, cmd string) string {
stdout, err := RunHostCmd(ns, name, cmd)
Logf("stdout: %v", stdout)
ExpectNoError(err)
return stdout
}
// RunHostCmdWithRetries calls RunHostCmd and retries all errors
// until it succeeds or the specified timeout expires.
// This can be used with idempotent commands to deflake transient Node issues.
func RunHostCmdWithRetries(ns, name, cmd string, interval, timeout time.Duration) (string, error) {
start := time.Now()
for {
out, err := RunHostCmd(ns, name, cmd)
if err == nil {
return out, nil
}
if elapsed := time.Since(start); elapsed > timeout {
return out, fmt.Errorf("RunHostCmd still failed after %v: %v", elapsed, err)
}
Logf("Waiting %v to retry failed RunHostCmd: %v", interval, err)
time.Sleep(interval)
}
}
// LaunchHostExecPod launches a hostexec pod in the given namespace and waits
// until it's Running
func LaunchHostExecPod(client clientset.Interface, ns, name string) *v1.Pod {
hostExecPod := NewHostExecPodSpec(ns, name)
pod, err := client.CoreV1().Pods(ns).Create(hostExecPod)
ExpectNoError(err)
err = WaitForPodRunningInNamespace(client, pod)
ExpectNoError(err)
return pod
}
// newExecPodSpec returns the pod spec of exec pod
func newExecPodSpec(ns, generateName string) *v1.Pod {
immediate := int64(0)
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
GenerateName: generateName,
Namespace: ns,
},
Spec: v1.PodSpec{
TerminationGracePeriodSeconds: &immediate,
Containers: []v1.Container{
{
Name: "exec",
Image: BusyBoxImage,
Command: []string{"sh", "-c", "while true; do sleep 5; done"},
},
},
},
}
return pod
}
// CreateExecPodOrFail creates a simple busybox pod in a sleep loop used as a
// vessel for kubectl exec commands.
// Returns the name of the created pod.
func CreateExecPodOrFail(client clientset.Interface, ns, generateName string, tweak func(*v1.Pod)) string {
Logf("Creating new exec pod")
execPod := newExecPodSpec(ns, generateName)
if tweak != nil {
tweak(execPod)
}
created, err := client.CoreV1().Pods(ns).Create(execPod)
Expect(err).NotTo(HaveOccurred())
err = wait.PollImmediate(Poll, 5*time.Minute, func() (bool, error) {
retrievedPod, err := client.CoreV1().Pods(execPod.Namespace).Get(created.Name, metav1.GetOptions{})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
return retrievedPod.Status.Phase == v1.PodRunning, nil
})
Expect(err).NotTo(HaveOccurred())
return created.Name
}
func CreatePodOrFail(c clientset.Interface, ns, name string, labels map[string]string, containerPorts []v1.ContainerPort) {
By(fmt.Sprintf("Creating pod %s in namespace %s", name, ns))
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: labels,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "pause",
Image: GetPauseImageName(c),
Ports: containerPorts,
// Add a dummy environment variable to work around a docker issue.
// https://github.com/docker/docker/issues/14203
Env: []v1.EnvVar{{Name: "FOO", Value: " "}},
},
},
},
}
_, err := c.CoreV1().Pods(ns).Create(pod)
Expect(err).NotTo(HaveOccurred())
}
func DeletePodOrFail(c clientset.Interface, ns, name string) {
By(fmt.Sprintf("Deleting pod %s in namespace %s", name, ns))
err := c.CoreV1().Pods(ns).Delete(name, nil)
Expect(err).NotTo(HaveOccurred())
}
// GetSigner returns an ssh.Signer for the provider ("gce", etc.) that can be
// used to SSH to their nodes.
func GetSigner(provider string) (ssh.Signer, error) {
// Get the directory in which SSH keys are located.
keydir := filepath.Join(os.Getenv("HOME"), ".ssh")
// Select the key itself to use. When implementing more providers here,
// please also add them to any SSH tests that are disabled because of signer
// support.
keyfile := ""
key := ""
switch provider {
case "gce", "gke", "kubemark":
keyfile = "google_compute_engine"
case "aws":
// If there is an env. variable override, use that.
aws_keyfile := os.Getenv("AWS_SSH_KEY")
if len(aws_keyfile) != 0 {
return sshutil.MakePrivateKeySignerFromFile(aws_keyfile)
}
// Otherwise revert to home dir
keyfile = "kube_aws_rsa"
case "local", "vsphere":
keyfile = os.Getenv("LOCAL_SSH_KEY") // maybe?
if len(keyfile) == 0 {
keyfile = "id_rsa"
}
case "skeleton":
keyfile = os.Getenv("KUBE_SSH_KEY")
if len(keyfile) == 0 {
keyfile = "id_rsa"
}
default:
return nil, fmt.Errorf("GetSigner(...) not implemented for %s", provider)
}
if len(key) == 0 {
key = filepath.Join(keydir, keyfile)
}
return sshutil.MakePrivateKeySignerFromFile(key)
}
// CheckPodsRunningReady returns whether all pods whose names are listed in
// podNames in namespace ns are running and ready, using c and waiting at most
// timeout.
func CheckPodsRunningReady(c clientset.Interface, ns string, podNames []string, timeout time.Duration) bool {
return CheckPodsCondition(c, ns, podNames, timeout, testutils.PodRunningReady, "running and ready")
}
// CheckPodsRunningReadyOrSucceeded returns whether all pods whose names are
// listed in podNames in namespace ns are running and ready, or succeeded; use
// c and waiting at most timeout.
func CheckPodsRunningReadyOrSucceeded(c clientset.Interface, ns string, podNames []string, timeout time.Duration) bool {
return CheckPodsCondition(c, ns, podNames, timeout, testutils.PodRunningReadyOrSucceeded, "running and ready, or succeeded")
}
// CheckPodsCondition returns whether all pods whose names are listed in podNames
// in namespace ns are in the condition, using c and waiting at most timeout.
func CheckPodsCondition(c clientset.Interface, ns string, podNames []string, timeout time.Duration, condition podCondition, desc string) bool {
np := len(podNames)
Logf("Waiting up to %v for %d pods to be %s: %s", timeout, np, desc, podNames)
type waitPodResult struct {
success bool
podName string
}
result := make(chan waitPodResult, len(podNames))
for _, podName := range podNames {
// Launch off pod readiness checkers.
go func(name string) {
err := WaitForPodCondition(c, ns, name, desc, timeout, condition)
result <- waitPodResult{err == nil, name}
}(podName)
}
// Wait for them all to finish.
success := true
for range podNames {
res := <-result
if !res.success {
Logf("Pod %[1]s failed to be %[2]s.", res.podName, desc)
success = false
}
}
Logf("Wanted all %d pods to be %s. Result: %t. Pods: %v", np, desc, success, podNames)
return success
}
// WaitForNodeToBeReady returns whether node name is ready within timeout.
func WaitForNodeToBeReady(c clientset.Interface, name string, timeout time.Duration) bool {
return WaitForNodeToBe(c, name, v1.NodeReady, true, timeout)
}
// WaitForNodeToBeNotReady returns whether node name is not ready (i.e. the
// readiness condition is anything but ready, e.g false or unknown) within
// timeout.
func WaitForNodeToBeNotReady(c clientset.Interface, name string, timeout time.Duration) bool {
return WaitForNodeToBe(c, name, v1.NodeReady, false, timeout)
}
func isNodeConditionSetAsExpected(node *v1.Node, conditionType v1.NodeConditionType, wantTrue, silent bool) bool {
// Check the node readiness condition (logging all).
for _, cond := range node.Status.Conditions {
// Ensure that the condition type and the status matches as desired.
if cond.Type == conditionType {
// For NodeReady condition we need to check Taints as well
if cond.Type == v1.NodeReady {
hasNodeControllerTaints := false
// For NodeReady we need to check if Taints are gone as well
taints := node.Spec.Taints
for _, taint := range taints {
if taint.MatchTaint(nodectlr.UnreachableTaintTemplate) || taint.MatchTaint(nodectlr.NotReadyTaintTemplate) {
hasNodeControllerTaints = true
break
}
}
if wantTrue {
if (cond.Status == v1.ConditionTrue) && !hasNodeControllerTaints {
return true
} else {
msg := ""
if !hasNodeControllerTaints {
msg = fmt.Sprintf("Condition %s of node %s is %v instead of %t. Reason: %v, message: %v",
conditionType, node.Name, cond.Status == v1.ConditionTrue, wantTrue, cond.Reason, cond.Message)
} else {
msg = fmt.Sprintf("Condition %s of node %s is %v, but Node is tainted by NodeController with %v. Failure",
conditionType, node.Name, cond.Status == v1.ConditionTrue, taints)
}
if !silent {
Logf(msg)
}
return false
}
} else {
// TODO: check if the Node is tainted once we enable NC notReady/unreachable taints by default
if cond.Status != v1.ConditionTrue {
return true
}
if !silent {
Logf("Condition %s of node %s is %v instead of %t. Reason: %v, message: %v",
conditionType, node.Name, cond.Status == v1.ConditionTrue, wantTrue, cond.Reason, cond.Message)
}
return false
}
}
if (wantTrue && (cond.Status == v1.ConditionTrue)) || (!wantTrue && (cond.Status != v1.ConditionTrue)) {
return true
} else {
if !silent {
Logf("Condition %s of node %s is %v instead of %t. Reason: %v, message: %v",
conditionType, node.Name, cond.Status == v1.ConditionTrue, wantTrue, cond.Reason, cond.Message)
}
return false
}
}
}
if !silent {
Logf("Couldn't find condition %v on node %v", conditionType, node.Name)
}
return false
}
func IsNodeConditionSetAsExpected(node *v1.Node, conditionType v1.NodeConditionType, wantTrue bool) bool {
return isNodeConditionSetAsExpected(node, conditionType, wantTrue, false)
}
func IsNodeConditionSetAsExpectedSilent(node *v1.Node, conditionType v1.NodeConditionType, wantTrue bool) bool {
return isNodeConditionSetAsExpected(node, conditionType, wantTrue, true)
}
func IsNodeConditionUnset(node *v1.Node, conditionType v1.NodeConditionType) bool {
for _, cond := range node.Status.Conditions {
if cond.Type == conditionType {
return false
}
}
return true
}
// WaitForNodeToBe returns whether node "name's" condition state matches wantTrue
// within timeout. If wantTrue is true, it will ensure the node condition status
// is ConditionTrue; if it's false, it ensures the node condition is in any state
// other than ConditionTrue (e.g. not true or unknown).
func WaitForNodeToBe(c clientset.Interface, name string, conditionType v1.NodeConditionType, wantTrue bool, timeout time.Duration) bool {
Logf("Waiting up to %v for node %s condition %s to be %t", timeout, name, conditionType, wantTrue)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
node, err := c.CoreV1().Nodes().Get(name, metav1.GetOptions{})
if err != nil {
Logf("Couldn't get node %s", name)
continue
}
if IsNodeConditionSetAsExpected(node, conditionType, wantTrue) {
return true
}
}
Logf("Node %s didn't reach desired %s condition status (%t) within %v", name, conditionType, wantTrue, timeout)
return false
}
// Checks whether all registered nodes are ready.
// TODO: we should change the AllNodesReady call in AfterEach to WaitForAllNodesHealthy,
// and figure out how to do it in a configurable way, as we can't expect all setups to run
// default test add-ons.
func AllNodesReady(c clientset.Interface, timeout time.Duration) error {
Logf("Waiting up to %v for all (but %d) nodes to be ready", timeout, TestContext.AllowedNotReadyNodes)
var notReady []*v1.Node
err := wait.PollImmediate(Poll, timeout, func() (bool, error) {
notReady = nil
// It should be OK to list unschedulable Nodes here.
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
for i := range nodes.Items {
node := &nodes.Items[i]
if !IsNodeConditionSetAsExpected(node, v1.NodeReady, true) {
notReady = append(notReady, node)
}
}
// Framework allows for <TestContext.AllowedNotReadyNodes> nodes to be non-ready,
// to make it possible e.g. for incorrect deployment of some small percentage
// of nodes (which we allow in cluster validation). Some nodes that are not
// provisioned correctly at startup will never become ready (e.g. when something
// won't install correctly), so we can't expect them to be ready at any point.
return len(notReady) <= TestContext.AllowedNotReadyNodes, nil
})
if err != nil && err != wait.ErrWaitTimeout {
return err
}
if len(notReady) > TestContext.AllowedNotReadyNodes {
msg := ""
for _, node := range notReady {
msg = fmt.Sprintf("%s, %s", msg, node.Name)
}
return fmt.Errorf("Not ready nodes: %#v", msg)
}
return nil
}
// checks whether all registered nodes are ready and all required Pods are running on them.
func WaitForAllNodesHealthy(c clientset.Interface, timeout time.Duration) error {
Logf("Waiting up to %v for all nodes to be ready", timeout)
var notReady []v1.Node
var missingPodsPerNode map[string][]string
err := wait.PollImmediate(Poll, timeout, func() (bool, error) {
notReady = nil
// It should be OK to list unschedulable Nodes here.
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{ResourceVersion: "0"})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
for _, node := range nodes.Items {
if !IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) {
notReady = append(notReady, node)
}
}
pods, err := c.CoreV1().Pods(metav1.NamespaceAll).List(metav1.ListOptions{ResourceVersion: "0"})
if err != nil {
return false, err
}
systemPodsPerNode := make(map[string][]string)
for _, pod := range pods.Items {
if pod.Namespace == metav1.NamespaceSystem && pod.Status.Phase == v1.PodRunning {
if pod.Spec.NodeName != "" {
systemPodsPerNode[pod.Spec.NodeName] = append(systemPodsPerNode[pod.Spec.NodeName], pod.Name)
}
}
}
missingPodsPerNode = make(map[string][]string)
for _, node := range nodes.Items {
if !system.IsMasterNode(node.Name) {
for _, requiredPod := range requiredPerNodePods {
foundRequired := false
for _, presentPod := range systemPodsPerNode[node.Name] {
if requiredPod.MatchString(presentPod) {
foundRequired = true
break
}
}
if !foundRequired {
missingPodsPerNode[node.Name] = append(missingPodsPerNode[node.Name], requiredPod.String())
}
}
}
}
return len(notReady) == 0 && len(missingPodsPerNode) == 0, nil
})
if err != nil && err != wait.ErrWaitTimeout {
return err
}
if len(notReady) > 0 {
return fmt.Errorf("Not ready nodes: %v", notReady)
}
if len(missingPodsPerNode) > 0 {
return fmt.Errorf("Not running system Pods: %v", missingPodsPerNode)
}
return nil
}
// Filters nodes in NodeList in place, removing nodes that do not
// satisfy the given condition
// TODO: consider merging with pkg/client/cache.NodeLister
func FilterNodes(nodeList *v1.NodeList, fn func(node v1.Node) bool) {
var l []v1.Node
for _, node := range nodeList.Items {
if fn(node) {
l = append(l, node)
}
}
nodeList.Items = l
}
// ParseKVLines parses output that looks like lines containing "<key>: <val>"
// and returns <val> if <key> is found. Otherwise, it returns the empty string.
func ParseKVLines(output, key string) string {
delim := ":"
key = key + delim
for _, line := range strings.Split(output, "\n") {
pieces := strings.SplitAfterN(line, delim, 2)
if len(pieces) != 2 {
continue
}
k, v := pieces[0], pieces[1]
if k == key {
return strings.TrimSpace(v)
}
}
return ""
}
func RestartKubeProxy(host string) error {
// TODO: Make it work for all providers.
if !ProviderIs("gce", "gke", "aws") {
return fmt.Errorf("unsupported provider: %s", TestContext.Provider)
}
// kubelet will restart the kube-proxy since it's running in a static pod
Logf("Killing kube-proxy on node %v", host)
result, err := SSH("sudo pkill kube-proxy", host, TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
return fmt.Errorf("couldn't restart kube-proxy: %v", err)
}
// wait for kube-proxy to come back up
sshCmd := "sudo /bin/sh -c 'pgrep kube-proxy | wc -l'"
err = wait.Poll(5*time.Second, 60*time.Second, func() (bool, error) {
Logf("Waiting for kubeproxy to come back up with %v on %v", sshCmd, host)
result, err := SSH(sshCmd, host, TestContext.Provider)
if err != nil {
return false, err
}
if result.Code != 0 {
LogSSHResult(result)
return false, fmt.Errorf("failed to run command, exited %d", result.Code)
}
if result.Stdout == "0\n" {
return false, nil
}
Logf("kube-proxy is back up.")
return true, nil
})
if err != nil {
return fmt.Errorf("kube-proxy didn't recover: %v", err)
}
return nil
}
func RestartKubelet(host string) error {
// TODO: Make it work for all providers and distros.
supportedProviders := []string{"gce", "aws", "vsphere"}
if !ProviderIs(supportedProviders...) {
return fmt.Errorf("unsupported provider: %s, supported providers are: %v", TestContext.Provider, supportedProviders)
}
if ProviderIs("gce") && !NodeOSDistroIs("debian", "gci") {
return fmt.Errorf("unsupported node OS distro: %s", TestContext.NodeOSDistro)
}
var cmd string
if ProviderIs("gce") && NodeOSDistroIs("debian") {
cmd = "sudo /etc/init.d/kubelet restart"
} else if ProviderIs("vsphere") {
var sudoPresent bool
sshResult, err := SSH("sudo --version", host, TestContext.Provider)
if err != nil {
return fmt.Errorf("Unable to ssh to host %s with error %v", host, err)
}
if !strings.Contains(sshResult.Stderr, "command not found") {
sudoPresent = true
}
sshResult, err = SSH("systemctl --version", host, TestContext.Provider)
if !strings.Contains(sshResult.Stderr, "command not found") {
cmd = "systemctl restart kubelet"
} else {
cmd = "service kubelet restart"
}
if sudoPresent {
cmd = fmt.Sprintf("sudo %s", cmd)
}
} else {
cmd = "sudo systemctl restart kubelet"
}
Logf("Restarting kubelet via ssh on host %s with command %s", host, cmd)
result, err := SSH(cmd, host, TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
return fmt.Errorf("couldn't restart kubelet: %v", err)
}
return nil
}
func WaitForKubeletUp(host string) error {
cmd := "curl http://localhost:" + strconv.Itoa(ports.KubeletReadOnlyPort) + "/healthz"
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
result, err := SSH(cmd, host, TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
}
if result.Stdout == "ok" {
return nil
}
}
return fmt.Errorf("waiting for kubelet timed out")
}
func RestartApiserver(cs clientset.Interface) error {
// TODO: Make it work for all providers.
if !ProviderIs("gce", "gke", "aws") {
return fmt.Errorf("unsupported provider: %s", TestContext.Provider)
}
if ProviderIs("gce", "aws") {
initialRestartCount, err := getApiserverRestartCount(cs)
if err != nil {
return fmt.Errorf("failed to get apiserver's restart count: %v", err)
}
if err := sshRestartMaster(); err != nil {
return fmt.Errorf("failed to restart apiserver: %v", err)
}
return waitForApiserverRestarted(cs, initialRestartCount)
}
// GKE doesn't allow ssh access, so use a same-version master
// upgrade to teardown/recreate master.
v, err := cs.Discovery().ServerVersion()
if err != nil {
return err
}
return masterUpgradeGKE(v.GitVersion[1:]) // strip leading 'v'
}
func sshRestartMaster() error {
if !ProviderIs("gce", "aws") {
return fmt.Errorf("unsupported provider: %s", TestContext.Provider)
}
var command string
if ProviderIs("gce") {
command = "pidof kube-apiserver | xargs sudo kill"
} else {
command = "sudo /etc/init.d/kube-apiserver restart"
}
Logf("Restarting master via ssh, running: %v", command)
result, err := SSH(command, net.JoinHostPort(GetMasterHost(), sshPort), TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
return fmt.Errorf("couldn't restart apiserver: %v", err)
}
return nil
}
func WaitForApiserverUp(c clientset.Interface) error {
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
body, err := c.CoreV1().RESTClient().Get().AbsPath("/healthz").Do().Raw()
if err == nil && string(body) == "ok" {
return nil
}
}
return fmt.Errorf("waiting for apiserver timed out")
}
// waitForApiserverRestarted waits until apiserver's restart count increased.
func waitForApiserverRestarted(c clientset.Interface, initialRestartCount int32) error {
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
restartCount, err := getApiserverRestartCount(c)
if err != nil {
Logf("Failed to get apiserver's restart count: %v", err)
continue
}
if restartCount > initialRestartCount {
Logf("Apiserver has restarted.")
return nil
}
Logf("Waiting for apiserver restart count to increase")
}
return fmt.Errorf("timed out waiting for apiserver to be restarted")
}
func getApiserverRestartCount(c clientset.Interface) (int32, error) {
label := labels.SelectorFromSet(labels.Set(map[string]string{"component": "kube-apiserver"}))
listOpts := metav1.ListOptions{LabelSelector: label.String()}
pods, err := c.CoreV1().Pods(metav1.NamespaceSystem).List(listOpts)
if err != nil {
return -1, err
}
if len(pods.Items) != 1 {
return -1, fmt.Errorf("unexpected number of apiserver pod: %d", len(pods.Items))
}
for _, s := range pods.Items[0].Status.ContainerStatuses {
if s.Name != "kube-apiserver" {
continue
}
return s.RestartCount, nil
}
return -1, fmt.Errorf("failed to find kube-apiserver container in pod")
}
func RestartControllerManager() error {
// TODO: Make it work for all providers and distros.
if !ProviderIs("gce", "aws") {
return fmt.Errorf("unsupported provider: %s", TestContext.Provider)
}
if ProviderIs("gce") && !MasterOSDistroIs("gci") {
return fmt.Errorf("unsupported master OS distro: %s", TestContext.MasterOSDistro)
}
cmd := "pidof kube-controller-manager | xargs sudo kill"
Logf("Restarting controller-manager via ssh, running: %v", cmd)
result, err := SSH(cmd, net.JoinHostPort(GetMasterHost(), sshPort), TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
return fmt.Errorf("couldn't restart controller-manager: %v", err)
}
return nil
}
func WaitForControllerManagerUp() error {
cmd := "curl http://localhost:" + strconv.Itoa(ports.InsecureKubeControllerManagerPort) + "/healthz"
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
result, err := SSH(cmd, net.JoinHostPort(GetMasterHost(), sshPort), TestContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
}
if result.Stdout == "ok" {
return nil
}
}
return fmt.Errorf("waiting for controller-manager timed out")
}
// CheckForControllerManagerHealthy checks that the controller manager does not crash within "duration"
func CheckForControllerManagerHealthy(duration time.Duration) error {
var PID string
cmd := "pidof kube-controller-manager"
for start := time.Now(); time.Since(start) < duration; time.Sleep(5 * time.Second) {
result, err := SSH(cmd, net.JoinHostPort(GetMasterHost(), sshPort), TestContext.Provider)
if err != nil {
// We don't necessarily know that it crashed, pipe could just be broken
LogSSHResult(result)
return fmt.Errorf("master unreachable after %v", time.Since(start))
} else if result.Code != 0 {
LogSSHResult(result)
return fmt.Errorf("SSH result code not 0. actually: %v after %v", result.Code, time.Since(start))
} else if result.Stdout != PID {
if PID == "" {
PID = result.Stdout
} else {
//its dead
return fmt.Errorf("controller manager crashed, old PID: %s, new PID: %s", PID, result.Stdout)
}
} else {
Logf("kube-controller-manager still healthy after %v", time.Since(start))
}
}
return nil
}
// NumberOfRegisteredNodes returns number of registered Nodes excluding Master Node.
func NumberOfRegisteredNodes(c clientset.Interface) (int, error) {
nodes, err := waitListSchedulableNodes(c)
if err != nil {
Logf("Failed to list nodes: %v", err)
return 0, err
}
return len(nodes.Items), nil
}
// NumberOfReadyNodes returns number of ready Nodes excluding Master Node.
func NumberOfReadyNodes(c clientset.Interface) (int, error) {
nodes, err := waitListSchedulableNodes(c)
if err != nil {
Logf("Failed to list nodes: %v", err)
return 0, err
}
// Filter out not-ready nodes.
FilterNodes(nodes, func(node v1.Node) bool {
return IsNodeConditionSetAsExpected(&node, v1.NodeReady, true)
})
return len(nodes.Items), nil
}
// WaitForReadyNodes waits until the cluster has desired size and there is no not-ready nodes in it.
// By cluster size we mean number of Nodes excluding Master Node.
func WaitForReadyNodes(c clientset.Interface, size int, timeout time.Duration) error {
for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) {
nodes, err := waitListSchedulableNodes(c)
if err != nil {
Logf("Failed to list nodes: %v", err)
continue
}
numNodes := len(nodes.Items)
// Filter out not-ready nodes.
FilterNodes(nodes, func(node v1.Node) bool {
return IsNodeConditionSetAsExpected(&node, v1.NodeReady, true)
})
numReady := len(nodes.Items)
if numNodes == size && numReady == size {
Logf("Cluster has reached the desired number of ready nodes %d", size)
return nil
}
Logf("Waiting for ready nodes %d, current ready %d, not ready nodes %d", size, numReady, numNodes-numReady)
}
return fmt.Errorf("timeout waiting %v for number of ready nodes to be %d", timeout, size)
}
func GenerateMasterRegexp(prefix string) string {
return prefix + "(-...)?"
}
// waitForMasters waits until the cluster has the desired number of ready masters in it.
func WaitForMasters(masterPrefix string, c clientset.Interface, size int, timeout time.Duration) error {
for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
Logf("Failed to list nodes: %v", err)
continue
}
// Filter out nodes that are not master replicas
FilterNodes(nodes, func(node v1.Node) bool {
res, err := regexp.Match(GenerateMasterRegexp(masterPrefix), ([]byte)(node.Name))
if err != nil {
Logf("Failed to match regexp to node name: %v", err)
return false
}
return res
})
numNodes := len(nodes.Items)
// Filter out not-ready nodes.
FilterNodes(nodes, func(node v1.Node) bool {
return IsNodeConditionSetAsExpected(&node, v1.NodeReady, true)
})
numReady := len(nodes.Items)
if numNodes == size && numReady == size {
Logf("Cluster has reached the desired number of masters %d", size)
return nil
}
Logf("Waiting for the number of masters %d, current %d, not ready master nodes %d", size, numNodes, numNodes-numReady)
}
return fmt.Errorf("timeout waiting %v for the number of masters to be %d", timeout, size)
}
// GetHostExternalAddress gets the node for a pod and returns the first External
// address. Returns an error if the node the pod is on doesn't have an External
// address.
func GetHostExternalAddress(client clientset.Interface, p *v1.Pod) (externalAddress string, err error) {
node, err := client.CoreV1().Nodes().Get(p.Spec.NodeName, metav1.GetOptions{})
if err != nil {
return "", err
}
for _, address := range node.Status.Addresses {
if address.Type == v1.NodeExternalIP {
if address.Address != "" {
externalAddress = address.Address
break
}
}
}
if externalAddress == "" {
err = fmt.Errorf("No external address for pod %v on node %v",
p.Name, p.Spec.NodeName)
}
return
}
type extractRT struct {
http.Header
}
func (rt *extractRT) RoundTrip(req *http.Request) (*http.Response, error) {
rt.Header = req.Header
return &http.Response{}, nil
}
// headersForConfig extracts any http client logic necessary for the provided
// config.
func headersForConfig(c *restclient.Config) (http.Header, error) {
extract := &extractRT{}
rt, err := restclient.HTTPWrappersForConfig(c, extract)
if err != nil {
return nil, err
}
if _, err := rt.RoundTrip(&http.Request{}); err != nil {
return nil, err
}
return extract.Header, nil
}
// OpenWebSocketForURL constructs a websocket connection to the provided URL, using the client
// config, with the specified protocols.
func OpenWebSocketForURL(url *url.URL, config *restclient.Config, protocols []string) (*websocket.Conn, error) {
tlsConfig, err := restclient.TLSConfigFor(config)
if err != nil {
return nil, fmt.Errorf("failed to create tls config: %v", err)
}
if tlsConfig != nil {
url.Scheme = "wss"
if !strings.Contains(url.Host, ":") {
url.Host += ":443"
}
} else {
url.Scheme = "ws"
if !strings.Contains(url.Host, ":") {
url.Host += ":80"
}
}
headers, err := headersForConfig(config)
if err != nil {
return nil, fmt.Errorf("failed to load http headers: %v", err)
}
cfg, err := websocket.NewConfig(url.String(), "http://localhost")
if err != nil {
return nil, fmt.Errorf("failed to create websocket config: %v", err)
}
cfg.Header = headers
cfg.TlsConfig = tlsConfig
cfg.Protocol = protocols
return websocket.DialConfig(cfg)
}
// Looks for the given string in the log of a specific pod container
func LookForStringInLog(ns, podName, container, expectedString string, timeout time.Duration) (result string, err error) {
return LookForString(expectedString, timeout, func() string {
return RunKubectlOrDie("logs", podName, container, fmt.Sprintf("--namespace=%v", ns))
})
}
// Looks for the given string in a file in a specific pod container
func LookForStringInFile(ns, podName, container, file, expectedString string, timeout time.Duration) (result string, err error) {
return LookForString(expectedString, timeout, func() string {
return RunKubectlOrDie("exec", podName, "-c", container, fmt.Sprintf("--namespace=%v", ns), "--", "cat", file)
})
}
// Looks for the given string in the output of a command executed in a specific pod container
func LookForStringInPodExec(ns, podName string, command []string, expectedString string, timeout time.Duration) (result string, err error) {
return LookForString(expectedString, timeout, func() string {
// use the first container
args := []string{"exec", podName, fmt.Sprintf("--namespace=%v", ns), "--"}
args = append(args, command...)
return RunKubectlOrDie(args...)
})
}
// Looks for the given string in the output of fn, repeatedly calling fn until
// the timeout is reached or the string is found. Returns last log and possibly
// error if the string was not found.
func LookForString(expectedString string, timeout time.Duration, fn func() string) (result string, err error) {
for t := time.Now(); time.Since(t) < timeout; time.Sleep(Poll) {
result = fn()
if strings.Contains(result, expectedString) {
return
}
}
err = fmt.Errorf("Failed to find \"%s\", last result: \"%s\"", expectedString, result)
return
}
// getSvcNodePort returns the node port for the given service:port.
func getSvcNodePort(client clientset.Interface, ns, name string, svcPort int) (int, error) {
svc, err := client.CoreV1().Services(ns).Get(name, metav1.GetOptions{})
if err != nil {
return 0, err
}
for _, p := range svc.Spec.Ports {
if p.Port == int32(svcPort) {
if p.NodePort != 0 {
return int(p.NodePort), nil
}
}
}
return 0, fmt.Errorf(
"No node port found for service %v, port %v", name, svcPort)
}
// GetNodePortURL returns the url to a nodeport Service.
func GetNodePortURL(client clientset.Interface, ns, name string, svcPort int) (string, error) {
nodePort, err := getSvcNodePort(client, ns, name, svcPort)
if err != nil {
return "", err
}
// This list of nodes must not include the master, which is marked
// unschedulable, since the master doesn't run kube-proxy. Without
// kube-proxy NodePorts won't work.
var nodes *v1.NodeList
if wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) {
nodes, err = client.CoreV1().Nodes().List(metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
if testutils.IsRetryableAPIError(err) {
return false, nil
}
return false, err
}
return true, nil
}) != nil {
return "", err
}
if len(nodes.Items) == 0 {
return "", fmt.Errorf("Unable to list nodes in cluster.")
}
for _, node := range nodes.Items {
for _, address := range node.Status.Addresses {
if address.Type == v1.NodeExternalIP {
if address.Address != "" {
return fmt.Sprintf("http://%v:%v", address.Address, nodePort), nil
}
}
}
}
return "", fmt.Errorf("Failed to find external address for service %v", name)
}
// TODO(random-liu): Change this to be a member function of the framework.
func GetPodLogs(c clientset.Interface, namespace, podName, containerName string) (string, error) {
return getPodLogsInternal(c, namespace, podName, containerName, false)
}
func getPreviousPodLogs(c clientset.Interface, namespace, podName, containerName string) (string, error) {
return getPodLogsInternal(c, namespace, podName, containerName, true)
}
// utility function for gomega Eventually
func getPodLogsInternal(c clientset.Interface, namespace, podName, containerName string, previous bool) (string, error) {
logs, err := c.CoreV1().RESTClient().Get().
Resource("pods").
Namespace(namespace).
Name(podName).SubResource("log").
Param("container", containerName).
Param("previous", strconv.FormatBool(previous)).
Do().
Raw()
if err != nil {
return "", err
}
if err == nil && strings.Contains(string(logs), "Internal Error") {
return "", fmt.Errorf("Fetched log contains \"Internal Error\": %q.", string(logs))
}
return string(logs), err
}
func GetGCECloud() (*gcecloud.GCECloud, error) {
gceCloud, ok := TestContext.CloudConfig.Provider.(*gcecloud.GCECloud)
if !ok {
return nil, fmt.Errorf("failed to convert CloudConfig.Provider to GCECloud: %#v", TestContext.CloudConfig.Provider)
}
return gceCloud, nil
}
// EnsureLoadBalancerResourcesDeleted ensures that cloud load balancer resources that were created
// are actually cleaned up. Currently only implemented for GCE/GKE.
func EnsureLoadBalancerResourcesDeleted(ip, portRange string) error {
if TestContext.Provider == "gce" || TestContext.Provider == "gke" {
return ensureGCELoadBalancerResourcesDeleted(ip, portRange)
}
return nil
}
func ensureGCELoadBalancerResourcesDeleted(ip, portRange string) error {
gceCloud, err := GetGCECloud()
if err != nil {
return err
}
project := TestContext.CloudConfig.ProjectID
region, err := gcecloud.GetGCERegion(TestContext.CloudConfig.Zone)
if err != nil {
return fmt.Errorf("could not get region for zone %q: %v", TestContext.CloudConfig.Zone, err)
}
return wait.Poll(10*time.Second, 5*time.Minute, func() (bool, error) {
service := gceCloud.ComputeServices().GA
list, err := service.ForwardingRules.List(project, region).Do()
if err != nil {
return false, err
}
for _, item := range list.Items {
if item.PortRange == portRange && item.IPAddress == ip {
Logf("found a load balancer: %v", item)
return false, nil
}
}
return true, nil
})
}
// The following helper functions can block/unblock network from source
// host to destination host by manipulating iptable rules.
// This function assumes it can ssh to the source host.
//
// Caution:
// Recommend to input IP instead of hostnames. Using hostnames will cause iptables to
// do a DNS lookup to resolve the name to an IP address, which will
// slow down the test and cause it to fail if DNS is absent or broken.
//
// Suggested usage pattern:
// func foo() {
// ...
// defer UnblockNetwork(from, to)
// BlockNetwork(from, to)
// ...
// }
//
func BlockNetwork(from string, to string) {
Logf("block network traffic from %s to %s", from, to)
iptablesRule := fmt.Sprintf("OUTPUT --destination %s --jump REJECT", to)
dropCmd := fmt.Sprintf("sudo iptables --insert %s", iptablesRule)
if result, err := SSH(dropCmd, from, TestContext.Provider); result.Code != 0 || err != nil {
LogSSHResult(result)
Failf("Unexpected error: %v", err)
}
}
func UnblockNetwork(from string, to string) {
Logf("Unblock network traffic from %s to %s", from, to)
iptablesRule := fmt.Sprintf("OUTPUT --destination %s --jump REJECT", to)
undropCmd := fmt.Sprintf("sudo iptables --delete %s", iptablesRule)
// Undrop command may fail if the rule has never been created.
// In such case we just lose 30 seconds, but the cluster is healthy.
// But if the rule had been created and removing it failed, the node is broken and
// not coming back. Subsequent tests will run or fewer nodes (some of the tests
// may fail). Manual intervention is required in such case (recreating the
// cluster solves the problem too).
err := wait.Poll(time.Millisecond*100, time.Second*30, func() (bool, error) {
result, err := SSH(undropCmd, from, TestContext.Provider)
if result.Code == 0 && err == nil {
return true, nil
}
LogSSHResult(result)
if err != nil {
Logf("Unexpected error: %v", err)
}
return false, nil
})
if err != nil {
Failf("Failed to remove the iptable REJECT rule. Manual intervention is "+
"required on host %s: remove rule %s, if exists", from, iptablesRule)
}
}
func isElementOf(podUID types.UID, pods *v1.PodList) bool {
for _, pod := range pods.Items {
if pod.UID == podUID {
return true
}
}
return false
}
// timeout for proxy requests.
const proxyTimeout = 2 * time.Minute
// NodeProxyRequest performs a get on a node proxy endpoint given the nodename and rest client.
func NodeProxyRequest(c clientset.Interface, node, endpoint string) (restclient.Result, error) {
// proxy tends to hang in some cases when Node is not ready. Add an artificial timeout for this call.
// This will leak a goroutine if proxy hangs. #22165
var result restclient.Result
finished := make(chan struct{})
go func() {
result = c.CoreV1().RESTClient().Get().
Resource("nodes").
SubResource("proxy").
Name(fmt.Sprintf("%v:%v", node, ports.KubeletPort)).
Suffix(endpoint).
Do()
finished <- struct{}{}
}()
select {
case <-finished:
return result, nil
case <-time.After(proxyTimeout):
return restclient.Result{}, nil
}
}
// GetKubeletPods retrieves the list of pods on the kubelet
func GetKubeletPods(c clientset.Interface, node string) (*v1.PodList, error) {
return getKubeletPods(c, node, "pods")
}
// GetKubeletRunningPods retrieves the list of running pods on the kubelet. The pods
// includes necessary information (e.g., UID, name, namespace for
// pods/containers), but do not contain the full spec.
func GetKubeletRunningPods(c clientset.Interface, node string) (*v1.PodList, error) {
return getKubeletPods(c, node, "runningpods")
}
func getKubeletPods(c clientset.Interface, node, resource string) (*v1.PodList, error) {
result := &v1.PodList{}
client, err := NodeProxyRequest(c, node, resource)
if err != nil {
return &v1.PodList{}, err
}
if err = client.Into(result); err != nil {
return &v1.PodList{}, err
}
return result, nil
}
// LaunchWebserverPod launches a pod serving http on port 8080 to act
// as the target for networking connectivity checks. The ip address
// of the created pod will be returned if the pod is launched
// successfully.
func LaunchWebserverPod(f *Framework, podName, nodeName string) (ip string) {
containerName := fmt.Sprintf("%s-container", podName)
port := 8080
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: containerName,
Image: imageutils.GetE2EImage(imageutils.Porter),
Env: []v1.EnvVar{{Name: fmt.Sprintf("SERVE_PORT_%d", port), Value: "foo"}},
Ports: []v1.ContainerPort{{ContainerPort: int32(port)}},
},
},
NodeName: nodeName,
RestartPolicy: v1.RestartPolicyNever,
},
}
podClient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)
_, err := podClient.Create(pod)
ExpectNoError(err)
ExpectNoError(f.WaitForPodRunning(podName))
createdPod, err := podClient.Get(podName, metav1.GetOptions{})
ExpectNoError(err)
ip = net.JoinHostPort(createdPod.Status.PodIP, strconv.Itoa(port))
Logf("Target pod IP:port is %s", ip)
return
}
type PingCommand string
const (
IPv4PingCommand PingCommand = "ping"
IPv6PingCommand PingCommand = "ping6"
)
// CheckConnectivityToHost launches a pod to test connectivity to the specified
// host. An error will be returned if the host is not reachable from the pod.
//
// An empty nodeName will use the schedule to choose where the pod is executed.
func CheckConnectivityToHost(f *Framework, nodeName, podName, host string, pingCmd PingCommand, timeout int) error {
contName := fmt.Sprintf("%s-container", podName)
command := []string{
string(pingCmd),
"-c", "3", // send 3 pings
"-W", "2", // wait at most 2 seconds for a reply
"-w", strconv.Itoa(timeout),
host,
}
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: contName,
Image: BusyBoxImage,
Command: command,
},
},
NodeName: nodeName,
RestartPolicy: v1.RestartPolicyNever,
},
}
podClient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)
_, err := podClient.Create(pod)
if err != nil {
return err
}
err = WaitForPodSuccessInNamespace(f.ClientSet, podName, f.Namespace.Name)
if err != nil {
logs, logErr := GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, contName)
if logErr != nil {
Logf("Warning: Failed to get logs from pod %q: %v", pod.Name, logErr)
} else {
Logf("pod %s/%s logs:\n%s", f.Namespace.Name, pod.Name, logs)
}
}
return err
}
// CoreDump SSHs to the master and all nodes and dumps their logs into dir.
// It shells out to cluster/log-dump/log-dump.sh to accomplish this.
func CoreDump(dir string) {
if TestContext.DisableLogDump {
Logf("Skipping dumping logs from cluster")
return
}
var cmd *exec.Cmd
if TestContext.LogexporterGCSPath != "" {
Logf("Dumping logs from nodes to GCS directly at path: %s", TestContext.LogexporterGCSPath)
cmd = exec.Command(path.Join(TestContext.RepoRoot, "cluster", "log-dump", "log-dump.sh"), dir, TestContext.LogexporterGCSPath)
} else {
Logf("Dumping logs locally to: %s", dir)
cmd = exec.Command(path.Join(TestContext.RepoRoot, "cluster", "log-dump", "log-dump.sh"), dir)
}
cmd.Env = append(os.Environ(), fmt.Sprintf("LOG_DUMP_SYSTEMD_SERVICES=%s", parseSystemdServices(TestContext.SystemdServices)))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
Logf("Error running cluster/log-dump/log-dump.sh: %v", err)
}
}
// parseSystemdServices converts services separator from comma to space.
func parseSystemdServices(services string) string {
return strings.TrimSpace(strings.Replace(services, ",", " ", -1))
}
func UpdatePodWithRetries(client clientset.Interface, ns, name string, update func(*v1.Pod)) (*v1.Pod, error) {
for i := 0; i < 3; i++ {
pod, err := client.CoreV1().Pods(ns).Get(name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("Failed to get pod %q: %v", name, err)
}
update(pod)
pod, err = client.CoreV1().Pods(ns).Update(pod)
if err == nil {
return pod, nil
}
if !apierrs.IsConflict(err) && !apierrs.IsServerTimeout(err) {
return nil, fmt.Errorf("Failed to update pod %q: %v", name, err)
}
}
return nil, fmt.Errorf("Too many retries updating Pod %q", name)
}
func GetPodsInNamespace(c clientset.Interface, ns string, ignoreLabels map[string]string) ([]*v1.Pod, error) {
pods, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{})
if err != nil {
return []*v1.Pod{}, err
}
ignoreSelector := labels.SelectorFromSet(ignoreLabels)
filtered := []*v1.Pod{}
for _, p := range pods.Items {
if len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(p.Labels)) {
continue
}
filtered = append(filtered, &p)
}
return filtered, nil
}
// RunCmd runs cmd using args and returns its stdout and stderr. It also outputs
// cmd's stdout and stderr to their respective OS streams.
func RunCmd(command string, args ...string) (string, string, error) {
return RunCmdEnv(nil, command, args...)
}
// RunCmdEnv runs cmd with the provided environment and args and
// returns its stdout and stderr. It also outputs cmd's stdout and
// stderr to their respective OS streams.
func RunCmdEnv(env []string, command string, args ...string) (string, string, error) {
Logf("Running %s %v", command, args)
var bout, berr bytes.Buffer
cmd := exec.Command(command, args...)
// We also output to the OS stdout/stderr to aid in debugging in case cmd
// hangs and never returns before the test gets killed.
//
// This creates some ugly output because gcloud doesn't always provide
// newlines.
cmd.Stdout = io.MultiWriter(os.Stdout, &bout)
cmd.Stderr = io.MultiWriter(os.Stderr, &berr)
cmd.Env = env
err := cmd.Run()
stdout, stderr := bout.String(), berr.String()
if err != nil {
return "", "", fmt.Errorf("error running %s %v; got error %v, stdout %q, stderr %q",
command, args, err, stdout, stderr)
}
return stdout, stderr, nil
}
// retryCmd runs cmd using args and retries it for up to SingleCallTimeout if
// it returns an error. It returns stdout and stderr.
func retryCmd(command string, args ...string) (string, string, error) {
var err error
stdout, stderr := "", ""
wait.Poll(Poll, SingleCallTimeout, func() (bool, error) {
stdout, stderr, err = RunCmd(command, args...)
if err != nil {
Logf("Got %v", err)
return false, nil
}
return true, nil
})
return stdout, stderr, err
}
// GetPodsScheduled returns a number of currently scheduled and not scheduled Pods.
func GetPodsScheduled(masterNodes sets.String, pods *v1.PodList) (scheduledPods, notScheduledPods []v1.Pod) {
for _, pod := range pods.Items {
if !masterNodes.Has(pod.Spec.NodeName) {
if pod.Spec.NodeName != "" {
_, scheduledCondition := podutil.GetPodCondition(&pod.Status, v1.PodScheduled)
Expect(scheduledCondition != nil).To(Equal(true))
Expect(scheduledCondition.Status).To(Equal(v1.ConditionTrue))
scheduledPods = append(scheduledPods, pod)
} else {
_, scheduledCondition := podutil.GetPodCondition(&pod.Status, v1.PodScheduled)
Expect(scheduledCondition != nil).To(Equal(true))
Expect(scheduledCondition.Status).To(Equal(v1.ConditionFalse))
if scheduledCondition.Reason == "Unschedulable" {
notScheduledPods = append(notScheduledPods, pod)
}
}
}
}
return
}
// WaitForStableCluster waits until all existing pods are scheduled and returns their amount.
func WaitForStableCluster(c clientset.Interface, masterNodes sets.String) int {
timeout := 10 * time.Minute
startTime := time.Now()
allPods, err := c.CoreV1().Pods(metav1.NamespaceAll).List(metav1.ListOptions{})
ExpectNoError(err)
// API server returns also Pods that succeeded. We need to filter them out.
currentPods := make([]v1.Pod, 0, len(allPods.Items))
for _, pod := range allPods.Items {
if pod.Status.Phase != v1.PodSucceeded && pod.Status.Phase != v1.PodFailed {
currentPods = append(currentPods, pod)
}
}
allPods.Items = currentPods
scheduledPods, currentlyNotScheduledPods := GetPodsScheduled(masterNodes, allPods)
for len(currentlyNotScheduledPods) != 0 {
time.Sleep(2 * time.Second)
allPods, err := c.CoreV1().Pods(metav1.NamespaceAll).List(metav1.ListOptions{})
ExpectNoError(err)
scheduledPods, currentlyNotScheduledPods = GetPodsScheduled(masterNodes, allPods)
if startTime.Add(timeout).Before(time.Now()) {
Failf("Timed out after %v waiting for stable cluster.", timeout)
break
}
}
return len(scheduledPods)
}
// GetMasterAndWorkerNodesOrDie will return a list masters and schedulable worker nodes
func GetMasterAndWorkerNodesOrDie(c clientset.Interface) (sets.String, *v1.NodeList) {
nodes := &v1.NodeList{}
masters := sets.NewString()
all, _ := c.CoreV1().Nodes().List(metav1.ListOptions{})
for _, n := range all.Items {
if system.IsMasterNode(n.Name) {
masters.Insert(n.Name)
} else if isNodeSchedulable(&n) && isNodeUntainted(&n) {
nodes.Items = append(nodes.Items, n)
}
}
return masters, nodes
}
func ListNamespaceEvents(c clientset.Interface, ns string) error {
ls, err := c.CoreV1().Events(ns).List(metav1.ListOptions{})
if err != nil {
return err
}
for _, event := range ls.Items {
glog.Infof("Event(%#v): type: '%v' reason: '%v' %v", event.InvolvedObject, event.Type, event.Reason, event.Message)
}
return nil
}
// E2ETestNodePreparer implements testutils.TestNodePreparer interface, which is used
// to create/modify Nodes before running a test.
type E2ETestNodePreparer struct {
client clientset.Interface
// Specifies how many nodes should be modified using the given strategy.
// Only one strategy can be applied to a single Node, so there needs to
// be at least <sum_of_keys> Nodes in the cluster.
countToStrategy []testutils.CountToStrategy
nodeToAppliedStrategy map[string]testutils.PrepareNodeStrategy
}
func NewE2ETestNodePreparer(client clientset.Interface, countToStrategy []testutils.CountToStrategy) testutils.TestNodePreparer {
return &E2ETestNodePreparer{
client: client,
countToStrategy: countToStrategy,
nodeToAppliedStrategy: make(map[string]testutils.PrepareNodeStrategy),
}
}
func (p *E2ETestNodePreparer) PrepareNodes() error {
nodes := GetReadySchedulableNodesOrDie(p.client)
numTemplates := 0
for k := range p.countToStrategy {
numTemplates += k
}
if numTemplates > len(nodes.Items) {
return fmt.Errorf("Can't prepare Nodes. Got more templates than existing Nodes.")
}
index := 0
sum := 0
for _, v := range p.countToStrategy {
sum += v.Count
for ; index < sum; index++ {
if err := testutils.DoPrepareNode(p.client, &nodes.Items[index], v.Strategy); err != nil {
glog.Errorf("Aborting node preparation: %v", err)
return err
}
p.nodeToAppliedStrategy[nodes.Items[index].Name] = v.Strategy
}
}
return nil
}
func (p *E2ETestNodePreparer) CleanupNodes() error {
var encounteredError error
nodes := GetReadySchedulableNodesOrDie(p.client)
for i := range nodes.Items {
var err error
name := nodes.Items[i].Name
strategy, found := p.nodeToAppliedStrategy[name]
if found {
if err = testutils.DoCleanupNode(p.client, name, strategy); err != nil {
glog.Errorf("Skipping cleanup of Node: failed update of %v: %v", name, err)
encounteredError = err
}
}
}
return encounteredError
}
func GetClusterID(c clientset.Interface) (string, error) {
cm, err := c.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(gcecloud.UIDConfigMapName, metav1.GetOptions{})
if err != nil || cm == nil {
return "", fmt.Errorf("error getting cluster ID: %v", err)
}
clusterID, clusterIDExists := cm.Data[gcecloud.UIDCluster]
providerID, providerIDExists := cm.Data[gcecloud.UIDProvider]
if !clusterIDExists {
return "", fmt.Errorf("cluster ID not set")
}
if providerIDExists {
return providerID, nil
}
return clusterID, nil
}
// CleanupGCEResources cleans up GCE Service Type=LoadBalancer resources with
// the given name. The name is usually the UUID of the Service prefixed with an
// alpha-numeric character ('a') to work around cloudprovider rules.
func CleanupGCEResources(c clientset.Interface, loadBalancerName, region, zone string) (retErr error) {
gceCloud, err := GetGCECloud()
if err != nil {
return err
}
if region == "" {
// Attempt to parse region from zone if no region is given.
region, err = gcecloud.GetGCERegion(zone)
if err != nil {
return fmt.Errorf("error parsing GCE/GKE region from zone %q: %v", zone, err)
}
}
if err := gceCloud.DeleteFirewall(gcecloud.MakeFirewallName(loadBalancerName)); err != nil &&
!IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) {
retErr = err
}
if err := gceCloud.DeleteRegionForwardingRule(loadBalancerName, region); err != nil &&
!IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) {
retErr = fmt.Errorf("%v\n%v", retErr, err)
}
if err := gceCloud.DeleteRegionAddress(loadBalancerName, region); err != nil &&
!IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) {
retErr = fmt.Errorf("%v\n%v", retErr, err)
}
clusterID, err := GetClusterID(c)
if err != nil {
retErr = fmt.Errorf("%v\n%v", retErr, err)
return
}
hcNames := []string{gcecloud.MakeNodesHealthCheckName(clusterID)}
hc, getErr := gceCloud.GetHttpHealthCheck(loadBalancerName)
if getErr != nil && !IsGoogleAPIHTTPErrorCode(getErr, http.StatusNotFound) {
retErr = fmt.Errorf("%v\n%v", retErr, getErr)
return
}
if hc != nil {
hcNames = append(hcNames, hc.Name)
}
if err := gceCloud.DeleteExternalTargetPoolAndChecks(&v1.Service{}, loadBalancerName, region, clusterID, hcNames...); err != nil &&
!IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) {
retErr = fmt.Errorf("%v\n%v", retErr, err)
}
return
}
// IsHTTPErrorCode returns true if the error is a google api
// error matching the corresponding HTTP error code.
func IsGoogleAPIHTTPErrorCode(err error, code int) bool {
apiErr, ok := err.(*googleapi.Error)
return ok && apiErr.Code == code
}
// getMaster populates the externalIP, internalIP and hostname fields of the master.
// If any of these is unavailable, it is set to "".
func getMaster(c clientset.Interface) Address {
master := Address{}
// Populate the internal IP.
eps, err := c.CoreV1().Endpoints(metav1.NamespaceDefault).Get("kubernetes", metav1.GetOptions{})
if err != nil {
Failf("Failed to get kubernetes endpoints: %v", err)
}
if len(eps.Subsets) != 1 || len(eps.Subsets[0].Addresses) != 1 {
Failf("There are more than 1 endpoints for kubernetes service: %+v", eps)
}
master.internalIP = eps.Subsets[0].Addresses[0].IP
// Populate the external IP/hostname.
url, err := url.Parse(TestContext.Host)
if err != nil {
Failf("Failed to parse hostname: %v", err)
}
if net.ParseIP(url.Host) != nil {
// TODO: Check that it is external IP (not having a reserved IP address as per RFC1918).
master.externalIP = url.Host
} else {
master.hostname = url.Host
}
return master
}
// GetMasterAddress returns the hostname/external IP/internal IP as appropriate for e2e tests on a particular provider
// which is the address of the interface used for communication with the kubelet.
func GetMasterAddress(c clientset.Interface) string {
master := getMaster(c)
switch TestContext.Provider {
case "gce", "gke":
return master.externalIP
case "aws":
return awsMasterIP
default:
Failf("This test is not supported for provider %s and should be disabled", TestContext.Provider)
}
return ""
}
// GetNodeExternalIP returns node external IP concatenated with port 22 for ssh
// e.g. 1.2.3.4:22
func GetNodeExternalIP(node *v1.Node) string {
Logf("Getting external IP address for %s", node.Name)
host := ""
for _, a := range node.Status.Addresses {
if a.Type == v1.NodeExternalIP {
host = net.JoinHostPort(a.Address, sshPort)
break
}
}
if host == "" {
Failf("Couldn't get the external IP of host %s with addresses %v", node.Name, node.Status.Addresses)
}
return host
}
// SimpleGET executes a get on the given url, returns error if non-200 returned.
func SimpleGET(c *http.Client, url, host string) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Host = host
res, err := c.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
rawBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
body := string(rawBody)
if res.StatusCode != http.StatusOK {
err = fmt.Errorf(
"GET returned http error %v", res.StatusCode)
}
return body, err
}
// PollURL polls till the url responds with a healthy http code. If
// expectUnreachable is true, it breaks on first non-healthy http code instead.
func PollURL(route, host string, timeout time.Duration, interval time.Duration, httpClient *http.Client, expectUnreachable bool) error {
var lastBody string
pollErr := wait.PollImmediate(interval, timeout, func() (bool, error) {
var err error
lastBody, err = SimpleGET(httpClient, route, host)
if err != nil {
Logf("host %v path %v: %v unreachable", host, route, err)
return expectUnreachable, nil
}
Logf("host %v path %v: reached", host, route)
return !expectUnreachable, nil
})
if pollErr != nil {
return fmt.Errorf("Failed to execute a successful GET within %v, Last response body for %v, host %v:\n%v\n\n%v\n",
timeout, route, host, lastBody, pollErr)
}
return nil
}
func DescribeIng(ns string) {
Logf("\nOutput of kubectl describe ing:\n")
desc, _ := RunKubectl(
"describe", "ing", fmt.Sprintf("--namespace=%v", ns))
Logf(desc)
}
// NewTestPod returns a pod that has the specified requests and limits
func (f *Framework) NewTestPod(name string, requests v1.ResourceList, limits v1.ResourceList) *v1.Pod {
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "pause",
Image: GetPauseImageName(f.ClientSet),
Resources: v1.ResourceRequirements{
Requests: requests,
Limits: limits,
},
},
},
},
}
}
// create empty file at given path on the pod.
func CreateEmptyFileOnPod(namespace string, podName string, filePath string) error {
_, err := RunKubectl("exec", fmt.Sprintf("--namespace=%s", namespace), podName, "--", "/bin/sh", "-c", fmt.Sprintf("touch %s", filePath))
return err
}
// GetAzureCloud returns azure cloud provider
func GetAzureCloud() (*azure.Cloud, error) {
cloud, ok := TestContext.CloudConfig.Provider.(*azure.Cloud)
if !ok {
return nil, fmt.Errorf("failed to convert CloudConfig.Provider to Azure: %#v", TestContext.CloudConfig.Provider)
}
return cloud, nil
}
func PrintSummaries(summaries []TestDataSummary, testBaseName string) {
now := time.Now()
for i := range summaries {
Logf("Printing summary: %v", summaries[i].SummaryKind())
switch TestContext.OutputPrintType {
case "hr":
if TestContext.ReportDir == "" {
Logf(summaries[i].PrintHumanReadable())
} else {
// TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".txt")
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintHumanReadable()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err)
}
}
case "json":
fallthrough
default:
if TestContext.OutputPrintType != "json" {
Logf("Unknown output type: %v. Printing JSON", TestContext.OutputPrintType)
}
if TestContext.ReportDir == "" {
Logf("%v JSON\n%v", summaries[i].SummaryKind(), summaries[i].PrintJSON())
Logf("Finished")
} else {
// TODO: learn to extract test name and append it to the kind instead of timestamp.
filePath := path.Join(TestContext.ReportDir, summaries[i].SummaryKind()+"_"+testBaseName+"_"+now.Format(time.RFC3339)+".json")
Logf("Writing to %s", filePath)
if err := ioutil.WriteFile(filePath, []byte(summaries[i].PrintJSON()), 0644); err != nil {
Logf("Failed to write file %v with test performance data: %v", filePath, err)
}
}
}
}
}
func DumpDebugInfo(c clientset.Interface, ns string) {
sl, _ := c.CoreV1().Pods(ns).List(metav1.ListOptions{LabelSelector: labels.Everything().String()})
for _, s := range sl.Items {
desc, _ := RunKubectl("describe", "po", s.Name, fmt.Sprintf("--namespace=%v", ns))
Logf("\nOutput of kubectl describe %v:\n%v", s.Name, desc)
l, _ := RunKubectl("logs", s.Name, fmt.Sprintf("--namespace=%v", ns), "--tail=100")
Logf("\nLast 100 log lines of %v:\n%v", s.Name, l)
}
}
// DsFromManifest reads a .json/yaml file and returns the daemonset in it.
func DsFromManifest(url string) (*extensions.DaemonSet, error) {
var controller extensions.DaemonSet
Logf("Parsing ds from %v", url)
var response *http.Response
var err error
for i := 1; i <= 5; i++ {
response, err = http.Get(url)
if err == nil && response.StatusCode == 200 {
break
}
time.Sleep(time.Duration(i) * time.Second)
}
if err != nil {
return nil, fmt.Errorf("failed to get url: %v", err)
}
if response.StatusCode != 200 {
return nil, fmt.Errorf("invalid http response status: %v", response.StatusCode)
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read html response body: %v", err)
}
json, err := utilyaml.ToJSON(data)
if err != nil {
return nil, fmt.Errorf("failed to parse data to json: %v", err)
}
err = runtime.DecodeInto(legacyscheme.Codecs.UniversalDecoder(), json, &controller)
if err != nil {
return nil, fmt.Errorf("failed to decode DaemonSet spec: %v", err)
}
return &controller, nil
}
// waitForServerPreferredNamespacedResources waits until server preferred namespaced resources could be successfully discovered.
// TODO: Fix https://github.com/kubernetes/kubernetes/issues/55768 and remove the following retry.
func waitForServerPreferredNamespacedResources(d discovery.DiscoveryInterface, timeout time.Duration) ([]*metav1.APIResourceList, error) {
Logf("Waiting up to %v for server preferred namespaced resources to be successfully discovered", timeout)
var resources []*metav1.APIResourceList
if err := wait.PollImmediate(Poll, timeout, func() (bool, error) {
var err error
resources, err = d.ServerPreferredNamespacedResources()
if err == nil || isDynamicDiscoveryError(err) {
return true, nil
}
if !discovery.IsGroupDiscoveryFailedError(err) {
return false, err
}
Logf("Error discoverying server preferred namespaced resources: %v, retrying in %v.", err, Poll)
return false, nil
}); err != nil {
return nil, err
}
return resources, nil
}
// WaitForPersistentVolumeClaimDeleted waits for a PersistentVolumeClaim to be removed from the system until timeout occurs, whichever comes first.
func WaitForPersistentVolumeClaimDeleted(c clientset.Interface, ns string, pvcName string, Poll, timeout time.Duration) error {
Logf("Waiting up to %v for PersistentVolumeClaim %s to be removed", timeout, pvcName)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) {
_, err := c.CoreV1().PersistentVolumeClaims(ns).Get(pvcName, metav1.GetOptions{})
if err != nil {
if apierrs.IsNotFound(err) {
Logf("Claim %q in namespace %q doesn't exist in the system", pvcName, ns)
return nil
}
Logf("Failed to get claim %q in namespace %q, retrying in %v. Error: %v", pvcName, ns, Poll, err)
}
}
return fmt.Errorf("PersistentVolumeClaim %s is not removed from the system within %v", pvcName, timeout)
}
func GetClusterZones(c clientset.Interface) (sets.String, error) {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("Error getting nodes while attempting to list cluster zones: %v", err)
}
// collect values of zone label from all nodes
zones := sets.NewString()
for _, node := range nodes.Items {
if zone, found := node.Labels[kubeletapis.LabelZoneFailureDomain]; found {
zones.Insert(zone)
}
}
return zones, nil
}
| {
"content_hash": "fda25d82df7cf4bef1601843e0574d3b",
"timestamp": "",
"source": "github",
"line_count": 5246,
"max_line_length": 195,
"avg_line_length": 35.18051849027831,
"alnum_prop": 0.7079872342961795,
"repo_name": "krousey/kubernetes",
"id": "19e090e4be9818011124adb14a02afb32b76caea",
"size": "185126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/e2e/framework/util.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Go",
"bytes": "41362248"
},
{
"name": "HTML",
"bytes": "1199467"
},
{
"name": "Makefile",
"bytes": "79223"
},
{
"name": "Python",
"bytes": "2719327"
},
{
"name": "Ruby",
"bytes": "1780"
},
{
"name": "Shell",
"bytes": "1417136"
}
],
"symlink_target": ""
} |
"""Support for (EMEA/EU-based) Honeywell TCC climate systems.
Such systems include evohome, Round Thermostat, and others.
"""
from datetime import datetime as dt, timedelta
import logging
import re
from typing import Any, Dict, Optional, Tuple
import aiohttp.client_exceptions
import evohomeasync
import evohomeasync2
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
HTTP_SERVICE_UNAVAILABLE,
HTTP_TOO_MANY_REQUESTS,
TEMP_CELSIUS,
)
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.service import verify_domain_control
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
import homeassistant.util.dt as dt_util
from .const import DOMAIN, EVO_FOLLOW, GWS, STORAGE_KEY, STORAGE_VER, TCS, UTC_OFFSET
_LOGGER = logging.getLogger(__name__)
ACCESS_TOKEN = "access_token"
ACCESS_TOKEN_EXPIRES = "access_token_expires"
REFRESH_TOKEN = "refresh_token"
USER_DATA = "user_data"
CONF_LOCATION_IDX = "location_idx"
SCAN_INTERVAL_DEFAULT = timedelta(seconds=300)
SCAN_INTERVAL_MINIMUM = timedelta(seconds=60)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_LOCATION_IDX, default=0): cv.positive_int,
vol.Optional(
CONF_SCAN_INTERVAL, default=SCAN_INTERVAL_DEFAULT
): vol.All(cv.time_period, vol.Range(min=SCAN_INTERVAL_MINIMUM)),
}
)
},
extra=vol.ALLOW_EXTRA,
)
ATTR_SYSTEM_MODE = "mode"
ATTR_DURATION_DAYS = "period"
ATTR_DURATION_HOURS = "duration"
ATTR_ZONE_TEMP = "setpoint"
ATTR_DURATION_UNTIL = "duration"
SVC_REFRESH_SYSTEM = "refresh_system"
SVC_SET_SYSTEM_MODE = "set_system_mode"
SVC_RESET_SYSTEM = "reset_system"
SVC_SET_ZONE_OVERRIDE = "set_zone_override"
SVC_RESET_ZONE_OVERRIDE = "clear_zone_override"
RESET_ZONE_OVERRIDE_SCHEMA = vol.Schema({vol.Required(ATTR_ENTITY_ID): cv.entity_id})
SET_ZONE_OVERRIDE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_id,
vol.Required(ATTR_ZONE_TEMP): vol.All(
vol.Coerce(float), vol.Range(min=4.0, max=35.0)
),
vol.Optional(ATTR_DURATION_UNTIL): vol.All(
cv.time_period, vol.Range(min=timedelta(days=0), max=timedelta(days=1))
),
}
)
# system mode schemas are built dynamically, below
def _dt_local_to_aware(dt_naive: dt) -> dt:
dt_aware = dt_util.now() + (dt_naive - dt.now())
if dt_aware.microsecond >= 500000:
dt_aware += timedelta(seconds=1)
return dt_aware.replace(microsecond=0)
def _dt_aware_to_naive(dt_aware: dt) -> dt:
dt_naive = dt.now() + (dt_aware - dt_util.now())
if dt_naive.microsecond >= 500000:
dt_naive += timedelta(seconds=1)
return dt_naive.replace(microsecond=0)
def convert_until(status_dict: dict, until_key: str) -> str:
"""Reformat a dt str from "%Y-%m-%dT%H:%M:%SZ" as local/aware/isoformat."""
if until_key in status_dict: # only present for certain modes
dt_utc_naive = dt_util.parse_datetime(status_dict[until_key])
status_dict[until_key] = dt_util.as_local(dt_utc_naive).isoformat()
def convert_dict(dictionary: Dict[str, Any]) -> Dict[str, Any]:
"""Recursively convert a dict's keys to snake_case."""
def convert_key(key: str) -> str:
"""Convert a string to snake_case."""
string = re.sub(r"[\-\.\s]", "_", str(key))
return (string[0]).lower() + re.sub(
r"[A-Z]", lambda matched: f"_{matched.group(0).lower()}", string[1:]
)
return {
(convert_key(k) if isinstance(k, str) else k): (
convert_dict(v) if isinstance(v, dict) else v
)
for k, v in dictionary.items()
}
def _handle_exception(err) -> bool:
"""Return False if the exception can't be ignored."""
try:
raise err
except evohomeasync2.AuthenticationError:
_LOGGER.error(
"Failed to authenticate with the vendor's server. "
"Check your network and the vendor's service status page. "
"Also check that your username and password are correct. "
"Message is: %s",
err,
)
return False
except aiohttp.ClientConnectionError:
# this appears to be a common occurrence with the vendor's servers
_LOGGER.warning(
"Unable to connect with the vendor's server. "
"Check your network and the vendor's service status page. "
"Message is: %s",
err,
)
return False
except aiohttp.ClientResponseError:
if err.status == HTTP_SERVICE_UNAVAILABLE:
_LOGGER.warning(
"The vendor says their server is currently unavailable. "
"Check the vendor's service status page"
)
return False
if err.status == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(
"The vendor's API rate limit has been exceeded. "
"If this message persists, consider increasing the %s",
CONF_SCAN_INTERVAL,
)
return False
raise # we don't expect/handle any other Exceptions
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Create a (EMEA/EU-based) Honeywell TCC system."""
async def load_auth_tokens(store) -> Tuple[Dict, Optional[Dict]]:
app_storage = await store.async_load()
tokens = dict(app_storage if app_storage else {})
if tokens.pop(CONF_USERNAME, None) != config[DOMAIN][CONF_USERNAME]:
# any tokens won't be valid, and store might be be corrupt
await store.async_save({})
return ({}, None)
# evohomeasync2 requires naive/local datetimes as strings
if tokens.get(ACCESS_TOKEN_EXPIRES) is not None:
tokens[ACCESS_TOKEN_EXPIRES] = _dt_aware_to_naive(
dt_util.parse_datetime(tokens[ACCESS_TOKEN_EXPIRES])
)
user_data = tokens.pop(USER_DATA, None)
return (tokens, user_data)
store = hass.helpers.storage.Store(STORAGE_VER, STORAGE_KEY)
tokens, user_data = await load_auth_tokens(store)
client_v2 = evohomeasync2.EvohomeClient(
config[DOMAIN][CONF_USERNAME],
config[DOMAIN][CONF_PASSWORD],
**tokens,
session=async_get_clientsession(hass),
)
try:
await client_v2.login()
except (aiohttp.ClientError, evohomeasync2.AuthenticationError) as err:
_handle_exception(err)
return False
finally:
config[DOMAIN][CONF_PASSWORD] = "REDACTED"
loc_idx = config[DOMAIN][CONF_LOCATION_IDX]
try:
loc_config = client_v2.installation_info[loc_idx]
except IndexError:
_LOGGER.error(
"Config error: '%s' = %s, but the valid range is 0-%s. "
"Unable to continue. Fix any configuration errors and restart HA",
CONF_LOCATION_IDX,
loc_idx,
len(client_v2.installation_info) - 1,
)
return False
if _LOGGER.isEnabledFor(logging.DEBUG):
_config = {"locationInfo": {"timeZone": None}, GWS: [{TCS: None}]}
_config["locationInfo"]["timeZone"] = loc_config["locationInfo"]["timeZone"]
_config[GWS][0][TCS] = loc_config[GWS][0][TCS]
_LOGGER.debug("Config = %s", _config)
client_v1 = evohomeasync.EvohomeClient(
client_v2.username,
client_v2.password,
user_data=user_data,
session=async_get_clientsession(hass),
)
hass.data[DOMAIN] = {}
hass.data[DOMAIN]["broker"] = broker = EvoBroker(
hass, client_v2, client_v1, store, config[DOMAIN]
)
await broker.save_auth_tokens()
await broker.async_update() # get initial state
hass.async_create_task(async_load_platform(hass, "climate", DOMAIN, {}, config))
if broker.tcs.hotwater:
hass.async_create_task(
async_load_platform(hass, "water_heater", DOMAIN, {}, config)
)
hass.helpers.event.async_track_time_interval(
broker.async_update, config[DOMAIN][CONF_SCAN_INTERVAL]
)
setup_service_functions(hass, broker)
return True
@callback
def setup_service_functions(hass: HomeAssistantType, broker):
"""Set up the service handlers for the system/zone operating modes.
Not all Honeywell TCC-compatible systems support all operating modes. In addition,
each mode will require any of four distinct service schemas. This has to be
enumerated before registering the appropriate handlers.
It appears that all TCC-compatible systems support the same three zones modes.
"""
@verify_domain_control(hass, DOMAIN)
async def force_refresh(call) -> None:
"""Obtain the latest state data via the vendor's RESTful API."""
await broker.async_update()
@verify_domain_control(hass, DOMAIN)
async def set_system_mode(call) -> None:
"""Set the system mode."""
payload = {
"unique_id": broker.tcs.systemId,
"service": call.service,
"data": call.data,
}
async_dispatcher_send(hass, DOMAIN, payload)
@verify_domain_control(hass, DOMAIN)
async def set_zone_override(call) -> None:
"""Set the zone override (setpoint)."""
entity_id = call.data[ATTR_ENTITY_ID]
registry = await hass.helpers.entity_registry.async_get_registry()
registry_entry = registry.async_get(entity_id)
if registry_entry is None or registry_entry.platform != DOMAIN:
raise ValueError(f"'{entity_id}' is not a known {DOMAIN} entity")
if registry_entry.domain != "climate":
raise ValueError(f"'{entity_id}' is not an {DOMAIN} controller/zone")
payload = {
"unique_id": registry_entry.unique_id,
"service": call.service,
"data": call.data,
}
async_dispatcher_send(hass, DOMAIN, payload)
hass.services.async_register(DOMAIN, SVC_REFRESH_SYSTEM, force_refresh)
# Enumerate which operating modes are supported by this system
modes = broker.config["allowedSystemModes"]
# Not all systems support "AutoWithReset": register this handler only if required
if [m["systemMode"] for m in modes if m["systemMode"] == "AutoWithReset"]:
hass.services.async_register(DOMAIN, SVC_RESET_SYSTEM, set_system_mode)
system_mode_schemas = []
modes = [m for m in modes if m["systemMode"] != "AutoWithReset"]
# Permanent-only modes will use this schema
perm_modes = [m["systemMode"] for m in modes if not m["canBeTemporary"]]
if perm_modes: # any of: "Auto", "HeatingOff": permanent only
schema = vol.Schema({vol.Required(ATTR_SYSTEM_MODE): vol.In(perm_modes)})
system_mode_schemas.append(schema)
modes = [m for m in modes if m["canBeTemporary"]]
# These modes are set for a number of hours (or indefinitely): use this schema
temp_modes = [m["systemMode"] for m in modes if m["timingMode"] == "Duration"]
if temp_modes: # any of: "AutoWithEco", permanent or for 0-24 hours
schema = vol.Schema(
{
vol.Required(ATTR_SYSTEM_MODE): vol.In(temp_modes),
vol.Optional(ATTR_DURATION_HOURS): vol.All(
cv.time_period,
vol.Range(min=timedelta(hours=0), max=timedelta(hours=24)),
),
}
)
system_mode_schemas.append(schema)
# These modes are set for a number of days (or indefinitely): use this schema
temp_modes = [m["systemMode"] for m in modes if m["timingMode"] == "Period"]
if temp_modes: # any of: "Away", "Custom", "DayOff", permanent or for 1-99 days
schema = vol.Schema(
{
vol.Required(ATTR_SYSTEM_MODE): vol.In(temp_modes),
vol.Optional(ATTR_DURATION_DAYS): vol.All(
cv.time_period,
vol.Range(min=timedelta(days=1), max=timedelta(days=99)),
),
}
)
system_mode_schemas.append(schema)
if system_mode_schemas:
hass.services.async_register(
DOMAIN,
SVC_SET_SYSTEM_MODE,
set_system_mode,
schema=vol.Any(*system_mode_schemas),
)
# The zone modes are consistent across all systems and use the same schema
hass.services.async_register(
DOMAIN,
SVC_RESET_ZONE_OVERRIDE,
set_zone_override,
schema=RESET_ZONE_OVERRIDE_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SVC_SET_ZONE_OVERRIDE,
set_zone_override,
schema=SET_ZONE_OVERRIDE_SCHEMA,
)
class EvoBroker:
"""Container for evohome client and data."""
def __init__(self, hass, client, client_v1, store, params) -> None:
"""Initialize the evohome client and its data structure."""
self.hass = hass
self.client = client
self.client_v1 = client_v1
self._store = store
self.params = params
loc_idx = params[CONF_LOCATION_IDX]
self.config = client.installation_info[loc_idx][GWS][0][TCS][0]
self.tcs = client.locations[loc_idx]._gateways[0]._control_systems[0]
self.tcs_utc_offset = timedelta(
minutes=client.locations[loc_idx].timeZone[UTC_OFFSET]
)
self.temps = {}
async def save_auth_tokens(self) -> None:
"""Save access tokens and session IDs to the store for later use."""
# evohomeasync2 uses naive/local datetimes
access_token_expires = _dt_local_to_aware(self.client.access_token_expires)
app_storage = {CONF_USERNAME: self.client.username}
app_storage[REFRESH_TOKEN] = self.client.refresh_token
app_storage[ACCESS_TOKEN] = self.client.access_token
app_storage[ACCESS_TOKEN_EXPIRES] = access_token_expires.isoformat()
if self.client_v1 and self.client_v1.user_data:
app_storage[USER_DATA] = {
"userInfo": {"userID": self.client_v1.user_data["userInfo"]["userID"]},
"sessionId": self.client_v1.user_data["sessionId"],
}
else:
app_storage[USER_DATA] = None
await self._store.async_save(app_storage)
async def call_client_api(self, api_function, refresh=True) -> Any:
"""Call a client API."""
try:
result = await api_function
except (aiohttp.ClientError, evohomeasync2.AuthenticationError) as err:
if not _handle_exception(err):
return
if refresh:
self.hass.helpers.event.async_call_later(1, self.async_update())
return result
async def _update_v1(self, *args, **kwargs) -> None:
"""Get the latest high-precision temperatures of the default Location."""
def get_session_id(client_v1) -> Optional[str]:
user_data = client_v1.user_data if client_v1 else None
return user_data.get("sessionId") if user_data else None
session_id = get_session_id(self.client_v1)
try:
temps = list(await self.client_v1.temperatures(force_refresh=True))
except aiohttp.ClientError as err:
_LOGGER.warning(
"Unable to obtain the latest high-precision temperatures. "
"Check your network and the vendor's service status page. "
"Proceeding with low-precision temperatures. "
"Message is: %s",
err,
)
self.temps = None # these are now stale, will fall back to v2 temps
else:
if (
str(self.client_v1.location_id)
!= self.client.locations[self.params[CONF_LOCATION_IDX]].locationId
):
_LOGGER.warning(
"The v2 API's configured location doesn't match "
"the v1 API's default location (there is more than one location), "
"so the high-precision feature will be disabled"
)
self.client_v1 = self.temps = None
else:
self.temps = {str(i["id"]): i["temp"] for i in temps}
_LOGGER.debug("Temperatures = %s", self.temps)
if session_id != get_session_id(self.client_v1):
await self.save_auth_tokens()
async def _update_v2(self, *args, **kwargs) -> None:
"""Get the latest modes, temperatures, setpoints of a Location."""
access_token = self.client.access_token
loc_idx = self.params[CONF_LOCATION_IDX]
try:
status = await self.client.locations[loc_idx].status()
except (aiohttp.ClientError, evohomeasync2.AuthenticationError) as err:
_handle_exception(err)
else:
async_dispatcher_send(self.hass, DOMAIN)
_LOGGER.debug("Status = %s", status)
if access_token != self.client.access_token:
await self.save_auth_tokens()
async def async_update(self, *args, **kwargs) -> None:
"""Get the latest state data of an entire Honeywell TCC Location.
This includes state data for a Controller and all its child devices, such as the
operating mode of the Controller and the current temp of its children (e.g.
Zones, DHW controller).
"""
await self._update_v2()
if self.client_v1:
await self._update_v1()
# inform the evohome devices that state data has been updated
async_dispatcher_send(self.hass, DOMAIN)
class EvoDevice(Entity):
"""Base for any evohome device.
This includes the Controller, (up to 12) Heating Zones and (optionally) a
DHW controller.
"""
def __init__(self, evo_broker, evo_device) -> None:
"""Initialize the evohome entity."""
self._evo_device = evo_device
self._evo_broker = evo_broker
self._evo_tcs = evo_broker.tcs
self._unique_id = self._name = self._icon = self._precision = None
self._supported_features = None
self._device_state_attrs = {}
async def async_refresh(self, payload: Optional[dict] = None) -> None:
"""Process any signals."""
if payload is None:
self.async_schedule_update_ha_state(force_refresh=True)
return
if payload["unique_id"] != self._unique_id:
return
if payload["service"] in [SVC_SET_ZONE_OVERRIDE, SVC_RESET_ZONE_OVERRIDE]:
await self.async_zone_svc_request(payload["service"], payload["data"])
return
await self.async_tcs_svc_request(payload["service"], payload["data"])
async def async_tcs_svc_request(self, service: dict, data: dict) -> None:
"""Process a service request (system mode) for a controller."""
raise NotImplementedError
async def async_zone_svc_request(self, service: dict, data: dict) -> None:
"""Process a service request (setpoint override) for a zone."""
raise NotImplementedError
@property
def should_poll(self) -> bool:
"""Evohome entities should not be polled."""
return False
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return self._unique_id
@property
def name(self) -> str:
"""Return the name of the evohome entity."""
return self._name
@property
def device_state_attributes(self) -> Dict[str, Any]:
"""Return the evohome-specific state attributes."""
status = self._device_state_attrs
if "systemModeStatus" in status:
convert_until(status["systemModeStatus"], "timeUntil")
if "setpointStatus" in status:
convert_until(status["setpointStatus"], "until")
if "stateStatus" in status:
convert_until(status["stateStatus"], "until")
return {"status": convert_dict(status)}
@property
def icon(self) -> str:
"""Return the icon to use in the frontend UI."""
return self._icon
@property
def supported_features(self) -> int:
"""Get the flag of supported features of the device."""
return self._supported_features
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
async_dispatcher_connect(self.hass, DOMAIN, self.async_refresh)
@property
def precision(self) -> float:
"""Return the temperature precision to use in the frontend UI."""
return self._precision
@property
def temperature_unit(self) -> str:
"""Return the temperature unit to use in the frontend UI."""
return TEMP_CELSIUS
class EvoChild(EvoDevice):
"""Base for any evohome child.
This includes (up to 12) Heating Zones and (optionally) a DHW controller.
"""
def __init__(self, evo_broker, evo_device) -> None:
"""Initialize a evohome Controller (hub)."""
super().__init__(evo_broker, evo_device)
self._schedule = {}
self._setpoints = {}
@property
def current_temperature(self) -> Optional[float]:
"""Return the current temperature of a Zone."""
if not self._evo_device.temperatureStatus["isAvailable"]:
return None
if self._evo_broker.temps:
return self._evo_broker.temps[self._evo_device.zoneId]
return self._evo_device.temperatureStatus["temperature"]
@property
def setpoints(self) -> Dict[str, Any]:
"""Return the current/next setpoints from the schedule.
Only Zones & DHW controllers (but not the TCS) can have schedules.
"""
def _dt_evo_to_aware(dt_naive: dt, utc_offset: timedelta) -> dt:
dt_aware = dt_naive.replace(tzinfo=dt_util.UTC) - utc_offset
return dt_util.as_local(dt_aware)
if not self._schedule["DailySchedules"]:
return {} # no schedule {'DailySchedules': []}, so no scheduled setpoints
day_time = dt_util.now()
day_of_week = int(day_time.strftime("%w")) # 0 is Sunday
time_of_day = day_time.strftime("%H:%M:%S")
try:
# Iterate today's switchpoints until past the current time of day...
day = self._schedule["DailySchedules"][day_of_week]
sp_idx = -1 # last switchpoint of the day before
for i, tmp in enumerate(day["Switchpoints"]):
if time_of_day > tmp["TimeOfDay"]:
sp_idx = i # current setpoint
else:
break
# Did the current SP start yesterday? Does the next start SP tomorrow?
this_sp_day = -1 if sp_idx == -1 else 0
next_sp_day = 1 if sp_idx + 1 == len(day["Switchpoints"]) else 0
for key, offset, idx in [
("this", this_sp_day, sp_idx),
("next", next_sp_day, (sp_idx + 1) * (1 - next_sp_day)),
]:
sp_date = (day_time + timedelta(days=offset)).strftime("%Y-%m-%d")
day = self._schedule["DailySchedules"][(day_of_week + offset) % 7]
switchpoint = day["Switchpoints"][idx]
dt_aware = _dt_evo_to_aware(
dt_util.parse_datetime(f"{sp_date}T{switchpoint['TimeOfDay']}"),
self._evo_broker.tcs_utc_offset,
)
self._setpoints[f"{key}_sp_from"] = dt_aware.isoformat()
try:
self._setpoints[f"{key}_sp_temp"] = switchpoint["heatSetpoint"]
except KeyError:
self._setpoints[f"{key}_sp_state"] = switchpoint["DhwState"]
except IndexError:
self._setpoints = {}
_LOGGER.warning(
"Failed to get setpoints, report as an issue if this error persists",
exc_info=True,
)
return self._setpoints
async def _update_schedule(self) -> None:
"""Get the latest schedule, if any."""
if "DailySchedules" in self._schedule and not self._schedule["DailySchedules"]:
if not self._evo_device.setpointStatus["setpointMode"] == EVO_FOLLOW:
return # avoid unnecessary I/O - there's nothing to update
self._schedule = await self._evo_broker.call_client_api(
self._evo_device.schedule(), refresh=False
)
_LOGGER.debug("Schedule['%s'] = %s", self.name, self._schedule)
async def async_update(self) -> None:
"""Get the latest state data."""
next_sp_from = self._setpoints.get("next_sp_from", "2000-01-01T00:00:00+00:00")
if dt_util.now() >= dt_util.parse_datetime(next_sp_from):
await self._update_schedule() # no schedule, or it's out-of-date
self._device_state_attrs = {"setpoints": self.setpoints}
| {
"content_hash": "9c1f973b9503bbef2b1bfded43f1e59f",
"timestamp": "",
"source": "github",
"line_count": 703,
"max_line_length": 88,
"avg_line_length": 36.173541963015644,
"alnum_prop": 0.6075108139992135,
"repo_name": "mKeRix/home-assistant",
"id": "e436268db63ef26bb9d8b2b17eff881a33a4f239",
"size": "25430",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "homeassistant/components/evohome/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1466026"
},
{
"name": "Python",
"bytes": "4770710"
},
{
"name": "Ruby",
"bytes": "379"
},
{
"name": "Shell",
"bytes": "12407"
}
],
"symlink_target": ""
} |
// JSmol.js -- Jmol pure JavaScript version
// author: Bob Hanson, hansonr@stolaf.edu 4/16/2012
// author: Takanori Nakane biochem_fan 6/12/2012
// BH 6/12/2015 6:08:08 AM image loading from PNGJ file bytes using data uri not working
// BH 3/28/2015 6:18:33 AM refactoring to generalize for non-Jmol-related SwingJS applications
// BH 9/6/2014 5:42:32 PM two-point gestures broken
// BH 5/8/2014 11:16:40 AM j2sPath starting with "/" fails to add idiom
// BH 1/16/2014 8:44:03 PM __execDelayMS = 100; // FF bug when loading into a tab that is not
// immediately focused and not using jQuery for adding the applet and having
// multiple applets.
// BH 12/6/2013 10:12:30 AM adding corejmoljsv.z.js
// BH 9/17/2013 10:18:40 AM file transfer functions moved to JSmolCore
// BH 3/5/2013 9:54:16 PM added support for a cover image: Info.coverImage, coverScript, coverTitle, deferApplet, deferUncover
// BH 1/3/2013 4:54:01 AM mouse binding should return false -- see d.bind(...), and d.bind("contextmenu") is not necessary
// This library requires prior inclusion of
// jQuery 9 or higher
// JSmoljQueryExt.js
// JSmolCore.js
// j2sjmol.js (Clazz and associated classes)
// these:
//
// JSmolApplet.js
// JSmolApi.js
// JSmolThree.js
// JSmolGLmol.js
//
// are optional
;(function (Jmol) {
Jmol._isAsync = false; // testing only
Jmol._asyncCallbacks = {};
Jmol._coreFiles = []; // required for package.js
///////////////////
// This section provides an asynchronous loading sequence
//
// methods and fields starting with double underscore are private to this .js file
var __clazzLoaded = false;
var __execLog = [];
var __execStack = [];
var __execTimer = 0;
var __coreSet = [];
var __coreMore = [];
var __execDelayMS = 100; // must be > 55 ms for FF
var __nextExecution = function(trigger) {
arguments.length || (trigger = true);
delete __execTimer;
var es = __execStack;
var e;
while (es.length > 0 && (e = es[0])[4] == "done")
es.shift();
if (es.length == 0)
return;
if (!Jmol._isAsync && !trigger) {
setTimeout(__nextExecution,10)
return;
}
e.push("done");
var s = "JSmol exec " + e[0]._id + " " + e[3] + " " + e[2];
if (self.System)
System.out.println(s);
//alert(s)
if (self.console)console.log(s + " -- OK")
__execLog.push(s);
e[1](e[0],e[2]);
};
var __loadClazz = function(applet) {
if (!__clazzLoaded) {
__clazzLoaded = true;
// create the Clazz object
LoadClazz();
if (applet._noMonitor)
Clazz._LoaderProgressMonitor.showStatus = function() {}
LoadClazz = null;
if (applet.__Info.uncompressed)
Clazz.loadClass(); // for now; allows for no compression
Clazz._Loader.onGlobalLoaded = function (file) {
// not really.... just nothing more yet to do yet
Clazz._LoaderProgressMonitor.showStatus("Application loaded.", true);
if (!Jmol._debugCode || !Jmol.haveCore) {
Jmol.haveCore = true;
__nextExecution();
}
};
// load package.js and j2s/core/core.z.js
Clazz._Loader.loadPackageClasspath("java", null, true, __nextExecution);
return;
}
__nextExecution();
};
var __loadClass = function(applet, javaClass) {
Clazz._Loader.loadClass(javaClass, function() {__nextExecution()});
};
Jmol.showExecLog = function() { return __execLog.join("\n") };
Jmol._addExec = function(e) {
e[1] || (e[1] = __loadClass);
var s = "JSmol load " + e[0]._id + " " + e[3];
if (self.console)console.log(s + "...")
__execLog.push(s);
__execStack.push(e);
}
Jmol._addCoreFile = function(type, path, more) {
// BH 3/15: idea here is that when both Jmol and JSV are present,
// we want to load a common core file -- jmoljsv.z.js --
// instead of just one. Otherwise we do a lot of duplication.
// It is not clear how this would play with other concurrent
// apps. So this will take some thinking. But the basic idea is that
// core file to load is
type = type.toLowerCase().split(".")[0]; // package name only
// return if type is already part of the set.
if (__coreSet.join("").indexOf(type) >= 0) return;
// create a concatenated lower-case name for a core file that includes
// all Java applets on the page
__coreSet.push(type);
__coreSet.sort();
Jmol._coreFiles = [path + "/core/core" + __coreSet.join("") + ".z.js" ];
if (more && (more = more.split(" ")))
for (var i = 0; i < more.length; i++)
if (__coreMore.join("").indexOf(more[i]) < 0)
__coreMore.push(path + "/core/core" + more[i] + ".z.js")
for (var i = 0; i < __coreMore.length; i++)
Jmol._coreFiles.push(__coreMore[i]);
}
Jmol._Canvas2D = function(id, Info, type, checkOnly){
// type: Jmol or JSV
this._uniqueId = ("" + Math.random()).substring(3);
this._id = id;
this._is2D = true;
this._isJava = false;
this._jmolType = "Jmol._Canvas2D (" + type + ")";
this._isLayered = Info._isLayered || false;
this._isSwing = Info._isSwing || false;
this._isJSV = Info._isJSV || false;
this._isAstex = Info._isAstex || false;
this._platform = Info._platform || "";
if (checkOnly)
return this;
window[id] = this;
this._createCanvas(id, Info);
if (!Jmol._document || this._deferApplet)
return this;
this._init();
return this;
};
Jmol._setAppletParams = function(availableParams, params, Info, isHashtable) {
for (var i in Info)
if(!availableParams || availableParams.indexOf(";" + i.toLowerCase() + ";") >= 0){
if (Info[i] == null || i == "language" && !Jmol.featureDetection.supportsLocalization())
continue;
if (isHashtable)
params.put(i, (Info[i] === true ? Boolean.TRUE: Info[i] === false ? Boolean.FALSE : Info[i]))
else
params[i] = Info[i];
}
}
Jmol._jsSetPrototype = function(proto) {
proto._init = function() {
this._setupJS();
this._showInfo(true);
if (this._disableInitialConsole)
this._showInfo(false);
};
proto._createCanvas = function(id, Info, glmol) {
Jmol._setObject(this, id, Info);
if (glmol) {
this._GLmol = glmol;
this._GLmol.applet = this;
this._GLmol.id = this._id;
}
var t = Jmol._getWrapper(this, true);
if (this._deferApplet) {
} else if (Jmol._document) {
Jmol._documentWrite(t);
this._newCanvas(false);
t = "";
} else {
this._deferApplet = true;
t += '<script type="text/javascript">' + id + '._cover(false)</script>';
}
t += Jmol._getWrapper(this, false);
if (Info.addSelectionOptions)
t += Jmol._getGrabberOptions(this);
if (Jmol._debugAlert && !Jmol._document)
alert(t);
this._code = Jmol._documentWrite(t);
};
proto._newCanvas = function(doReplace) {
if (this._is2D)
this._createCanvas2d(doReplace);
else
this._GLmol.create();
};
//////// swingjs.api.HTML5Applet interface
proto._getHtml5Canvas = function() { return this._canvas };
proto._getWidth = function() { return this._canvas.width };
proto._getHeight = function() { return this._canvas.height };
proto._getContentLayer = function() { return Jmol.$(this, "contentLayer")[0] };
proto._repaintNow = function() { Jmol._repaint(this, false) };
////////
proto._createCanvas2d = function(doReplace) {
var container = Jmol.$(this, "appletdiv");
//if (doReplace) {
try {
container[0].removeChild(this._canvas);
if (this._canvas.frontLayer)
container[0].removeChild(this._canvas.frontLayer);
if (this._canvas.rearLayer)
container[0].removeChild(this._canvas.rearLayer);
if (this._canvas.contentLayer)
container[0].removeChild(this._canvas.contentLayer);
Jmol._jsUnsetMouse(this._mouseInterface);
} catch (e) {}
//}
var w = Math.round(container.width());
var h = Math.round(container.height());
var canvas = document.createElement( 'canvas' );
canvas.applet = this;
this._canvas = canvas;
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = w;
canvas.height = h; // w and h used in setScreenDimension
canvas.id = this._id + "_canvas2d";
container.append(canvas);
Jmol._$(canvas.id).css({"z-index":Jmol._getZ(this, "main")});
if (this._isLayered){
var img = document.createElement("div");
canvas.contentLayer = img;
img.id = this._id + "_contentLayer";
container.append(img);
Jmol._$(img.id).css({zIndex:Jmol._getZ(this, "image"),position:"absolute",left:"0px",top:"0px",
width:(this._isSwing ? w : 0) + "px", height:(this._isSwing ? h : 0) +"px", overflow:"hidden"});
if (this._isSwing) {
var d = document.createElement("div");
d.id = this._id + "_swingdiv";
Jmol._$(this._id + "_appletinfotablediv").append(d);
Jmol._$(d.id).css({zIndex:Jmol._getZ(this, "rear"),position:"absolute",left:"0px",top:"0px", width:w +"px", height:h+"px", overflow:"hidden"});
this._mouseInterface = canvas.contentLayer;
canvas.contentLayer.applet = this;
} else {
this._mouseInterface = this._getLayer("front", container, w, h, false);
}
//this._getLayer("rear", container, w, h, true);
//Jmol._$(canvas.id).css({background:"rgb(0,0,0,0.001)", "z-index":Jmol._z.main});
} else {
this._mouseInterface = canvas;
}
Jmol._jsSetMouse(this._mouseInterface);
}
proto._getLayer = function(name, container, w, h, isOpaque) {
var c = document.createElement("canvas");
this._canvas[name + "Layer"] = c;
c.style.width = "100%";
c.style.height = "100%";
c.id = this._id + "_" + name + "Layer";
c.width = w;
c.height = h; // w and h used in setScreenDimension
container.append(c);
c.applet = this;
Jmol._$(c.id).css({background:(isOpaque ? "rgb(0,0,0,1)" : "rgb(0,0,0,0.001)"), "z-index": Jmol._getZ(this,name),position:"absolute",left:"0px",top:"0px",overflow:"hidden"});
return c;
}
proto._setupJS = function() {
window["j2s.lib"] = {
base : this._j2sPath + "/",
alias : ".",
console : this._console,
monitorZIndex : Jmol._getZ(this, "monitorZIndex")
};
var isFirst = (__execStack.length == 0);
if (isFirst)
Jmol._addExec([this, __loadClazz, null, "loadClazz"]);
this._addCoreFiles();
Jmol._addExec([this, this.__startAppletJS, null, "start applet"])
this._isSigned = true; // access all files via URL hook
this._ready = false;
this._applet = null;
this._canScript = function(script) {return true;};
this._savedOrientations = [];
__execTimer && clearTimeout(__execTimer);
__execTimer = setTimeout(__nextExecution, __execDelayMS);
};
proto.__startAppletJS = function(applet) {
if (Jmol._version.indexOf("$Date: ") == 0)
Jmol._version = (Jmol._version.substring(7) + " -").split(" -")[0] + " (JSmol/j2s)"
var viewerOptions = Clazz._4Name("java.util.Hashtable").newInstance();
Jmol._setAppletParams(applet._availableParams, viewerOptions, applet.__Info, true);
viewerOptions.put("appletReadyCallback","Jmol._readyCallback");
viewerOptions.put("applet", true);
viewerOptions.put("name", applet._id);// + "_object");
viewerOptions.put("syncId", Jmol._syncId);
if (Jmol._isAsync)
viewerOptions.put("async", true);
if (applet._color)
viewerOptions.put("bgcolor", applet._color);
if (applet._startupScript)
viewerOptions.put("script", applet._startupScript)
if (Jmol._syncedApplets.length)
viewerOptions.put("synccallback", "Jmol._mySyncCallback");
viewerOptions.put("signedApplet", "true");
viewerOptions.put("platform", applet._platform);
if (applet._is2D)
viewerOptions.put("display",applet._id + "_canvas2d");
// viewerOptions.put("repaintManager", "J.render");
viewerOptions.put("documentBase", document.location.href);
var codePath = applet._j2sPath + "/";
if (codePath.indexOf("://") < 0) {
var base = document.location.href.split("#")[0].split("?")[0].split("/");
if (codePath.indexOf("/") == 0)
base = [base[0], codePath.substring(1)];
else
base[base.length - 1] = codePath;
codePath = base.join("/");
}
viewerOptions.put("codePath", codePath);
Jmol._registerApplet(applet._id, applet);
try {
applet._newApplet(viewerOptions);
} catch (e) {
System.out.println((Jmol._isAsync ? "normal async abort from " : "") + e);
return;
}
applet._jsSetScreenDimensions();
__nextExecution();
};
if (!proto._restoreState)
proto._restoreState = function(clazzName, state) {
// applet-dependent
}
proto._jsSetScreenDimensions = function() {
if (!this._appletPanel)return
// strangely, if CTRL+/CTRL- are used repeatedly, then the
// applet div can be not the same size as the canvas if there
// is a border in place.
var d = Jmol._getElement(this, (this._is2D ? "canvas2d" : "canvas"));
this._appletPanel.setScreenDimension(d.width, d.height);
};
proto._show = function(tf) {
Jmol.$setVisible(Jmol.$(this,"appletdiv"), tf);
if (tf)
Jmol._repaint(this, true);
};
proto._canScript = function(script) {return true};
proto.equals = function(a) { return this == a };
proto.clone = function() { return this };
proto.hashCode = function() { return parseInt(this._uniqueId) };
proto._processGesture = function(touches) {
return this._appletPanel.processTwoPointGesture(touches);
}
proto._processEvent = function(type, xym) {
this._appletPanel.processMouseEvent(type,xym[0],xym[1],xym[2],System.currentTimeMillis());
}
proto._resize = function() {
var s = "__resizeTimeout_" + this._id;
// only at end
if (Jmol[s])
clearTimeout(Jmol[s]);
var me = this;
Jmol[s] = setTimeout(function() {Jmol._repaint(me, true);Jmol[s]=null}, 100);
}
return proto;
};
Jmol._repaint = function(applet, asNewThread) {
// JmolObjectInterface
// asNewThread: true is from RepaintManager.repaintNow()
// false is from Repaintmanager.requestRepaintAndWait()
// called from apiPlatform Display.repaint()
//alert("_repaint " + Clazz.getStackTrace())
if (!applet || !applet._appletPanel)return;
// asNewThread = false;
var container = Jmol.$(applet, "appletdiv");
var w = Math.round(container.width());
var h = Math.round(container.height());
if (applet._is2D && (applet._canvas.width != w || applet._canvas.height != h)) {
applet._newCanvas(true);
applet._appletPanel.setDisplay(applet._canvas);
}
applet._appletPanel.setScreenDimension(w, h);
var f = function(){
if (applet._appletPanel.paint)
applet._appletPanel.paint(null);
else
applet._appletPanel.update(null)
};
if (asNewThread) {
setTimeout(f);
} else {
f();
}
// System.out.println(applet._appletPanel.getFullName())
}
/**
* _loadImage is called for asynchronous image loading.
* If bytes are not null, they are from a ZIP file. They are processed sychronously
* here using an image data URI. Can all browsers handle MB of data in data URI?
*
*/
Jmol._loadImage = function(platform, echoName, path, bytes, fOnload, image) {
// JmolObjectInterface
var id = "echo_" + echoName + path + (bytes ? "_" + bytes.length : "");
var canvas = Jmol._getHiddenCanvas(platform.vwr.html5Applet, id, 0, 0, false, true);
// System.out.println(["JSmol.js loadImage ",id,path,canvas,image])
if (canvas == null) {
if (image == null) {
image = new Image();
if (bytes == null) {
image.onload = function() {Jmol._loadImage(platform, echoName, path, null, fOnload, image)};
image.src = path;
return null;
} else {
System.out.println("Jsmol.js Jmol._loadImage using data URI for " + id)
}
var mimetype = JU.Rdr.guessMimeTypeForBytes(bytes);
var filename = path.substring(path.lastIndexOf("/") + 1);
if (filename.length == 3)
filename = "." + filename; // was a mime type
image.src = "data:" + mimetype + ";base64," + JU.Base64.getBase64(bytes);
}
var width = image.width;
var height = image.height;
canvas = Jmol._getHiddenCanvas(platform.vwr.html5Applet, id, width, height, true, false);
canvas.imageWidth = width;
canvas.imageHeight = height;
canvas.id = id;
canvas.image=image;
Jmol._setCanvasImage(canvas, width, height);
// return a null canvas and the error in path if there is a problem
} else {
System.out.println("Jsmol.js Jmol._loadImage reading cached image for " + id)
}
return (bytes == null? fOnload(canvas,path) : canvas);
};
Jmol._canvasCache = {};
Jmol._getHiddenCanvas = function(applet, id, width, height, forceNew, checkOnly) {
id = applet._id + "_" + id;
var d = Jmol._canvasCache[id];
if (checkOnly)
return d;
if (forceNew || !d || d.width != width || d.height != height) {
d = document.createElement( 'canvas' );
// for some reason both these need to be set, or maybe just d.width?
d.width = d.style.width = width;
d.height = d.style.height = height;
d.id = id;
Jmol._canvasCache[id] = d;
//System.out.println("JSmol.js loadImage setting cache" + id + " to " + d)
}
return d;
}
Jmol._setCanvasImage = function(canvas, width, height) {
// called from org.jmol.awtjs2d.Platform
canvas.buf32 = null;
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(canvas.image, 0, 0, width, height);
};
Jmol._apply = function(f,a) {
// JmolObjectInterface
return f(a);
}
})(Jmol);
| {
"content_hash": "e81e325b8abf5e925a6a3ac2f4c0b34d",
"timestamp": "",
"source": "github",
"line_count": 516,
"max_line_length": 177,
"avg_line_length": 35.28294573643411,
"alnum_prop": 0.603757003185763,
"repo_name": "ekimb/esperite",
"id": "4d383fd8f59f29ddad46e6665e749c74eddd5027",
"size": "18206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsmol/js/JSmol.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "59"
},
{
"name": "C",
"bytes": "318959"
},
{
"name": "C++",
"bytes": "3588"
},
{
"name": "CSS",
"bytes": "117994"
},
{
"name": "Go",
"bytes": "81699"
},
{
"name": "HTML",
"bytes": "8685811"
},
{
"name": "Hack",
"bytes": "5415"
},
{
"name": "JavaScript",
"bytes": "26102467"
},
{
"name": "Makefile",
"bytes": "981"
},
{
"name": "PHP",
"bytes": "20559"
}
],
"symlink_target": ""
} |
typedef struct _oparam
{
std::string alias;
s32 index;
u8 is_fp16;
} oparam;
class CFPParser : public CParser
{
public:
CFPParser();
virtual ~CFPParser();
virtual int Parse(const char *str);
private:
void ParseInstruction(struct nvfx_insn *insn,opcode *opc,const char *param_str);
void ParseMaskedDstReg(const char *token,struct nvfx_insn *insn);
void ParseVectorSrc(const char *token,struct nvfx_src *reg);
void ParseScalarSrc(const char *token,struct nvfx_src *reg);
void ParseOutput(const char *param_str);
const char* ParseOutputReg(const char *token,s32 *reg,u8 *is_fp16);
const char* ParseInputReg(const char *token,s32 *reg);
const char* ParseOutputRegAlias(const char *token,s32 *reg,u8 *is_fp16);
void SetNoneDestReg(struct nvfx_insn *insn);
u8 IsPCDisablingInstruction(struct nvfx_insn *insn);
opcode FindOpcode(const char *mnemonic);
int GetConstRegType(int index);
virtual s32 ConvertInputReg(const char *token);
virtual const char* ParseOutputMask(const char *token,u8 *mask);
std::list<oparam> m_lOParameters;
};
#endif
| {
"content_hash": "8c6c952b668bf040b3ecaefdf7d68440",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 81,
"avg_line_length": 25.428571428571427,
"alnum_prop": 0.75,
"repo_name": "ps3dev/PSL1GHT",
"id": "b15cc37eca46abfc188e63ea24059fba37bdf937",
"size": "1221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/cgcomp/include/fpparser.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2196"
},
{
"name": "C",
"bytes": "2003636"
},
{
"name": "C++",
"bytes": "1324504"
},
{
"name": "Makefile",
"bytes": "132918"
},
{
"name": "Objective-C",
"bytes": "5517"
},
{
"name": "Python",
"bytes": "40380"
},
{
"name": "Shell",
"bytes": "390"
}
],
"symlink_target": ""
} |
import frappe
def get_data():
return frappe._dict({
"dashboards": get_dashboards(),
"charts": get_charts(),
"number_cards": None,
})
def get_dashboards():
return [{
"name": "Website",
"dashboard_name": "Website",
"charts": [
{ "chart": "Website Analytics", "width": "Full" }
]
}]
def get_charts():
return [{
"chart_name": "Website Analytics",
"chart_type": "Report",
"custom_options": "{\"type\": \"line\", \"lineOptions\": {\"regionFill\": 1}, \"axisOptions\": {\"shortenYAxisNumbers\": 1}, \"tooltipOptions\": {}}",
"doctype": "Dashboard Chart",
"filters_json": "{}",
"group_by_type": "Count",
"is_custom": 1,
"is_public": 1,
"name": "Website Analytics",
"number_of_groups": 0,
"report_name": "Website Analytics",
"time_interval": "Yearly",
"timeseries": 0,
"timespan": "Last Year",
"type": "Line"
}] | {
"content_hash": "115e2031de955b6c06db47589f4eb089",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 152,
"avg_line_length": 23.833333333333332,
"alnum_prop": 0.5897435897435898,
"repo_name": "mhbu50/frappe",
"id": "1ac7ca60ec7c208335158a83aa4b932e60e091ce",
"size": "858",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "frappe/website/dashboard_fixtures.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "67734"
},
{
"name": "HTML",
"bytes": "247122"
},
{
"name": "JavaScript",
"bytes": "2359670"
},
{
"name": "Less",
"bytes": "25489"
},
{
"name": "Makefile",
"bytes": "99"
},
{
"name": "Python",
"bytes": "3464477"
},
{
"name": "SCSS",
"bytes": "248877"
},
{
"name": "Shell",
"bytes": "3505"
},
{
"name": "Vue",
"bytes": "96912"
}
],
"symlink_target": ""
} |
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRGraphics2DExporter;
import net.sf.jasperreports.engine.export.JRGraphics2DExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
public class JasperTeste {
/**
* @param args
* @throws JRException
* @throws IOException
*/
public static void main(String[] args) throws JRException, IOException {
//createPDF();
createImage();
}
public static void createPDF() throws FileNotFoundException, JRException, IOException {
// TODO Auto-generated method stub
InputStream jrxmlStream = new FileInputStream("/home/darcio/workspace/modules/JazzAV/bsn/src/main/resources/modeloAdes1.jrxml");
JasperReport compiled = JasperCompileManager.compileReport(jrxmlStream);
Map rootMap = new HashMap();
JasperPrint jasperPrint = JasperFillManager.fillReport(compiled, rootMap, new JREmptyDataSource());
int pageIndex = 0;
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_FILE, new File("/home/darcio/workspace/modules/JazzAV/bsn/src/main/resources/modeloAdes1.pdf"));
exporter.exportReport();
}
public static void createImage() throws FileNotFoundException, JRException, IOException {
// TODO Auto-generated method stub
InputStream jrxmlStream = new FileInputStream("/home/darcio/workspace/modules/JazzAV/bsn/src/main/resources/modeloAdes1.jrxml");
FileOutputStream out = new FileOutputStream("/home/darcio/workspace/modules/JazzAV/bsn/src/main/resources/modeloAdes1.png");
JasperReport compiled = JasperCompileManager.compileReport(jrxmlStream);
Map rootMap = new HashMap();
JasperPrint jasperPrint = JasperFillManager.fillReport(compiled, rootMap, new JREmptyDataSource(1));
int pageIndex = 0;
BufferedImage pageImage = new BufferedImage(jasperPrint.getPageWidth() + 1, jasperPrint.getPageHeight() + 1, BufferedImage.TYPE_INT_RGB);
JRGraphics2DExporter exporter = new JRGraphics2DExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, 0.6f);
exporter.exportReport();
ImageIO.write(pageImage, "png", out);
}
}
| {
"content_hash": "34d6a3e6a045ae5b78430f06df21083e",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 150,
"avg_line_length": 32.505050505050505,
"alnum_prop": 0.7675574891236793,
"repo_name": "darciopacifico/omr",
"id": "5fa1a6e00daebedb1e29774e5e3ce35c67396c10",
"size": "3218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/JazzAV/bsn/src/main/java/JasperTeste.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "311170"
},
{
"name": "HTML",
"bytes": "1481488"
},
{
"name": "Java",
"bytes": "9727768"
},
{
"name": "JavaScript",
"bytes": "306302"
},
{
"name": "Shell",
"bytes": "1456"
}
],
"symlink_target": ""
} |
"use strict";
var error = require("./../../error");
var Util = require("./../../util");
var user = module.exports = {
user: {}
};
(function() {
/** section: github
* user#getFrom(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
**/
this.getFrom = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#get(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* No params, simply pass an empty Object literal `{}`
**/
this.get = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#update(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - name (String): Optional.
* - email (String): Optional.
* - blog (String): Optional.
* - company (String): Optional.
* - location (String): Optional.
* - hireable (Boolean): Optional.
* - bio (String): Optional.
**/
this.update = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getOrgs(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getOrgs = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getEmails(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getEmails = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#addEmails(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* No params, simply pass an empty Object literal `{}`
**/
this.addEmails = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#deleteEmails(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* No params, simply pass an empty Object literal `{}`
**/
this.deleteEmails = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getFollowers(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getFollowers = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getFollowingFromUser(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getFollowingFromUser = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getFollowing(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getFollowing = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getFollowUser(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getFollowUser = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#followUser(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
**/
this.followUser = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#unFollowUser(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - user (String): Required.
**/
this.unFollowUser = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getKeys(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `.
* - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `.
**/
this.getKeys = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#getKey(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - id (String): Required.
**/
this.getKey = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#createKey(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - title (String): Required.
* - key (String): Required.
**/
this.createKey = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#updateKey(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - id (String): Required.
* - title (String): Required.
* - key (String): Required.
**/
this.updateKey = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
/** section: github
* user#deleteKey(msg, callback) -> null
* - msg (Object): Object that contains the parameters and their values to be sent to the server.
* - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument.
*
* ##### Params on the `msg` object:
*
* - id (String): Required.
**/
this.deleteKey = function(msg, block, callback) {
var self = this;
this.client.httpSend(msg, block, function(err, res) {
if (err)
return self.sendError(err, null, msg, callback);
var ret;
try {
ret = res.data && JSON.parse(res.data);
}
catch (ex) {
if (callback)
callback(new error.InternalServerError(ex.message), res);
return;
}
if (!ret)
ret = {};
if (!ret.meta)
ret.meta = {};
["x-ratelimit-limit", "x-ratelimit-remaining", "x-oauth-scopes", "link", "location"].forEach(function(header) {
if (res.headers[header])
ret.meta[header] = res.headers[header];
});
if (callback)
callback(null, ret);
});
};
}).call(user.user);
| {
"content_hash": "7aba414dd088f5bb49e6249c4093bb54",
"timestamp": "",
"source": "github",
"line_count": 734,
"max_line_length": 148,
"avg_line_length": 36.85422343324251,
"alnum_prop": 0.4907766810838786,
"repo_name": "smwhit/technotes",
"id": "23a9991d0475b591288ac36ef1b1690737a3111c",
"size": "27249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/github/api/v3.0.0/user.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "283837"
},
{
"name": "JavaScript",
"bytes": "309780"
},
{
"name": "PHP",
"bytes": "167"
},
{
"name": "Perl",
"bytes": "10173"
},
{
"name": "Scala",
"bytes": "256"
},
{
"name": "Shell",
"bytes": "17"
}
],
"symlink_target": ""
} |
NRML="$(tput sgr0)"
RED="$(tput setaf 1)"
BLUE="$(tput setaf 4)"
GREEN="$(tput setaf 2)"
DIR="`pwd`"
declare -A platforms=(
["ingress-ice-linux32"]="https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-i686.tar.bz2"
["ingress-ice-linux64"]="https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2"
["ingress-ice-armv6l"]="https://github.com/spfaffly/phantomjs-linux-armv6l/blob/master/phantomjs-2.0.1-development-linux-armv6l.tar.gz?raw=true"
["ingress-ice-osx"]="https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip"
["ingress-ice-win32"]="https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip"
)
declare -A cmds=(
["ingress-ice-linux32"]="tar xvjf "
["ingress-ice-linux64"]="tar xvjf "
["ingress-ice-armv6l"]="tar xvzf "
["ingress-ice-osx"]="unzip "
["ingress-ice-win32"]="unzip "
)
declare -A pack=(
["ingress-ice-linux32"]="tar cvzf ingress-ice-linux32.tar.gz"
["ingress-ice-linux64"]="tar cvzf ingress-ice-linux64.tar.gz"
["ingress-ice-armv6l"]="tar cvzf ingress-ice-armv6l.tar.gz"
["ingress-ice-osx"]="zip -r ingress-ice-osx.zip"
["ingress-ice-win32"]="zip -r ingress-ice-win32.zip"
)
declare -A clean=(
["ingress-ice-linux32"]="ingress-ice.cmd reconfigure.cmd"
["ingress-ice-linux64"]="ingress-ice.cmd reconfigure.cmd"
["ingress-ice-armv6l"]="ingress-ice.cmd reconfigure.cmd"
["ingress-ice-osx"]="ingress-ice.cmd reconfigure.cmd"
["ingress-ice-win32"]="ingress-ice.sh"
)
TEMP_DIR="/tmp/ingress-ice"
say_red() {
echo -e "> $RED$1$NRML"
exit 1
}
say_blue() {
echo "> $BLUE$1$NRML"
}
say_green() {
echo "> $GREEN$1$NRML"
}
quit() {
echo -e ">$RED Operation cancelled by user.$NRML"
kill -- -$(ps -o pgid= $pokepid | grep -o '[0-9]*') >/dev/null
exit 2
}
remove() {
for i in $@; do
rm "$i" -rf
say_green "Deleted $i"
done
}
trap "quit" 2
[[ -d "$TEMP_DIR" ]] && rm -rf "$TEMP_DIR"
say_blue "Copying everything to a temporary directory..."
mkdir "$TEMP_DIR/original" -p
cp * "$TEMP_DIR/original" -R
say_blue "Removing development-related files..."
cd $TEMP_DIR/original
remove .git .gitattributes .gitignore CONTRIBUTING.md Dockerfile docker-ingress-ice.sh .editorconfig .dockerignore build.sh ingress-ice-* phantom-bin
cd ..
say_blue "Creating directories for different OS..."
for i in ${!platforms[@]}; do
cp original "$i" -R
say_green "Created $i"
done
say_blue "Downloading PhantomJS for each OS..."
mkdir phantom-bin && cd phantom-bin
for i in ${!platforms[@]}; do
[[ ! -d "$i" ]] && mkdir "$i"
cd "$i"
wget ${platforms[$i]} -O phntm
${cmds[$i]} phntm
say_green "Downloaded for $i"
find -regex ".\/phantom.*\/bin\/phantom.*" -exec mv {} "../../$i" \;
cd ..
done
cd ..
say_blue "Cleaning..."
for i in ${!clean[@]}; do
if [[ -d "$i" ]]; then
cd "$i"
rm -rf ${clean[$i]}
say_green "Found and removed ${clean[$i]}"
cd ..
fi
done
say_blue "Archiving Ingress ICE"
for i in ${!platforms[@]}; do
${pack[$i]} "$i"
say_green "Packed $i"
done
say_blue "Saving your archives..."
mv *.tar.gz $DIR
mv *.zip $DIR
cd $DIR
say_blue "You now have these builds:"
ls -l *.tar.gz *.zip
rm "$TEMP_DIR" -rf
| {
"content_hash": "0d40bf57ec6fd9fb43068593e1c09453",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 149,
"avg_line_length": 25.376,
"alnum_prop": 0.6560529634300126,
"repo_name": "wposada/ingress-ice",
"id": "a90c980ce4ae8b7a2ce6f510f1c71b58fc078b4e",
"size": "3211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1559"
},
{
"name": "JavaScript",
"bytes": "30054"
},
{
"name": "Shell",
"bytes": "8668"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Text;
namespace PicasaDatabaseReader.Fields
{
internal class StringField : FieldBase, IField
{
public StringField(string fieldFilepath) : base(fieldFilepath)
{
Type = typeof (string);
}
public override object ReadValue()
{
byte b;
var result = new List<byte>();
try
{
while ((b = reader.ReadByte()) != 0x0 )
{
result.Add(b);
}
}
catch{}
return Encoding.UTF8.GetString(result.ToArray());
}
}
} | {
"content_hash": "b421ca4a68c15d3817cd4b64f3adffdb",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 70,
"avg_line_length": 23,
"alnum_prop": 0.4827586206896552,
"repo_name": "jabacrack/Picasa-database-reader",
"id": "dd668e70d105c2a516defa7912e84a6da0e1e82a",
"size": "669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PicasaDatabaseReader/Fields/StringField.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "42877"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit — statsmodels v0.10.2 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula" href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula.html" />
<link rel="prev" title="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter" href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula.html" title="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter.html" title="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../tsa.html" >Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.html" accesskey="U">statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-tsa-regime-switching-markov-autoregression-markovautoregression-fit">
<h1>statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit<a class="headerlink" href="#statsmodels-tsa-regime-switching-markov-autoregression-markovautoregression-fit" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit">
<code class="sig-prename descclassname">MarkovAutoregression.</code><code class="sig-name descname">fit</code><span class="sig-paren">(</span><em class="sig-param">start_params=None</em>, <em class="sig-param">transformed=True</em>, <em class="sig-param">cov_type='approx'</em>, <em class="sig-param">cov_kwds=None</em>, <em class="sig-param">method='bfgs'</em>, <em class="sig-param">maxiter=100</em>, <em class="sig-param">full_output=1</em>, <em class="sig-param">disp=0</em>, <em class="sig-param">callback=None</em>, <em class="sig-param">return_params=False</em>, <em class="sig-param">em_iter=5</em>, <em class="sig-param">search_reps=0</em>, <em class="sig-param">search_iter=5</em>, <em class="sig-param">search_scale=1.0</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit" title="Permalink to this definition">¶</a></dt>
<dd><p>Fits the model by maximum likelihood via Hamilton filter.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>start_params</strong><span class="classifier">array_like, optional</span></dt><dd><p>Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.</p>
</dd>
<dt><strong>transformed</strong><span class="classifier">boolean, optional</span></dt><dd><p>Whether or not <cite>start_params</cite> is already transformed. Default is
True.</p>
</dd>
<dt><strong>cov_type</strong><span class="classifier">str, optional</span></dt><dd><p>The type of covariance matrix estimator to use. Can be one of
‘approx’, ‘opg’, ‘robust’, or ‘none’. Default is ‘approx’.</p>
</dd>
<dt><strong>cov_kwds</strong><span class="classifier">dict or None, optional</span></dt><dd><p>Keywords for alternative covariance estimators</p>
</dd>
<dt><strong>method</strong><span class="classifier">str, optional</span></dt><dd><p>The <cite>method</cite> determines which solver from <cite>scipy.optimize</cite>
is used, and it can be chosen from among the following strings:</p>
<ul class="simple">
<li><p>‘newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead</p></li>
<li><p>‘bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS)</p></li>
<li><p>‘lbfgs’ for limited-memory BFGS with optional box constraints</p></li>
<li><p>‘powell’ for modified Powell’s method</p></li>
<li><p>‘cg’ for conjugate gradient</p></li>
<li><p>‘ncg’ for Newton-conjugate gradient</p></li>
<li><p>‘basinhopping’ for global basin-hopping solver</p></li>
</ul>
<p>The explicit arguments in <cite>fit</cite> are passed to the solver,
with the exception of the basin-hopping solver. Each
solver has several optional arguments that are not the same across
solvers. See the notes section below (or scipy.optimize) for the
available arguments and for the list of explicit arguments that the
basin-hopping solver supports.</p>
</dd>
<dt><strong>maxiter</strong><span class="classifier">int, optional</span></dt><dd><p>The maximum number of iterations to perform.</p>
</dd>
<dt><strong>full_output</strong><span class="classifier">boolean, optional</span></dt><dd><p>Set to True to have all available output in the Results object’s
mle_retvals attribute. The output is dependent on the solver.
See LikelihoodModelResults notes section for more information.</p>
</dd>
<dt><strong>disp</strong><span class="classifier">boolean, optional</span></dt><dd><p>Set to True to print convergence messages.</p>
</dd>
<dt><strong>callback</strong><span class="classifier">callable callback(xk), optional</span></dt><dd><p>Called after each iteration, as callback(xk), where xk is the
current parameter vector.</p>
</dd>
<dt><strong>return_params</strong><span class="classifier">boolean, optional</span></dt><dd><p>Whether or not to return only the array of maximizing parameters.
Default is False.</p>
</dd>
<dt><strong>em_iter</strong><span class="classifier">int, optional</span></dt><dd><p>Number of initial EM iteration steps used to improve starting
parameters.</p>
</dd>
<dt><strong>search_reps</strong><span class="classifier">int, optional</span></dt><dd><p>Number of randomly drawn search parameters that are drawn around
<cite>start_params</cite> to try and improve starting parameters. Default is
0.</p>
</dd>
<dt><strong>search_iter</strong><span class="classifier">int, optional</span></dt><dd><p>Number of initial EM iteration steps used to improve each of the
search parameter repetitions.</p>
</dd>
<dt><strong>search_scale</strong><span class="classifier">float or array, optional.</span></dt><dd><p>Scale of variates for random start parameter search.</p>
</dd>
<dt><strong>**kwargs</strong></dt><dd><p>Additional keyword arguments to pass to the optimizer.</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl class="simple">
<dt><strong>MarkovSwitchingResults</strong></dt><dd></dd>
</dl>
</dd>
</dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter.html"
title="previous chapter">statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula.html"
title="next chapter">statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.from_formula</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1.
</div>
</body>
</html> | {
"content_hash": "274318f3a5fff487bf221859c5a6c9ea",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 961,
"avg_line_length": 54.814655172413794,
"alnum_prop": 0.6855390422269403,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "df8bb486d493458765836b5617fd8c4c57e1c25f",
"size": "12777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.10.2/generated/statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.fit.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/**
* Created by ben on 2/2/16.
*/
export class App {
configureRouter(config, router) {
config.title = 'Aurelia';
//config.map([
// { route: ['', 'welcome'], name: 'welcome', moduleId: 'welcome', nav: true, title: 'Welcome' },
// { route: 'users', name: 'users', moduleId: 'users', nav: true, title: 'Github Users' },
// { route: 'child-router', name: 'child-router', moduleId: 'child-router', nav: true, title: 'Child Router' }
//]);
this.router = router;
}
} | {
"content_hash": "32e3ad30e315b2c24048652522e066c9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 123,
"avg_line_length": 37.93333333333333,
"alnum_prop": 0.5043936731107206,
"repo_name": "weagle08/aurelia-cordova-test",
"id": "266508540fae4de9c6c0ee483757ca166c009c31",
"size": "569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/js/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3723"
},
{
"name": "HTML",
"bytes": "2427"
},
{
"name": "JavaScript",
"bytes": "19361"
}
],
"symlink_target": ""
} |
<?php defined('SYSPATH') or die('No direct script access.');
class Model_Catstate extends Model {
public function fetch_all()
{
return DB::select('id', 'name')
->from('cat_state')
->order_by('name', 'ASC')
->execute();
}
} | {
"content_hash": "8b1461b0d72136b4873db2b3fff7934d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 60,
"avg_line_length": 18.46153846153846,
"alnum_prop": 0.6125,
"repo_name": "rjsteinert/taktaktak",
"id": "796357ddb09f9589619402d44d05583f23f69d18",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/classes/model/catstate.php",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', {
user: req.user
});
});
router.get('/register', function(req, res) {
res.render('register', {});
});
router.post('/register', function(req, res) {
Account.register(new Account({
username: req.body.username
}), req.body.password, function(err, account) {
if (err) {
return res.render('register', {
account: account
});
}
passport.authenticate('local')(req, res, function() {
res.redirect('/');
});
});
});
router.get('/login', function(req, res) {
res.render('login', {
user: req.user
});
});
router.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/ping', function(req, res) {
console.log(req.user);
res.status(200).send("pong!");
});
module.exports = router;
| {
"content_hash": "45e2317a83180bd988638b6e817034eb",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 74,
"avg_line_length": 22.423076923076923,
"alnum_prop": 0.5600343053173242,
"repo_name": "moodpo/Plucked",
"id": "388b46a35a7732c3af0a6525f1b95dbd9154f602",
"size": "1166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Express/passport-local-express4/routes/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13003"
},
{
"name": "HTML",
"bytes": "3150"
},
{
"name": "JavaScript",
"bytes": "30541"
}
],
"symlink_target": ""
} |
/*************************************************************************/
/* navigation_server_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef NAVIGATION_SERVER_2D_H
#define NAVIGATION_SERVER_2D_H
#include "core/object/class_db.h"
#include "core/templates/rid.h"
#include "scene/2d/navigation_region_2d.h"
// This server exposes the `NavigationServer3D` features in the 2D world.
class NavigationServer2D : public Object {
GDCLASS(NavigationServer2D, Object);
static NavigationServer2D *singleton;
void _emit_map_changed(RID p_map);
protected:
static void _bind_methods();
public:
/// Thread safe, can be used across many threads.
static const NavigationServer2D *get_singleton() { return singleton; }
/// MUST be used in single thread!
static NavigationServer2D *get_singleton_mut() { return singleton; }
/// Create a new map.
virtual RID map_create() const;
/// Set map active.
virtual void map_set_active(RID p_map, bool p_active) const;
/// Returns true if the map is active.
virtual bool map_is_active(RID p_map) const;
/// Set the map cell size used to weld the navigation mesh polygons.
virtual void map_set_cell_size(RID p_map, real_t p_cell_size) const;
/// Returns the map cell size.
virtual real_t map_get_cell_size(RID p_map) const;
/// Set the map edge connection margin used to weld the compatible region edges.
virtual void map_set_edge_connection_margin(RID p_map, real_t p_connection_margin) const;
/// Returns the edge connection margin of this map.
virtual real_t map_get_edge_connection_margin(RID p_map) const;
/// Returns the navigation path to reach the destination from the origin.
virtual Vector<Vector2> map_get_path(RID p_map, Vector2 p_origin, Vector2 p_destination, bool p_optimize, uint32_t p_layers = 1) const;
virtual Vector2 map_get_closest_point(RID p_map, const Vector2 &p_point) const;
virtual RID map_get_closest_point_owner(RID p_map, const Vector2 &p_point) const;
/// Creates a new region.
virtual RID region_create() const;
/// Set the map of this region.
virtual void region_set_map(RID p_region, RID p_map) const;
/// Set the region's layers
virtual void region_set_layers(RID p_region, uint32_t p_layers) const;
virtual uint32_t region_get_layers(RID p_region) const;
/// Set the global transformation of this region.
virtual void region_set_transform(RID p_region, Transform2D p_transform) const;
/// Set the navigation poly of this region.
virtual void region_set_navpoly(RID p_region, Ref<NavigationPolygon> p_nav_mesh) const;
/// Get a list of a region's connection to other regions.
virtual int region_get_connections_count(RID p_region) const;
virtual Vector2 region_get_connection_pathway_start(RID p_region, int p_connection_id) const;
virtual Vector2 region_get_connection_pathway_end(RID p_region, int p_connection_id) const;
/// Creates the agent.
virtual RID agent_create() const;
/// Put the agent in the map.
virtual void agent_set_map(RID p_agent, RID p_map) const;
/// The maximum distance (center point to
/// center point) to other agents this agent
/// takes into account in the navigation. The
/// larger this number, the longer the running
/// time of the simulation. If the number is too
/// low, the simulation will not be safe.
/// Must be non-negative.
virtual void agent_set_neighbor_dist(RID p_agent, real_t p_dist) const;
/// The maximum number of other agents this
/// agent takes into account in the navigation.
/// The larger this number, the longer the
/// running time of the simulation. If the
/// number is too low, the simulation will not
/// be safe.
virtual void agent_set_max_neighbors(RID p_agent, int p_count) const;
/// The minimal amount of time for which this
/// agent's velocities that are computed by the
/// simulation are safe with respect to other
/// agents. The larger this number, the sooner
/// this agent will respond to the presence of
/// other agents, but the less freedom this
/// agent has in choosing its velocities.
/// Must be positive.
virtual void agent_set_time_horizon(RID p_agent, real_t p_time) const;
/// The radius of this agent.
/// Must be non-negative.
virtual void agent_set_radius(RID p_agent, real_t p_radius) const;
/// The maximum speed of this agent.
/// Must be non-negative.
virtual void agent_set_max_speed(RID p_agent, real_t p_max_speed) const;
/// Current velocity of the agent
virtual void agent_set_velocity(RID p_agent, Vector2 p_velocity) const;
/// The new target velocity.
virtual void agent_set_target_velocity(RID p_agent, Vector2 p_velocity) const;
/// Position of the agent in world space.
virtual void agent_set_position(RID p_agent, Vector2 p_position) const;
/// Agent ignore the Y axis and avoid collisions by moving only on the horizontal plane
virtual void agent_set_ignore_y(RID p_agent, bool p_ignore) const;
/// Returns true if the map got changed the previous frame.
virtual bool agent_is_map_changed(RID p_agent) const;
/// Callback called at the end of the RVO process
virtual void agent_set_callback(RID p_agent, Object *p_receiver, StringName p_method, Variant p_udata = Variant()) const;
/// Destroy the `RID`
virtual void free(RID p_object) const;
NavigationServer2D();
virtual ~NavigationServer2D();
};
#endif // NAVIGATION_SERVER_2D_H
| {
"content_hash": "f442e4597ad491a415567b65b57010ba",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 136,
"avg_line_length": 43.48235294117647,
"alnum_prop": 0.648538961038961,
"repo_name": "vnen/godot",
"id": "7350eeb5b16b98a887d07c0eba38fa8b5d7a844f",
"size": "7392",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "servers/navigation_server_2d.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AIDL",
"bytes": "1633"
},
{
"name": "C",
"bytes": "820090"
},
{
"name": "C#",
"bytes": "949573"
},
{
"name": "C++",
"bytes": "36914081"
},
{
"name": "CMake",
"bytes": "589"
},
{
"name": "GAP",
"bytes": "62"
},
{
"name": "GDScript",
"bytes": "54031"
},
{
"name": "GLSL",
"bytes": "798581"
},
{
"name": "Java",
"bytes": "512037"
},
{
"name": "JavaScript",
"bytes": "182635"
},
{
"name": "Kotlin",
"bytes": "16172"
},
{
"name": "Makefile",
"bytes": "1421"
},
{
"name": "Objective-C",
"bytes": "20550"
},
{
"name": "Objective-C++",
"bytes": "286548"
},
{
"name": "PowerShell",
"bytes": "2713"
},
{
"name": "Python",
"bytes": "444369"
},
{
"name": "Shell",
"bytes": "27141"
}
],
"symlink_target": ""
} |
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
// Load the view framework
if(!class_exists('VmViewAdmin'))require(VMPATH_ADMIN.DS.'helpers'.DS.'vmviewadmin.php');
// Load some common models
if(!class_exists('VirtueMartModelCustomfields')) require(VMPATH_ADMIN.DS.'models'.DS.'customfields.php');
/**
* HTML View class for the VirtueMart Component
*
* @package VirtueMart
* @author
*/
class VirtuemartViewProduct extends VmViewAdmin {
var $json = array();
function __construct( ){
$this->type = vRequest::getCmd('type', false);
$this->row = vRequest::getInt('row', false);
$this->db = JFactory::getDBO();
$this->model = VmModel::getModel('Customfields') ;
}
function display($tpl = null) {
$filter = vRequest::getVar('q', vRequest::getVar('term', false) );
$id = vRequest::getInt('id', false);
$virtuemart_product_id = vRequest::getInt('virtuemart_product_id',array());
if(is_array($virtuemart_product_id) && count($virtuemart_product_id) > 0){
$product_id = (int)$virtuemart_product_id[0];
} else {
$product_id = (int)$virtuemart_product_id;
}
//$customfield = $this->model->getcustomfield();
/* Get the task */
if ($this->type=='relatedproducts') {
$query = "SELECT virtuemart_product_id AS id, CONCAT(product_name, '::', product_sku) AS value
FROM #__virtuemart_products_".VmConfig::$vmlang."
JOIN `#__virtuemart_products` AS p using (`virtuemart_product_id`)";
if ($filter) $query .= " WHERE product_name LIKE '%". $this->db->escape( $filter, true ) ."%' or product_sku LIKE '%". $this->db->escape( $filter, true ) ."%' limit 0,10";
self::setRelatedHtml($product_id,$query,'R');
}
else if ($this->type=='relatedcategories')
{
$query = "SELECT virtuemart_category_id AS id, CONCAT(category_name, '::', virtuemart_category_id) AS value
FROM #__virtuemart_categories_".VmConfig::$vmlang;
if ($filter) $query .= " WHERE category_name LIKE '%". $this->db->escape( $filter, true ) ."%' limit 0,10";
self::setRelatedHtml($product_id,$query,'Z');
}
else if ($this->type=='custom')
{
$query = "SELECT CONCAT(virtuemart_custom_id, '|', custom_value, '|', field_type) AS id, CONCAT(custom_title, '::', custom_tip) AS value
FROM #__virtuemart_customs";
if ($filter) $query .= " WHERE custom_title LIKE '%".$filter."%' limit 0,50";
$this->db->setQuery($query);
$this->json['value'] = $this->db->loadObjectList();
$this->json['ok'] = 1 ;
}
else if ($this->type=='fields')
{
if (!class_exists ('VirtueMartModelCustom')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'custom.php');
}
$fieldTypes = VirtueMartModelCustom::getCustomTypes();
$query = 'SELECT *,`custom_value` as value FROM `#__virtuemart_customs`
WHERE (`virtuemart_custom_id`='.$id.' or `custom_parent_id`='.$id.') ';
$query .= 'order by `ordering` asc';
$this->db->setQuery($query);
$rows = $this->db->loadObjectlist();
$html = array ();
foreach ($rows as $field) {
if ($field->field_type =='deprecatedwasC' ){
$this->json['table'] = 'childs';
$q='SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE `published`=1
AND `product_parent_id`= '.vRequest::getInt('virtuemart_product_id');
//$this->db->setQuery(' SELECT virtuemart_product_id, product_name FROM `#__virtuemart_products` WHERE `product_parent_id` ='.(int)$product_id);
$this->db->setQuery($q);
if ($childIds = $this->db->loadColumn()) {
// Get childs
foreach ($childIds as $childId) {
$field->custom_value = $childId;
$display = $this->model->displayProductCustomfieldBE($field,$childId,$this->row);
if ($field->is_cart_attribute) $cartIcone= 'default';
else $cartIcone= 'default-off';
$html[] = '<div class="removable">
<td>'.$field->custom_title.'</td>
<td>'.$display.$field->custom_tip.'</td>
<td>'.vmText::_($fieldTypes[$field->field_type]).'
'.$this->model->setEditCustomHidden($field, $this->row).'
</td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span></td>
<td></td>
</div>';
$this->row++;
}
}
} elseif ($field->field_type =='E') {
$this->json['table'] = 'customPlugins';
$this->model->bindCustomEmbeddedFieldParams($field,'E');
$display = $this->model->displayProductCustomfieldBE($field,$product_id,$this->row);
if ($field->is_cart_attribute) {
$cartIcone= 'default';
} else {
$cartIcone= 'default-off';
}
$field->virtuemart_product_id=$product_id;
$html[] = '
<tr class="removable">
<td><span class="hasTip" title="'.vmText::_($field->custom_tip).'">'.$field->custom_title.'</td>
<td>'.$display.'
'.$this->model->setEditCustomHidden($field, $this->row).'
<p>'.vmText::_('COM_VIRTUEMART_CUSTOM_ACTIVATE_JAVASCRIPT').'</p></td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span>'.vmText::_('COM_VIRTUEMART_CUSTOM_EXTENSION').'</td>
<td><span class="vmicon vmicon-16-move"></span>
<span class="vmicon vmicon-16-remove"></span><input class="ordering" type="hidden" value="'.$this->row.'" name="field['.$this->row .'][ordering]" />
</td>
</tr>';
$this->row++;
} else {
$this->json['table'] = 'fields';
$display = $this->model->displayProductCustomfieldBE($field,$product_id,$this->row);
if ($field->is_cart_attribute) $cartIcone= 'default';
else $cartIcone= 'default-off';
if(isset($fieldTypes[$field->field_type])){
$type =vmText::_($fieldTypes[$field->field_type]);
} else {
$type = 'deprecated';
}
$html[] = '<tr class="removable">
<td><span class="hasTip" title="'.vmText::_($field->custom_tip).'">'.$field->custom_title.'</td>
<td>'.$display.'</td>
<td><span class="vmicon vmicon-16-'.$cartIcone.'"></span>'.vmText::_($fieldTypes[$field->field_type]).'
'.$type.$this->model->setEditCustomHidden($field, $this->row).'
</td>
<td><span class="vmicon vmicon-16-move"></span><span class="vmicon vmicon-16-remove"></span><input class="ordering" type="hidden" value="'.$this->row.'" name="field['.$this->row .'][ordering]" /></td>
</tr>';
$this->row++;
}
}
$this->json['value'] = $html;
$this->json['ok'] = 1 ;
} else if ($this->type=='userlist')
{
$status = vRequest::getvar('status');
$productShoppers=0;
if ($status) {
$productModel = VmModel::getModel('product');
$productShoppers = $productModel->getProductShoppersByStatus($product_id ,$status);
}
if(!class_exists('ShopFunctions'))require(VMPATH_ADMIN.DS.'helpers'.DS.'shopfunctions.php');
$html = ShopFunctions::renderProductShopperList($productShoppers);
$this->json['value'] = $html;
} else $this->json['ok'] = 0 ;
if ( empty($this->json)) {
$this->json['value'] = null;
$this->json['ok'] = 1 ;
}
echo json_encode($this->json);
}
function setRelatedHtml($product_id,$query,$fieldType) {
$this->db->setQuery($query);
$this->json = $this->db->loadObjectList();
$query = 'SELECT * FROM `#__virtuemart_customs` WHERE field_type ="'.$fieldType.'" ';
$this->db->setQuery($query);
$custom = $this->db->loadObject();
if(!$custom) {
vmdebug('setRelatedHtml could not find $custom for field type '.$fieldType);
return false;
}
$custom->virtuemart_product_id = $product_id;
foreach ($this->json as &$related) {
$custom->customfield_value = $related->id;
$display = $this->model->displayProductCustomfieldBE($custom,$related->id,$this->row);
$html = '<div class="vm_thumb_image">
<span class="vmicon vmicon-16-move"></span>
<div class="vmicon vmicon-16-remove"></div>
<span>'.$display.'</span>
'.$this->model->setEditCustomHidden($custom, $this->row).'
</div>';
$related->label = $html;
}
}
}
// pure php no closing tag
| {
"content_hash": "d8d84b7053c3b34277cb96f61c9a6942",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 207,
"avg_line_length": 38.56521739130435,
"alnum_prop": 0.6104221470625079,
"repo_name": "mssnaveensharma/venison-jaqui",
"id": "8c2cce62aebe34098b6548fd1e4f847fc15c067c",
"size": "8569",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "administrator/components/com_virtuemart/views/product/view.json.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1810540"
},
{
"name": "Erlang",
"bytes": "19643"
},
{
"name": "JavaScript",
"bytes": "2447041"
},
{
"name": "PHP",
"bytes": "15379259"
},
{
"name": "Perl",
"bytes": "231114"
}
],
"symlink_target": ""
} |
package org.openqa.selenium;
import junit.extensions.TestSetup;
import junit.framework.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.openqa.selenium.internal.CommandLine;
import org.openqa.selenium.internal.PortProber;
import static org.openqa.selenium.internal.PortProber.pollPort;
public class SeleniumServerStarter extends TestSetup {
private static final String SELENIUM_JAR = "build/remote/server/server-standalone.jar";
private CommandLine command;
public SeleniumServerStarter(Test test) {
super(test);
}
@Override
protected void setUp() throws Exception {
// Walk up the path until we find the "third_party/selenium" directory
File seleniumJar = findSeleniumJar();
if (!seleniumJar.exists()) {
throw new IllegalStateException("Cannot locate selenium jar");
}
String port = startSeleniumServer(seleniumJar);
// Wait until the server process is running (port 4444)
if (!pollPort(Integer.valueOf(port))) {
throw new RuntimeException("Unable to start selenium server");
}
super.setUp();
}
private String startSeleniumServer(File seleniumJar) throws IOException {
String port = System.getProperty("webdriver.selenium.server.port", "5555");
command = new CommandLine("java", "-jar", seleniumJar.getAbsolutePath(), "-port", port);
command.executeAsync();
return port;
}
private File findSeleniumJar() {
File dir = new File(".");
File seleniumJar = null;
while (dir != null) {
seleniumJar = new File(dir, SELENIUM_JAR);
if (seleniumJar.exists()) {
break;
}
dir = dir.getParentFile();
}
return seleniumJar;
}
@Override
protected void tearDown() throws Exception {
if (command != null) {
command.destroy();
}
super.tearDown();
}
}
| {
"content_hash": "13cd254a77e1ab0a38fa149426a27e87",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 92,
"avg_line_length": 26.493150684931507,
"alnum_prop": 0.6685625646328852,
"repo_name": "hugs/selenium",
"id": "dfb1b8699f4090589eec5af02ebf80a36dc5e4df",
"size": "1934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "selenium/test/java/org/openqa/selenium/SeleniumServerStarter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "C",
"bytes": "9165596"
},
{
"name": "C#",
"bytes": "1276218"
},
{
"name": "C++",
"bytes": "245706"
},
{
"name": "Java",
"bytes": "5070618"
},
{
"name": "JavaScript",
"bytes": "11186985"
},
{
"name": "Objective-C",
"bytes": "430464"
},
{
"name": "Python",
"bytes": "2146977"
},
{
"name": "Ruby",
"bytes": "249671"
},
{
"name": "Shell",
"bytes": "13541"
}
],
"symlink_target": ""
} |
set -e -x
ls
cd ${PKG_NAME}-*/
./configure --prefix="${PKG_DIR}" \
--libdir=${PKG_DIR}/lib --with-sysdeps=/lib/skalibs/sysdeps \
--disable-shared --enable-static-libc
make $MAKE_JOBS
make $MAKE_JOBS install DESTDIR="${PKG_INSTDIR}"
| {
"content_hash": "56bfd2bc6ad981d6c904549477bd6fde",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 65,
"avg_line_length": 30,
"alnum_prop": 0.6541666666666667,
"repo_name": "FreakyPenguin/static-distro",
"id": "51e728c80ba87fffbba5ae65b95202993486b234",
"size": "250",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "packages/s6-rc/0.1.0.0/build.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "20656"
}
],
"symlink_target": ""
} |
@interface PPNetworkHelper ()
@property PPSDK *sdk;
@property PPReachability *reachability;
@end
@implementation PPNetworkHelper
-(instancetype)initWithSDK:(PPSDK *)sdk {
if (self = [super init]) {
self.sdk = sdk;
}
return self;
}
- (void) startNotifier {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.reachability = [PPReachability reachabilityForInternetConnection];
[self.reachability startNotifier];
self.netStatus = [self.reachability currentReachabilityStatus];
[self setNetworkStatus:self.netStatus];
}
- (void) stopNotifier {
}
- (void)reachabilityChanged:(NSNotification *)note {
PPReachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[PPReachability class]]);
self.netStatus = [curReach currentReachabilityStatus];
[self setNetworkStatus:self.netStatus];
}
- (void)setNetworkStatus: (NetworkStatus)netStatus {
switch (netStatus) {
case NotReachable:
PPFastLog(@"network not reachable");
if (self.networkHelperDelegate && [self.networkHelperDelegate respondsToSelector:@selector(didNetworkUnreachable)]) {
[self.networkHelperDelegate didNetworkUnreachable];
}
break;
case ReachableViaWiFi:
PPFastLog(@"network reachable via wifi");
if (self.networkHelperDelegate && [self.networkHelperDelegate respondsToSelector:@selector(didNetworkReachable:)]) {
[self.networkHelperDelegate didNetworkReachable:netStatus];
}
break;
case ReachableViaWWAN:
PPFastLog(@"network reachable via wwan");
if (self.networkHelperDelegate && [self.networkHelperDelegate respondsToSelector:@selector(didNetworkReachable:)]) {
[self.networkHelperDelegate didNetworkReachable:netStatus];
}
default:
break;
}
}
@end
| {
"content_hash": "6e4f5a68d382ac3ab121102af721a3d4",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 150,
"avg_line_length": 32.82258064516129,
"alnum_prop": 0.685995085995086,
"repo_name": "PPMESSAGE/ppcom-ios-sdk",
"id": "0f1757a936f29cc323bd83d4874cb2d86218850b",
"size": "2178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PPComLib/Classes/utils/PPNetworkHelper.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "535373"
},
{
"name": "Ruby",
"bytes": "1885"
},
{
"name": "Shell",
"bytes": "563"
}
],
"symlink_target": ""
} |
var request = require('..')
, https = require('https')
, fs = require('fs')
, path = require('path')
, should = require('should')
, express = require('express');
describe('request(url)', function(){
it('should be supported', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hello');
});
var s = app.listen(function(){
var url = 'http://localhost:' + s.address().port;
request(url)
.get('/')
.expect("hello", done);
});
})
describe('.end(cb)', function() {
it('should set `this` to the test object when calling cb', function(done) {
var app = express();
var s = app.listen(function(){
var url = 'http://localhost:' + s.address().port;
var test = request(url).get('/');
test.end(function(err, res) {
this.should.eql(test);
done();
});
});
})
})
})
describe('request(app)', function(){
it('should fire up the app on an ephemeral port', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
})
it('should work with an active server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var server = app.listen(4000, function(){
request(server)
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
});
})
it('should work with remote server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var server = app.listen(4001, function(){
request('http://localhost:4001')
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
});
})
it('should work with a https server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var fixtures = path.join(__dirname, 'fixtures');
var server = https.createServer({
key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
}, app);
request(server)
.get('/')
.end(function(err, res){
if (err) return done(err);
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
})
it('should work with .send() etc', function(done){
var app = express();
app.use(express.bodyParser());
app.post('/', function(req, res){
res.send(req.body.name);
});
request(app)
.post('/')
.send({ name: 'tobi' })
.expect('tobi', done);
})
it('should work when unbuffered', function(done){
var app = express();
app.get('/', function(req, res){
res.end('Hello');
});
request(app)
.get('/')
.expect('Hello', done);
})
it('should default redirects to 0', function(done){
var app = express();
app.get('/', function(req, res){
res.redirect('/login');
});
request(app)
.get('/')
.expect(302, done);
})
it('should handle socket errors', function(done) {
var app = express();
app.get('/', function(req, res){
res.destroy();
});
request(app)
.get('/')
.end(function(err) {
should.exist(err);
done();
});
})
describe('.end(fn)', function(){
it('should close server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('supertest FTW!');
});
var test = request(app)
.get('/')
.end(function(){});
test._server.on('close', function(){
done();
});
});
it('should wait for server to close before invoking fn', function(done){
var app = express();
var closed = false;
app.get('/', function(req, res){
res.send('supertest FTW!');
});
var test = request(app)
.get('/')
.end(function(){
closed.should.be.true;
done();
});
test._server.on('close', function(){
closed = true;
});
});
it('should support nested requests', function(done){
var app = express();
var test = request(app);
app.get('/', function(req, res){
res.send('supertest FTW!');
});
test
.get('/')
.end(function(){
test
.get('/')
.end(function(err, res){
(err === null).should.be.true;
res.should.have.status(200);
res.text.should.equal('supertest FTW!');
done();
});
});
});
});
describe('.expect(status[, fn])', function(){
it('should assert the response status', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect(404)
.end(function(err, res){
err.message.should.equal('expected 404 "Not Found", got 200 "OK"');
done();
});
})
})
describe('.expect(status)', function () {
it('should assert only status', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send('hey');
})
request(app)
.get('/')
.expect(200)
.end(done)
})
})
describe('.expect(status, body[, fn])', function(){
it('should assert the response body and status', function(done){
var app = express();
app.get('/', function(req, res){
res.send('foo');
});
request(app)
.get('/')
.expect(200, 'foo', done)
});
describe("when the body argument is an empty string", function() {
it("should not quietly pass on failure", function(done) {
var app = express();
app.get('/', function(req, res){
res.send('foo');
});
request(app)
.get('/')
.expect(200, '')
.end(function(err, res){
err.message.should.equal('expected \'\' response body, got \'foo\'');
done();
});
});
});
})
describe('.expect(body[, fn])', function(){
it('should assert the response body', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('hey')
.end(function(err, res){
err.message.should.equal('expected \'hey\' response body, got \'{"foo":"bar"}\'');
done();
});
})
it('should assert the body before the status', function (done) {
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send(500, { message: 'something went wrong' });
});
request(app)
.get('/')
.expect(200)
.expect('hey')
.end(function(err, res){
err.message.should.equal('expected \'hey\' response body, got \'{"message":"something went wrong"}\'');
done();
});
});
it('should assert the response text', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('{"foo":"bar"}', done);
})
it('should assert the parsed response body', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect({ foo: 'baz' })
.end(function(err, res){
err.message.should.equal('expected { foo: \'baz\' } response body, got { foo: \'bar\' }');
request(app)
.get('/')
.expect({ foo: 'bar' })
.end(done);
});
})
it('should support regular expressions', function(done){
var app = express();
app.get('/', function(req, res){
res.send('foobar');
});
request(app)
.get('/')
.expect(/^bar/)
.end(function(err, res){
err.message.should.equal('expected body \'foobar\' to match /^bar/');
done();
});
})
it('should assert response body multiple times', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey tj');
});
request(app)
.get('/')
.expect(/tj/)
.expect('hey')
.expect('hey tj')
.end(function (err, res) {
err.message.should.equal("expected 'hey' response body, got 'hey tj'");
done();
});
})
it('should assert response body multiple times with no exception', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey tj');
});
request(app)
.get('/')
.expect(/tj/)
.expect(/^hey/)
.expect('hey tj', done);
})
})
describe('.expect(field, value[, fn])', function(){
it('should assert the header field presence', function(done){
var app = express();
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('Content-Foo', 'bar')
.end(function(err, res){
err.message.should.equal('expected "Content-Foo" header field');
done();
});
})
it('should assert the header field value', function(done){
var app = express();
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('Content-Type', 'text/html')
.end(function(err, res){
err.message.should.equal('expected "Content-Type" of "text/html", got "application/json; charset=utf-8"');
done();
});
})
it('should assert multiple fields', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect('Content-Length', '3')
.end(done);
})
it('should support regular expressions', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /^application/)
.end(function(err){
err.message.should.equal('expected "Content-Type" matching /^application/, got "text/html; charset=utf-8"');
done();
});
})
it('should support numbers', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Length', 4)
.end(function(err){
err.message.should.equal('expected "Content-Length" of "4", got "3"');
done();
});
})
describe('handling arbitrary expect functions', function(){
it('reports errors',function(done) {
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect(function(res) {
throw new Error("failed")
})
.end(function(err) {
err.message.should.equal('failed');
done()
});
});
it('ensures truthy non-errors returned from asserts are promoted to errors',function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect(function(res) {
return "some descriptive error";
})
.end(function(err) {
err.message.should.equal('some descriptive error');
done()
});
});
it("doesn't create false negatives", function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect(function(res) {})
.end(done);
});
it("handles multiple asserts", function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var calls = [];
request(app)
.get('/')
.expect(function(res) { calls[0] = 1 })
.expect(function(res) { calls[1] = 1 })
.expect(function(res) { calls[2] = 1 })
.end(function() {
| {
"content_hash": "bbf89e40c3fdbacf15bf3cd7d146a3e3",
"timestamp": "",
"source": "github",
"line_count": 557,
"max_line_length": 116,
"avg_line_length": 22.978456014362656,
"alnum_prop": 0.5012110321118838,
"repo_name": "wenjoy/homePage",
"id": "3713701a391bea86c66c6af512ffd8ed0013094b",
"size": "12800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/geetest/node_modules/request/node_modules/karma-phantomjs-launcher/node_modules/phantomjs/node_modules/request-progress/node_modules/expect.js/node_modules/serve/node_modules/less-middleware/node_modules/supertest/test/supertest.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "330"
},
{
"name": "HTML",
"bytes": "4292"
},
{
"name": "JavaScript",
"bytes": "26625"
}
],
"symlink_target": ""
} |
namespace HaloOnline.Server.Core.Http.Model.User
{
public class ApplyOfferListRequest
{
}
}
| {
"content_hash": "1e6571782e932e9fc231fc65ad908100",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 49,
"avg_line_length": 17.5,
"alnum_prop": 0.7047619047619048,
"repo_name": "Atvaark/Emurado",
"id": "0e7e3739fd1995129cf688f2556d55d4630b114a",
"size": "107",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "HaloOnline.Server.Core.Http/Model/User/ApplyOfferListRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "358746"
},
{
"name": "CSS",
"bytes": "35"
},
{
"name": "HTML",
"bytes": "5357"
},
{
"name": "JavaScript",
"bytes": "6499"
}
],
"symlink_target": ""
} |
<?php
require_once dirname(dirname(__DIR__)) . "/classes/autoloader.php";
require_once dirname(dirname(__DIR__)) . "/lib/xsrf.php";
require_once("/etc/apache2/capstone-mysql/encrypted-config.php");
/**
* controller/api for the listing type class
*
* @author Bradley Brown <tall.white.ninja@gmail.com>
* @author Tamra Fenstermaker <fenstermaker505@gmail.com>
*/
//verify the xsrf challenge
if(session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
//prepare an empty reply
$reply = new stdClass();
$reply->status = 200;
$reply->data = null;
try {
//grab the mySQL connection
$pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/breadbasket.ini");
//if the volunteer session is empty, the user is not logged in, throw an exception
if(empty($_SESSION["volunteer"]) === true) {
//set XSRF cookie
setXsrfCookie("/");
throw(new RuntimeException("Please log-in or sign up", 401));
}
//determine which HTTP method was used
$method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"];
//sanitize inputs
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
//make sure the id is valid for methods that require it
if(($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) {
throw(new InvalidArgumentException("id cannot be empty or negative", 405));
}
//sanitize and trim the Listing Type (Info) fields
$listingTypeInfo = filter_input(INPUT_GET, "listingType", FILTER_SANITIZE_STRING);
//handle REST calls, while only allowing administrators access to database-modifying methods
if($method === "GET") {
//set XSRF cookie
setXsrfCookie("/");
//get the listing type based on the given field
if(empty($id) === false) {
$reply->data = ListingType::getListingTypeById($pdo, $id);
} elseif(empty($listingTypeInfo)=== false) {
$reply->data = ListingType::getListingByTypeInfo($pdo, $listingTypeInfo);
} else {
$reply->data = ListingType::getAllListingTypes($pdo)->toArray();
}
}
//if the session belongs to an admin, allow post, put, and delete methods
if(empty($_SESSION["volunteer"]) === false && $_SESSION["volunteer"]->getVolIsAdmin() === true) {
if($method === "PUT" || $method === "POST") {
//verifyXsrf();
$requestContent = file_get_contents("php://input");
$requestObject = json_decode($requestContent);
//make sure all fields are present, in order to prevent database issues
if(empty($requestObject->listingType) === true) {
throw(new InvalidArgumentException ("listing type info cannot be empty", 405));
}
//perform the actual put or post
if($method === "PUT") {
$listingType = ListingType::getListingTypeById($pdo, $id);
if($listingType === null) {
throw(new RuntimeException("Listing type does not exist", 404));
}
$listingType = new ListingType($id, $requestObject->listingType);
$listingType->update($pdo);
$reply->message = "Listing type updated OK";
} else if($method === "POST") {
$listingType = new ListingType(null, $requestObject->listingType);
$listingType->insert($pdo);
$reply->message = "Listing type created OK";
}
} else if($method === "DELETE") {
//verifyXsrf();
$listingType = ListingType::getListingTypeById($pdo, $id);
if($listingType === null) {
throw(new RuntimeException("Listing type does not exist", 404));
}
$listingType->delete($pdo);
$deletedObject = new stdClass();
$deletedObject->listingTypeId = $id;
$reply->message = "Listing type deleted OK";
}
} else {
//if not an admin, and attempting a method other than get, throw an exception
if((empty($method) === false) && ($method !== "GET")) {
throw(new RuntimeException("Only administrators are allowed to modify entries", 401));
}
}
} catch(Exception $exception) {
$reply->status = $exception->getCode();
$reply->message = $exception->getMessage();
}
header("Content-type: application/json");
if($reply->data === null) {
unset($reply->data);
}
echo json_encode($reply); | {
"content_hash": "e6c3c3cd5593eb48ba93dc8c32912ed8",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 122,
"avg_line_length": 32.17460317460318,
"alnum_prop": 0.6697089294523927,
"repo_name": "brbrown59/bread-basket",
"id": "6437261da874537041c37881ed11411e37ee53b2",
"size": "4054",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public_html/php/api/listingtype/index.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "11982"
},
{
"name": "JavaScript",
"bytes": "56219"
},
{
"name": "PHP",
"bytes": "447393"
}
],
"symlink_target": ""
} |
/* fast file-to-file copy */
/* p0=input fno, p1=output fno, p2=inputskip, p3=output skip, p4=dur */
#include "ugens.h"
#include "sfheader.h"
#include <stdio.h>
#include <unistd.h>
/* these are all defined in sound.c */
extern int sfd[NFILES]; /* soundfile descriptors */
extern char *sndbuf[NFILES]; /* address of buffer */
extern off_t filepointer[NFILES]; /* to save current pointer in file */
extern int nbytes;
extern SFHEADER sfdesc[NFILES];
double
sfcopy(float p[], int n_args)
{
int maxread,n,input,output,bytes,jj;
if(!n_args) fprintf(stderr,"(sfcopy(input_fno,output_fno,input_skip,output_skip,dur)\n");
input = (int)p[0];
output = (int)p[1];
if((sfclass(&sfdesc[input]) != sfclass(&sfdesc[output])) ||
(sfchans(&sfdesc[input]) != sfchans(&sfdesc[output]))) {
fprintf(stderr,
"Input and output specifications do not match. Canot copy.\n");
closesf();
}
bytes = setnote(p[2],p[4],input) *
sfchans(&sfdesc[input]) * sfclass(&sfdesc[input]);
setnote(p[3],p[4],output);
_backup(input);
_backup(output);
fprintf(stderr,"Copy %d bytes\n",bytes);
while(bytes) {
maxread = (bytes > nbytes) ? nbytes : bytes;
if((n = read(sfd[input],sndbuf[input],maxread)) <= 0) {
fprintf(stderr,"Apparent eof on input\n");
return -1.0;
}
if((jj = write(sfd[output],sndbuf[input],n)) <= 0) {
fprintf(stderr,"Trouble writing output file\n");
closesf();
}
bytes -= n;
filepointer[input] += n;
filepointer[output] += n;
}
if(fsync(sfd[output]) < 0 ) {
fprintf(stderr,"trouble fsyncing file");
closesf();
}
fprintf(stderr,"Copy completed\n");
return 0.0;
}
| {
"content_hash": "9137282768c885812d59b5436e9a9bf7",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 90,
"avg_line_length": 26.467741935483872,
"alnum_prop": 0.6404631322364412,
"repo_name": "RTcmix/RTcmix",
"id": "81d08723693c625de06fe456c8ea4b4d04f051b1",
"size": "1641",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/rtcmix/sfcopy.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1593016"
},
{
"name": "C++",
"bytes": "3017803"
},
{
"name": "Csound Score",
"bytes": "313048"
},
{
"name": "HTML",
"bytes": "60302"
},
{
"name": "Lex",
"bytes": "10472"
},
{
"name": "M4",
"bytes": "12968"
},
{
"name": "Makefile",
"bytes": "267126"
},
{
"name": "Objective-C",
"bytes": "5199"
},
{
"name": "Objective-C++",
"bytes": "31925"
},
{
"name": "Perl",
"bytes": "7461"
},
{
"name": "Python",
"bytes": "2674"
},
{
"name": "Rich Text Format",
"bytes": "715"
},
{
"name": "Roff",
"bytes": "3137"
},
{
"name": "Shell",
"bytes": "42490"
},
{
"name": "XS",
"bytes": "2642"
},
{
"name": "Yacc",
"bytes": "27658"
}
],
"symlink_target": ""
} |
<?php
// ######################## SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE & ~8192);
// ##################### DEFINE IMPORTANT CONSTANTS #######################
define('CVS_REVISION', '$RCSfile$ - $Revision: 31381 $');
// #################### PRE-CACHE TEMPLATES AND DATA ######################
$phrasegroups = array('cphome', 'help_faq', 'fronthelp');
$specialtemplates = array();
// ########################## REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/functions_faq.php');
// ######################## CHECK ADMIN PERMISSIONS #######################
if (!can_administer('canadminfaq'))
{
print_cp_no_permission();
}
// ############################# LOG ACTION ###############################
log_admin_action();
// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################
print_cp_header($vbphrase['faq_manager']);
// #############################################################################
if (empty($_REQUEST['do']))
{
$_REQUEST['do'] = 'modify';
}
// #############################################################################
if ($_POST['do'] == 'kill')
{
$vbulletin->input->clean_array_gpc('p', array(
'faqname' => TYPE_STR
));
// get list of items to delete
$faqDeleteNames = implode(', ', fetch_faq_delete_list($vbulletin->GPC['faqname']));
// delete faq
$db->query_write("
DELETE FROM " . TABLE_PREFIX . "faq
WHERE faqname IN($faqDeleteNames)
");
// delete phrases
$db->query_write("
DELETE FROM " . TABLE_PREFIX . "phrase
WHERE varname IN ($faqDeleteNames)
AND fieldname IN ('faqtitle', 'faqtext')
");
// get parent item
$parent = $faqcache[$vbulletin->GPC['faqname']]['faqparent'];
define('CP_REDIRECT', "faq.php?faq=$parent");
print_stop_message('deleted_faq_item_successfully');
}
// #############################################################################
if ($_REQUEST['do'] == 'delete')
{
$vbulletin->input->clean_array_gpc('r', array(
'faq' => TYPE_STR
));
print_delete_confirmation('faq', $db->escape_string($vbulletin->GPC['faq']), 'faq', 'kill', 'faq_item', '', $vbphrase['please_note_deleting_this_item_will_remove_children']);
}
// #############################################################################
if ($_POST['do'] == 'update')
{
$vbulletin->input->clean_array_gpc('p', array(
'faq' => TYPE_STR,
'faqparent' => TYPE_STR,
'deftitle' => TYPE_STR
));
if ($vbulletin->GPC['deftitle'] == '')
{
print_stop_message('invalid_title_specified');
}
if (!preg_match('#^[a-z0-9_]+$#i', $vbulletin->GPC['faq']))
{
print_stop_message('invalid_faq_varname');
}
if ($vbulletin->GPC['faqparent'] == $vbulletin->GPC['faq'])
{
print_stop_message('cant_parent_faq_item_to_self');
}
else
{
$faqarray = array();
$getfaqs = $db->query_read("SELECT faqname, faqparent FROM " . TABLE_PREFIX . "faq");
while ($getfaq = $db->fetch_array($getfaqs))
{
$faqarray["$getfaq[faqname]"] = $getfaq['faqparent'];
}
$db->free_result($getfaqs);
$parent_item = $vbulletin->GPC['faqparent'];
// Traverses up the parent list to check we're not moving an faq item to something already below it
while ($parent_item != 'faqroot' AND $parent_item != '' AND $i++ < 100)
{
$parent_item = $faqarray["$parent_item"];
if ($parent_item == $vbulletin->GPC['faq'])
{
print_stop_message('cant_parent_faq_item_to_child');
}
}
}
$db->query_write("
DELETE FROM " . TABLE_PREFIX . "phrase
WHERE varname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'
AND fieldname IN('faqtitle', 'faqtext')
" . (!$vbulletin->debug ? 'AND languageid <> -1' : '') . "
");
$db->query_write("
DELETE FROM " . TABLE_PREFIX . "faq
WHERE faqname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'
");
$_POST['do'] = 'insert';
}
// #############################################################################
if ($_POST['do'] == 'insert')
{
$vars = array(
'faq' => TYPE_STR,
'faqparent' => TYPE_STR,
'volatile' => TYPE_INT,
'product' => TYPE_STR,
'displayorder' => TYPE_INT,
'title' => TYPE_ARRAY_STR, // Originally NULL though not type checking incode, used as an array
'text' => TYPE_ARRAY_STR, // Originally NULL though not type checking incode, used as an array
'deftitle' => TYPE_STR,
'deftext' => TYPE_STR
);
$vbulletin->input->clean_array_gpc('r', $vars);
if ($vbulletin->GPC['deftitle'] == '')
{
print_stop_message('invalid_title_specified');
}
if (!preg_match('#^[a-z0-9_]+$#i', $vbulletin->GPC['faq']))
{
print_stop_message('invalid_faq_varname');
}
// ensure that the faq name is in 'word_word_word' format
$fixedfaq = strtolower(preg_replace('#\s+#s', '_', $vbulletin->GPC['faq']));
if ($fixedfaq !== $vbulletin->GPC['faq'])
{
print_form_header('faq', 'insert');
print_table_header($vbphrase['faq_link_name_changed']);
print_description_row(construct_phrase($vbphrase['to_maintain_compatibility_with_the_system_name_changed'], $vbulletin->GPC['faq'], $fixedfaq));
print_input_row($vbphrase['varname'], 'faq', $fixedfaq);
$vbulletin->GPC['faq'] = $fixedfaq;
foreach(array_keys($vars) AS $varname_outer)
{
$var &= $vbulletin->GPC[$varname_outer];
if (is_array($var))
{
foreach($var AS $varname_inner => $value)
{
construct_hidden_code($varname_outer . "[$varname_inner]", $value);
}
}
else if ($vbulletin->GPC['varname'] != 'faq')
{
construct_hidden_code($varname_outer, $var);
}
}
print_submit_row($vbphrase['continue'], 0, 2, $vbphrase['go_back']);
print_cp_footer();
exit;
}
if ($check = $db->query_first("SELECT faqname FROM " . TABLE_PREFIX . "faq WHERE faqname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'"))
{
print_stop_message('there_is_already_faq_item_named_x', $check['faqname']);
}
if ($check = $db->query_first("
SELECT varname
FROM " . TABLE_PREFIX . "phrase
WHERE varname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'
AND fieldname IN ('faqtitle', 'faqtext')
" . (!$vbulletin->debug ? 'AND languageid <> -1' : '') . "
"))
{
print_stop_message('there_is_already_phrase_named_x', $check['varname']);
}
$faqname = $db->escape_string($vbulletin->GPC['faq']);
// set base language versions
$baselang = iif($vbulletin->GPC['volatile'], -1, 0);
if ($baselang != -1 OR $vbulletin->debug)
{
// can't edit a master version if not in debug mode
$vbulletin->GPC['title']["$baselang"] =& $vbulletin->GPC['deftitle'];
$vbulletin->GPC['text']["$baselang"] =& $vbulletin->GPC['deftext'];
}
$full_product_info = fetch_product_list(true);
$product_version = $full_product_info[$vbulletin->GPC['product']]['version'];
$insertSql = array();
foreach (array_keys($vbulletin->GPC['title']) AS $languageid)
{
$newtitle = trim($vbulletin->GPC['title']["$languageid"]);
$newtext = trim($vbulletin->GPC['text']["$languageid"]);
if ($newtitle OR $newtext)
{
$insertSql[] = "
($languageid,
'$faqname',
'" . $db->escape_string($newtitle) . "',
'faqtitle',
'" . $db->escape_string($vbulletin->GPC['product']) . "',
'" . $db->escape_string($vbulletin->userinfo['username']) . "',
" . TIMENOW . ",
'" . $db->escape_string($product_version) . "')
";
$insertSql[] = "
($languageid,
'$faqname',
'" . $db->escape_string($newtext) . "',
'faqtext',
'" . $db->escape_string($vbulletin->GPC['product']) . "',
'" . $db->escape_string($vbulletin->userinfo['username']) . "',
" . TIMENOW . ",
'" . $db->escape_string($product_version) . "')
";
}
}
if (!empty($insertSql))
{
/*insert query*/
$db->query_write("
INSERT INTO " . TABLE_PREFIX . "phrase
(languageid, varname, text, fieldname, product, username, dateline, version)
VALUES
" . implode(",\n\t", $insertSql)
);
}
/*insert query*/
$db->query_write("
REPLACE INTO " . TABLE_PREFIX . "faq
(faqname, faqparent, displayorder, volatile, product)
VALUES
('$faqname',
'" . $db->escape_string($vbulletin->GPC['faqparent']) . "',
" . $vbulletin->GPC['displayorder'] . ",
" . $vbulletin->GPC['volatile'] . ",
'" . $db->escape_string($vbulletin->GPC['product']) . "')
");
define('CP_REDIRECT', "faq.php?faq= " . $vbulletin->GPC['faqparent']);
print_stop_message('saved_faq_x_successfully', $vbulletin->GPC['deftitle']);
}
// #############################################################################
if ($_REQUEST['do'] == 'edit' OR $_REQUEST['do'] == 'add')
{
require_once(DIR . '/includes/adminfunctions_language.php');
$faqphrase = array();
if ($_REQUEST['do'] == 'edit')
{
$vbulletin->input->clean_array_gpc('r', array(
'faq' => TYPE_STR
));
$faq = $db->query_first("
SELECT * FROM " . TABLE_PREFIX . "faq AS faq
WHERE faqname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'
");
if (!$faq)
{
print_stop_message('no_matches_found');
}
$phrases = $db->query_read("
SELECT text, languageid, fieldname
FROM " . TABLE_PREFIX . "phrase AS phrase
WHERE varname = '" . $db->escape_string($vbulletin->GPC['faq']) . "'
AND fieldname IN ('faqtitle', 'faqtext')
");
while ($phrase = $db->fetch_array($phrases))
{
if ($phrase['fieldname'] == 'faqtitle')
{
$faqphrase["$phrase[languageid]"]['title'] = $phrase['text'];
}
else
{
$faqphrase["$phrase[languageid]"]['text'] = $phrase['text'];
}
}
print_form_header('faq', 'update');
construct_hidden_code('faq', $faq['faqname']);
print_table_header(construct_phrase($vbphrase['x_y_id_z'], $vbphrase['faq_item'], $faqphrase['-1']['title'], $faq['faqname']));
}
else
{
$vbulletin->input->clean_array_gpc('r', array(
'faq' => TYPE_STR
));
$faq = array(
'faqparent' => iif($vbulletin->GPC['faq'], $vbulletin->GPC['faq'], 'faqroot'),
'displayorder' => 1,
'volatile' => iif($vbulletin->debug, 1, 0)
);
?>
<script type="text/javascript">
<!--
function js_check_shortname(theform, checkvb)
{
theform.faq.value = theform.faq.value.toLowerCase();
for (i = 0; i < theform.faqparent.options.length; i++)
{
if (theform.faq.value == theform.faqparent.options[i].value)
{
alert(" <?php echo $vbphrase['sorry_there_is_already_an_item_called']; ?> '" + theform.faq.value + "'");
return false;
}
}
return true;
}
//-->
</script>
<?php
print_form_header('faq', 'insert', 0, 1, 'cpform" onsubmit="return js_check_shortname(this, ' . iif($vbulletin->debug, 'false', 'true') . ');');
print_table_header($vbphrase['add_new_faq_item']);
print_input_row($vbphrase['varname'], 'faq', '', 0, '35" onblur="js_check_shortname(this.form, ' . iif($vbulletin->debug, 'false', 'true') . ');');
}
cache_ordered_faq();
$parentoptions = array('faqroot' => $vbphrase['no_parent_faq_item']);
fetch_faq_parent_options($faq['faqname']);
print_select_row($vbphrase['parent_faq_item'], 'faqparent', $parentoptions, $faq['faqparent']);
if (is_array($faqphrase['-1']))
{
$defaultlang = -1;
}
else
{
$defaultlang = 0;
}
if ($vbulletin->debug OR $defaultlang == 0)
{
print_input_row($vbphrase['title'], 'deftitle', $faqphrase["$defaultlang"]['title'], 1, '70" style="width:100%');
print_textarea_row($vbphrase['text'], 'deftext', $faqphrase["$defaultlang"]['text'], 10, '70" style="width:100%');
}
else
{
construct_hidden_code('deftitle', $faqphrase["$defaultlang"]['title'], 1, 69);
construct_hidden_code('deftext', $faqphrase["$defaultlang"]['text'], 10, 70);
print_label_row($vbphrase['title'], htmlspecialchars($faqphrase["$defaultlang"]['title']));
print_label_row($vbphrase['text'], nl2br(htmlspecialchars($faqphrase["$defaultlang"]['text'])));
}
print_input_row($vbphrase['display_order'], 'displayorder', $faq['displayorder']);
if ($vbulletin->debug)
{
print_yes_no_row($vbphrase['vbulletin_default'], 'volatile', $faq['volatile']);
}
else
{
construct_hidden_code('volatile', $faq['volatile']);
}
print_select_row($vbphrase['product'], 'product', fetch_product_list(), $faq['product']);
print_table_header($vbphrase['translations']);
$languages = fetch_languages_array();
foreach($languages AS $languageid => $lang)
{
print_input_row("$vbphrase[title] <dfn>(" . construct_phrase($vbphrase['x_translation'], "<b>$lang[title]</b>") . ")</dfn>", "title[$languageid]", $faqphrase["$languageid"]['title'], 1, 69, 0, $lang['direction']);
// reset bgcounter so that both entries are the same colour
$bgcounter --;
print_textarea_row("$vbphrase[text] <dfn>(" . construct_phrase($vbphrase['x_translation'], "<b>$lang[title]</b>") . ")</dfn>", "text[$languageid]", $faqphrase["$languageid"]['text'], 4, 70, 1, 1, $lang['direction']);
print_description_row('<img src="../' . $vbulletin->options['cleargifurl'] . '" width="1" height="1" alt="" />', 0, 2, 'thead');
}
print_submit_row($vbphrase['save']);
}
// #############################################################################
if ($_POST['do'] == 'updateorder')
{
$vbulletin->input->clean_array_gpc('p', array(
'order' => TYPE_NOCLEAN,
'faqparent' => TYPE_STR
));
if (empty($vbulletin->GPC['order']) OR !is_array($vbulletin->GPC['order']))
{
print_stop_message('invalid_array_specified');
}
$faqnames = array();
foreach($vbulletin->GPC['order'] AS $faqname => $displayorder)
{
$vbulletin->GPC['order']["$faqname"] = intval($displayorder);
$faqnames[] = "'" . $db->escape_string($faqname) . "'";
}
$faqs = $db->query_read("
SELECT faqname, displayorder
FROM " . TABLE_PREFIX . "faq AS faq
WHERE faqname IN (" . implode(', ', $faqnames) . ")
");
while($faq = $db->fetch_array($faqs))
{
if ($faq['displayorder'] != $vbulletin->GPC['order']["$faq[faqname]"])
{
$db->query_write("
UPDATE " . TABLE_PREFIX . "faq
SET displayorder = " . $vbulletin->GPC['order']["$faq[faqname]"] . "
WHERE faqname = '" . $db->escape_string($faq['faqname']) . "'
");
}
}
define('CP_REDIRECT', "faq.php?faq=" . $vbulletin->GPC['faqparent']);
print_stop_message('saved_display_order_successfully');
}
// #############################################################################
if ($_REQUEST['do'] == 'modify')
{
$vbulletin->input->clean_array_gpc('r', array(
'faq' => TYPE_STR
));
$faqparent = iif(empty($vbulletin->GPC['faq']), 'faqroot', $vbulletin->GPC['faq']);
cache_ordered_faq();
if (!is_array($ifaqcache["$faqparent"]))
{
$faqparent = $faqcache["$faqparent"]['faqparent'];
if (!is_array($ifaqcache["$faqparent"]))
{
print_stop_message('invalid_faq_item_specified');
}
}
$parents = array();
fetch_faq_parents($faqcache["$faqparent"]['faqname']);
$parents = array_reverse($parents);
$nav = "<a href=\"faq.php?" . $vbulletin->session->vars['sessionurl'] . "\">$vbphrase[faq]</a>";
if (!empty($parents))
{
$i = 1;
foreach($parents AS $link => $name)
{
$nav .= '<br />' . str_repeat(' ', $i) . iif(empty($link), $name, "<a href=\"$link\">$name</a>");
$i ++;
}
$nav .= '
<span class="smallfont">' .
construct_link_code($vbphrase['edit'], "faq.php?" . $vbulletin->session->vars['sessionurl'] . "do=edit&faq=" . urlencode($faqparent)) .
construct_link_code($vbphrase['add_child_faq_item'], "faq.php?" . $vbulletin->session->vars['sessionurl'] . "do=add&faq=" . urlencode($faqparent)) .
construct_link_code($vbphrase['delete'], "faq.php?" . $vbulletin->session->vars['sessionurl'] . "do=delete&faq=" . urlencode($faqparent)) .
'</span>';
}
print_form_header('faq', 'updateorder');
construct_hidden_code('faqparent', $faqparent);
print_table_header($vbphrase['faq_manager'], 3);
print_description_row("<b>$nav</b>", 0, 3);
print_cells_row(array($vbphrase['title'], $vbphrase['display_order'], $vbphrase['controls']), 1);
foreach($ifaqcache["$faqparent"] AS $faq)
{
print_faq_admin_row($faq);
if (is_array($ifaqcache["$faq[faqname]"]))
{
foreach($ifaqcache["$faq[faqname]"] AS $subfaq)
{
print_faq_admin_row($subfaq, ' ');
}
}
}
print_submit_row($vbphrase['save_display_order'], false, 3);
}
print_cp_footer();
/*======================================================================*\
|| ####################################################################
|| #
|| # CVS: $RCSfile$ - $Revision: 31381 $
|| ####################################################################
\*======================================================================*/
?>
| {
"content_hash": "6c0bb53aee8f1248012f63d2c445aad4",
"timestamp": "",
"source": "github",
"line_count": 548,
"max_line_length": 218,
"avg_line_length": 30.490875912408757,
"alnum_prop": 0.5558680950386019,
"repo_name": "monkeyboz/coachella",
"id": "b7c0a0ae7d6d0f71fb7be76bba5c94ab681f9c61",
"size": "17404",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/vbulletin/admincp/faq.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "48011"
},
{
"name": "CSS",
"bytes": "404356"
},
{
"name": "JavaScript",
"bytes": "3519432"
},
{
"name": "PHP",
"bytes": "14103742"
},
{
"name": "Shell",
"bytes": "248"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XTriangle` type in crate `x11_dl`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XTriangle">
<title>x11_dl::xrender::XTriangle - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>xrender</a></p><script>window.sidebarCurrent = {name: 'XTriangle', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content type">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>xrender</a>::<wbr><a class='type' href=''>XTriangle</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-70597' class='srclink' href='../../src/x11_dl/xrender.rs.html#310' title='goto source code'>[src]</a></span></h1>
<pre class='rust typedef'>type XTriangle = <a class='struct' href='../../x11_dl/xrender/struct._XTriangle.html' title='x11_dl::xrender::_XTriangle'>_XTriangle</a>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "x11_dl";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html> | {
"content_hash": "d5eef4499a967444a699bf97a32051bc",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 237,
"avg_line_length": 37.0990099009901,
"alnum_prop": 0.5230851347744863,
"repo_name": "mcanders/bevy",
"id": "d0dee8570942c8ed80c8f09d7775fe132aa4e635",
"size": "3747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/x11_dl/xrender/type.XTriangle.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "316751"
}
],
"symlink_target": ""
} |
using Autofac.Features.AttributeFilters;
using Common;
using Common.Log;
using Lykke.Job.EthereumCore.Contracts.Enums.LykkePay;
using Lykke.Job.EthereumCore.Contracts.Events.LykkePay;
using Lykke.JobTriggers.Triggers.Attributes;
using Lykke.JobTriggers.Triggers.Bindings;
using Lykke.Service.EthereumCore.Core;
using Lykke.Service.EthereumCore.Core.Messages.LykkePay;
using Lykke.Service.EthereumCore.Core.Repositories;
using Lykke.Service.EthereumCore.Core.Settings;
using Lykke.Service.RabbitMQ;
using Nethereum.RPC.Eth.DTOs;
using System;
using System.Threading.Tasks;
using Nethereum.Web3;
namespace Lykke.Service.AirlinesJobRunner.Job
{
public class TransferNotificationJob
{
private readonly ILog _logger;
private readonly AppSettings _settings;
private readonly IHotWalletOperationRepository _operationsRepository;
private readonly IRabbitQueuePublisher _rabbitQueuePublisher;
private readonly IWeb3 _web3;
public TransferNotificationJob(AppSettings settings,
ILog logger,
[KeyFilter(Constants.AirLinesKey)]IHotWalletOperationRepository operationsRepository,
IRabbitQueuePublisher rabbitQueuePublisher,
IWeb3 web3
)
{
_settings = settings;
_logger = logger;
_operationsRepository = operationsRepository;
_rabbitQueuePublisher = rabbitQueuePublisher;
_web3 = web3;
}
[QueueTrigger(Constants.AirlinesErc223TransferNotificationsQueue, 200, true)]
public async Task Execute(LykkePayErc20TransferNotificationMessage message, QueueTriggeringContext context)
{
if (string.IsNullOrEmpty(message?.OperationId))
{
await _logger.WriteWarningAsync(nameof(TransferNotificationJob),
"Execute", "", "Empty message skipped");
return;
}
try
{
var operation = await _operationsRepository.GetAsync(message.OperationId);
if (operation == null)
{
await _logger.WriteWarningAsync(nameof(TransferNotificationJob),
"Execute", message.ToJson(), $"No operation for id {message?.OperationId} message skipped");
return;
}
Transaction transaction = await _web3.Eth.Transactions.GetTransactionByHash.SendRequestAsync(message.TransactionHash);
if (transaction == null)
{
message.LastError = "Not yet indexed";
message.DequeueCount++;
context.MoveMessageToEnd(message.ToJson());
context.SetCountQueueBasedDelay(_settings.EthereumCore.MaxQueueDelay, 30000);
return;
}
TransferEvent @event = new TransferEvent(operation.OperationId,
message.TransactionHash,
message.Balance,
operation.TokenAddress,
operation.FromAddress,
operation.ToAddress,
transaction?.BlockHash,
(ulong)transaction?.BlockNumber.Value,
SenderType.EthereumCore,
EventType.Started,
WorkflowType.Airlines,
DateTime.UtcNow);
await _rabbitQueuePublisher.PublshEvent(@event);
}
catch (Exception ex)
{
if (message == null)
return;
if (ex.Message != message.LastError)
await _logger.WriteWarningAsync(nameof(TransferNotificationJob),
"Execute", message.ToJson(), "transaction.OperationId");
message.LastError = ex.Message;
message.DequeueCount++;
context.MoveMessageToEnd(message.ToJson());
context.SetCountQueueBasedDelay(_settings.EthereumCore.MaxQueueDelay, 200);
await _logger.WriteErrorAsync(nameof(TransferNotificationJob), "Execute", message.ToJson(), ex);
}
}
}
}
| {
"content_hash": "94956301c9d9a0954a685d25653630b4",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 134,
"avg_line_length": 38.46363636363636,
"alnum_prop": 0.6064760103994328,
"repo_name": "LykkeCity/EthereumApiDotNetCore",
"id": "bf44dcbf1a56b431807fef1ab9b793e3ecaec14e",
"size": "4233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Lykke.Job.EthereumCore/Job/Airlines/TransferNotificationJob.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2078724"
},
{
"name": "Dockerfile",
"bytes": "354"
},
{
"name": "HTML",
"bytes": "6825"
},
{
"name": "JavaScript",
"bytes": "603"
},
{
"name": "PowerShell",
"bytes": "49430"
},
{
"name": "Solidity",
"bytes": "36566"
}
],
"symlink_target": ""
} |
<!--
Copyright (C) 2015 The Gravitee team (http://gravitee.io)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div ng-if="$ctrl.availability >= 0">
<progress-bar value="$ctrl.availability | floor "></progress-bar>
<md-tooltip md-direction="top"> {{$ctrl.availability | number: 3}}% </md-tooltip>
</div>
<span ng-if="$ctrl.responsetime >= 0" class="label label-primary" style="font-weight: bold; font-size: 10.5px">
{{$ctrl.responsetime | number: 0 }}ms
</span>
| {
"content_hash": "b037b3c8a7bf87235b54f5e0f5365e8f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 111,
"avg_line_length": 41.5,
"alnum_prop": 0.6997991967871486,
"repo_name": "gravitee-io/gravitee-management-webui",
"id": "10c72b0bf3b7fc6ed879a2e1f48982975132d152",
"size": "996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/healthcheckmetric/healthcheck-metric.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "88928"
},
{
"name": "HTML",
"bytes": "831483"
},
{
"name": "JavaScript",
"bytes": "39748"
},
{
"name": "TypeScript",
"bytes": "1091169"
}
],
"symlink_target": ""
} |
void buildBoxMesh(Kray::Prototyper& prot,Kray::MeshSymbol& msh){
Kray::VertexMapSymbol vmap(prot,3); // create vertex map
vmap.data(0,Kray::Vector(-1,-1,-1)); // fill vertex map with cube vertex positions
vmap.data(1,Kray::Vector(-1,-1, 1));
vmap.data(2,Kray::Vector(-1, 1,-1));
vmap.data(3,Kray::Vector(-1, 1, 1));
vmap.data(4,Kray::Vector( 1,-1,-1));
vmap.data(5,Kray::Vector( 1,-1, 1));
vmap.data(6,Kray::Vector( 1, 1,-1));
vmap.data(7,Kray::Vector( 1, 1, 1));
msh.points(vmap); // connect positions vertex map with a mesh
Kray::VarLenDoubleDynamic polygon; // create class for storing polygon data
polygon.set(0,2,6,4); msh.addPoly(0,polygon); // add polygons to mesh
polygon.set(5,7,3,1); msh.addPoly(0,polygon); // all polygons have tag==0
polygon.set(1,3,2,0); msh.addPoly(0,polygon); // tag is an index to materials table
polygon.set(4,6,7,5); msh.addPoly(1,polygon); // we will connect yellowMat with tag==0
polygon.set(0,4,5,1); msh.addPoly(1,polygon); // and redMat with tag==1 later
polygon.set(3,7,6,2); msh.addPoly(1,polygon);
}
void setupSimpleMaterialsForMesh(Kray::Prototyper& prot,Kray::MeshSymbol& msh){
Kray::Symbol yellowMat(prot); // create material object, create new KraySymbol
prot.material(yellowMat); // register it, as material
prot.materialSet_color(yellowMat,Kray::Vector(0.9,0.9,0.3)); // modify default color
Kray::Symbol redMat(prot); // another material
prot.material(redMat);
prot.materialSet_color(redMat,Kray::Vector(0.9,0.2,0));
prot.meshTag_material(msh,0,yellowMat); // attach yellowMat to mesh tag==0
prot.meshTag_material(msh,1,redMat); // attach redMat to mesh tag==1
}
void setupSimpleMeshScene(Kray::Prototyper& prot){
//prot.lightAdd_point(Kray::Vector(-1, 5, -2),Kray::Vector(1,1,1)); // add light source to scene
//prot.background_sky(Kray::Vector(0.4,0.8,0.9),Kray::Vector(0,0,0),Kray::Vector(1,1,1),Kray::Vector(0,1,0)); // gradient background
//prot.pixelFilter_mitchell(); // Mitchel pixel filter makes antialias looks better then box filter (which is default filter becouse of its simplicity)
prot.splitScreen_none(); // how render screen is divided between render threads
} | {
"content_hash": "2fed7036d4e717d2c55aa6a661d7ade0",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 154,
"avg_line_length": 50.27272727272727,
"alnum_prop": 0.6948462929475587,
"repo_name": "haggi/OpenMaya",
"id": "b83a3f1bdd1580cef8c80fecd822f3eee3b2e0e1",
"size": "2240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mayaToKray/src/kray/krayTestScene.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AMPL",
"bytes": "5333"
},
{
"name": "Batchfile",
"bytes": "587"
},
{
"name": "C",
"bytes": "246300"
},
{
"name": "C++",
"bytes": "4178594"
},
{
"name": "Mathematica",
"bytes": "12660820"
},
{
"name": "Objective-C",
"bytes": "316"
},
{
"name": "Python",
"bytes": "1583249"
}
],
"symlink_target": ""
} |
package com.seovic.maven.plugins.npm;
import java.io.File;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Base class for individual npm command mojos.
*
* @author Aleksandar Seovic 2015.09.21
*/
@Mojo(name = "exec", threadSafe = true)
public class ExecMojo
extends AbstractMojo
{
// ---- parameters -------------------------------------------------------
/**
* The npm command to execute, such as 'install', 'test', etc. Required.
*/
@Parameter(property = "npm.command")
private String command;
/**
* The arguments to pass to npm command. Optional.
*/
@Parameter(property = "npm.args")
private String[] args;
/**
* The working directory. Optional. If not specified, basedir will be used.
*/
@Parameter(property = "npm.workingDir", defaultValue = "${basedir}")
private File workingDir;
/**
* The directory that contains npm executable. Optional. If not specified,
* we will assume that npm is in the system path.
*/
@Parameter(property = "npm.home")
private File npmHome;
// ---- constructors ----------------------------------------------------
/**
* Default constructor.
*/
public ExecMojo()
{
}
/**
* Construct ExecMojo instance.
*
* @param sCmd the npm command to execute, such as 'install', 'test', etc.
*/
protected ExecMojo(String sCmd)
{
command = sCmd;
}
// ---- Mojo interface --------------------------------------------------
@Override
public void execute()
throws MojoExecutionException, MojoFailureException
{
if (command == null)
{
throw new MojoExecutionException("The npm command to execute must be set");
}
CommandLine cmdLine = getNpmCommand();
addCommand(cmdLine);
addArguments(cmdLine);
execute(cmdLine);
}
// ---- helpers ---------------------------------------------------------
protected void execute(CommandLine cmdLine)
throws MojoFailureException, MojoExecutionException
{
try
{
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(workingDir);
executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
executor.execute(cmdLine);
}
catch (ExecuteException e)
{
throw new MojoFailureException("npm failure", e);
}
catch (IOException e)
{
throw new MojoExecutionException("Error executing NPM", e);
}
}
protected void addCommand(CommandLine cmdLine)
{
cmdLine.addArgument(command);
}
protected void addArguments(CommandLine cmdLine)
{
cmdLine.addArguments(args);
}
protected Package getPackage()
throws MojoExecutionException
{
File file = new File(workingDir, "package.json");
if (!file.exists())
{
throw new MojoExecutionException(file.getAbsolutePath() + " does not exist");
}
try
{
return Package.parse(file);
}
catch (IOException e)
{
throw new MojoExecutionException("Unable to parse " + file.getAbsolutePath(), e);
}
}
protected CommandLine getNpmCommand()
{
String sNpm = npmHome == null
? "npm"
: new File(npmHome, "npm").getAbsolutePath();
if (isWindows())
{
sNpm = sNpm + ".cmd";
CommandLine cmd = new CommandLine("cmd");
cmd.addArgument("/c");
cmd.addArgument(sNpm);
return cmd;
}
else
{
return new CommandLine(sNpm);
}
}
protected static boolean isWindows()
{
return System.getProperty("os.name").toLowerCase().contains("win");
}
}
| {
"content_hash": "37c1efcb653fb48d3347ab539232e6c0",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 96,
"avg_line_length": 27.566265060240966,
"alnum_prop": 0.5509178321678322,
"repo_name": "aseovic/npm-maven-plugin",
"id": "2e223a6c2190b4b7b16a60a5df7f1589cc63e88b",
"size": "4576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/seovic/maven/plugins/npm/ExecMojo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "11709"
}
],
"symlink_target": ""
} |
package com.github.anba.es6draft.runtime.types.builtins;
import static com.github.anba.es6draft.runtime.internal.Errors.newTypeError;
import static com.github.anba.es6draft.runtime.types.Null.NULL;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.util.Collection;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.LexicalEnvironment;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.CompatibilityOption;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.internal.RuntimeInfo;
import com.github.anba.es6draft.runtime.internal.SourceCompressor;
import com.github.anba.es6draft.runtime.internal.TailCallInvocation;
import com.github.anba.es6draft.runtime.types.Callable;
import com.github.anba.es6draft.runtime.types.Property;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Symbol;
/**
* <h1>9 Ordinary and Exotic Objects Behaviours</h1><br>
* <ul>
* <li>9.2 ECMAScript Function Objects
* </ul>
*/
public abstract class FunctionObject extends OrdinaryObject implements Callable {
private static final String SOURCE_NOT_AVAILABLE = "function F() { /* source not available */ }";
protected static final MethodHandle uninitialisedFunctionMH;
protected static final MethodHandle uninitialisedGeneratorMH;
static {
Lookup lookup = MethodHandles.lookup();
try {
MethodHandle mh = lookup.findStatic(FunctionObject.class,
"uninitialisedFunctionObject",
MethodType.methodType(Object.class, ExecutionContext.class));
mh = MethodHandles.dropArguments(mh, 1, Object.class, Object[].class);
uninitialisedFunctionMH = MethodHandles.dropArguments(mh, 0, OrdinaryFunction.class);
uninitialisedGeneratorMH = MethodHandles.dropArguments(mh, 0, OrdinaryGenerator.class);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unused")
private static final Object uninitialisedFunctionObject(ExecutionContext cx) {
throw newTypeError(cx, Messages.Key.UninitialisedObject);
}
/** [[Environment]] */
private LexicalEnvironment environment;
/** [[FunctionKind]] */
private FunctionKind functionKind;
/** [[FormalParameters]] / [[Code]] */
private RuntimeInfo.Function function;
/** [[Realm]] */
private Realm realm;
/** [[ThisMode]] */
private ThisMode thisMode;
/** [[Strict]] */
private boolean strict;
/** [[NeedsSuper]] */
private boolean needsSuper;
/** [[HomeObject]] */
private ScriptObject homeObject;
/** [[MethodName]] */
private Object /* String|ExoticSymbol */methodName;
private boolean isConstructor;
private String source;
private MethodHandle callMethod;
private MethodHandle tailCallMethod;
private Property caller = new Property(NULL, false, false, false);
private Property arguments = new Property(NULL, false, false, false);
protected FunctionObject(Realm realm) {
super(realm);
}
public enum FunctionKind {
Normal, ConstructorMethod, Method, Arrow
}
public enum ThisMode {
Lexical, Strict, Global
}
public static boolean isStrictFunction(Object v) {
return v instanceof FunctionObject && ((FunctionObject) v).isStrict();
}
private final boolean isInitialised() {
return function != null;
}
/**
* Returns {@code true} iff legacy .caller and .arguments properties are available for this
* function object
*/
private final boolean isLegacy() {
// TODO: 'caller' and 'arguments' properties are never updated for generator functions
// Uninitialised and non-strict functions have legacy support
return !(isInitialised() && strict)
&& realm.isEnabled(CompatibilityOption.FunctionPrototype);
}
/**
* Returns {@code true} iff the [[Construct]] method is attached to this function object
*/
protected boolean isConstructor() {
return isConstructor;
}
/**
* Sets the [[Construct]] flag for this function object
*/
protected final void setConstructor(boolean isConstructor) {
this.isConstructor = isConstructor;
}
/**
* Returns the {@link MethodHandle} for the function entry method
*/
public final MethodHandle getCallMethod() {
return callMethod;
}
/**
* Returns the {@link MethodHandle} for the function tail-call entry method
*/
public final MethodHandle getTailCallMethod() {
return tailCallMethod;
}
/**
* [Called from generated code]
*/
public final Object getLegacyCaller() {
return caller.getValue();
}
/**
* [Called from generated code]
*/
public final Object getLegacyArguments() {
return arguments.getValue();
}
/**
* [Called from generated code]
*/
public final void setLegacyCaller(FunctionObject caller) {
if (caller == null || caller.isStrict()) {
this.caller.applyValue(NULL);
} else {
this.caller.applyValue(caller);
}
}
/**
* [Called from generated code]
*/
public final void setLegacyArguments(ExoticArguments arguments) {
this.arguments.applyValue(arguments);
}
/**
* [Called from generated code]
*/
public final void restoreLegacyProperties(Object oldCaller, Object oldArguments) {
this.caller.applyValue(oldCaller);
this.arguments.applyValue(oldArguments);
}
@Override
public final String toSource() {
if (!isInitialised()) {
return SOURCE_NOT_AVAILABLE;
}
String source = this.source;
if (source == null) {
String src = function.source();
if (src != null) {
try {
source = SourceCompressor.decompress(src).call();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
source = SOURCE_NOT_AVAILABLE;
}
this.source = source;
}
return source;
}
@Override
public boolean defineOwnProperty(ExecutionContext cx, String propertyKey,
PropertyDescriptor desc) {
Property current = getOwnProperty(cx, propertyKey);
boolean extensible = isExtensible();
return ValidateAndApplyPropertyDescriptor(this, propertyKey, extensible, desc, current);
}
@Override
protected boolean hasOwnProperty(String propertyKey) {
boolean has = super.hasOwnProperty(propertyKey);
if (has) {
return true;
}
if (isLegacy() && ("caller".equals(propertyKey) || "arguments".equals(propertyKey))) {
return true;
}
return false;
}
@Override
protected Collection<Object> enumerateOwnKeys() {
Collection<Object> ownKeys = super.enumerateOwnKeys();
if (isLegacy()) {
if (!super.hasOwnProperty("caller")) {
ownKeys.add("caller");
}
if (!super.hasOwnProperty("arguments")) {
ownKeys.add("arguments");
}
}
return ownKeys;
}
/**
* 9.2.2 [[GetOwnProperty]] (P)
*/
@Override
public Property getOwnProperty(ExecutionContext cx, String propertyKey) {
Property desc = super.getOwnProperty(cx, propertyKey);
if (desc != null) {
return desc;
}
if (isLegacy()) {
if ("caller".equals(propertyKey)) {
assert !isStrictFunction(caller.getValue());
return caller;
}
if ("arguments".equals(propertyKey)) {
return arguments;
}
}
return null;
}
/**
* Returns a copy of this function object with the [[HomeObject]] property set to
* {@code newHomeObject} and the [[MethodName]] property set to {@code newMethodName}
*/
protected final FunctionObject clone(ScriptObject newHomeObject, Object newMethodName) {
FunctionObject clone = allocateNew();
if (isInitialised()) {
clone.initialise(getFunctionKind(), getCode(), getEnvironment());
}
clone.inheritProperties(this);
clone.setExtensible(isExtensible());
clone.setConstructor(isConstructor());
if (isNeedsSuper()) {
assert isInitialised() : "uninitialised function object with [[NeedsSuper]] = true";
if (newMethodName != null) {
clone.toMethod(newMethodName, newHomeObject);
} else {
clone.toMethod(getMethodName(), newHomeObject);
}
}
return clone;
}
/**
* Allocates a new, uninitialised copy of this function object
*/
protected abstract FunctionObject allocateNew();
/**
* 9.2.3 FunctionAllocate Abstract Operation
*/
protected final void allocate(Realm realm, ScriptObject functionPrototype, boolean strict,
FunctionKind kind, MethodHandle defaultCallMethod) {
assert this.realm == null && realm != null : "function object already allocated";
this.callMethod = defaultCallMethod;
this.tailCallMethod = defaultCallMethod;
/* step 9 */
this.setStrict(strict);
/* step 10 */
this.functionKind = kind;
/* step 11 */
this.setPrototype(functionPrototype);
/* step 12 */
// f.[[Extensible]] = true (implicit)
/* step 13 */
this.realm = realm;
}
/**
* 9.2.5 FunctionInitialise Abstract Operation
*/
protected final void initialise(FunctionKind kind, RuntimeInfo.Function function,
LexicalEnvironment scope) {
assert this.function == null && function != null : "function object already initialised";
assert this.functionKind == kind : String.format("%s != %s", functionKind, kind);
/* step 6 */
this.environment = scope;
/* steps 7-8 */
this.function = function;
this.callMethod = tailCallAdapter(function);
this.tailCallMethod = function.callMethod();
/* steps 9-11 */
if (kind == FunctionKind.Arrow) {
this.thisMode = ThisMode.Lexical;
} else if (strict) {
this.thisMode = ThisMode.Strict;
} else {
this.thisMode = ThisMode.Global;
}
}
/**
* 9.2.10 MakeMethod ( F, methodName, homeObject ) Abstract Operation
*/
protected final void toMethod(Object methodName, ScriptObject homeObject) {
assert isInitialised() : "uninitialised function object";
assert !needsSuper : "function object already method";
this.needsSuper = true;
this.methodName = methodName;
this.homeObject = homeObject;
}
/**
*
*/
public final void updateMethod(Object methodName, ScriptObject homeObject) {
assert isInitialised() : "uninitialised function object";
assert needsSuper : "function object not method";
assert methodName != null && homeObject != null;
assert methodName instanceof String || methodName instanceof Symbol;
this.methodName = methodName;
this.homeObject = homeObject;
}
private static MethodHandle tailCallAdapter(RuntimeInfo.Function function) {
MethodHandle mh = function.callMethod();
if (function.hasTailCall()) {
assert !function.isGenerator() && function.isStrict();
MethodHandle result = TailCallInvocation.getTailCallHandler();
result = MethodHandles.dropArguments(result, 1, OrdinaryFunction.class);
result = MethodHandles.dropArguments(result, 3, Object.class, Object[].class);
result = MethodHandles.foldArguments(result, mh);
return result;
}
return mh;
}
/**
* [[Environment]]
*/
public final LexicalEnvironment getEnvironment() {
return environment;
}
/**
* [[FunctionKind]]
*/
public final FunctionKind getFunctionKind() {
return functionKind;
}
/**
* [[Code]]
*/
public final RuntimeInfo.Function getCode() {
return function;
}
/**
* [[Realm]]
*/
public final Realm getRealm() {
return realm;
}
/**
* [[ThisMode]]
*/
public final ThisMode getThisMode() {
return thisMode;
}
/**
* [[Strict]]
*/
public final boolean isStrict() {
return strict;
}
/**
* [[Strict]]
*/
public final void setStrict(boolean strict) {
this.strict = strict;
}
/**
* [[NeedsSuper]]
*/
public final boolean isNeedsSuper() {
return needsSuper;
}
/**
* [[HomeObject]]
*/
public final ScriptObject getHomeObject() {
return homeObject;
}
/**
* [[MethodName]]
*/
public final Object getMethodName() {
return methodName;
}
}
| {
"content_hash": "e527ab90c196fa7a58853ca593e42340",
"timestamp": "",
"source": "github",
"line_count": 437,
"max_line_length": 101,
"avg_line_length": 31.08695652173913,
"alnum_prop": 0.6193595877806404,
"repo_name": "rwaldron/es6draft",
"id": "40ee8cc1f384a71419beeb57cb874e4cfe60c627",
"size": "13759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/anba/es6draft/runtime/types/builtins/FunctionObject.java",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import java.util.concurrent.ThreadLocalRandom;
public class GenerateLargeIntArray {
static int min = 1;
static int max = 1000000;
static int mult = 1;
static int size = 25;
public static void main(String[] args) {
//~ try {
//~ min = Integer.parseInt(args[0]);
//~ max = Integer.parseInt(args[1]);
//~ mult = Integer.parseInt(args[2]);
//~ size = Integer.parseInt(args[3]);
//~ } catch (Exception e) {
//~ System.out.println("usage is: java GenerateLargeIntArray <min> <max> <mult> <size>");
//~ return;
//~ }
StringBuilder result = new StringBuilder();
for(int i = 0; i < size; i++) {
int rand = randInt(min, max);
result.append(rand + ",");
}
result.deleteCharAt(result.length()-1);
System.out.println(result.toString());
}
private static int randInt(int min, int max) {
int rand = ThreadLocalRandom.current().nextInt(min,max) * mult;
return rand;
}
}
| {
"content_hash": "e3427909440b4efe9c9cb5124795cb3c",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 92,
"avg_line_length": 25,
"alnum_prop": 0.6302702702702703,
"repo_name": "tiagopnoliveira/programming",
"id": "0a502a99cc44ec6e38d91d06e8c0ae0ef15c51c7",
"size": "925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GenerateLargeIntArray.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1121"
},
{
"name": "Java",
"bytes": "280435"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<!-- Local transactions for unit tests -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.searchisko.persistence.jpa.model.Contributor</class>
<class>org.searchisko.persistence.jpa.model.Project</class>
<class>org.searchisko.persistence.jpa.model.Query</class>
<class>org.searchisko.persistence.jpa.model.Rating</class>
<class>org.searchisko.persistence.jpa.model.Tag</class>
<class>org.searchisko.api.tasker.TaskStatusInfo</class>
<properties>
<!-- Bean validation is used for validation and DDL as well -->
<property name="javax.persistence.validation.mode" value="callback, ddl"/>
<!-- Properties for Hibernate -->
<property name="hibernate.connection.url" value="${hibernate.connection.url}"/>
<property name="hibernate.connection.driver_class" value="${hibernate.connection.driver_class}"/>
<property name="hibernate.dialect" value="${hibernate.dialect}"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.connection.username" value="${hibernate.connection.username}"/>
<property name="hibernate.connection.password" value="${hibernate.connection.password}"/>
<!--
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
-->
</properties>
</persistence-unit>
</persistence> | {
"content_hash": "92399c3c06dde500145b3a4d39fec1fb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 100,
"avg_line_length": 52.61764705882353,
"alnum_prop": 0.7272219116825042,
"repo_name": "searchisko/searchisko",
"id": "2a65b05ae0c87d7a39c702a31432d1a1696a2f7d",
"size": "1789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/src/test/resources/META-INF/persistence.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "API Blueprint",
"bytes": "70155"
},
{
"name": "CSS",
"bytes": "531"
},
{
"name": "HTML",
"bytes": "963"
},
{
"name": "Java",
"bytes": "1860622"
},
{
"name": "Shell",
"bytes": "63"
}
],
"symlink_target": ""
} |
using System;
using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using DocaLabs.Http.Client.Configuration;
using DocaLabs.Test.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DocaLabs.Http.Client.Tests.Configuration
{
[TestClass]
public class when_finding_certificate_for_null_reference
{
static Exception _exception;
[ClassInitialize]
public static void EsatblishContext(TestContext context)
{
BecauseOf();
}
static void BecauseOf()
{
_exception = Catch.Exception(() => ((IClientCertificateReference) null).Find());
}
[TestMethod]
public void it_should_throw_argument_null_exception()
{
_exception.ShouldBeOfType<ArgumentNullException>();
}
[TestMethod]
public void it_should_report_reference_argument()
{
((ArgumentNullException) _exception).ParamName.ShouldEqual("reference");
}
}
[TestClass]
public class when_converting_certificate_store_location_enum_values
{
[TestMethod]
public void it_should_convert_known_values()
{
CertificateStoreLocation.CurrentUser.ToStoreLocation().ShouldEqual(StoreLocation.CurrentUser);
CertificateStoreLocation.LocalMachine.ToStoreLocation().ShouldEqual(StoreLocation.LocalMachine);
}
[TestMethod]
public void it_should_throw_ivlaid_enum_exception_for_unknown_values()
{
Catch.Exception(() => ((CertificateStoreLocation)99999).ToStoreLocation()).ShouldBeOfType<InvalidEnumArgumentException>();
}
}
[TestClass]
public class when_converting_certificate_store_name_enum_values
{
[TestMethod]
public void it_should_convert_known_values()
{
CertificateStoreName.AddressBook.ToStoreName().ShouldEqual(StoreName.AddressBook);
CertificateStoreName.AuthRoot.ToStoreName().ShouldEqual(StoreName.AuthRoot);
CertificateStoreName.CertificateAuthority.ToStoreName().ShouldEqual(StoreName.CertificateAuthority);
CertificateStoreName.Disallowed.ToStoreName().ShouldEqual(StoreName.Disallowed);
CertificateStoreName.My.ToStoreName().ShouldEqual(StoreName.My);
CertificateStoreName.Root.ToStoreName().ShouldEqual(StoreName.Root);
CertificateStoreName.TrustedPeople.ToStoreName().ShouldEqual(StoreName.TrustedPeople);
CertificateStoreName.TrustedPublisher.ToStoreName().ShouldEqual(StoreName.TrustedPublisher);
}
[TestMethod]
public void it_should_throw_ivlaid_enum_exception_for_unknown_values()
{
Catch.Exception(() => ((CertificateStoreName)99999).ToStoreName()).ShouldBeOfType<InvalidEnumArgumentException>();
}
}
[TestClass]
public class when_converting_certificate_x509_find_type_enum_values
{
[TestMethod]
public void it_should_convert_known_values()
{
CertificateX509FindType.FindByApplicationPolicy.ToX509FindType().ShouldEqual(X509FindType.FindByApplicationPolicy);
CertificateX509FindType.FindByCertificatePolicy.ToX509FindType().ShouldEqual(X509FindType.FindByCertificatePolicy);
CertificateX509FindType.FindByExtension.ToX509FindType().ShouldEqual(X509FindType.FindByExtension);
CertificateX509FindType.FindByIssuerDistinguishedName.ToX509FindType().ShouldEqual(X509FindType.FindByIssuerDistinguishedName);
CertificateX509FindType.FindByIssuerName.ToX509FindType().ShouldEqual(X509FindType.FindByIssuerName);
CertificateX509FindType.FindByKeyUsage.ToX509FindType().ShouldEqual(X509FindType.FindByKeyUsage);
CertificateX509FindType.FindBySerialNumber.ToX509FindType().ShouldEqual(X509FindType.FindBySerialNumber);
CertificateX509FindType.FindBySubjectDistinguishedName.ToX509FindType().ShouldEqual(X509FindType.FindBySubjectDistinguishedName);
CertificateX509FindType.FindBySubjectKeyIdentifier.ToX509FindType().ShouldEqual(X509FindType.FindBySubjectKeyIdentifier);
CertificateX509FindType.FindBySubjectName.ToX509FindType().ShouldEqual(X509FindType.FindBySubjectName);
CertificateX509FindType.FindByTemplateName.ToX509FindType().ShouldEqual(X509FindType.FindByTemplateName);
CertificateX509FindType.FindByThumbprint.ToX509FindType().ShouldEqual(X509FindType.FindByThumbprint);
CertificateX509FindType.FindByTimeExpired.ToX509FindType().ShouldEqual(X509FindType.FindByTimeExpired);
CertificateX509FindType.FindByTimeNotYetValid.ToX509FindType().ShouldEqual(X509FindType.FindByTimeNotYetValid);
CertificateX509FindType.FindByTimeValid.ToX509FindType().ShouldEqual(X509FindType.FindByTimeValid);
}
[TestMethod]
public void it_should_throw_ivlaid_enum_exception_for_unknown_values()
{
Catch.Exception(() => ((CertificateX509FindType)99999).ToX509FindType()).ShouldBeOfType<InvalidEnumArgumentException>();
}
}
}
| {
"content_hash": "f128054d00ddb18616e2f2deadc9fb71",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 141,
"avg_line_length": 47.861111111111114,
"alnum_prop": 0.7250918939833624,
"repo_name": "alexey-kadyrov/DocaLabs.Http.Client",
"id": "f62a52372ab61d4934e0704768f5ea70e2749a70",
"size": "5171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/DocaLabs.Http.Client.DotNet.Tests/Configuration/ConfigurationExtenstionsTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "2232528"
}
],
"symlink_target": ""
} |
package com.sksamuel.elastic4s
import com.sksamuel.elastic4s.ElasticDsl._
import org.scalatest.FlatSpec
import org.scalatest.mock.MockitoSugar
import scala.concurrent.duration._
/** @author Stephen Samuel */
class BulkTest extends FlatSpec with MockitoSugar with ElasticSugar {
implicit val duration: Duration = 10.seconds
client.execute {
index into "transport/air" fields "company" -> "delta" id 99
}.await
refresh("transport")
blockUntilCount(1, "transport")
"a bulk request" should "execute all index queries" in {
client.execute(
bulk(
index into "transport/air" id 1 fields "company" -> "ba",
index into "transport/air" id 2 fields "company" -> "aeroflot",
index into "transport/air" id 3 fields "company" -> "american air",
index into "transport/air" id 4 fields "company" -> "egypt air"
)
).await
refresh("transport")
blockUntilCount(5, "transport", "air")
}
"a bulk request" should "execute all delete queries" in {
client.execute(
bulk(
delete(4) from "transport/air",
delete id 2 from "transport/air"
)
).await
refresh("transport")
blockUntilCount(3, "transport", "air")
}
"a sync bulk request" should "execute all index queries" in {
client.execute(
bulk(
index into "transport/air" id 5 fields "company" -> "aeromexico",
index into "transport/air" id 6 fields "company" -> "alaska air",
index into "transport/air" id 7 fields "company" -> "hawaiian air",
index into "transport/air" id 8 fields "company" -> "aerotaxi"
)
).await
}
"a sync bulk request" should "execute all delete queries" in {
client.execute(
bulk(
delete(8) from "transport/air",
delete id 5 from "transport/air"
)
).await
}
}
| {
"content_hash": "605bdcb78b175e8520f8eb2b85d0a860",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 75,
"avg_line_length": 27.492537313432837,
"alnum_prop": 0.6416938110749185,
"repo_name": "alexander-svendsen/elastic4s",
"id": "6574c30046be3b1037c1ca6149299f808645a58e",
"size": "1842",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "elastic4s-core/src/test/scala/com/sksamuel/elastic4s/BulkTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "599060"
}
],
"symlink_target": ""
} |
<!--
Write your names here:
1. Andrew Crowley
2. Julia Giraldi
We spent [1.5] hours on this challenge.
-->
<!-- This challenge uses HTML5 syntax that may not be available in all browsers (It works in Chrome and Safari, from my testing. (<details> and<summary>). -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="gps2-1.css"> <!-- Insert a link to the stylesheet here -->
<title>Git Cheat Sheet</title>
</head>
<body>
<header>
<h1>GitHub: Git Cheat Sheet</h1>
<p>Git is the open source distributed version control system that
facilitates GitHub activities on your laptop or desktop.
This cheat sheet summarizes commonly used Git command line
instructions for quick reference.</p>
</header>
<section class="column-1">
<article>
<h2>INSTALL GIT</h2>
<p>GitHub provides desktop clients that include a graphical user
interface for the most common repository actions and an automatically
updating command line edition of Git for advanced scenarios.</p>
<ul>
<li><a href="https://windows.github.com">GitHub for Windows</a></li>
<li><a href="https://mac.github.com">GitHub for Mac</a></li>
<li><a href="http://git-scm.com">Git for All Platforms</a></li>
</ul>
Git distributions for Linux and POSIX systems are available on the
official Git SCM web site.
</article>
<article>
<h2>CONFIGURE TOOLING</h2>
<p>Configure user information for all local repositories</p>
<p> To see a summary of each command, click it.</p>
<details>
<summary><code>$ git config --global user.name "[name]"</code></summary>
<p>Sets the name you want attached to your commit transactions</p>
</details>
<details>
<summary><code>$ git config --global user.email "[email address]"</code></summary>
<p>Sets the email you want atached to your commit transactions</p>
</details>
<details>
<summary><code>$ git config --global color.ui auto</code></summary>
<p>Enables helpful colorization of command line output</p>
</details>
</article>
<article>
<h2>CREATE REPOSITORIES</h2>
<p>Start a new repository or obtain one from an existing URL</p>
<details>
<summary><code>$ git init [project-name]</code></summary>
<p>Creates a new local repository with the specified name</p>
</details>
<details>
<summary><code>$ git clone [url]</code></summary>
<p>Downloads a project and its entire version history</p>
</details>
</article>
<article>
<h2>MAKE CHANGES</h2>
<p>Review edits and craft a commit transaction</p>
<details>
<summary><code>$ git status</code></summary>
<p>Lists all new or modified files to be committed</p>
</details>
<details>
<summary><code>$ git add [file]</code></summary>
<p>Snapshots the file in preparation for versioning</p>
</details>
<details>
<summary><code>$ git reset [file]</code></summary>
<p>Unstages the file, but preserve its contents</p>
</details>
<details>
<summary><code>$ git diff</code></summary>
<p>Shows file differences not yet staged</p>
</details>
<details>
<summary><code>$ git diff --staged</code></summary>
<p>Shows file differences between staging and the last file version</p>
</details>
<details>
<summary><code>$ git commit -m "[descriptive message]"</code></summary>
<p>Records file snapshots permanently in version history</p>
</details>
</article>
<article>
<h2>GROUP CHANGES</h2>
<p>Name a series of commits and combine completed efforts</p>
<details>
<summary><code>$ git branch</code></summary>
<p>Lists all local branches in the current repository</p>
</details>
<details>
<summary><code>$ git branch [branch-name]</code></summary>
<p>Creates a new branch</p>
</details>
<details>
<summary><code>$ git checkout [branch-name]</code></summary>
<p>Switches to the specified branch and updates the working directory</p>
</details>
<details>
<summary><code>$ git merge [branch]</code></summary>
<p>Combines the specified branch’s history into the current branch</p>
</details>
<details>
<summary><code>$ git branch -d [branch-name]</code></summary>
<p>Deletes the specified branch</p>
</details>
</article>
</section>
<section class="column-2">
<article>
<h2>REFACTOR FILENAMES</h2>
<p>Relocate and remove versioned files</p>
<details>
<summary><code>$ git rm [file]</code></summary>
<p>Deletes the file from the working directory and stages the deletion</p>
</details>
<details>
<summary><code>$ git rm --cached [file]</code></summary>
<p>Removes the file from version control but preserves the file locally</p>
</details>
<details>
<summary><code>$ git mv [file-original] [file-renamed]</code></summary>
<p>Changes the file name and prepares it for commit</p>
</details>
</article>
<article>
<h2>SUPPRESS TRACKING</h2>
<p>Exclude temporary files and paths</p>
<details>
<summary><code>*.log
build/
temp-*
</code></summary>
<p>A text file named .gitignore suppresses accidental versioning of files and paths matching the specified paterns</p>
</details>
<details>
<summary><code>$ git ls-files --other --ignored --exclude-standard</code></summary>
<p>Lists all ignored files in this project</p>
</details>
</article>
<article>
<h2>SAVE FRAGMENTS</h2>
<p>Shelve and restore incomplete changes</p>
<details>
<summary><code>$ git stash</code></summary>
<p>Temporarily stores all modified tracked files</p>
</details>
<details>
<summary><code>$ git stash list</code>Lists all stashed changesets</summary>
<p></p>
</details>
<details>
<summary><code>$ git stash pop</code></summary>
<p>Restores the most recently stashed files</p>
</details>
<details>
<summary><code>$ git stash drop</code></summary>
<p>Discards the most recently stashed changeset</p>
</details>
</article>
<article>
<h2>REVIEW HISTORY</h2>
<p>Browse and inspect the evolution of project files</p>
<details>
<summary><code>$ git log</code></summary>
<p>Lists version history for the current branch</p>
</details>
<details>
<summary><code>$ git log --follow [file]</code></summary>
<p>Lists version history for a file, including renames</p>
</details>
<details>
<summary><code>$ git diff [first-branch]...[second-branch]</code></summary>
<p>Shows content differences between two branches</p>
</details>
<details>
<summary><code>$ git show [commit]</code></summary>
<p>Outputs metadata and content changes of the specified commit</p>
</details>
</article>
<article>
<h2>REDO COMMITS</h2>
<p>Erase mistakes and craft replacement history</p>
<details>
<summary><code>$ git reset [commit]</code></summary>
<p>Undoes all commits after [commit], preserving changes locally</p>
</details>
<details>
<summary><code>$ git reset --hard [commit]</code></summary>
<p>Discards all history and changes back to the specified commit</p>
</details>
</article>
<article>
<h2>SYNCHRONIZE CHANGES</h2>
<p>Register a repository bookmark and exchange version history</p>
<details>
<summary><code>$ git fetch [bookmark]</code></summary>
<p>Downloads all history from the repository bookmark</p>
</details>
<details>
<summary><code>$ git merge [bookmark]/[branch]</code></summary>
<p>Combines bookmark’s branch into current local branch</p>
</details>
<details>
<summary><code>$ git push [alias] [branch]</code></summary>
<p>Uploads all local branch commits to GitHub</p>
</details>
<details>
<summary><code>$ git pull</code></summary>
<p>Downloads bookmark history and incorporates changes</p>
</details>
</article>
</section>
<footer>
This information is copied directly from <a href="https://training.github.com/kit/downloads/github-git-cheat-sheet.pdf">GitHub's Training Cheatsheet</a>.
</footer>
<!-- Did you feel more confident with CSS positioning? How did you do with the learning competencies in general?
I felt more confident, yes. Pairing is a great way to practice thinking out loud - or else it would be a pretty silent video chat! It helped alot to be able to talk out ideas and work together to find a solution. It turns out, we knew alot more CSS than we originally thought. I thought we did well all the way around.
CSS is a fantastic program and I would like to explore a CSS "bootcamp" in the future. At this point it feels a bit overwhelming. Just looking through the Google Fonts site cost me 45 minutes! That said, in a few short weeks I feel alot more competent and I'm sure if I keep it going and learn a few more tricks I can get my site looking how I want... Cheers to my pair parter Julia - turns out we went to the same high school, in the Bronx!
-->
</body>
</html> | {
"content_hash": "a5873b4988e301192ccafc6116fe5152",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 450,
"avg_line_length": 35.78169014084507,
"alnum_prop": 0.5959456799842551,
"repo_name": "AndyVegas/phase-0",
"id": "a717132066e9513a18ae0bbca86ed26f2c49d517",
"size": "10166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-4/gps/gps2-1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4069"
},
{
"name": "HTML",
"bytes": "19626"
},
{
"name": "JavaScript",
"bytes": "30657"
},
{
"name": "Ruby",
"bytes": "116402"
}
],
"symlink_target": ""
} |
from py_bing_search import PyBingWebSearch
import os
import codecs
def getResultsList(word,numResults):
bing_web = PyBingWebSearch('cdos0agEe4I2roLpBVQC6WHZErUb3ih4sU75CvxOlDI', word, web_only=True)
results= bing_web.search(limit=numResults, format='json')
return results
def getResultsDescriptionList(word,numResults):
results=getResultsList(word,numResults)
descriptions=[]
for result in results:
descriptions.append(result.description)
return descriptions
def getResultsDescriptionListCorpus(path,word, yearInit, yearEnd):
descriptions=[]
for file in os.listdir(path):
if not file.endswith("_errors"):
print(file)
name=path+"/"+file
year=int(str(file))
print("Year: "+str(year))
if(year>=int(yearInit) and year<=int(yearEnd)):
for file in os.listdir(name):
if file.endswith(".txt"):
name2=name+"/"+file
print name2
f = codecs.open(name2, "r", "utf-8")
desc=f.read()
#print desc
f.close()
descriptions.append(desc)
return descriptions
| {
"content_hash": "b2c6cc50bf67dcdc7e837434ce289bfa",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 98,
"avg_line_length": 36,
"alnum_prop": 0.580952380952381,
"repo_name": "CesarCardam/CesarCardam.github.io",
"id": "e0ed9549561d797ad4fbdb45787079ed9768bc7e",
"size": "1308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/WordRelation/Python/Webutils/websearcher.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "523440"
},
{
"name": "HTML",
"bytes": "17122"
},
{
"name": "JavaScript",
"bytes": "582952"
},
{
"name": "Python",
"bytes": "14368"
}
],
"symlink_target": ""
} |
/*
* Definitions etc. for regexp(3) routines.
*
* Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
* not the System V one.
*/
/* Refs count, struct rstr * and prototypes added by GBH */
#define NSUBEXP 10
typedef struct regexp {
int refs;
struct rstr *rs;
char *startp[NSUBEXP];
char *endp[NSUBEXP];
char regstart; /* Internal use only. */
char reganch; /* Internal use only. */
char *regmust; /* Internal use only. */
int regmlen; /* Internal use only. */
char program[1]; /* Unwarranted chumminess with compiler. */
} regexp;
extern regexp *regcomp();
extern int regexec();
extern void regsub();
extern void regerror();
#ifdef PROTOTYPES
regexp *regcomp(char *);
int regexec(regexp *, char *);
#endif
| {
"content_hash": "418db9082d3479d82d00277ab9ce3a7e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 72,
"avg_line_length": 26.482758620689655,
"alnum_prop": 0.6627604166666666,
"repo_name": "tibbetts/vaportalk",
"id": "df01c5641e02c5f046ae2828097d9d0345379589",
"size": "768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "regexp.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Bison",
"bytes": "21420"
},
{
"name": "C",
"bytes": "175833"
},
{
"name": "Makefile",
"bytes": "568"
},
{
"name": "Shell",
"bytes": "93"
}
],
"symlink_target": ""
} |
package partition;
import static gblib.Util.downCast;
import java.lang.reflect.Array;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import partition.Util.Pair;
/**
* A symmetric weighed adjacency matrix for undirected graph.
*
* @param <T> weight value type.
* @author gburdell
*/
public class SymmetricWeightedAdjMatrix<T extends Comparable> {
public SymmetricWeightedAdjMatrix(int n, final T dflt) {
m_n = n;
init(dflt);
}
private void init(final T dflt) {
m_matrix = new Object[m_n - 1]; //last row never used
for (int row = 0; row < m_matrix.length; row++) {
final int ncols = getNcols(row);
m_matrix[row] = Array.newInstance(dflt.getClass(), ncols);
for (int col = 0; col < ncols; col++) {
Array.set(m_matrix[row], col, dflt);
}
}
}
public T set(int row, int col, final T val) {
Pair<Integer, Integer> rowCol = getCoords(row, col);
Array.set(m_matrix[rowCol.first], rowCol.second, val);
return val;
}
public T get(int row, int col) {
Pair<Integer, Integer> rowCol = getCoords(row, col);
return downCast(Array.get(m_matrix[rowCol.first], rowCol.second));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < m_n; row++) {
sb.append('[');
for (int col = 0; col < m_n; col++) {
if (0 < col) {
sb.append(',');
}
if (row != col) {
sb.append(get(row, col));
} else {
sb.append('_');
}
}
sb.append("]\n");
}
return sb.toString();
}
/**
* Composite of weight and vertex pair. Used for sorting (by weight).
* @param <T> weight type.
*/
public static class Ele<T extends Comparable> {
public Ele(int vx1, int vx2, T weight) {
m_vx1 = vx1;
m_vx2 = vx2;
m_weight = weight;
}
public final int m_vx1, m_vx2;
public final T m_weight;
}
public List<Ele<T>> toList() {
final List<Ele<T>> list = new LinkedList<>();
for (int i = 0; i < m_n - 1; i++) {
for (int j = i + 1; j < m_n; j++) {
list.add(new Ele<>(i, j, get(i, j)));
}
}
return list;
}
/**
* Sort by by weight.
*
* @return Sorted list (in descending order by weight).
*/
public List<Ele<T>> sort() {
List<Ele<T>> list = toList();
Collections.sort(list, (Ele<T> o1, Ele<T> o2)
-> o2.m_weight.compareTo(o1.m_weight)
);
return list;
}
private Pair<Integer, Integer> getCoords(int row, int col) {
gblib.Util.assertTrue(row != col,
"diagonal reference not allowed: [" + row + "," + col + "]");
Pair<Integer, Integer> rowcol;
if (row < col) {
rowcol = new Pair<>(row, col - (row + 1));
} else {
rowcol = new Pair<>(col, row - (col + 1));
}
//adjust col offset
return rowcol;
}
private int getNcols(int row) {
return m_n - row - 1;
}
private final int m_n;
/**
* Maintain symmetric matrix with valid indices [row,col] where row < col.
* For example: we have [0,1], [0,2], [0,3], and [1,2], [1,3]. We do not
* have [1,0] since that is same as [0,1] (and we'll return same value for
* [0,1] and [1,0]). Since no self-loops, diagonal values [i,i] are invalid.
*/
private Object m_matrix[];
}
| {
"content_hash": "02d95b11449bd3c18a40a41f64e5cf60",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 80,
"avg_line_length": 28.884615384615383,
"alnum_prop": 0.5102529960053263,
"repo_name": "gburdell/partition",
"id": "2b0c24b4529f3c514d92822952947345965560fa",
"size": "4886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/partition/SymmetricWeightedAdjMatrix.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "35867"
},
{
"name": "Makefile",
"bytes": "332"
}
],
"symlink_target": ""
} |
use rocks::prelude::*;
fn main() {
let opt = Options::default().map_db_options(|db_opt| db_opt.create_if_missing(true));
let db = DB::open(opt, "./data").unwrap();
assert!(db.put(WriteOptions::default_instance(), b"hello", b"world").is_ok());
match db.get(ReadOptions::default_instance(), b"hello") {
Ok(ref value) => println!("hello: {:?}", value),
Err(e) => eprintln!("error: {}", e),
}
let _ = db.delete(WriteOptions::default_instance(), b"hello").unwrap();
}
| {
"content_hash": "c0e4c38faa060500644927e11c0f9351",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 89,
"avg_line_length": 38.84615384615385,
"alnum_prop": 0.5881188118811881,
"repo_name": "bh1xuw/rust-rocks",
"id": "46e02d319c437c13aadc38fc6d3645a2527dd065",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/hello.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "246557"
},
{
"name": "Makefile",
"bytes": "499"
},
{
"name": "Rust",
"bytes": "723564"
}
],
"symlink_target": ""
} |
var wrench = require('wrench'),
colors = require('colors'),
packageInfo = require('./package.json'),
fs = require('fs');
var emojiCommands = module.exports = function(hexo) {
emojiCommands.hexo = hexo;
emojiCommands.emojiConfig = hexo.config.emojis || false;
emojiCommands.emojiImageDir = emojiCommands.emojiConfig.image_dir || false;
emojiCommands.emojisCDN = emojiCommands.emojiConfig.cdn || false;
emojiCommands.sourceDir = __dirname + '/source/images/emojis';
emojiCommands.deployDir = hexo.base_dir + 'source/' + emojiCommands.emojiImageDir;
if (!emojiCommands.emojiConfig ) {
throw new Error('Emoji configuration was not found.');
}
if( !emojiCommands.emojiImageDir && !emojiCommands.emojisCDN){
throw new Error('Emoji configuration was not found.');
}
return emojiCommands;
};
/**
* Copies all emoji assets into `emojis.image_dir`.
*/
emojiCommands.install = function(callback) {
if (!emojiCommands.emojiImageDir) {
console.error('[ERROR] Hey! You forgot to add %s to your %s file!'.red, 'image_config'.inverse, '_config.yml'.inverse);
return;
}
console.log('>> Copying emojis to '+emojiCommands.deployDir.inverse);
if (!fs.existsSync(emojiCommands.deployDir)) {
wrench.mkdirSyncRecursive(emojiCommands.deployDir, 0777);
}
wrench.copyDirRecursive(emojiCommands.sourceDir, emojiCommands.deployDir, {forceDelete: true}, function(err) {
if (err) {
console.error(('[ERROR] '+err).red);
callback(err); // error
} else {
console.log('>> Done!\n');
callback(); // done with no errors
}
});
};
/**
* Removes all emoji assets from `emojis.image_dir`.
*/
emojiCommands.remove = function(callback) {
if (!emojiCommands.emojiImageDir) {
console.error('[ERROR] Hey! You forgot to add %s to your %s file!'.red, 'image_config'.inverse, '_config.yml'.inverse);
return;
}
console.log('>> Removing emojis from '+emojiCommands.deployDir.inverse);
wrench.rmdirRecursive(emojiCommands.deployDir, false, function (err) {
if (err) {
console.warn('!! There was an error removing '+emojiCommands.deployDir.inverse+' directory. Please, remove it manually.');
callback(err);
} else {
console.log('>> Done!\n');
callback();
}
});
};
/**
* Display useful information
*/
emojiCommands.showInfo = function(callback) {
console.log('\\|°▿▿▿▿°|/ hey there!\n');
console.log('Version'.bold+': '+packageInfo.version);
console.log('Author'.bold+': '+packageInfo.author.name+' <'+packageInfo.author.email+'>');
console.log('Website'.bold+': '+packageInfo.author.url);
console.log('Help'.bold+': hexo help emojis');
console.log('Github'.bold+': '+packageInfo.repository.url);
console.log('Bugs'.bold+': '+packageInfo.bugs.url);
console.log('\nThank you so much for using it!\n');
callback();
}; | {
"content_hash": "f8e0c682fb598ca6a27ef2105ad1ba9a",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 134,
"avg_line_length": 34.146067415730336,
"alnum_prop": 0.6344192168476472,
"repo_name": "sergiolepore/hexo-tag-emojis",
"id": "c9794929697562985a63e92321e5f24bfe2abe62",
"size": "3049",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "emojiCommands.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7384"
}
],
"symlink_target": ""
} |
namespace {
MONITORINFO GetMonitorInfoForMonitor(HMONITOR monitor) {
MONITORINFO monitor_info = { 0 };
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(monitor, &monitor_info);
return monitor_info;
}
gfx::Display GetDisplay(MONITORINFO& monitor_info) {
// TODO(oshima): Implement ID and Observer.
gfx::Display display(0, gfx::Rect(monitor_info.rcMonitor));
display.set_work_area(gfx::Rect(monitor_info.rcWork));
return display;
}
} // namespace
namespace gfx {
ScreenWin::ScreenWin() {
}
ScreenWin::~ScreenWin() {
}
bool ScreenWin::IsDIPEnabled() {
return false;
}
gfx::Point ScreenWin::GetCursorScreenPoint() {
POINT pt;
GetCursorPos(&pt);
return gfx::Point(pt);
}
gfx::NativeWindow ScreenWin::GetWindowAtCursorScreenPoint() {
POINT location;
HWND window_hwnd = GetCursorPos(&location) ? WindowFromPoint(location) : NULL;
return GetNativeWindowFromHWND(window_hwnd);
}
int ScreenWin::GetNumDisplays() {
return GetSystemMetrics(SM_CMONITORS);
}
gfx::Display ScreenWin::GetDisplayNearestWindow(gfx::NativeView window) const {
HWND window_hwnd = GetHWNDFromNativeView(window);
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(MonitorFromWindow(window_hwnd, MONITOR_DEFAULTTONEAREST),
&monitor_info);
return GetDisplay(monitor_info);
}
gfx::Display ScreenWin::GetDisplayNearestPoint(const gfx::Point& point) const {
POINT initial_loc = { point.x(), point.y() };
HMONITOR monitor = MonitorFromPoint(initial_loc, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = {0};
mi.cbSize = sizeof(mi);
if (monitor && GetMonitorInfo(monitor, &mi))
return GetDisplay(mi);
return gfx::Display();
}
gfx::Display ScreenWin::GetDisplayMatching(const gfx::Rect& match_rect) const {
RECT other_bounds_rect = match_rect.ToRECT();
MONITORINFO monitor_info = GetMonitorInfoForMonitor(MonitorFromRect(
&other_bounds_rect, MONITOR_DEFAULTTONEAREST));
return GetDisplay(monitor_info);
}
gfx::Display ScreenWin::GetPrimaryDisplay() const {
MONITORINFO mi = GetMonitorInfoForMonitor(
MonitorFromWindow(NULL, MONITOR_DEFAULTTOPRIMARY));
gfx::Display display = GetDisplay(mi);
DCHECK_EQ(GetSystemMetrics(SM_CXSCREEN), display.size().width());
DCHECK_EQ(GetSystemMetrics(SM_CYSCREEN), display.size().height());
return display;
}
HWND ScreenWin::GetHWNDFromNativeView(NativeView window) const {
#if defined(USE_AURA)
NOTREACHED();
return NULL;
#else
return window;
#endif // USE_AURA
}
NativeWindow ScreenWin::GetNativeWindowFromHWND(HWND hwnd) const {
#if defined(USE_AURA)
NOTREACHED();
return NULL;
#else
return hwnd;
#endif // USE_AURA
}
#if !defined(USE_AURA)
Screen* CreateNativeScreen() {
return new ScreenWin;
}
#endif // !USE_AURA
} // namespace gfx
| {
"content_hash": "f51fcf3c4eb8e1976f7ccb95da847ef9",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 80,
"avg_line_length": 26.452830188679247,
"alnum_prop": 0.7325249643366619,
"repo_name": "junmin-zhu/chromium-rivertrail",
"id": "072f47a6458165233752b1f5e6dec5b7f9de32f8",
"size": "3083",
"binary": false,
"copies": "1",
"ref": "refs/heads/v8-binding",
"path": "ui/gfx/screen_win.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75806807"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "145161929"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "1546515"
},
{
"name": "JavaScript",
"bytes": "18675242"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "6981387"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "926245"
},
{
"name": "Python",
"bytes": "8088373"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3239"
},
{
"name": "Shell",
"bytes": "1513486"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.newsarea.search.settings.source {
public interface ISettings : IDictionary<String, StringValue> {
void Add(String key, String value);
}
}
| {
"content_hash": "c2175c31260b00ea8ec92719bc6e6fc7",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 67,
"avg_line_length": 18.571428571428573,
"alnum_prop": 0.7269230769230769,
"repo_name": "RBernhardt/unisono",
"id": "f57e05eec0033da5ac782e013010e42c05c80170",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "unisono-api/settings/source/Settings.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "376145"
}
],
"symlink_target": ""
} |
const int cListenBacklog = 5; // maximum length of the queue of pending connections
const int cMaxConcurrentRequests = min(4095,cMaxServiceInsts * cMaxNumSessions); // can process at most this many concurrent service requests over all session instances independent of service type
const int cMaxReqID = cMaxConcurrentRequests; // request identifiers will range from 1..cMaxConcurrentRequests
// when negotiating with potential service providers then minimal buffer tx/rx buffer sizes are allocated
const int cMinTxRxBuffSize = (cMaxServiceTypes * sizeof(tsServiceDetail)) + sizeof(tsBKSReqServices) * 3; // always allocate at least this sized TxdBuff/RxdBuffs - ensures negotiation frames fit!
// Session service providers will be in one of these exclusive states
typedef enum TAG_eBKSEPProvState
{
eBKSPSUndefined = 0, // service provider state is undefined waiting on a potential service provider to connect
eBKSPSRegisteringNeg, // initiated negotiation of capabilities with connected service provider
eBKSPSRegisteredActv, // completed capabilities negotiation and provider can now actively process service requests
eBKSPSRegisteredTerm, // currently terminating service provider connection
eBKSPSPlaceHolder
} teBKSPEPProvState;
typedef enum TAG_eSessEstabState
{
eSESnone = 0, // not yet started
eSESTxReqServices, // send required service type details to potential provider
eSESRxOfferedService, // expecting to receive potential providers offered service
eSESTxAcceptService, // sending acceptance of offered service to provider
eSESTxRejectService, // sending rejection of offered service to provider
eSESPlaceHolder
} teSessEstabState;
#pragma pack(1)
typedef INT64 tJobIDEx; // >0 extended job identifier; 0 if none assigned, <0 if errors
typedef struct TAG_sTxdRxd
{
UINT32 SessionID; // uniquely identifying this session between service requester and provider, requester specified
UINT16 flgSelMonExcept : 1; // socket to be monitored for exceptions
UINT16 flgSelMonRead : 1; // socket to be monitored for received data available to be read
UINT16 flgSelMonWrite : 1; // socket to be monitored for write completed
UINT16 flgKeepAliveReq: 1; // set if a keepalive is to be sent
UINT16 flgRxCplt : 1; // set when complete frame received
UINT16 flgTxCplt : 1; // set when complete frame sent
UINT16 flgErr : 1; // set on any unrecoverable error
UINT16 flgErrReason : 4; // holds reason for socket level error flag set
socket_t Socket; // assumed connected socket
time_t PacRxdAtSecs; // the time at which a frame was last received, used for determining if session still active
time_t PacTxdAtSecs; // the time at which a frame was last sent, used for keep alive generation
UINT8 RxdRxFrameID; // RxFrameID of last received frame - will be 0 if no frame yet received by session peer
UINT8 RxdTxFrameID; // TxFrameID of last received frame - will be 0 if no frame yet received from session peer
UINT8 TxFrameID; // FrameID of next frame to send, will wraparound back to 1 when incremented past 0x07f
UINT32 TotRxd; // pRcvBuff contains this total number of received bytes
UINT32 CurPacRxd; // number of bytes in currently received packet
UINT32 TotTxd; // total number of bytes in pTxdBuff to be sent
UINT32 CurTxd; // number of bytes currently sent from pTxdBuff
UINT32 AllocdRxdBuff; // pRxdBuff allocated to hold at most this many received bytes
UINT32 AllocdTxdBuff; // pTxdBuff allocated to hold at most this many bytes
UINT8 *pRxdBuff; // receiving data into this buffer
UINT8 *pTxdBuff; // sending data from this buffer
SOCKADDR_STORAGE IPaddress; // remote IP address + port of endpoint service provider (IPv4 or IPv6)
} tsTxdRxd;
typedef struct TAG_sBKSSessEstab
{
UINT8 SEState; // current session establishment state - eSESnone, eSESTxServices, eSESRxOfferService, eSESTxAcceptService
time_t StartSecs; // started session establishment at this time
teBKSPType BKSPType; // confirmation of service type being accepted or eBKSPTUndefined if offered type not accepted
UINT32 MaxInstances; // max number of instances supported
UINT32 MaxClassInstances;// Session can instantiate at most this many class instances
tsTxdRxd TxdRxd; // holding low level send/receive buffers + connected socket
} tsBKSSessEstab;
// Session service providers are registered into the following
typedef struct TAG_sBKSRegSession
{
UINT32 SessionID; // uniquely identifying this session between service requester and provider
UINT32 TypeSessionID; // used as an index within the type to reference this session
UINT8 BKSPType; // Session is providing this teBKSType service
UINT8 BKSPState; // Session is currently in this teBKSPEPProvState registration state
UINT32 MaxInstances; // Session can process at most this many service instances
UINT32 MaxClassInstances; // Session can instantiate at most this many class instances
UINT32 NumBusy; // total number of instances currently committed to requests, processing, or with responses
UINT32 NumReqs; // number of instances with service request ready to send to a service provider
UINT32 NumProcs; // number of instances with service requests currently being processed by service provider
UINT32 NumCpltd; // number of instances with service requests finished processing with response available
UINT64 TotNumCpltd; // total number of completed requests in this session
} tsBKSRegSession;
typedef struct TAG_sReqRespInst
{
INT64 JobIDEx; // unique job identifier as was generated when job was accepted for submission
UINT32 SubmitAt; // when job was accepted for submission
UINT32 CpltdAt; // when job was returned as completed
UINT16 ReqID; // instance specific identifier
UINT16 FlgReq:1; // this job instance has been initialised and is ready to be sent for processing
UINT16 FlgProc:1; // this job instance is currently being processed by service provider
UINT16 FlgCpltd:1; // service provider has completed processing and returned results are available
UINT32 JobRslt; // service provider completion result
UINT64 ClassInstanceID; // class instance referenced
UINT32 ClassMethodID; // identifies class method
UINT32 ParamSize; // instance specific parameter size
UINT32 InDataSize; // instance specific input data size
UINT32 OutDataSize; // instance specific result data size
UINT8 Data[1]; // when service requested then parameters followed by input data, if service response then response result data
} tsReqRespInst;
typedef struct TAG_sBKSRegSessionEx
{
struct TAG_sBKSRegSessionEx *pNext; // Sessions are linked as will be dynamically allocated
tsBKSRegSession Session; // Session
UINT32 LastChkdReqIdx; // start checking for service requests to send from this instance index
UINT32 NumClassInstances; // number of class instance identifiers currently in ClassInstanceIDs
UINT64 ClassInstanceIDs[cMaxClassInsts]; // holds all instantiated class instance identifiers for this session
UINT32 AllocdReqResp; // allocation size for pReqResp
UINT8 *pReqResp; // allocation for NumInstances of requests and associated responses
tsTxdRxd TxdRxd; // holding low level send/receive buffers + connected socket
} tsBKSRegSessionEx;
typedef struct TAG_sBKSType
{
tsServiceDetail Detail; // service type detail
UINT32 MaxSessions; // allowing at most this many sessions of specified service type
UINT32 NumSessions; // currently this number of registered sessions of this type
UINT32 NumInstances; // totaling this many service instances
UINT32 ReqRespInstSize; // each service instance requires this much memory
UINT32 FlgReq:1; // at least 1 session has a service request ready to send to a service provider
tsBKSRegSessionEx *pFirstSession; // ptr to first session of this type
tsBKSRegSessionEx *pSessions[cMaxNumSessions]; // ptr to each session as indexed by TypeSessvIdx
} tsBKSType;
typedef struct TAG_sChkPtReq { // individual check pointed request
UINT32 ClassMethodID; // identifies class method
UINT32 ParamSize; // instance specific parameter size
UINT32 InDataSize; // instance specific input data size
UINT32 MaxOutDataSize; // instance specific max expected output data for this method
UINT8 Data[1]; // parameters followed by input data
} tsChkPtReq;
typedef struct TAG_sChkPtReqs { // list of all check pointed requests for a specific class instance
UINT32 SessionID; // uniquely identifying this session between service requester and provider (set to 0 if this class instance can be reused)
UINT32 TypeSessionID; // used as an index within the type to reference this session
UINT64 ClassInstanceID; // check pointing this class instance
UINT32 JobRslt; // last job processing result as returned by service provider
UINT32 UsedRespData; // pRespData currently holds this sized response for last job submitted
UINT32 AllocRespData; // pRespData allocated to this size
UINT8 *pRespData; // response data for last check pointed method successfully processed by service provider
UINT32 NumChkPtReqs; // number of check pointed requests in ChkPtReqs[]
size_t AllocMem; // total memory allocated to hold this check pointed list (includes this header)
size_t UsedMem; // currently using this sized memory to hold check pointed list (includes this header)
tsChkPtReq ChkPtReqs[1]; // 1st check pointed request
} tsChkPtReqs;
typedef struct TAG_sRequesterThread {
int ThreadIdx; // uniquely identifies this thread
void *pThis; // will be initialised to pt to class instance
#ifdef _WIN32
HANDLE threadHandle; // handle as returned by _beginthreadex()
UINT32 threadID; // identifier as set by _beginthreadex()
#else
int threadRslt; // result as returned by pthread_create ()
pthread_t threadID; // identifier as set by pthread_create ()
#endif
int Rslt; // processing result
} tsRequesterThread;
#pragma pack()
class CBKSRequester
{
char m_szHostName[cMaxHostNameLen+1]; // host on which to listen for connections
char m_szServiceName[cMaxServiceNameLen+1]; // listening on this port
tsRequesterThread m_RequesterThread; // requester thread parameters
#ifdef WIN32
#ifdef _ChkLockDepth_ // if checking that serialisation locks are actually working!
alignas(4) volatile UINT32 m_LockDepth;
alignas(4) volatile UINT32 m_CASSerialiseDepth;
#endif
alignas(4) volatile UINT32 m_CreatedMutexes; // set to 1 after serialisation locks/mutexes initialised
alignas(4) volatile UINT32 m_ThreadActive; // set to 1 after requester thread has started and initialised
alignas(4) volatile UINT32 m_Terminate; // set to 1 if requester thread is required to self terminate
alignas(4) volatile UINT32 m_LockEnabled; // set to 1 if AcquireLock has been initialised and can be used for serialisation
alignas(4) volatile UINT32 m_CASSerialise; // used with synchronous compare and swap (CAS) for serialising access
alignas(4) volatile UINT32 m_NumPendingReqs; // number of outstanding pending requests from RMI worker threads to be processed
alignas(4) volatile UINT32 m_NumPendingResps; // number of outstanding pending response checks from RMI worker threads to be processed
alignas(4) volatile LONG m_TotRespsAvail; // current total number of responses available to RMI worker threads over all sessions
#else
#ifdef _ChkLockDepth_ // if checking that serialisation locks are actually working!
__attribute__((aligned(4))) volatile UINT32 m_LockDepth;
__attribute__((aligned(4))) volatile UINT32 m_CASSerialiseDepth;
#endif
__attribute__((aligned(4))) volatile UINT32 m_CreatedMutexes; // set to 1 after serialisation locks/mutexes initialised
__attribute__((aligned(4))) volatile UINT32 m_ThreadActive; // set to 1 after requester thread has started and initialised
__attribute__((aligned(4))) volatile UINT32 m_Terminate; // set to 1 if requester thread is required to self terminate
__attribute__((aligned(4))) volatile UINT32 m_LockEnabled; // set to 1 if AcquireLock has been initialised and can be used for serialisation
__attribute__((aligned(4))) volatile UINT32 m_CASSerialise; // used with synchronous compare and swap (CAS) for serialising access
__attribute__((aligned(4))) volatile UINT32 m_NumPendingReqs; // number of outstanding pending requests from RMI worker threads to be processed
__attribute__((aligned(4))) volatile UINT32 m_NumPendingResps; // number of outstanding pending response checks from RMI worker threads to be processed
__attribute__((aligned(4))) volatile UINT32 m_TotRespsAvail; // current total number of responses available to RMI worker threads over all sessions
#endif
bool m_bNotifiedReqs; // set TRUE if control message has been sent to control socket 2
bool m_bSessionTermReq; // true whilst a Session is being deleted
UINT32 m_NumChkPtReqs; // m_pChkPtReqs contains this many currently active check pointed class request ptrs
UINT32 m_MaxChkPtReqs; // m_pChkPtReqs allocated to hold at most this many check pointed class request ptrs
tsChkPtReqs **m_ppChkPtReqs; // allocated to hold check pointed class request ptrs
UINT32 m_NumInitTypes; // number of service types initialised in m_pBKSTypes
tsBKSType *m_pBKSTypes; // pts to allocated array of entries for each potentially supported service type indexed by Type-1
UINT32 m_NumSessEstabs; // number of sessions currently in pBKSSessEstab being negotiated with
tsBKSSessEstab *m_pBKSSessEstabs; // pts to allocated array of session peer endpoints currently being negotiated with
UINT32 m_NumSessions; // currently there are this many registered sessions
UINT32 m_SessionIDVect[(cMaxConcurrentSessions+31)/32]; // bit vector containing all possible session identifiers, if bit set then that session identifier has been allocated and is in use
UINT32 m_ReqIDVect[(cMaxReqID+31) / 32]; // bit vector containing all possible request identifiers, if bit set then that request identifier has been allocated and is in use
socket_t m_ListenerSock; // listening on this socket for Session connections
tsTxdRxd m_Ctrl[2]; // Ctrl[0] written to by threads needing to signal select() processing thread, select() processing thread monitors m_Ctrl[1]
UINT32 // returned request identifier or 0 if all identifiers have already been allocated
AllocReqID(void); // returns next available unused request identifier and sets that identifier in m_ReqIDVect[] as now allocated
bool // true if ReqID was previously allocated (used), false if previously unallocated (unused)
UnallocReqID(UINT32 ReqID); // sets the ReqID in m_ReqIDVect as unallocated and available to be reused
bool // true if ReqID is currently allocated (used), false if unallocated (unused)
IsAllocReqID(UINT32 ReqID); // checking this ReqID in m_ReqIDVect
UINT32 // returned session identifier or 0 if all identifiers have already been allocated
AllocSessionID(void); // returns next available unused session identifier and sets that identifier in m_SessionIDVect as allocated
bool // true if SessionID was previously allocated (used), false if previously unallocated (unused)
UnallocSessionID(UINT32 SessionID); // sets the SessionID in m_SessionIDVect as unallocated and available to be reused
bool // true if SessionID is currently allocated (used), false if unallocated (unused)
IsAllocSessionID(UINT32 SessionID); // checking this SessionID in m_SessionIDVect
tsBKSRegSessionEx *LocateSession(UINT32 SessionID); // locates an established session which is identified by SessionID
void
ResetSessEstab(tsBKSSessEstab *pSessEstab, // reset this tsBKSSessEstab instance
bool bKeepAllocs = true,// if true then retain any existing buffer allocations
bool bKeepSessionID = false); // if true then retain SessionID as session has been accepted
bool
StartSessEstab(UINT32 SessionID, // Session identifier for this potential Session
socket_t Socket, // communicating with Session over this connected socket
SOCKADDR_STORAGE *pIPaddress); // peer is at this socket network address
bool
ProgressSessEstab(tsBKSSessEstab *pSessEstab,
bool bCpltdWrite); // false if frame received, true if frame sent
bool
AcceptFullSession(tsBKSSessEstab *pSessEstab); // accepting session being established as full session ready for normal payload request/responses
int TerminateAllSessions(void);
int // returns number of sessions deleted
DeleteAllSessionsInState(teBKSPEPProvState TermState = eBKSPSRegisteredTerm); // terminate and delete any session in specific state (normally eBKSPSRegisteredTerm) or with an invalid socket
int CreateMutexes(void); // create mutexes used in access serialisations
int DeleteMutexes(void); // delete mutexes used in access serialisations
bool AcquireLock(bool bExclusive); // lock for serialised access by multiple concurrent reader threads (bExclusive == false), or serialised access by single thread (bExclusive == true)
bool ReleaseLock(bool bExclusive); // release serialised access lock
void AcquireCASSerialise(bool bPriority = false); // if bPriority true then backoff time is reduced relative to if bPriority is false, increasing the probability of acquiring the serialisation lock if there is contention
void ReleaseCASSerialise(void);
#ifdef _WIN32
SRWLOCK m_hRWLock; // serialising multiple reader access but single writer
#else
pthread_rwlock_t m_hRWLock; // serialising multiple reader access but single writer
#endif
bool InitialiseListener(const char* pszHost, char *pszService); // initialise listening socket
bool InitialiseCtrlSocks(void); // initialise the control sockets in m_Ctrl[]
int AcceptConnections(void); // start accepting connections
int SendRequestFrames(void); // iterate all sessions and if any frames ready to send and room to accept the frame in TxdBuff then initiate the sending
int // 0: accepted frame, -1: JobIDEx errors, -2 Session or type errors, -3 mismatch between instance JobIDEx's, ClassInstanceID mismatch
ProcessResponseFrame(tsBKSRegSessionEx *pSession); // process a received response frame on this session
bool RxData(tsTxdRxd *pRxd);
bool TxData(tsTxdRxd *pTxd);
bool NotifyCtrl(UINT8 Msg = 0); // notify via control sockets that, default, there is at least 1 request available to be sent to a session instance provider
bool SendCtrlMsg(int Len, // number of control message bytes to send ptd at by pCtrlMsg, can be 0
UINT8 *pCtrlMsg); // pCtrlMsg pts to control message bytes
int // received message is this length, 0 if no outstanding messages, < 0 if errors
RcvCtrl(int BuffLen, // available buffer into which the control message can be copied
UINT8 *pBuff); // copy control message into this buffer
bool ProcessCtrlMsg(int MsgLen,UINT8 *pMsg); // process a message received by control socket m_Ctrl[1] - note: currently these messages are simply discarded
UINT32 // identifies created and initialised check point requests list
CreateChkPtReqs(UINT32 SessionID, // uniquely identifying this session between service requester and provider
UINT32 TypeSessionID, // used as an index within the type to reference this session
UINT64 ClassInstanceID, // check pointing this class instance
UINT32 ClassMethodID, // identifies class method
UINT32 ParamSize, // instance specific parameter size
UINT32 InDataSize, // instance specific input data size
UINT32 MaxOutDataSize, // instance specific max expected output data for this method
UINT8 *pData); // request parameters followed by input data
bool
DeleteChkPtReqs(UINT32 ChkPtID); // identifies check point list to be deleted
bool // true if request was successfully check pointed
AddChkPtReq(UINT32 ChkPtID, // identifies check point list to extend with this request
UINT32 SessionID, // uniquely identifying this session between service requester and provider
UINT32 ClassMethodID, // identifies class method
UINT32 ParamSize, // instance specific parameter size
UINT32 InDataSize, // instance specific input data size
UINT32 MaxOutDataSize, // instance specific max expected output data for this method
UINT8 *pData); // request parameters followed by input data
bool // true if response was successfully updated
AddChkPtResp(UINT32 ChkPtID, // identifies check point list to update with this response
UINT32 SessionID, // uniquely identifying this session between service requester and provider
UINT32 JobRslt, // job processing result as returned by service provider
UINT32 RespSize, // response size
UINT8 *pData); // response data
bool ShutdownConnection(socket_t *pSocket);
int // returns 0 if no sockets to be monitored with select(), on windows the total number of monitored sockets, on linux the highest socket file descriptor plus 1
SetupFDSets(fd_set& ReadFDs, // select() read available socket descriptor set
fd_set& WriteFDs, // select() write accepted socket descriptor set
fd_set& ExceptFDs); // select() exceptions descriptor set
tJobIDEx // packed job identifier or 0 if range errors
PackIntoJobIDEx(UINT32 ReqID, // must be in the range 1..16777215 (24bits)
UINT32 SessionID, // service provider session identifier, must be in the range 1..131071 (17bits)
UINT32 InstanceID, // service instance in the service providers session SessionID, must be in the range 1..511 (9bits)
UINT32 TypeID, // identifies service being provided by the service provider, must be in the range 1..15 (4bits)
UINT32 TypeSessionID); // index of this session in the service type, must be in the range 1..511 (9bits)
bool // false if any range errors whilst unpacking
UnpackFromJobIDEx(tJobIDEx JobIDEx, // unpack from this extended job identifier
UINT32 *pReqID, // returned ReqID, will be in the range 1..16777215
UINT32 *pSessionID, // returned SessionID, will be in the range 1..131071
UINT32 *pInstanceID, // returned InstanceID, will be in the range 1..511
UINT32 *pTypeID, // returned service TypeID, will be in the range 1..15
UINT32 *pTypeSessionID); // returned index of this session in the service type, will be in the range 1..511
#ifdef WIN32
const char *WSAGetLastErrorMessage(const char* pcMessagePrefix, int nErrorID = 0);
#endif
int Reset(bool bReleaseLock); // locked mutex requires releasing immediately prior to deleting the mutexes
public:
CBKSRequester();
~CBKSRequester();
int StartThread(tsRequesterThread *pPars);
// NOTE: defaults chosen are representative for Smith-Waterman service processing
int // returns total number of registered service types or teBSFrsltCodes error code if any parameterisation errors or already registered type
RegServiceType(teBKSPType BKSPType = eBKSPTSmithWaterman, // registering this service type
UINT32 MinProviderVersion = cMinProviderVersion, // service provider version must be at least this software version
UINT32 MaxProviderVersion = cMaxProviderVersion, // service provider version must be no more than this software version
UINT32 KeepaliveSecs = cDfltKeepaliveSecs, // expecting packet activity from session peer with periodicity of no more than this number of seconds
UINT32 MaxSessions = cDfltNumSessions, // allowing at most this many concurrent sessions of specified service type
UINT32 MinServiceInsts = cMinServiceInsts, // any session to support at least this minimum number of service instances
UINT32 MaxServiceInsts = cDfltServiceInsts, // limit any session to support a maximum of this many service instances
UINT32 MaxProcSecs = cMaxSWProcSecs, // expecting any service provider to take no more than this number of seconds to complete processing a given request
UINT32 MaxParamLen = cMaxSWParamLen, // service job parameters can be up to this length
UINT32 MaxQuerySeqLen = cMaxSWQuerySeqLen, // query sequences can be up to this length
UINT32 MaxTargSeqLen = cMaxSWTargSeqLen, // target sequences can be up to this length
UINT32 MaxReqPayloadSize = cMaxSWReqPayloadSize, // request payloads to the service provider, including framing, can be up to this size (UINT8s),
UINT32 MaxRespPayloadSize = cMaxSWRespPayloadSize); // response payloads from the service provider, including framing, can be up to this size (UINT8s)
int // returns number of registered sessions which are in requested state
GetNumSessions(teBKSPType BKSPType = eBKSPTSmithWaterman, // may request number of sessions providing this specific service type, or if eBKSPTUndefined then the total
teBKSPEPProvState BKSPState = eBKSPSRegisteredActv); // sessions must be in this specific state
int // returns total number of service instances in all registered sessions which are in requested state
GetNumInstances(teBKSPType BKSPType = eBKSPTSmithWaterman, // may request number of instances providing this specific service type, or if eBKSPTUndefined then the total
teBKSPEPProvState BKSPState = eBKSPSRegisteredActv); // sessions providing service instances must be in this specific state
int // actual number of sessions returned
GetSessions(teBKSPType BKSPType, // return sessions for this service type, or if eBKSPTUndefined then all service types registered
teBKSPEPProvState BKSPState, // sessions must be in this state
int MaxSessions, // return at most this many sessions in pSessions[]
tsBKSRegSession *pSessions); // caller has preallocated to hold returned array snapshot of sessions
int
Initialise(char* pszHost = NULL, // listening on this host/IP address; NULL to use first INET IP local to this machine
char *pszService = NULL, // listening on this service/port; NULL to use default port
teBKSPType BKSPType = eBKSPTSmithWaterman, // registering this service type
UINT32 MinProviderVersion = cMinProviderVersion, // service provider version must be at least this software version
UINT32 MaxProviderVersion = cMaxProviderVersion, // service provider version must be no more than this software version
UINT32 KeepaliveSecs = cDfltKeepaliveSecs, // expecting packet activity from session peer with periodicity of no more than this number of seconds
UINT32 MaxSessions = cDfltNumSessions, // allowing at most this many concurrent sessions of specified service type
UINT32 MinServiceInsts = cMinServiceInsts, // any session to support at least this minimum number of service instances
UINT32 MaxServiceInsts = cDfltServiceInsts, // limit any session to support a maximum of this many service instances
UINT32 MaxProcSecs = cMaxSWProcSecs, // expecting any service provider to take no more than this number of seconds to complete processing a given request
UINT32 MaxParamLen = cMaxSWParamLen, // service job parameters can be up to this length
UINT32 MaxQuerySeqLen = cMaxSWQuerySeqLen, // query sequences can be up to this length
UINT32 MaxTargSeqLen = cMaxSWTargSeqLen, // target sequences can be up to this length
UINT32 MaxReqPayloadSize = cMaxSWReqPayloadSize, // request payloads to the service provider, including framing, can be up to this size (UINT8s),
UINT32 MaxRespPayloadSize = cMaxSWRespPayloadSize); // response payloads from the service provider, including framing, can be up to this size (UINT8s)
bool Run(int Secs=180); // false if unable to begin thread execution or if executing thread took too long (default 3min) to initialise ready to accept connections
void Terminate(int Secs = 120); // allow this many seconds for thread to self-terminate before forcing termination
int // total number of classes
GetNumClassInstances(teBKSPType TypeID = eBKSPTSmithWaterman, // service required
UINT32 *pCommited = NULL, // returned number of class instances currently committed or instantiated
UINT32 *pUncommited = NULL); // returned number of class instances currently not committed and available to be instantiated
int // -2: parameter errors, -1: class instance no longer exists, 0: currently no available service instance 1: if job accepted
AddJobRequest( tJobIDEx *pJobID, // returned unique job identifier by which job can later be referenced
teBKSPType TypeID, // service type required
UINT64 ClassInstanceID, // class instance on which job method is to be applied
UINT32 ClassMethodID, // class method to apply on the class instance
UINT32 ParamsSize = 0, // processing parameters are this total size in bytes
void *pParams = NULL, // service processing parameters
UINT32 InDataSize = 0, // service processing input data is this total size in bytes
void *pInData = NULL, // service processing input data
UINT32 SessionID = 0); // if 0 then use session as specified by ClassInstanceID, otherwise use session corresponding to specific session identifier
int // < 0 if job no longer exists, 0 if job still being processed, > 0 if job completed
GetJobResponse(tJobIDEx JobID, // unique job identifier returned when job was submitted
UINT64 *pClassInstanceID, // returned class instance on which job method was applied
UINT32 *pClassMethodID, // returned class method applied
UINT32 *pJobRslt, // job processing result as returned by service provider
UINT32 *pOutDataSize, // (IN) service processing output results expected to be at most this total length, [OUT] bytes of response data copied into pOutData
void *pOutData, // service processing output results data
bool bRetain=false); // true if job response is to be retained and not deleted; subsequent call with bRetain==false will delete this response
};
| {
"content_hash": "12e01108a022d5eb965c37ffd6327eb9",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 221,
"avg_line_length": 67.97550111358575,
"alnum_prop": 0.7541692605091577,
"repo_name": "ste69r/Biokanga",
"id": "9163ee933453df97554f774aec61d47992906b48",
"size": "30559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pacbiokanga/BKSRequester.h",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Symplify\MultiCodingStandard\PhpCsFixer\Factory;
use PhpCsFixer\Config;
use PhpCsFixer\Console\ConfigurationResolver;
use PhpCsFixer\Fixer\FixerInterface;
final class FixerFactory
{
/**
* @return FixerInterface[]
*/
public function createFromLevelsFixersAndExcludedFixers(array $fixerLevels, array $fixers, array $excludedFixers)
{
$fixersFromLevels = $this->createFromLevelsAndExcludedFixers($fixerLevels, $excludedFixers);
$standaloneFixers = $this->createFromFixers($fixers);
return array_merge($fixersFromLevels, $standaloneFixers);
}
private function createFromLevelsAndExcludedFixers(array $fixerLevels, array $excludedFixers) : array
{
if (!count($fixerLevels)) {
return [];
}
$fixers = [];
foreach ($fixerLevels as $fixerLevel) {
$excludedFixersAsString = $this->turnExcludedFixersToString($excludedFixers);
$newFixers = $this->resolveFixersForLevelsAndFixers($fixerLevel, $excludedFixersAsString);
$fixers = array_merge($fixers, $newFixers);
}
return $fixers;
}
private function createFromFixers(array $fixers) : array
{
if (!count($fixers)) {
return [];
}
$fixersAsString = $this->turnFixersToString($fixers);
return $this->resolveFixersForLevelsAndFixers('none', $fixersAsString);
}
/**
* @return FixerInterface[]
*/
private function resolveFixersForLevelsAndFixers(string $level, string $fixersAsString) : array
{
$config = new Config();
$configurationResolver = new ConfigurationResolver($config, [
'rules' => $this->combineSetAndFixersToRules($level, $fixersAsString)
], getcwd());
return $configurationResolver->getFixers();
}
private function turnFixersToString(array $fixers) : string
{
return $this->implodeWithPresign($fixers);
}
private function turnExcludedFixersToString(array $excludedFixers) : string
{
return $this->implodeWithPresign($excludedFixers, '-');
}
private function implodeWithPresign(array $items, string $presign = '')
{
if (count($items)) {
return $presign.implode(','.$presign, $items);
}
return '';
}
private function combineSetAndFixersToRules(string $level, string $fixersAsString) : string
{
$rules = '';
if ($level && $level !== 'none') {
$rules .= '@' . strtoupper($level);
}
if ($fixersAsString) {
if ($rules) {
$rules .= ',';
}
$rules .= $fixersAsString;
}
return $rules;
}
}
| {
"content_hash": "4052098ab3a6ca3a2094fe353e11d539",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 117,
"avg_line_length": 27.30392156862745,
"alnum_prop": 0.6157989228007181,
"repo_name": "Symplify/MultiCodingStandard",
"id": "7b9559e0da1ce64e35e91fc003bee1dd2fa036ad",
"size": "2886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/PhpCsFixer/Factory/FixerFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "25640"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "44cf0b4edfe1357eaca90313c2916578",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "f7c1bdfbb1e13d4225b1c73a0b5b572470f2d4bd",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus reflexiaristatus/ Syn. Triticum strigosum microcalyx/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.banana.banana.MissionPopupActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
</menu>
| {
"content_hash": "10fdbea670dcd53c812592b19d8e1745",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 64,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.6778846153846154,
"repo_name": "Limjunghwa/wholeba_android",
"id": "787f36a891630b7e8e1e866a1780978f7cbe9513",
"size": "416",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "res/menu/mission_popup.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "302082"
}
],
"symlink_target": ""
} |
package org.derkani.sight;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
/**
* @author Masih Hajiarabderkani (mh638@st-andrews.ac.uk)
*/
public class ChartMergeUtils {
public static JFreeChart merge(JFreeChart... charts) {
final JFreeChart merge;
if (charts == null || charts.length == 0) {
merge = null;
} else if (charts.length == 1) {
merge = charts[0];
} else {
merge = null;
for (JFreeChart chart : charts) {
final Plot plot = chart.getPlot();
if (plot instanceof XYPlot) {
final XYPlot xy = (XYPlot) plot;
final XYDataset dataset = xy.getDataset();
}
}
}
return merge;
}
}
| {
"content_hash": "3dbbd4ae4f30bc45ab4b54f1629f70a2",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 62,
"avg_line_length": 24.027027027027028,
"alnum_prop": 0.545556805399325,
"repo_name": "masih/sight",
"id": "c8eab5c152a8c6001b8c9e48b79a71b51a39a019",
"size": "2468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/derkani/sight/ChartMergeUtils.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "16094"
}
],
"symlink_target": ""
} |
define("p3/widget/JobsGrid", [
"dojo/_base/declare", "./PageGrid", "dojo/store/JsonRest", "dgrid/extensions/DijitRegistry",
"dgrid/Keyboard", "dgrid/Selection", "./formatter", "dgrid/extensions/ColumnResizer", "dgrid/extensions/ColumnHider",
"dgrid/extensions/DnD", "dojo/dnd/Source", "dojo/_base/Deferred", "dojo/aspect", "dojo/_base/lang",
"dojo/topic", "dgrid/editor", "dijit/Menu", "dijit/MenuItem", "../WorkspaceManager", "dijit/Dialog",
"../JobManager", "dojo/on"
],
function(declare, Grid, Store, DijitRegistry,
Keyboard, Selection, formatter, ColumnResizer,
ColumnHider, DnD, DnDSource,
Deferred, aspect, lang, Topic, editor, Menu, MenuItem, WorkspaceManager, Dialog,
JobManager, on){
var store = JobManager.getStore();
return declare([Grid, ColumnHider, Selection, Keyboard, ColumnResizer, DijitRegistry], {
store: store,
selectionMode: "single",
allowTextSelection: false,
deselectOnRefresh: false,
minRowsPerPage: 50,
bufferRows: 100,
maxRowsPerPage: 1000,
pagingDelay: 250,
//pagingMethod: "throttleDelayed",
farOffRemoval: 2000,
keepScrollPosition: true,
rowHeight: 24,
loadingMessage: "Loading...",
dndDataType: "genome",
dndParams: {
accept: "none",
selfAccept: false,
copyOnly: true
},
columns: {
"status": {
label: "Status",
field: "status",
formatter: formatter.status_alias
},
"submit_time": {
label: "Submit",
field: "submit_time",
formatter: formatter.date
},
"id": {
label: "ID",
field: "id",
hidden: true
},
"app": {
label: "App",
field: "app",
formatter: formatter.appLabel
},
"parameters": {
label: "Output Name",
field: "parameters",
formatter: function(val){
return val.output_file || "";
}
},
"start_time": {
label: "Start",
field: "start_time",
formatter: formatter.date
},
"completed_time": {
label: "Completed",
field: "completed_time",
formatter: formatter.date
}
},
constructor: function(){
this.queryOptions = {
sort: [{attribute: "submit_time", descending: true}]
};
this.dndParams.creator = lang.hitch(this, function(item, hint){
//console.log("item: ", item, " hint:", hint, "dataType: ", this.dndDataType);
var avatar = dojo.create("div", {
innerHTML: item.organism_name || item.ncbi_taxon_id || item.id
});
avatar.data = item;
if(hint == 'avatar'){
// create your avatar if you want
}
return {
node: avatar,
data: item,
type: this.dndDataType
}
})
},
queryOptions: {
sort: [
{attribute: "submit_time", descending: true}
]
},
sort: [
{attribute: "submit_time", descending: true }
],
_setTotalRows: function(rows){
this.totalRows = rows;
if(this.controlButton){
if(!this._originalTitle){
this._originalTitle = this.controlButton.get('label');
}
this.controlButton.set('label', this._originalTitle + " (" + rows + ")");
}
},
showErrorDialog: function(data){
//console.log("Show Error Dialog: ", data);
if(!this.errorDialog){
this.errorDialog = new Dialog({title: "Task Output", content: "Loading Task Detail..."});
}else{
this.errorDialog.set("content", "Loading Task Detail...");
}
var _self = this;
var timer = setTimeout(function(){
_self.errorDialog.set("content", "Unable to retreive additional details about this task at this task. The operation timed out.");
}, 30000);
JobManager.queryTaskDetail(data.id, true, true).then(function(detail){
//console.log("JOB DETAIL: ", detail);
clearTimeout(timer);
if(detail.stderr){
_self.errorDialog.set("content", "<div style='overflow:auto;'><div data-dojo-type='dijit/TitlePane' title='STDOUT' open='false'><pre>" + (detail.stdout || "None.") + "</pre></div><br><div data-dojo-type='dijit/TitlePane' title='STDERR'><pre>" + (detail.stderr || "None.") + "</pre></div>");
}else{
_self.errorDialog.set("content", "Unable to retreive additional details about this task at this task.<br><pre>" + JSON.stringify(detail, null, 4) + "</pre>");
}
}, function(err){
_self.errorDialog.set("content", "Unable to retreive additional details about this task at this task.<br>" + err + "<br><pre></pre>");
});
this.errorDialog.show();
},
startup: function(){
if(this._started){
return;
}
var _self = this;
aspect.before(_self, 'renderArray', function(results){
Deferred.when(results.total, function(x){
_self.set("totalRows", x);
});
});
_selection = {};
Topic.publish("/select", []);
this.on("dgrid-select", function(evt){
var newEvt = {
rows: evt.rows,
selected: evt.grid.selection,
grid: _self,
bubbles: true,
cancelable: true
};
on.emit(_self.domNode, "select", newEvt);
});
this.on("dgrid-deselect", function(evt){
var newEvt = {
rows: evt.rows,
selected: evt.grid.selection,
grid: _self,
bubbles: true,
cancelable: true
};
on.emit(_self.domNode, "deselect", newEvt);
});
this.refresh();
}
});
});
| {
"content_hash": "392461f81247cd3d6b1b88d844d9aab1",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 295,
"avg_line_length": 27.026315789473685,
"alnum_prop": 0.6216163583252191,
"repo_name": "aswarren/p3_web",
"id": "d82fa6306949db2490a92a3373a3de14c835946d",
"size": "5135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/release/p3/widget/JobsGrid.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "17567"
},
{
"name": "AngelScript",
"bytes": "4817"
},
{
"name": "Batchfile",
"bytes": "1371"
},
{
"name": "CSS",
"bytes": "6252455"
},
{
"name": "CoffeeScript",
"bytes": "30579"
},
{
"name": "HTML",
"bytes": "3252307"
},
{
"name": "JavaScript",
"bytes": "33799174"
},
{
"name": "Makefile",
"bytes": "848"
},
{
"name": "Mako",
"bytes": "405"
},
{
"name": "PHP",
"bytes": "38090"
},
{
"name": "Shell",
"bytes": "2996"
},
{
"name": "XSLT",
"bytes": "47383"
}
],
"symlink_target": ""
} |
Gauges - SAP Lumira visualization extension
=================================================
* By [Andrew Jabbitt](http://scn.sap.com/people/andrew.jabbitt01)
Files
-----------
* `ucs.viz.ext.gauge.zip` - SAP Lumira extension, packaged with SAP WebIDE
Resources
-----------
* Blog post - [SAP Lumira Extension - Taking D3 Gauges to the next level](http://scn.sap.com/community/lumira/blog/2014/05/05/sap-lumira-extension--taking-gauges-to-the-next-level) | {
"content_hash": "6fcb922a596fb8593a544a96c3aade60",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 180,
"avg_line_length": 41.63636363636363,
"alnum_prop": 0.6419213973799127,
"repo_name": "ganchengyuan1990/lumira-extension-viz",
"id": "6264e9939f236c91f97251a32d7d0e1c448e9e28",
"size": "458",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gauges/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6843"
},
{
"name": "HTML",
"bytes": "31208"
},
{
"name": "JavaScript",
"bytes": "461973"
}
],
"symlink_target": ""
} |
require "docker/model"
module Docker
class Container < Model
map_attribute "ID", :id
map_attribute "Image", :image
map_attribute "NetworkSettings", :network_settings
def ip
network_settings["IPAddress"] if network_settings
end
def env
return {} unless config["Env"]
Hash[config["Env"].map { |e| e.split("=") }]
end
def pid
state["Pid"]
end
def started_at
Time.parse(state["StartedAt"]) if state["StartedAt"]
end
def state
attributes["State"] || {}
end
def config
attributes["Config"] || {}
end
def created_at
Time.parse(attributes["Created"])
end
end
end
| {
"content_hash": "6266fef4075ef3698e10d8122fbb4e7b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 58,
"avg_line_length": 17.973684210526315,
"alnum_prop": 0.5900439238653001,
"repo_name": "dynport/dockland",
"id": "458d3893f5f1e5f8f57ac94c179894ab02844c32",
"size": "683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/docker/container.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "18955"
},
{
"name": "Shell",
"bytes": "1646"
}
],
"symlink_target": ""
} |
<?php
/**
* The Template for displaying all single passports.
*
* @package Listify
*/
get_header(); ?>
<?php //Passports with featured image
if ( has_post_thumbnail() ){ ?>
<div
<?php
echo apply_filters(
'listify_cover', 'page-cover page-cover--large badge-image', array( // WPCS: XSS ok.
'size' => 'full',
)
);
?>
>
<h1 class="page-title cover-wrapper passport-title" style="color: white;">
<?php
the_post();
the_title();
$language = get_term_by('id', get_post_meta( $post->ID,'_passport_language',true ), 'field_of_education');
echo '<center><h3 style="color: white;">Language : '. $language->name . '</h3></center>';
rewind_posts();
?>
</h1>
</div>
<?php }
//Passports without featured image
else { ?>
<div>
<h1 class="page-title cover-wrapper passport-title">
<?php
the_post();
the_title();
$language = get_term_by('id', get_post_meta( $post->ID,'_passport_language',true ), 'field_of_education');
echo '<center><h3>Language : '. $language->name . '</h3></center>';
rewind_posts();
?>
</h1>
</div>
<?php } ?>
<div id="primary" class="container single-badge-content">
<div class="row content-area">
<?php if ( 'left' === esc_attr( listify_theme_mod( 'content-sidebar-position', 'right' ) ) ) : ?>
<?php get_sidebar(); ?>
<?php endif; ?>
<main id="main" class="site-main col-xs-12
<?php
if ( 'none' !== esc_attr( listify_theme_mod( 'content-sidebar-position', 'right' ) ) && is_active_sidebar( 'widget-area-sidebar-1' ) ) :
?>
col-sm-7 col-md-8<?php endif; ?>" role="main">
<?php
while ( have_posts() ) :
the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="content-box-inner">
<?php
$value = 'yes';
$counter = 0;
$counter_lp = 1;
$counter_la = 1;
$counter_ltq = 1;
$counter_ltp = 1;
$counter_te = 1;
$counter_mks = 1;
$counter_lcp = 1;
$counter_imm = 1;
$counter_ast = 1;
$counter_td = 1;
$counter_dm = 1;
$t_portfolio = array(
"language" => array(
"lp" => array(
11 => __("Studying the language at tertiary level. B1 proficiency.",'b4l-profiling-grid-for-teachers'),
21 => __("Studying the language at tertiary level. B2 proficiency.",'b4l-profiling-grid-for-teachers'),
31 => __("A B2 certificate in the language; oral competence at C1 level.",'b4l-profiling-grid-for-teachers'),
41 => __("A C1 examination certificate (eg CAE); oral competence at C2 level.",'b4l-profiling-grid-for-teachers'),
51 => __("Degree in the language, or: A C2 examination certificate (eg CPE).",'b4l-profiling-grid-for-teachers'),
61 => __("Native speaker, or: Language degree or C2 certificate plus a natural command of the language.",'b4l-profiling-grid-for-teachers')
),
"la" => array(
11 => __("Answer simple queries with the help of reference works.",'b4l-profiling-grid-for-teachers'),
21 => __("Answer queries related to high frequency structures.",'b4l-profiling-grid-for-teachers'),
31 => __("Give correct models of usage on most occasions. Answer most language queries satisfactorily at A1-B1, using reference sources as necessary.",'b4l-profiling-grid-for-teachers'),
41 => __("Give correct models of usage on most occasions. Answer language queries adequately though not always comprehensively, using reference sources as necessary.",'b4l-profiling-grid-for-teachers'),
51 => __("Give correct examples of usage on all occasions. Answer language queries reliably.",'b4l-profiling-grid-for-teachers'),
61 => __("Provide clear explanations. Teach usage and register at all levels. Understand what is confusing learners. Give comprehensive, accurate answers to queries.",'b4l-profiling-grid-for-teachers')
)
),
"qualifications" => array(
"ltq" => array(
11 => __("Taking a certificate in teaching the target language. or: Following an internal training course.",'b4l-profiling-grid-for-teachers'),
21 => __(" A minimum of 30 hours documented, structured training in language awareness and methodology of teaching the target language.",'b4l-profiling-grid-for-teachers'),
31 => __("A minimum of 60 hours of documented, structured training in teaching the target language.",'b4l-profiling-grid-for-teachers'),
41 => __(" Degree in the target language, or: Internationally recognised (min. 100 hour) certificate in teaching the target language.",'b4l-profiling-grid-for-teachers'),
51 => __("Degree or degree module in teaching the target language, or: Internationally recognised (min. 100 hour) certificate in teaching the target language.",'b4l-profiling-grid-for-teachers'),
61 => __(" Masters degree or module in language teaching or applied linguistics, or: Postgraduate or professional diploma in teaching the language (min. 200 hours)",'b4l-profiling-grid-for-teachers')
),
"ltp" => array(
11 => __("Experience of team teaching, or: Of acting as a teacher’s assistant.",'b4l-profiling-grid-for-teachers'),
21 => __("Experience of supervision and assessment while teaching phases of lessons.",'b4l-profiling-grid-for-teachers'),
31 => __("A minimum of 2 hours of documented, assessed teaching practice. Has been observed & had feedback on some actual teaching.",'b4l-profiling-grid-for-teachers'),
41 => __(" A minimum of 6 hours of documented, assessed teaching practice. Has been observed & had feedback on at least 5 hrs of real teaching.",'b4l-profiling-grid-for-teachers'),
51 => __(" A minimum of 12 hours of documented, assessed teaching practice. Has been observed & had feedback on at least 8 hours of teaching.",'b4l-profiling-grid-for-teachers'),
61 => __("A minimum of 18 hours of documented, assessed teaching practice. Has been observed & had feedback on at least 12 hours of teaching.",'b4l-profiling-grid-for-teachers')
),
"te" => array(
11 => __(" Taught some lessons, or: Parts of lessons at one or two levels.",'b4l-profiling-grid-for-teachers'),
21 => __("Own class(es) but limited experience which only includes teaching at lower levels.",'b4l-profiling-grid-for-teachers'),
31 => __(" A minimum of 200 hours, documented teaching experience. Taught a range of levels up to B1.",'b4l-profiling-grid-for-teachers'),
41 => __(" A minimum of 800 hours, documented teaching experience. Taught all levels except C1 & C2.",'b4l-profiling-grid-for-teachers'),
51 => __("A minimum of 2,400 hours, documented teaching experience. Taught all levels except C2, examination or specialised classes.",'b4l-profiling-grid-for-teachers'),
61 => __("A minimum of 4,000 hours, documented teaching experience. Taught all levels successfully, general, exam and specialised.",'b4l-profiling-grid-for-teachers')
)
),
"core_competencies" => array(
"mks" => array(
11 => __("Sensitisation to learning theories and features of language. Familiarity with a limited range of techniques and materials for one or two levels.",'b4l-profiling-grid-for-teachers'),
21 => __("Basic understanding of learning theories and features of language. Familiarity with techniques and materials for 2+ levels. Select new techniques & materials with advice from colleagues.",'b4l-profiling-grid-for-teachers'),
31 => __("Familiarity with theories of language learning and with learning styles. Familiarity with an expanding range of techniques and materials. Choose which to apply based on the needs of a particular group. Evaluate usefulness of techniques and materials in teaching context.",'b4l-profiling-grid-for-teachers'),
41 => __("Familiarity with learning theory, learning styles and learning strategies. Identify the theoretical rationale behind a wide range of techniques and materials, with which familiar. Evaluate appropriateness of techniques and materials in different teaching situations.",'b4l-profiling-grid-for-teachers'),
51 => __("Good familiarity with teaching approaches, learning styles, strategies. Provide theoretical rationale for teaching approach and for a very wide range of techniques / materials. Evaluate materials effectively from practical and theoretical perspectives.",'b4l-profiling-grid-for-teachers'),
61 => __("Detailed knowledge of theories of language and learning. Select an optimum combination of techniques to suit each type of learner and learning situation & provide clear theoretical rationale for decisions.",'b4l-profiling-grid-for-teachers')
),
"lcp" => array(
11 => __("Work with lesson plans in teachers’ notes to published materials.",'b4l-profiling-grid-for-teachers'),
21 => __("Use published or in-house materials to develop plans for different types of lessons. Plan phases and timing of various lesson types.",'b4l-profiling-grid-for-teachers'),
31 => __("Use a syllabus and specified materials to prepare lesson plans that are well-balanced and meet the needs of the group;. Adjust these plans as required. Take account of lesson outcomes in planning next lesson.",'b4l-profiling-grid-for-teachers'),
41 => __("Analyse individual learners’ needs in detail, including learning-to-learn. Plan clear main and supplementary objectives for lessons. Provide a rationale for lesson stages. Select/design supplementary activities. Ensure lesson-to-lesson coherence.",'b4l-profiling-grid-for-teachers'),
51 => __("Plan a balanced, varied scheme of work for a module based on detailed needs analysis. Design tasks to exploit linguistic and communicative potential of materials. Design multi-level tasks to meet individual needs and lesson objectives.",'b4l-profiling-grid-for-teachers'),
61 => __("Plan an entire course with recycling and revision. Create or select appropriate activities for balanced learning modules with communicative and linguistic content. Design multi-level tasks to meet individual needs and lesson objectives.",'b4l-profiling-grid-for-teachers')
),
"imm" => array(
11 => __("Alternate between whole class teaching and pair practice following suggestions in a teachers’ guide.",'b4l-profiling-grid-for-teachers'),
21 => __("Manage teacher-class interaction effectively. Give clear instructions for pair and group work. Monitor the resulting activity. Give clear feedback.",'b4l-profiling-grid-for-teachers'),
31 => __("Set up pairs and groups efficiently. Ensure all learners are involved in productive pair and group work. Monitor performance at all times. Bring the class back together and manage feedback.",'b4l-profiling-grid-for-teachers'),
41 => __("Set up a varied and balanced sequence of class, group and pair work appropriate to the lesson objectives. Monitor individual and group work effectively providing or eliciting appropriate feedback.",'b4l-profiling-grid-for-teachers'),
51 => __("Set up group interaction focused on multiple learning objectives. Monitor individual and group performances accurately and thoroughly. Give various forms of relevant individual feedback.",'b4l-profiling-grid-for-teachers'),
61 => __("Facilitate task-based learning. Manage learner-centred, multi-level group work. Derive appropriate action points from monitoring and analysis of the interaction.",'b4l-profiling-grid-for-teachers')
),
"ast" => array(
11 => __("Supervise and mark class quizzes and progress tests.",'b4l-profiling-grid-for-teachers'),
21 => __("Supervise and mark tests. Write a class quiz or revision activity to revise recent work.",'b4l-profiling-grid-for-teachers'),
31 => __("Select suitable progress tests and set up and supervise them. Use the results and simple oral and written tasks to assess learners’ progress and things to work on. Use a homework marking code to increase language awareness.",'b4l-profiling-grid-for-teachers'),
41 => __("Conduct tests and interviews if given material to do so. Train learners to code their errors to increase language awareness. Design or select appropriate quizzes, revision activities, and progress tests. CEFR standardisation experience.",'b4l-profiling-grid-for-teachers'),
51 => __("Coordinate placement testing and progress assessment (oral & written). Use video & hw codes to help learners recognise strengths / weaknesses. Use CEFR criteria reliably to assess spoken and written proficiency.",'b4l-profiling-grid-for-teachers'),
61 => __("Write progress tests. Develop assessment tasks. Run CEFR standardisation sessions. Use video & hw codes to help learners recognise strengths / weaknesses. Use CEFR criteria reliably to assess spoken and written proficiency.",'b4l-profiling-grid-for-teachers')
)
),
"complementary_skills" => array(
"td" => array(
11 => __("Take part in training sessions. Cooperate with colleagues with set tasks. Regularly observe real teaching.",'b4l-profiling-grid-for-teachers'),
21 => __("Take an active part in group work during training. Liaise well with other teachers. Observe & team-teach with teachers at restricted levels. Act on observation feedback.",'b4l-profiling-grid-for-teachers'),
31 => __("Take an active part in various kindsof in-service training/development. Actively seek advice from colleagues and relevant books. Observe colleagues at various levels. Act on colleagues’ feedback on serial observations of own teaching.",'b4l-profiling-grid-for-teachers'),
41 => __("Develop awareness and competence through professional reading. Lead discussions sometimes and exchange ideas about materials and techniques. Seek opportunities to be observed and receive feedback on own teaching.",'b4l-profiling-grid-for-teachers'),
51 => __("Act as mentor to less experienced colleagues. Lead a training session or even series of sessions given materials to use and distance support from a colleague. Seek opportunities for peerobservation.",'b4l-profiling-grid-for-teachers'),
61 => __("Create a series of training modules for less experienced teachers. Run a teacher CPD programme Take part in institutional or (inter) national projects. Observe colleagues and provide effective feedback.",'b4l-profiling-grid-for-teachers')
),
"dm" => array(
11 => __("Write a worksheet following conventions. Follow menus to operate software. Download from resource sites.",'b4l-profiling-grid-for-teachers'),
21 => __("Search effectively for material on the internet. Select and download from resource sites. Organize materials in hierarchically structured folders.",'b4l-profiling-grid-for-teachers'),
31 => __("Use data projectors for class lessons with internet, DVD etc. Use software for handling images, DVDs, sound files. Use a camcorder to record tasks. Set a class an exercise with CALL materials.",'b4l-profiling-grid-for-teachers'),
41 => __("Create lessons with downloaded texts, pictures, graphics, etc. Devise tasks using internet-based media such as wikis, blogs, webquests. Set & supervise individual CALL work. Coordinate project work with media (camcorder, internet downloads etc).",'b4l-profiling-grid-for-teachers'),
51=> __("Use PowerPoint for presentations, including animation. Train students to select and use CALL exercises effectively. Use authoring program to create CALL. Troubleshoot with basic equipment (e.g. data projector, printer).",'b4l-profiling-grid-for-teachers'),
61 => __("Show colleagues how to use new soft/hardware, incl. authoring programs. Design blended learning modules. Use any standard Windows software, including media, video editing. Troubleshoot hardware.",'b4l-profiling-grid-for-teachers')
)
)
);
?>
<p>
<?php
_e("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",'b4l-profiling-grid-for-teachers');
?>
</p>
<!-- Level aquired for each section -->
<div id="result_content">
<center><h1><?php _e('Current Result','b4l-profiling-grid-for-teachers'); ?></h1></center>
<?php
echo __("Language level : ",'b4l-profiling-grid-for-teachers') . get_language_level($post, $value) . "<br>";
echo __("Qualifications level : ",'b4l-profiling-grid-for-teachers') . get_qualifications_level($post, $value) . "<br>";
echo __("Core Competencies level : ",'b4l-profiling-grid-for-teachers') . get_core_competencies_level($post, $value) . "<br>";
echo __("Complementary Skills level : ",'b4l-profiling-grid-for-teachers') . get_complementary_skills_level($post, $value) . "<br>";
?>
</div>
<div id="error-content">
</div>
<script>
jQuery(document).ready(function(jQuery) {
jQuery('#tabs').tabs();
jQuery(".nav-tab").click(function(){
jQuery(".nav-tab").removeClass("nav-tab-active");
jQuery(this).addClass("nav-tab-active");
});
});
</script>
<!-- Form to update the passport (display the content above) -->
<form action="" id="save-teacher-form" method="POST">
<div id="tabs" style="border: 0px;">
<h2 class="nav-tab-wrapper">
<ul id="passport-list">
<li style="border: 0px;"><a href="#tabs-1" class="nav-tab nav-tab-active"><?php _e( 'Language','b4l-portofolio' ); ?></a></li>
<li style="border: 0px;"><a href="#tabs-2" class="nav-tab"><?php _e( 'Qualifications','b4l-portofolio' ); ?></a></li>
<li style="border: 0px;"><a href="#tabs-3" class="nav-tab"><?php _e( 'Core Competencies','b4l-portofolio' ); ?></a></li>
<li style="border: 0px;"><a href="#tabs-4" class="nav-tab"><?php _e( 'Complementary Skills','b4l-portofolio' ); ?></a></li>
</ul>
</h2>
<div id="tabs-1" style="border: 0px;">
<input type="hidden" id="post_ID" value="<?php echo $post->ID; ?>"/>
<br>
<b>● <?php _e('Language Proficiency','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["language"]["lp"]); $i++){
echo '<br>' . '<input type="checkbox" name="teacher_portfolio[]" id="lp'.$counter_lp.'" value="'.$value.$counter.'" style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["language"]["lp"][$i+1 . 1]. '</br>';
$counter++;
$counter_lp++;
}
?>
<br>
<b>● <?php _e('Language Awareness','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["language"]["la"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="la'.$counter_la.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["language"]["la"][$i+1 . 1]. '</br>';
$counter++;
$counter_la++;
}
?>
<br>
<?php _e('Evidence :','b4l-profiling-grid-for-teachers'); ?>
<?php
//If a file is already uploaded we allow the user to show the evidence or to delete it
if(get_post_meta($post->ID,'file_tab_a',true)){
echo get_post_meta($post->ID,'file_tab_a',true);
?>
<br>
<div style="margin-top: 5px;">
<!-- Show the evidence (by clickin, open the file in a new tab) -->
<input id="show_evidence" type="button" class="button button-small" value="Show Evidence" onclick="window.open('<?php echo content_url() . '/uploads/profiling-grids/teacher-files/' . get_current_user_id() . '/' . get_post_meta($post->ID,'file_tab_a',true) . ''; ?>')"/>
<!-- Delete the evidence (delete the file on the server) -->
<input id="delete_evidence_button" name="file_tab_a" type="button" class="button button-small" value="<?php _e('Delete Evidence','b4l-profiling-grid-for-teachers'); ?>" style="background-color: #d62121;" />
<div id="result_delete_evidence">
</div>
</div>
<?php
}
//IF not, we allow the user to upload a file
else{ ?>
<input name="file_tab_a" id="evidence" accept=".pdf, .png, .jpeg, .jpg" type="file"/>
<div id="error_content">
</div>
<div id="result_upload_files" style="margin-top: 10px;">
<input id="upload_files_button" name="file_tab_a" type="button" class="button button-small" value="<?php _e('Upload file','b4l-profiling-grid-for-teachers'); ?>" />
</div>
<?php
}
?>
</div>
<div id="tabs-2" style="border: 0px;">
<br>
<b>● <?php _e('Language Teacher Qualifications','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["qualifications"]["ltq"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="ltq'.$counter_ltq.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["qualifications"]["ltq"][$i+1 . 1]. '</br>';
$counter++;
$counter_ltq++;
}
?>
<br>
<b>● <?php _e('Language Teaching Practice','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["qualifications"]["ltp"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="ltp'.$counter_ltp.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["qualifications"]["ltp"][$i+1 . 1]. '</br>';
$counter++;
$counter_ltp++;
}
?>
<br>
<b>● <?php _e('Teaching Experience','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["qualifications"]["te"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="te'.$counter_te.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["qualifications"]["te"][$i+1 . 1]. '</br>';
$counter++;
$counter_te++;
}
?>
<br>
<?php _e('Evidence :','b4l-profiling-grid-for-teachers'); ?>
<?php
if(get_post_meta($post->ID,'file_tab_b',true)){
echo get_post_meta($post->ID,'file_tab_b',true);
?>
<br>
<div style="margin-top: 5px;">
<input id="show_evidence" type="button" class="button button-small" value="Show Evidence" onclick="window.open('<?php echo content_url() . '/uploads/profiling-grids/teacher-files/' . get_current_user_id() . '/' . get_post_meta($post->ID,'file_tab_b',true) . ''; ?>')"/>
<input id="delete_evidence_button" name="file_tab_b" type="button" class="button button-small" value="Delete Evidence" />
<div id="result_delete_evidence">
</div>
</div>
<?php
} else{ ?>
<input name="file_tab_b" id="evidence" accept=".pdf, .png, .jpeg, .jpg" type="file"/>
<div id="error_content">
</div>
<div id="result_upload_files" style="margin-top: 10px;">
<input id="upload_files_button" name="file_tab_b" type="button" class="button button-small" value="<?php _e('Upload file','b4l-profiling-grid-for-teachers'); ?>" />
</div>
<?php
}
?>
</div>
<div id="tabs-3" style="border: 0px;">
<br>
<b>● <?php _e('Methodology: knowledge and skills','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["core_competencies"]["mks"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="mks'.$counter_mks.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["core_competencies"]["mks"][$i+1 . 1]. '</br>';
$counter++;
$counter_mks++;
}
?>
<br>
<b>● <?php _e('Lesson and Course Planning','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["core_competencies"]["lcp"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="lcp'.$counter_lcp.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["core_competencies"]["lcp"][$i+1 . 1]. '</br>';
$counter++;
$counter_lcp++;
}
?>
<br>
<b>● <?php _e('Interaction Management and Monitoring','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["core_competencies"]["imm"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="imm'.$counter_imm.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["core_competencies"]["imm"][$i+1 . 1]. '</br>';
$counter++;
$counter_imm++;
}
?>
<br>
<b>● <?php _e('Assessment','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["core_competencies"]["ast"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="ast'.$counter_ast.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["core_competencies"]["ast"][$i+1 . 1]. '</br>';
$counter++;
$counter_ast++;
}
?>
<br>
Evidence :
<?php
if(get_post_meta($post->ID,'file_tab_c',true)){
echo get_post_meta($post->ID,'file_tab_c',true);
?>
<br>
<div style="margin-top: 5px;">
<input id="show_evidence" type="button" class="button button-small" value="Show Evidence" onclick="window.open('<?php echo content_url() . '/uploads/profiling-grids/teacher-files/' . get_current_user_id() . '/' . get_post_meta($post->ID,'file_tab_c',true) . ''; ?>')"/>
<input id="delete_evidence_button" name="file_tab_c" type="button" class="button button-small" value="Delete Evidence" />
<div id="result_delete_evidence">
</div>
</div>
<?php
} else{ ?>
<input name="file_tab_c" id="evidence" accept=".pdf, .png, .jpeg, .jpg" type="file"/>
<div id="error_content">
</div>
<div id="result_upload_files" style="margin-top: 10px;">
<input id="upload_files_button" name="file_tab_c" type="button" class="button button-small" value="<?php _e('Upload file','b4l-profiling-grid-for-teachers'); ?>" />
</div>
<?php
}
?>
</div>
<div id="tabs-4" style="border: 0px;">
<br>
<b>● <?php _e('Teacher Development','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["complementary_skills"]["td"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="td'.$counter_td.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '> ' . $t_portfolio["complementary_skills"]["td"][$i+1 . 1]. '</br>';
$counter++;
$counter_td++;
}
?>
<br>
<b>● <?php _e('Digital Media','b4l-profiling-grid-for-teachers'); ?> </b><br>
<?php
for($i = 0 ; $i < count($t_portfolio["complementary_skills"]["dm"]); $i++){
echo '<br>'. '<input type="checkbox" name="teacher_portfolio[]" id="dm'.$counter_dm.'" value="'.$value.$counter.'"style="margin-left: 30px;" ' . check_teacher($value.$counter) . '>' . $t_portfolio["complementary_skills"]["dm"][$i+1 . 1]. '</br>';
$counter++;
$counter_dm++;
}
?>
<br>
<?php _e('Evidence :','b4l-profiling-grid-for-teachers'); ?>
<?php
if(get_post_meta($post->ID,'file_tab_d',true)){
echo get_post_meta($post->ID,'file_tab_d',true);
?>
<br>
<div style="margin-top: 5px;">
<input id="show_evidence" type="button" class="button button-small" value="Show Evidence" onclick="window.open('<?php echo content_url() . '/uploads/profiling-grids/teacher-files/' . get_current_user_id() . '/' . get_post_meta($post->ID,'file_tab_d',true) . ''; ?>')"/>
<input id="delete_evidence_button" name="file_tab_d" type="button" class="button button-small" value="Delete Evidence" />
<div id="result_delete_evidence">
</div>
</div>
<?php
} else{ ?>
<input name="file_tab_d" id="evidence" accept=".pdf, .png, .jpeg, .jpg" type="file"/>
<div id="error_content">
</div>
<div id="result_upload_files" style="margin-top: 10px;">
<input id="upload_files_button" name="file_tab_d" type="button" class="button button-small" value="<?php _e('Upload file','b4l-profiling-grid-for-teachers'); ?>" />
</div>
<?php
}
?>
</div>
</div>
<input type="hidden" name="postID" id="postID" value="<?php echo $post->ID; ?>" />
<button type="submit" class="button button-small passport-save-button">Save Portfolio</button>
</form>
<!-- Delete a profiling grid form (just a button) -->
<form action="" id="delete-teacher-PG-form" method="POST">
<input type="hidden" name="postID" id="postID" value="<?php echo $post->ID; ?>" />
<button type="submit" class="button button-small passport-delete-button">Delete Profiling Grid</button>
</form>
</div>
<!-- Change the PG thumbnail form -->
<div id="portfolio-cover" style="margin-top: 120px;">
<h3>Profiling grid's cover</h3>
<form action="" id="thumbnail-PG-form" method="POST">
<input type="hidden" name="postID" id="postID" value="<?php echo $post->ID; ?>" />
<input id="thumbnail" accept=".png, .jpeg, .jpg" type="file"/>
<button type="submit" class="button button-small">Change profiling grid's image</button>
<?php
if( has_post_thumbnail() ){
global $wpdb;
$the_thumbnail_id = get_post_thumbnail_id($post->ID);
$the_thumbnail_name = $wpdb->get_var( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$the_thumbnail_id' AND meta_key = '_wp_attached_file'" );
?>
<input type="hidden" name="thumbnail_name" id="thumbnail_name" value="<?php echo $the_thumbnail_name; ?>" />
<input type="hidden" name="thumbnail_id" id="thumbnail_id" value="<?php echo $the_thumbnail_id; ?>" />
<input id="delete_thumbnail_button" type="button" style="background-color: #d62121;" class="button button-small" value="Delete cover" />
<?php
}
?>
</form>
<div id="result_upload_thumbnail">
</div>
</div>
</article><!-- #post-## -->
<?php endwhile; ?>
</main>
</div>
</div>
<?php get_footer(); ?>
| {
"content_hash": "ecae0f27993b95b607496e31be07a85c",
"timestamp": "",
"source": "github",
"line_count": 544,
"max_line_length": 327,
"avg_line_length": 59.887867647058826,
"alnum_prop": 0.6109150065993432,
"repo_name": "Badges4Languages/B4L-Listify-Child",
"id": "fcd5d26f356dfed3f4637e412179adc2f0e4c8f4",
"size": "32591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "single-teacher_portfolio.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33175"
},
{
"name": "JavaScript",
"bytes": "1808"
},
{
"name": "PHP",
"bytes": "98289"
}
],
"symlink_target": ""
} |
thrift -out server --gen py tthrift/tclog.thrift
thrift -out client/clog_client --gen py tthrift/tclog.thrift
| {
"content_hash": "38c3da68c2d7e5264692148bdd26a61f",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 60,
"avg_line_length": 55,
"alnum_prop": 0.7818181818181819,
"repo_name": "iamsudip/he-clog",
"id": "6ba1f586324a5e1d786c80515c220797805a430d",
"size": "110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build_thrift_classes.sh",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "13016"
},
{
"name": "Shell",
"bytes": "110"
},
{
"name": "Thrift",
"bytes": "72"
}
],
"symlink_target": ""
} |
/*
-- clMAGMA (version 1.3.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date November 2014
@precisions normal z -> s d c
*/
#include "common_magma.h"
/* ////////////////////////////////////////////////////////////////////////////
-- Auxiliary function: 'a' is pointer to the current panel holding the
Householder vectors for the QR factorization of the panel. This routine
puts ones on the diagonal and zeros in the upper triangular part of 'a'.
The upper triangular values are stored in work.
Then, the inverse is calculated in place in work, so as a final result,
work holds the inverse of the upper triangular diagonal block.
*/
void zsplit_diag_block(magma_int_t ib, magmaDoubleComplex *a, magma_int_t lda, magmaDoubleComplex *work)
{
magma_int_t i, j, info;
magmaDoubleComplex *cola, *colw;
magmaDoubleComplex c_zero = MAGMA_Z_ZERO;
magmaDoubleComplex c_one = MAGMA_Z_ONE;
for(i=0; i<ib; i++){
cola = a + i*lda;
colw = work + i*ib;
for(j=0; j<i; j++){
colw[j] = cola[j];
cola[j] = c_zero;
}
colw[i] = cola[i];
cola[i] = c_one;
}
lapackf77_ztrtri( MagmaUpperStr, MagmaNonUnitStr, &ib, work, &ib, &info);
}
extern "C" magma_int_t
magma_zgeqrf_gpu(
magma_int_t m, magma_int_t n,
magmaDoubleComplex_ptr dA, size_t dA_offset, magma_int_t ldda,
magmaDoubleComplex *tau, magmaDoubleComplex_ptr dT, size_t dT_offset,
magma_queue_t queue,
magma_int_t *info)
{
/* -- clMAGMA (version 1.3.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date November 2014
Purpose
=======
ZGEQRF computes a QR factorization of a complex M-by-N matrix A:
A = Q * R.
This version stores the triangular dT matrices used in
the block QR factorization so that they can be applied directly (i.e.,
without being recomputed) later. As a result, the application
of Q is much faster. Also, the upper triangular matrices for V have 0s
in them. The corresponding parts of the upper triangular R are inverted
and stored separately in dT.
Arguments
=========
M (input) INTEGER
The number of rows of the matrix A. M >= 0.
N (input) INTEGER
The number of columns of the matrix A. N >= 0.
dA (input/output) COMPLEX_16 array on the GPU, dimension (LDDA,N)
On entry, the M-by-N matrix A.
On exit, the elements on and above the diagonal of the array
contain the min(M,N)-by-N upper trapezoidal matrix R (R is
upper triangular if m >= n); the elements below the diagonal,
with the array TAU, represent the orthogonal matrix Q as a
product of min(m,n) elementary reflectors (see Further
Details).
LDDA (input) INTEGER
The leading dimension of the array dA. LDDA >= max(1,M).
To benefit from coalescent memory accesses LDDA must be
divisible by 16.
TAU (output) COMPLEX_16 array, dimension (min(M,N))
The scalar factors of the elementary reflectors (see Further
Details).
dT (workspace/output) COMPLEX_16 array on the GPU,
dimension (2*MIN(M, N) + (N+31)/32*32 )*NB,
where NB can be obtained through magma_get_zgeqrf_nb(M).
It starts with MIN(M,N)*NB block that store the triangular T
matrices, followed by the MIN(M,N)*NB block of the diagonal
inverses for the R matrix. The rest of the array is used as workspace.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
or another error occured, such as memory allocation failed.
Further Details
===============
The matrix Q is represented as a product of elementary reflectors
Q = H(1) H(2) . . . H(k), where k = min(m,n).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a complex scalar, and v is a complex vector with
v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i),
and tau in TAU(i).
===================================================================== */
#define a_ref(a_1,a_2) dA, (dA_offset + (a_1) + (a_2)*(ldda))
#define t_ref(a_1) dT, (dT_offset + (a_1)*nb)
#define d_ref(a_1) dT, (dT_offset + (minmn + (a_1))*nb)
#define dd_ref(a_1) dT, (dT_offset + (2*minmn+(a_1))*nb)
#define work_ref(a_1) ( work + (a_1))
#define hwork ( work + (nb)*(m))
magma_int_t i, k, minmn, old_i, old_ib, rows, cols;
magma_int_t ib, nb;
magma_int_t ldwork, lddwork, lwork, lhwork;
magmaDoubleComplex *work, *ut;
/* check arguments */
*info = 0;
if (m < 0) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (ldda < max(1,m)) {
*info = -4;
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
k = minmn = min(m,n);
if (k == 0)
return *info;
nb = magma_get_zgeqrf_nb(m);
lwork = (m + n + nb)*nb;
lhwork = lwork - m*nb;
if (MAGMA_SUCCESS != magma_zmalloc_cpu( &work, lwork )) {
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
ut = hwork+nb*(n);
memset( ut, 0, nb*nb*sizeof(magmaDoubleComplex));
magma_event_t event[2] = {NULL, NULL};
ldwork = m;
lddwork= n;
if ( (nb > 1) && (nb < k) ) {
/* Use blocked code initially */
old_i = 0; old_ib = nb;
for (i = 0; i < k-nb; i += nb) {
ib = min(k-i, nb);
rows = m -i;
magma_zgetmatrix_async( rows, ib,
a_ref(i,i), ldda,
work_ref(i), ldwork, queue, &event[1] );
if (i>0){
/* Apply H' to A(i:m,i+2*ib:n) from the left */
cols = n-old_i-2*old_ib;
magma_zlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise,
m-old_i, cols, old_ib,
a_ref(old_i, old_i ), ldda, t_ref(old_i), nb,
a_ref(old_i, old_i+2*old_ib), ldda, dd_ref(0), lddwork, queue);
/* store the diagonal */
magma_zsetmatrix_async( old_ib, old_ib,
ut, old_ib,
d_ref(old_i), old_ib, queue, &event[0] );
}
magma_event_sync(event[1]);
lapackf77_zgeqrf(&rows, &ib, work_ref(i), &ldwork, tau+i, hwork, &lhwork, info);
/* Form the triangular factor of the block reflector
H = H(i) H(i+1) . . . H(i+ib-1) */
lapackf77_zlarft( MagmaForwardStr, MagmaColumnwiseStr,
&rows, &ib,
work_ref(i), &ldwork, tau+i, hwork, &ib);
/* Put 0s in the upper triangular part of a panel (and 1s on the
diagonal); copy the upper triangular in ut and invert it. */
magma_event_sync(event[0]);
zsplit_diag_block(ib, work_ref(i), ldwork, ut);
magma_zsetmatrix( rows, ib, work_ref(i), ldwork, a_ref(i,i), ldda, queue);
if (i + ib < n) {
/* Send the triangular factor T to the GPU */
magma_zsetmatrix( ib, ib, hwork, ib, t_ref(i), nb, queue );
if (i+nb < k-nb){
/* Apply H' to A(i:m,i+ib:i+2*ib) from the left */
magma_zlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise,
rows, ib, ib,
a_ref(i, i ), ldda, t_ref(i), nb,
a_ref(i, i+ib), ldda, dd_ref(0), lddwork, queue);
}
else {
cols = n-i-ib;
magma_zlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise,
rows, cols, ib,
a_ref(i, i ), ldda, t_ref(i), nb,
a_ref(i, i+ib), ldda, dd_ref(0), lddwork, queue);
/* Fix the diagonal block */
magma_zsetmatrix( ib, ib, ut, ib, d_ref(i), ib , queue);
}
old_i = i;
old_ib = ib;
}
}
} else {
i = 0;
}
/* Use unblocked code to factor the last or only block. */
if (i < k) {
ib = n-i;
rows = m-i;
magma_zgetmatrix( rows, ib, a_ref(i, i), ldda, work, rows, queue );
lhwork = lwork - rows*ib;
lapackf77_zgeqrf(&rows, &ib, work, &rows, tau+i, work+ib*rows, &lhwork, info);
magma_zsetmatrix( rows, ib, work, rows, a_ref(i, i), ldda, queue );
}
magma_free_cpu( work );
return *info;
} /* magma_zgeqrf_gpu */
#undef a_ref
#undef t_ref
#undef d_ref
#undef work_ref
| {
"content_hash": "bfee0bcf841e0c53e78baee15169873a",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 104,
"avg_line_length": 37.16334661354582,
"alnum_prop": 0.5060034305317325,
"repo_name": "kjbartel/clmagma",
"id": "e680d49fca8a8109ff765bd883dd311d2b582c2f",
"size": "9328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/zgeqrf_gpu.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "778871"
},
{
"name": "C++",
"bytes": "5002432"
},
{
"name": "FORTRAN",
"bytes": "6995114"
},
{
"name": "Makefile",
"bytes": "27473"
},
{
"name": "Python",
"bytes": "35170"
},
{
"name": "Shell",
"bytes": "3001"
}
],
"symlink_target": ""
} |
package com.orientechnologies.orient.core.sql.operator;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
import com.orientechnologies.orient.core.index.OIndexInternal;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemParameter;
/**
* EQUALS operator.
*
* @author Luca Garulli
*
*/
public class OQueryOperatorEquals extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorEquals() {
super("=", 5, false);
}
@Override
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
return equals(iLeft, iRight);
}
public static boolean equals(final Object iLeft, final Object iRight) {
if (iLeft instanceof ORecord<?>) {
// RECORD & ORID
return comparesValues(iRight, (ORecord<?>) iLeft);
} else if (iRight instanceof ORecord<?>) {
return comparesValues(iLeft, (ORecord<?>) iRight);
}
// ALL OTHER CASES
final Object right = OType.convert(iRight, iLeft.getClass());
if (right == null)
return false;
return iLeft.equals(right);
}
protected static boolean comparesValues(final Object iValue, final ORecord<?> iRecord) {
// ORID && RECORD
final ORID other = ((ORecord<?>) iRecord).getIdentity();
if (!other.isPersistent() && iRecord instanceof ODocument) {
// ODOCUMENT AS RESULT OF SUB-QUERY: GET THE FIRST FIELD IF ANY
final String[] firstFieldName = ((ODocument) iRecord).fieldNames();
if (firstFieldName.length > 0) {
Object fieldValue = ((ODocument) iRecord).field(firstFieldName[0]);
if (fieldValue != null)
return fieldValue.equals(iValue);
}
return false;
}
return other.equals(iValue);
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
if (iLeft instanceof OIdentifiable && iRight instanceof OIdentifiable)
return OIndexReuseType.NO_INDEX;
if (iRight == null || iLeft == null)
return OIndexReuseType.NO_INDEX;
return OIndexReuseType.INDEX_METHOD;
}
@SuppressWarnings("unchecked")
@Override
public Object executeIndexQuery(OIndex<?> index, final INDEX_OPERATION_TYPE iOperationType, List<Object> keyParams, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators())
return null;
if (indexDefinition.getParamCount() == 1) {
final Object key;
if (indexDefinition instanceof OIndexDefinitionMultiValue)
key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
else
key = indexDefinition.createValue(keyParams);
if (key == null)
return null;
final Object indexResult;
if (iOperationType == INDEX_OPERATION_TYPE.GET)
indexResult = index.get(key);
else
indexResult = index.count(key);
if (indexResult instanceof Collection)
return (Collection<OIdentifiable>) indexResult;
if (indexResult == null)
return Collections.emptyList();
else if (indexResult instanceof Collection<?>)
return Collections.singletonList((OIdentifiable) indexResult);
else
return indexResult;
} else {
// in case of composite keys several items can be returned in case of we perform search
// using part of composite key stored in index.
final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
final Collection<OIdentifiable> result;
if (fetchLimit > -1)
result = index.getValuesBetween(keyOne, true, keyTwo, true, fetchLimit);
else
result = index.getValuesBetween(keyOne, true, keyTwo, true);
updateProfiler(index, keyParams, indexDefinition);
return result;
}
}
@Override
public ORID getBeginRidRange(final Object iLeft, final Object iRight) {
if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot()))
if (iRight instanceof ORID)
return (ORID) iRight;
else {
if (iRight instanceof OSQLFilterItemParameter && ((OSQLFilterItemParameter) iRight).getValue(null, null) instanceof ORID)
return (ORID) ((OSQLFilterItemParameter) iRight).getValue(null, null);
}
if (iRight instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iRight).getRoot()))
if (iLeft instanceof ORID)
return (ORID) iLeft;
else {
if (iLeft instanceof OSQLFilterItemParameter && ((OSQLFilterItemParameter) iLeft).getValue(null, null) instanceof ORID)
return (ORID) ((OSQLFilterItemParameter) iLeft).getValue(null, null);
}
return null;
}
@Override
public ORID getEndRidRange(final Object iLeft, final Object iRight) {
return getBeginRidRange(iLeft, iRight);
}
}
| {
"content_hash": "6c025cefd26a9724c0221044c13f5b49",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 135,
"avg_line_length": 37.16374269005848,
"alnum_prop": 0.7024390243902439,
"repo_name": "wuman/orientdb-android",
"id": "bad3272c8175ffe89d8b9307622112db28a975df",
"size": "7008",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3916612"
},
{
"name": "Shell",
"bytes": "714"
}
],
"symlink_target": ""
} |
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exam.Models
{
public class ApplicationUser : User
{
}
}
| {
"content_hash": "d897d8755c2318c925e6480523b94cbe",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 49,
"avg_line_length": 17.571428571428573,
"alnum_prop": 0.7601626016260162,
"repo_name": "niki-funky/Telerik_Academy",
"id": "61bceb9f7e94d3657b0ef3f58f7489706031a4d2",
"size": "248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Web Development/ASP.NET MVC/--Exam--/Exam.Models/ApplicationUser.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "2773"
},
{
"name": "C#",
"bytes": "4074086"
},
{
"name": "CSS",
"bytes": "850276"
},
{
"name": "JavaScript",
"bytes": "5915582"
},
{
"name": "PowerShell",
"bytes": "785001"
},
{
"name": "Puppet",
"bytes": "329334"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>NcmSplineRBF: NumCosmo Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" />
<link rel="home" href="index.html" title="NumCosmo Reference Manual" />
<link rel="up" href="ch02s05.html" title="Splines 1D" />
<link rel="prev" href="NcmSplineCubicNotaknot.html" title="NcmSplineCubicNotaknot" />
<link rel="next" href="numcosmo-NcmSplineFunc.html" title="NcmSplineFunc" />
<meta name="generator" content="GTK-Doc V1.33.1 (XML mode)" />
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" href="container.css" type="text/css" />
<script type="text/x-mathjax-config">
//<![CDATA[
MathJax.Hub.Config({"HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"], linebreaks: { automatic:true }, EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) },
tex2jax: { inlineMath: [ ["$", "$"], ["\\\\(","\\\\)"] ], displayMath: [ ["$$","$$"], ["\\[", "\\]"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" },
TeX: { noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } },
equationNumbers: { autoNumber: "AMS" } },
messageStyle: "none"
});
//]]>
</script>
<script type="text/javascript" async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_HTML">
</script>
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div id="container" class="gtk-doc"><div class="content">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="5"><tr valign="middle">
<td width="100%" align="left" class="shortcuts">
<a href="#" class="shortcut">Top</a><span id="nav_description"> <span class="dim">|</span>
<a href="#NcmSplineRBF.description" class="shortcut">Description</a></span><span id="nav_hierarchy"> <span class="dim">|</span>
<a href="#NcmSplineRBF.object-hierarchy" class="shortcut">Object Hierarchy</a></span><span id="nav_properties"> <span class="dim">|</span>
<a href="#NcmSplineRBF.properties" class="shortcut">Properties</a></span>
</td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home" /></a></td>
<td><a accesskey="u" href="ch02s05.html"><img src="up.png" width="16" height="16" border="0" alt="Up" /></a></td>
<td><a accesskey="p" href="NcmSplineCubicNotaknot.html"><img src="left.png" width="16" height="16" border="0" alt="Prev" /></a></td>
<td><a accesskey="n" href="numcosmo-NcmSplineFunc.html"><img src="right.png" width="16" height="16" border="0" alt="Next" /></a></td>
</tr></table>
<div class="refentry">
<a name="NcmSplineRBF" id="NcmSplineRBF"></a><div class="titlepage"></div>
<div class="refnamediv"><table width="100%"><tr>
<td valign="top">
<h2><span class="refentrytitle"><a name="NcmSplineRBF.top_of_page" id="NcmSplineRBF.top_of_page"></a>NcmSplineRBF</span></h2>
<p>NcmSplineRBF — Radial Basis Function implementation of spline class.</p>
</td>
<td class="gallery_image" valign="top" align="right"></td>
</tr></table></div>
<div class="refsect1">
<a name="NcmSplineRBF.stability-level" id="NcmSplineRBF.stability-level"></a><h2>Stability Level</h2>
<acronym title="Unstable interfaces are experimental or transitional. They are typically used to give outside developers early access to new or rapidly changing technology, or to provide an interim solution to a problem where a more general solution is anticipated. No claims are made about either source or binary compatibility from one minor release to the next. The Unstable interface level is a warning that these interfaces are subject to change without warning and should not be used in unbundled products. Given such caveats, customer impact need not be a factor when considering incompatible changes to an Unstable interface in a major or minor release. Nonetheless, when such changes are introduced, the changes should still be mentioned in the release notes for the affected release. "><span class="acronym">Unstable</span></acronym>, unless otherwise indicated
</div>
<div class="refsect1">
<a name="NcmSplineRBF.functions" id="NcmSplineRBF.functions"></a><h2>Functions</h2>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="functions_proto_type" />
<col class="functions_proto_name" />
</colgroup>
<tbody>
<tr>
<td class="function_type">
<a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="returnvalue">NcmSplineRBF</span></a> *
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-new" title="ncm_spline_rbf_new ()">ncm_spline_rbf_new</a> <span class="c_punctuation">()</span>
</td>
</tr>
<tr>
<td class="function_type">
<a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="returnvalue">NcmSplineRBF</span></a> *
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-ref" title="ncm_spline_rbf_ref ()">ncm_spline_rbf_ref</a> <span class="c_punctuation">()</span>
</td>
</tr>
<tr>
<td class="function_type">
<span class="returnvalue">void</span>
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-free" title="ncm_spline_rbf_free ()">ncm_spline_rbf_free</a> <span class="c_punctuation">()</span>
</td>
</tr>
<tr>
<td class="function_type">
<span class="returnvalue">void</span>
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-clear" title="ncm_spline_rbf_clear ()">ncm_spline_rbf_clear</a> <span class="c_punctuation">()</span>
</td>
</tr>
<tr>
<td class="function_type">
<span class="returnvalue">void</span>
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-set-type" title="ncm_spline_rbf_set_type ()">ncm_spline_rbf_set_type</a> <span class="c_punctuation">()</span>
</td>
</tr>
<tr>
<td class="function_type">
<span class="returnvalue">void</span>
</td>
<td class="function_name">
<a class="link" href="NcmSplineRBF.html#ncm-spline-rbf-set-shape-params" title="ncm_spline_rbf_set_shape_params ()">ncm_spline_rbf_set_shape_params</a> <span class="c_punctuation">()</span>
</td>
</tr>
</tbody>
</table></div>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.properties" id="NcmSplineRBF.properties"></a><h2>Properties</h2>
<div class="informaltable"><table class="informaltable" border="0">
<colgroup>
<col width="150px" class="properties_type" />
<col width="300px" class="properties_name" />
<col width="200px" class="properties_flags" />
</colgroup>
<tbody><tr>
<td class="property_type"><a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a></td>
<td class="property_name"><a class="link" href="NcmSplineRBF.html#NcmSplineRBF--type-id" title="The “type-id” property">type-id</a></td>
<td class="property_flags">Read / Write / Construct</td>
</tr></tbody>
</table></div>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.other" id="NcmSplineRBF.other"></a><h2>Types and Values</h2>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="other_proto_type" />
<col class="other_proto_name" />
</colgroup>
<tbody><tr>
<td class="datatype_keyword">enum</td>
<td class="function_name"><a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType">NcmSplineRBFType</a></td>
</tr></tbody>
</table></div>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.object-hierarchy" id="NcmSplineRBF.object-hierarchy"></a><h2>Object Hierarchy</h2>
<pre class="screen"> <a href="/usr/share/gtk-doc/html/gobject/gobject-Enumeration-and-Flag-Types.html">GEnum</a>
<span class="lineart">╰──</span> NcmSplineRBFType
<a href="/usr/share/gtk-doc/html/gobject/gobject-The-Base-Object-Type.html#GObject-struct">GObject</a>
<span class="lineart">╰──</span> <a class="link" href="NcmSpline.html" title="NcmSpline">NcmSpline</a>
<span class="lineart">╰──</span> NcmSplineRBF
</pre>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.includes" id="NcmSplineRBF.includes"></a><h2>Includes</h2>
<pre class="synopsis">#include <numcosmo/math/ncm_spline_rbf.h>
</pre>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.description" id="NcmSplineRBF.description"></a><h2>Description</h2>
<p>This object implements <a class="link" href="NcmSpline.html" title="NcmSpline"><span class="type">NcmSpline</span></a>, using <a class="ulink" href="https://en.wikipedia.org/wiki/Radial_basis_function" target="_top">Radial Basis Function (RBF)</a> methods.</p>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.functions_details" id="NcmSplineRBF.functions_details"></a><h2>Functions</h2>
<div class="refsect2">
<a name="ncm-spline-rbf-new" id="ncm-spline-rbf-new"></a><h3>ncm_spline_rbf_new ()</h3>
<pre class="programlisting"><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="returnvalue">NcmSplineRBF</span></a> *
ncm_spline_rbf_new (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a> type_id</code></em>);</pre>
<p>Creates a new RBF using <em class="parameter"><code>type_id</code></em>
.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-new.parameters" id="ncm-spline-rbf-new.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody><tr>
<td class="parameter_name"><p>type_id</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr></tbody>
</table></div>
</div>
<div class="refsect3">
<a name="ncm-spline-rbf-new.returns" id="ncm-spline-rbf-new.returns"></a><h4>Returns</h4>
<p>a newly created <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a>. </p>
<p><span class="annotation">[<acronym title="The caller owns the data, and is responsible for free it."><span class="acronym">transfer full</span></acronym>]</span></p>
</div>
</div>
<hr />
<div class="refsect2">
<a name="ncm-spline-rbf-ref" id="ncm-spline-rbf-ref"></a><h3>ncm_spline_rbf_ref ()</h3>
<pre class="programlisting"><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="returnvalue">NcmSplineRBF</span></a> *
ncm_spline_rbf_ref (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a> *rbf</code></em>);</pre>
<p>Increase the reference of <em class="parameter"><code>rbf</code></em>
by one.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-ref.parameters" id="ncm-spline-rbf-ref.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody><tr>
<td class="parameter_name"><p>rbf</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr></tbody>
</table></div>
</div>
<div class="refsect3">
<a name="ncm-spline-rbf-ref.returns" id="ncm-spline-rbf-ref.returns"></a><h4>Returns</h4>
<p><em class="parameter"><code>rbf</code></em>
. </p>
<p><span class="annotation">[<acronym title="The caller owns the data, and is responsible for free it."><span class="acronym">transfer full</span></acronym>]</span></p>
</div>
</div>
<hr />
<div class="refsect2">
<a name="ncm-spline-rbf-free" id="ncm-spline-rbf-free"></a><h3>ncm_spline_rbf_free ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span>
ncm_spline_rbf_free (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a> *rbf</code></em>);</pre>
<p>Decrease the reference count of <em class="parameter"><code>rbf</code></em>
by one.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-free.parameters" id="ncm-spline-rbf-free.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody><tr>
<td class="parameter_name"><p>rbf</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr></tbody>
</table></div>
</div>
</div>
<hr />
<div class="refsect2">
<a name="ncm-spline-rbf-clear" id="ncm-spline-rbf-clear"></a><h3>ncm_spline_rbf_clear ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span>
ncm_spline_rbf_clear (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a> **rbf</code></em>);</pre>
<p>Decrease the reference count of <em class="parameter"><code>rbf</code></em>
by one, and sets the pointer *<em class="parameter"><code>rbf</code></em>
to
NULL.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-clear.parameters" id="ncm-spline-rbf-clear.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody><tr>
<td class="parameter_name"><p>rbf</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr></tbody>
</table></div>
</div>
</div>
<hr />
<div class="refsect2">
<a name="ncm-spline-rbf-set-type" id="ncm-spline-rbf-set-type"></a><h3>ncm_spline_rbf_set_type ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span>
ncm_spline_rbf_set_type (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a> *rbf</code></em>,
<em class="parameter"><code><a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a> type_id</code></em>);</pre>
<p>Sets the RBF type function to <em class="parameter"><code>type_id</code></em>
.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-set-type.parameters" id="ncm-spline-rbf-set-type.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody>
<tr>
<td class="parameter_name"><p>rbf</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr>
<tr>
<td class="parameter_name"><p>type_id</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr>
</tbody>
</table></div>
</div>
</div>
<hr />
<div class="refsect2">
<a name="ncm-spline-rbf-set-shape-params" id="ncm-spline-rbf-set-shape-params"></a><h3>ncm_spline_rbf_set_shape_params ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span>
ncm_spline_rbf_set_shape_params (<em class="parameter"><code><a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a> *rbf</code></em>,
<em class="parameter"><code><a class="link" href="NcmVector.html" title="NcmVector"><span class="type">NcmVector</span></a> *shape_params</code></em>);</pre>
<p>Sets the RBF shape parameters to <em class="parameter"><code>shape_params</code></em>
.</p>
<div class="refsect3">
<a name="ncm-spline-rbf-set-shape-params.parameters" id="ncm-spline-rbf-set-shape-params.parameters"></a><h4>Parameters</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>
<tbody>
<tr>
<td class="parameter_name"><p>rbf</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html" title="NcmSplineRBF"><span class="type">NcmSplineRBF</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr>
<tr>
<td class="parameter_name"><p>shape_params</p></td>
<td class="parameter_description"><p>a <a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a></p></td>
<td class="parameter_annotations"> </td>
</tr>
</tbody>
</table></div>
</div>
</div>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.other_details" id="NcmSplineRBF.other_details"></a><h2>Types and Values</h2>
<div class="refsect2">
<a name="NcmSplineRBFType" id="NcmSplineRBFType"></a><h3>enum NcmSplineRBFType</h3>
<p>Enumeration to choose which Gaussian <a class="ulink" href="https://en.wikipedia.org/wiki/Radial_basis_function" target="_top">RBF</a> interpolation method to be applied by the object.</p>
<div class="refsect3">
<a name="NcmSplineRBFType.members" id="NcmSplineRBFType.members"></a><h4>Members</h4>
<div class="informaltable"><table class="informaltable" width="100%" border="0">
<colgroup>
<col width="300px" class="enum_members_name" />
<col class="enum_members_description" />
<col width="200px" class="enum_members_annotations" />
</colgroup>
<tbody>
<tr>
<td class="enum_member_name"><p><a name="NCM-SPLINE-RBF-TYPE-POSDEF-GAUSS:CAPS" id="NCM-SPLINE-RBF-TYPE-POSDEF-GAUSS:CAPS"></a>NCM_SPLINE_RBF_TYPE_POSDEF_GAUSS</p></td>
<td class="enum_member_description">
<p>Gaussian <a class="ulink" href="https://en.wikipedia.org/wiki/Radial_basis_function" target="_top">RBF</a> interpolation method for positive defined functions. </p>
</td>
<td class="enum_member_annotations"> </td>
</tr>
<tr>
<td class="enum_member_name"><p><a name="NCM-SPLINE-RBF-TYPE-GAUSS:CAPS" id="NCM-SPLINE-RBF-TYPE-GAUSS:CAPS"></a>NCM_SPLINE_RBF_TYPE_GAUSS</p></td>
<td class="enum_member_description">
<p>Gaussian <a class="ulink" href="https://en.wikipedia.org/wiki/Radial_basis_function" target="_top">RBF</a> interpolation method for any kind of function. </p>
</td>
<td class="enum_member_annotations"> </td>
</tr>
</tbody>
</table></div>
</div>
</div>
</div>
<div class="refsect1">
<a name="NcmSplineRBF.property-details" id="NcmSplineRBF.property-details"></a><h2>Property Details</h2>
<div class="refsect2">
<a name="NcmSplineRBF--type-id" id="NcmSplineRBF--type-id"></a><h3>The <code class="literal">“type-id”</code> property</h3>
<pre class="programlisting"> “type-id” <a class="link" href="NcmSplineRBF.html#NcmSplineRBFType" title="enum NcmSplineRBFType"><span class="type">NcmSplineRBFType</span></a></pre>
<p>The <a class="ulink" href="https://en.wikipedia.org/wiki/Radial_basis_function" target="_top">RBF</a> method to be applied by the object.</p>
<p>Owner: NcmSplineRBF</p>
<p>Flags: Read / Write / Construct</p>
<p>Default value: NCM_SPLINE_RBF_TYPE_POSDEF_GAUSS</p>
</div>
</div>
</div>
<div class="footer">
<hr />Generated by GTK-Doc V1.33.1</div>
</div></div></body>
</html>
| {
"content_hash": "c41ab39131484f72f36acd6133ad7cc7",
"timestamp": "",
"source": "github",
"line_count": 376,
"max_line_length": 926,
"avg_line_length": 54.92553191489362,
"alnum_prop": 0.6922816192136355,
"repo_name": "NumCosmo/NumCosmo.github.io",
"id": "b1bf7716b1c319770627c625306155c428196422",
"size": "20725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "manual/NcmSplineRBF.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "24198"
},
{
"name": "CSS",
"bytes": "34878"
},
{
"name": "HTML",
"bytes": "11859499"
},
{
"name": "JavaScript",
"bytes": "1095"
}
],
"symlink_target": ""
} |
@class GHCommits;
@interface IOCCommitsController : IOCCollectionController
- (id)initWithCommits:(GHCommits *)commits;
@end | {
"content_hash": "98f81a597734d8eebb63f3c81234d025",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 57,
"avg_line_length": 25,
"alnum_prop": 0.816,
"repo_name": "iCrany/ioctocat",
"id": "c91f38d8aa016f48e86be042e44993107d1f9b08",
"size": "162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/IOCCommitsController.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "7640"
},
{
"name": "Objective-C",
"bytes": "682549"
},
{
"name": "Perl",
"bytes": "1397"
},
{
"name": "Ruby",
"bytes": "6644"
},
{
"name": "Shell",
"bytes": "934"
}
],
"symlink_target": ""
} |
package com.sheplu.blackjack.test.card;
import static org.junit.Assert.*;
import org.junit.Test;
public class Card {
@Test
public void test() {
fail("Not yet implemented");
}
}
| {
"content_hash": "23a88a6b055b270a07b446e665ac8b58",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 39,
"avg_line_length": 13.357142857142858,
"alnum_prop": 0.7005347593582888,
"repo_name": "sheplu/BlackJack",
"id": "c91ea012cf60c44b82e449022497a6ba98c4afc0",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/sheplu/blackjack/test/card/Card.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "4322"
}
],
"symlink_target": ""
} |
import React from 'react';
import ReactDOM from 'react-dom';
import Dotdotdot from 'react-dotdotdot'
class App extends React.Component {
render() {
return (
<div>
<div>
This page is clamped version of: <a href="https://codepen.io/carolynmcneillie/pen/Lewxrm" target="_blank">Codepen</a>
<br />
Thanks to Carolyn McNeillie
</div>
<hr />
<p className="intro">
What CSS property do you use to set the colour of a text block? If you said <em>color</em> you were … wrong!
</p>
<p className="intro">
Don’t take it too hard, though. It was a trick question. In typographic parlance, “color” refers to the visual density of a block of text. Here's a little sandbox where you can play with some of the properties that impact typographic color.
</p>
<h1>Font Weight</h1>
<div className="wrapper">
<div className="font-weight small">
<h2>Light / clamp=3 useNativeClamp=false</h2>
<Dotdotdot
clamp={ 3 }
useNativeClamp={ false }
>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="font-weight medium">
<h2>Normal / clamp=7 useNativeClamp=true</h2>
<Dotdotdot clamp={ 7 } useNativeClamp={ true }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="font-weight large">
<h2>Heavy / clamp=7</h2>
<Dotdotdot clamp={ 7 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
</div>
<h1>Tracking</h1>
<div className="wrapper">
<div className="letter-spacing small">
<h2>Tight / clamp=5 useNativeClamp=false truncationChar="»"</h2>
<Dotdotdot clamp={ 5 } useNativeClamp={ false } truncationChar="»">
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="letter-spacing medium">
<h2>Normal / clamp=5 useNativeClamp=false truncationHTML="<br /><marquee>…</marquee>" truncationChar=""</h2>
<Dotdotdot clamp={ 5 } useNativeClamp={ false } truncationHTML="<br /><marquee>…</marquee>" truncationChar="">
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="letter-spacing large">
<h2>Wide / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
</div>
<h1>Word Spacing / clamp=3</h1>
<div className="wrapper">
<div className="word-spacing small">
<h2>Tight</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="word-spacing medium">
<h2>Normal / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="word-spacing large">
<h2>Wide / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
</div>
<h1>Ledding</h1>
<div className="wrapper">
<div className="line-height small">
<h2>Tight / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="line-height medium">
<h2>Normal / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="line-height large">
<h2>Double / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
</div>
<h1>Justification / clamp=3</h1>
<div className="wrapper">
<div className="left">
<h2>Ragged Right</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="justified">
<h2>Justified / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
<div className="justified-hyphen">
<h2>Justified with Hyphenation / clamp=3</h2>
<Dotdotdot clamp={ 3 }>
<p>
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.
</p>
</Dotdotdot>
</div>
</div>
</div>
);
}
}
ReactDOM.hydrate(<App />, document.querySelector('#app'));
| {
"content_hash": "fe2bfddc31639f3cc9f676a844492958",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 720,
"avg_line_length": 94.85975609756098,
"alnum_prop": 0.6667095198303015,
"repo_name": "CezaryDanielNowak/React-dotdotdot",
"id": "90ed79acebd7088990d934aa5a2f85dcc7b2f6f6",
"size": "15569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "11686"
}
],
"symlink_target": ""
} |
package com.wangyin.alarm.emit.impl;
import com.wangyin.alarm.emit.Sender;
import com.wangyin.alarm.third.EmailUtils;
import com.wangyin.alarm.third.SmsUtils;
import com.wangyin.common.Contact;
import com.wangyin.common.Message;
import com.wangyin.mq.IMQ;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wylipengming on 2014/7/26.
*/
@Component("smsSender")
public class SmsSender extends BaseSender{
public SmsSender() {
super();
}
@Override
protected void thirdSend(String content, String calling) {
SmsUtils.getInstance().sendMessage(content, calling);
}
}
| {
"content_hash": "ec3e146b0b8c037367a94c50966d4867",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 62,
"avg_line_length": 24.5,
"alnum_prop": 0.7510204081632653,
"repo_name": "cncduLee/alarm-platform",
"id": "f0d8f47b598e235046e1c783888951f248eee0f0",
"size": "735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "alarm-emit/src/main/java/com/wangyin/alarm/emit/impl/SmsSender.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "30975"
},
{
"name": "Shell",
"bytes": "8799"
}
],
"symlink_target": ""
} |
package ru.otus.l62.b1.command;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by tully.
*/
public class Main {
private Queue<Command> commandQueue = new ConcurrentLinkedQueue<>();
public static void main(String[] args) {
Main main = new Main();
main.addCommand(new Command2Receiver("Out 1", new Receiver()));
main.addCommand(new Command2Receiver("Out 2", new Receiver()));
main.processCommands();
}
// add in thread 1
private void addCommand(Command command) {
commandQueue.add(command);
}
// process in thread 2
// Invoker of the Command pattern.
private void processCommands() {
for (Command command : commandQueue) {
command.execute();
}
}
}
| {
"content_hash": "079a49d6e47ba9a2c363307d9c4bd126",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 72,
"avg_line_length": 24.393939393939394,
"alnum_prop": 0.6372670807453417,
"repo_name": "vitaly-chibrikov/otus_java_2017_06",
"id": "715be5aad99992fcf3cf78a8e5b942bd1455fc0b",
"size": "805",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "L6.2.1/src/main/java/ru/otus/l62/b1/command/Main.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "13227"
},
{
"name": "Java",
"bytes": "348805"
},
{
"name": "JavaScript",
"bytes": "1886"
},
{
"name": "Prolog",
"bytes": "306"
},
{
"name": "Shell",
"bytes": "1794"
}
],
"symlink_target": ""
} |
import "core-js/es6/promise";
import "core-js/es6/array"
import "core-js/es6/set"
import {IObservable} from "./interfaces/observable";
import {IObservableEvent} from "./interfaces/observable-event";
import {IObserver, ObserverCallback} from "./interfaces/observer";
import {IObserverItem} from "./interfaces/obervable-item"
import {ICancel} from "./interfaces/cancel";
export class Observable implements IObservable {
private observers : IObserverItem[] = [];
constructor() {}
count(): number {
return this.observers.length;
}
clear(): void {
this.observers.splice(0, this.observers.length);
}
on(type: string | IObservableEvent | (string | IObservableEvent)[], callback: ObserverCallback | IObserver)
: ICancel {
let cancel : ICancel = {
cancel: () => {
let index : number = this.observers.findIndex((item : IObserverItem) => item.id === cancel);
// If the index is larger than -1, then remove the item
if (index > -1) {
this.observers.splice(index, 1);
return true;
}
// Else the remove failed
return false;
}
};
// If type is an array then push that to the observers
if (Array.isArray(type)) {
this.observers.push({
id: cancel,
types: new Set<string>(type.map(item => isObservableEvent(item) ? item.name : item)),
callback: callback
});
}
// If type is not an array
else {
this.observers.push({
id: cancel,
types: new Set<string>([isObservableEvent(type) ? type.name : type]),
callback: callback
});
}
return cancel;
}
off(observer: IObserver): boolean {
// Find the index of the array
let index : number = this.observers.findIndex((item : IObserverItem) => item.callback === observer);
// If the index is larger than -1, then remove the item
if (index > -1) {
this.observers.splice(index, 1);
return true;
}
// Else the remove failed
return false;
}
notify(event: IObservableEvent, data: any): Promise<void> {
// Make function decoupled
return Promise.resolve().then(() => {
let types: string[] = [event.name],
calledEventName: string = event.name;
// Select all events to be called
while (event.parent !== undefined && event.parent !== null) {
event = event.parent;
types.push(event.name);
}
// Call all observers having the type
this.observers.forEach(observer => {
if (types.some(type => observer.types.has(type))) {
if (isObserver(observer.callback)) {
observer.callback.update(data, calledEventName);
} else {
observer.callback(data, calledEventName);
}
}
});
});
}
}
/**
* Check if the item is of type IObservableEvent
* @param tested is the parameter to be tested
* @return {boolean} true if the item is instance of IObservableEvent, otherwise false
*/
function isObservableEvent(tested: any) : tested is IObservableEvent {
return tested !== undefined && tested !== null && tested.hasOwnProperty('name') && tested.hasOwnProperty('parent');
}
/**
* Check if the item is of type IObserver
* @param tested is the parameter to be tested
* @return {boolean} true if the item is instance of IObserver, otherwise false
*/
function isObserver(tested: any) : tested is IObserver {
return tested !== undefined && tested !== null && typeof tested.update === 'function';
} | {
"content_hash": "9fab7243dddb19f8af1e53695a7810da",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 119,
"avg_line_length": 32.47107438016529,
"alnum_prop": 0.5627386103334182,
"repo_name": "FlareMind/typescript-observable",
"id": "59f8ef65b68b5bbea0c5727310411dadc6ec0f53",
"size": "3929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/observable.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "19615"
}
],
"symlink_target": ""
} |
module FinApps
module REST
class DocumentsOrdersNotifications < FinAppsCore::REST::Resources
def create(id, params = [])
not_blank(id, :id)
path = "documents/orders/#{ERB::Util.url_encode(id)}/notify"
super params, path
end
end
end
end
| {
"content_hash": "91596c5bfa63b7eedb70309a8cf446f2",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 69,
"avg_line_length": 23.75,
"alnum_prop": 0.6280701754385964,
"repo_name": "finapps/ruby-client",
"id": "0c99ac97c82e5c680e6520195e916f1497d64cfa",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/finapps/rest/documents_orders_notifications.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "207323"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Pertusaria nivea G. Merr.
### Remarks
null | {
"content_hash": "5c7aa13ce948a65c22c48f982326bf54",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 25,
"avg_line_length": 10,
"alnum_prop": 0.6923076923076923,
"repo_name": "mdoering/backbone",
"id": "3072b98a27c49e90972fc0ca37ddfa434b501f99",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Pertusariales/Pertusariaceae/Pertusaria/Pertusaria nivea/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: noushi
* Date: 18/7/16
* Time: 5:09 PM
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Check_Logged extends CI_Controller
{
public $logged = '';
public function __construct()
{
parent::__construct();
$this->load->library(['session', 'image_lib']);
$this->logged = $this->session_check();
}
/*
* Check the Session status
* if session exist return true
* else return false
* */
public function session_check()
{
if($this->session->userdata('logged_in') != null)
return TRUE;
else
return FALSE;
}
} | {
"content_hash": "14129ce0c61e3ae1f065e52573f51e86",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 63,
"avg_line_length": 19.11111111111111,
"alnum_prop": 0.5537790697674418,
"repo_name": "Noushid/Dashboard",
"id": "11699d534a3d67e17afe40071dfa3b7fc87b176a",
"size": "688",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/core/Check_Logged.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "140035"
},
{
"name": "HTML",
"bytes": "8227026"
},
{
"name": "JavaScript",
"bytes": "140531"
},
{
"name": "PHP",
"bytes": "1905034"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.