text stringlengths 2 1.04M | meta dict |
|---|---|
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include <QuickLook/QuickLook.h>
#import <CrashReporter/CrashReporter.h>
OSStatus GeneratePreviewForURL (void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options);
void CancelPreviewGeneration (void *thisInterface, QLPreviewRequestRef preview);
/* -----------------------------------------------------------------------------
Generate a preview for file
This function's job is to create preview for designated file
----------------------------------------------------------------------------- */
OSStatus GeneratePreviewForURL (void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options)
{
@autoreleasepool {
NSData *data = [NSData dataWithContentsOfURL: (__bridge NSURL *)url];
if (!data)
return noErr;
PLCrashReport *report = [[PLCrashReport alloc] initWithData: data error: NULL];
if (!report)
return noErr;
NSString *text = [PLCrashReportTextFormatter stringValueForCrashReport: report
withTextFormat: PLCrashReportTextFormatiOS];
NSData *utf8Data = [text dataUsingEncoding: NSUTF8StringEncoding];
QLPreviewRequestSetDataRepresentation(preview, (__bridge CFDataRef)utf8Data, kUTTypePlainText, NULL);
}
return noErr;
}
void CancelPreviewGeneration (void *thisInterface, QLPreviewRequestRef preview)
{
// Implement only if supported
}
| {
"content_hash": "d79e15612e3422d448516e91a2266e68",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 149,
"avg_line_length": 43.972972972972975,
"alnum_prop": 0.645359557467732,
"repo_name": "AppBlade/AppBladeSDK",
"id": "9d7a2459308f2612337cc6656c53719dfbfaa675",
"size": "1627",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "iOS/Framework/AppBlade/CrashReporter/Tools/CrashViewer/CrashReporterQuicklook/GeneratePreviewForURL.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "18419"
},
{
"name": "Assembly",
"bytes": "271213"
},
{
"name": "C",
"bytes": "568541"
},
{
"name": "C++",
"bytes": "323776"
},
{
"name": "Java",
"bytes": "225573"
},
{
"name": "Makefile",
"bytes": "3644"
},
{
"name": "Objective-C",
"bytes": "4069293"
},
{
"name": "Objective-C++",
"bytes": "173035"
},
{
"name": "Protocol Buffer",
"bytes": "27620"
},
{
"name": "Shell",
"bytes": "36814"
}
],
"symlink_target": ""
} |
package entities
import "time"
// Different types to identify tokens.
const (
UnsubscribeTokenType = "unsubscribe"
ForgotPasswordTokenType = "forgot_password"
VerifyEmailTokenType = "verify_email"
)
// Token entity represents a one-time token which a user can use
// in an "unsubscribe" or "forgot password" scenario.
type Token struct {
ID int64 `json:"id"`
UserID int64 `json:"-" gorm:"column:user_id; index"`
Token string `json:"token" gorm:"not null" valid:"required,stringlength(1|191)"`
Type string `json:"type"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
| {
"content_hash": "1f7bde6d209e39c9922050d762ab3509",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 88,
"avg_line_length": 31.5,
"alnum_prop": 0.6926406926406926,
"repo_name": "FilipNikolovski/news-maily",
"id": "1ae1fe7056a34435207105b535d69e4ae3090a20",
"size": "693",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "entities/tokens.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "77806"
},
{
"name": "Makefile",
"bytes": "548"
}
],
"symlink_target": ""
} |
binary for google protobuff
| {
"content_hash": "68f91f7b6ea45e14c871825933a2e277",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 27,
"avg_line_length": 28,
"alnum_prop": 0.8571428571428571,
"repo_name": "John-Chan/protobuff-prebuild",
"id": "8a65fdb59858bd2595857e890f507bf447ce4780",
"size": "49",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3897"
},
{
"name": "C++",
"bytes": "698169"
}
],
"symlink_target": ""
} |
package org.apache.samza.sql.client.impl;
import org.apache.samza.Partition;
import org.apache.samza.config.Config;
import org.apache.samza.metrics.MetricsRegistry;
import org.apache.samza.system.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* System factory of Samza Sql Shell which needs to provide Consumer, Producer and Admin
*/
public class CliLoggingSystemFactory implements SystemFactory {
private static final Logger LOG = LoggerFactory.getLogger(CliLoggingSystemFactory.class);
private static AtomicInteger messageCounter = new AtomicInteger(0);
@Override
public SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry) {
throw new UnsupportedOperationException();
}
@Override
public SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry) {
return new CliLoggingSystemFactory.LoggingSystemProducer();
}
@Override
public SystemAdmin getAdmin(String systemName, Config config) {
return new CliLoggingSystemFactory.SimpleSystemAdmin(config);
}
private static class SimpleSystemAdmin implements SystemAdmin {
public SimpleSystemAdmin(Config config) {
}
@Override
public Map<SystemStreamPartition, String> getOffsetsAfter(Map<SystemStreamPartition, String> offsets) {
return offsets.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, null));
}
@Override
public Map<String, SystemStreamMetadata> getSystemStreamMetadata(Set<String> streamNames) {
return streamNames.stream()
.collect(Collectors.toMap(Function.identity(), streamName -> new SystemStreamMetadata(streamName,
Collections.singletonMap(new Partition(0),
new SystemStreamMetadata.SystemStreamPartitionMetadata(null, null, null)))));
}
@Override
public Integer offsetComparator(String offset1, String offset2) {
if (offset1 == null) {
return offset2 == null ? 0 : -1;
} else if (offset2 == null) {
return 1;
}
return offset1.compareTo(offset2);
}
}
private class LoggingSystemProducer implements SystemProducer {
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public void register(String source) {
LOG.info("Registering source" + source);
}
@Override
public void send(String source, OutgoingMessageEnvelope envelope) {
LOG.info(String.format(String.format("Message %d :", messageCounter.incrementAndGet())));
String msg = String.format("OutputStream:%s Key:%s Value:%s", envelope.getSystemStream(), envelope.getKey(),
new String((byte[]) envelope.getMessage()));
LOG.info(msg);
SamzaExecutor.saveOutputMessage(envelope);
}
@Override
public void flush(String source) {
}
}
} | {
"content_hash": "a85b3bf54fef60647f00af0fa8e9ac7f",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 114,
"avg_line_length": 30.86,
"alnum_prop": 0.7161373946856773,
"repo_name": "apache/samza",
"id": "49e051ad0972480c3424b5ff88e32996dcf27c78",
"size": "3893",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "samza-sql-shell/src/main/java/org/apache/samza/sql/client/impl/CliLoggingSystemFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "603"
},
{
"name": "HTML",
"bytes": "3182"
},
{
"name": "Java",
"bytes": "9201577"
},
{
"name": "JavaScript",
"bytes": "3373"
},
{
"name": "Less",
"bytes": "7492"
},
{
"name": "Python",
"bytes": "87956"
},
{
"name": "Scala",
"bytes": "1236634"
},
{
"name": "Scaml",
"bytes": "20736"
},
{
"name": "Shell",
"bytes": "61590"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Scope of Network Manager. */
@Fluent
public final class NetworkManagerPropertiesNetworkManagerScopes {
/*
* List of management groups.
*/
@JsonProperty(value = "managementGroups")
private List<String> managementGroups;
/*
* List of subscriptions.
*/
@JsonProperty(value = "subscriptions")
private List<String> subscriptions;
/*
* List of cross tenant scopes.
*/
@JsonProperty(value = "crossTenantScopes", access = JsonProperty.Access.WRITE_ONLY)
private List<CrossTenantScopes> crossTenantScopes;
/** Creates an instance of NetworkManagerPropertiesNetworkManagerScopes class. */
public NetworkManagerPropertiesNetworkManagerScopes() {
}
/**
* Get the managementGroups property: List of management groups.
*
* @return the managementGroups value.
*/
public List<String> managementGroups() {
return this.managementGroups;
}
/**
* Set the managementGroups property: List of management groups.
*
* @param managementGroups the managementGroups value to set.
* @return the NetworkManagerPropertiesNetworkManagerScopes object itself.
*/
public NetworkManagerPropertiesNetworkManagerScopes withManagementGroups(List<String> managementGroups) {
this.managementGroups = managementGroups;
return this;
}
/**
* Get the subscriptions property: List of subscriptions.
*
* @return the subscriptions value.
*/
public List<String> subscriptions() {
return this.subscriptions;
}
/**
* Set the subscriptions property: List of subscriptions.
*
* @param subscriptions the subscriptions value to set.
* @return the NetworkManagerPropertiesNetworkManagerScopes object itself.
*/
public NetworkManagerPropertiesNetworkManagerScopes withSubscriptions(List<String> subscriptions) {
this.subscriptions = subscriptions;
return this;
}
/**
* Get the crossTenantScopes property: List of cross tenant scopes.
*
* @return the crossTenantScopes value.
*/
public List<CrossTenantScopes> crossTenantScopes() {
return this.crossTenantScopes;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (crossTenantScopes() != null) {
crossTenantScopes().forEach(e -> e.validate());
}
}
}
| {
"content_hash": "5d42496de9a533a46abbed4323900760",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 109,
"avg_line_length": 29.810526315789474,
"alnum_prop": 0.6839689265536724,
"repo_name": "Azure/azure-sdk-for-java",
"id": "fe8d93f0e1d8826ae7a20ae529f844db4cd11bd3",
"size": "2832",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/NetworkManagerPropertiesNetworkManagerScopes.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $mod_files</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('mod_files');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#mod_files">$mod_files</a></h2>
<br><b>Referenced 3 times:</b><ul>
<li><a href="../bonfire/modules/docs/views/_sidebar.php.html">/bonfire/modules/docs/views/_sidebar.php</a> -> <a href="../bonfire/modules/docs/views/_sidebar.php.source.html#l67"> line 67</a></li>
<li><a href="../bonfire/modules/docs/views/_sidebar.php.html">/bonfire/modules/docs/views/_sidebar.php</a> -> <a href="../bonfire/modules/docs/views/_sidebar.php.source.html#l68"> line 68</a></li>
<li><a href="../bonfire/modules/docs/views/_sidebar.php.html">/bonfire/modules/docs/views/_sidebar.php</a> -> <a href="../bonfire/modules/docs/views/_sidebar.php.source.html#l73"> line 73</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "0cd2503118f5bc563ea79e6ceadfe961",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 253,
"avg_line_length": 52.189473684210526,
"alnum_prop": 0.6686163775716014,
"repo_name": "inputx/code-ref-doc",
"id": "a8f3fa90a43bd79c32d257ccd53697c283e6ef9c",
"size": "4958",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bonfire/_variables/mod_files.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
using KendoGridBinder.ModelBinder.Mvc;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication.NETCore2
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// services.AddMvc();
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new KendoGridMvcModelBinderProvider());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| {
"content_hash": "7e642b86e72908d9c0b091dfec54cfed",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 106,
"avg_line_length": 29.596153846153847,
"alnum_prop": 0.5756985055230669,
"repo_name": "StefH/KendoGridBinderEx",
"id": "f752ae37e03423747cedca5e0a3b6bb5231c1000",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/WebApplication.NETCore2/Startup.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "171281"
}
],
"symlink_target": ""
} |
#ifndef EXCEPTION_HH
#define EXCEPTION_HH
#include <exception>
#include <iostream>
#include <string>
namespace hadoop {
/**
* Parent-type for all exceptions in hadoop.
* Provides an application specified message to the user, a call stack from
* where the exception was created, and optionally an exception that caused
* this one.
*/
class Exception: public std::exception {
public:
/**
* Create an exception.
* @param message The message to give to the user.
* @param reason The exception that caused the new exception.
*/
explicit Exception(const std::string& message,
const std::string& component="",
const std::string& location="",
const Exception* reason=NULL);
/**
* Copy the exception.
* Clones the reason, if there is one.
*/
Exception(const Exception&);
virtual ~Exception() throw ();
/**
* Make a new copy of the given exception by dynamically allocating
* memory.
*/
virtual Exception* clone() const;
/**
* Print all of the information about the exception.
*/
virtual void print(std::ostream& stream=std::cerr) const;
/**
* Result of print() as a string.
*/
virtual std::string toString() const;
/**
* Print the call stack where the exception was created.
*/
virtual void printCallStack(std::ostream& stream=std::cerr) const;
const std::string& getMessage() const {
return mMessage;
}
const std::string& getComponent() const {
return mComponent;
}
const std::string& getLocation() const {
return mLocation;
}
const Exception* getReason() const {
return mReason;
}
/**
* Provide a body for the virtual from std::exception.
*/
virtual const char* what() const throw () {
return mMessage.c_str();
}
virtual const char* getTypename() const;
private:
const static int sMaxCallStackDepth = 10;
const std::string mMessage;
const std::string mComponent;
const std::string mLocation;
int mCalls;
void* mCallStack[sMaxCallStackDepth];
const Exception* mReason;
// NOT IMPLEMENTED
std::exception& operator=(const std::exception& right) throw ();
};
class IOException: public Exception {
public:
IOException(const std::string& message,
const std::string& component="",
const std::string& location="",
const Exception* reason = NULL);
virtual IOException* clone() const;
virtual const char* getTypename() const;
};
}
#endif
| {
"content_hash": "334332c13684730a95086016362c7da7",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 78,
"avg_line_length": 23.98198198198198,
"alnum_prop": 0.6164537941397445,
"repo_name": "moreus/hadoop",
"id": "9bfba01c5ae4d57e089891db7513eb9e796bfef2",
"size": "3468",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "hadoop-0.10.1/src/c++/librecordio/exception.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "31146"
},
{
"name": "C",
"bytes": "1067911"
},
{
"name": "C++",
"bytes": "521803"
},
{
"name": "CSS",
"bytes": "157107"
},
{
"name": "Erlang",
"bytes": "232"
},
{
"name": "Java",
"bytes": "43984644"
},
{
"name": "JavaScript",
"bytes": "87848"
},
{
"name": "Perl",
"bytes": "18992"
},
{
"name": "Python",
"bytes": "32767"
},
{
"name": "Shell",
"bytes": "1369281"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "185841"
}
],
"symlink_target": ""
} |
layout: post
title: "Welcome to Jekyll!"
date: 2016-09-17 23:34:56 +0530
categories: jekyll update
icon: thumbs-o-up
---
You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
Jekyll also offers powerful support for code snippets:
{% highlight ruby %}
def print_hi(name)
puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.
{% endhighlight %}
Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk].
[jekyll-docs]: http://jekyllrb.com/docs/home
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-talk]: https://talk.jekyllrb.com/
| {
"content_hash": "c959b5663415d5c9ab267dcc07d9a1a3",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 295,
"avg_line_length": 48.64,
"alnum_prop": 0.7384868421052632,
"repo_name": "transparentgeek/transparentgeek.github.io",
"id": "457ba345e6f94008eb58e0bea10bb52c831897ec",
"size": "1224",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "_posts/2016-09-17-welcome-to-jekyll.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10740"
},
{
"name": "HTML",
"bytes": "3367"
}
],
"symlink_target": ""
} |
local init = os.clock()
minetest.log("action", "["..minetest.get_current_modname().."] loading init")
working_villages={
modpath = minetest.get_modpath("working_villages"),
}
if not minetest.get_modpath("modutil") then
dofile(working_villages.modpath.."/modutil/portable.lua")
end
modutil.require("local_require")(working_villages)
local log = working_villages.require("log")
function working_villages.setting_enabled(name, default)
local b = minetest.settings:get_bool("working_villages_enable_"..name)
if b == nil then
if default == nil then
return false
end
return default
end
return b
end
working_villages.require("groups")
--TODO: check for which preloading is needed
--content
working_villages.require("forms")
working_villages.require("talking")
--TODO: instead use the building sign mod when it is ready
working_villages.require("building")
working_villages.require("storage")
--base
working_villages.require("api")
working_villages.require("register")
working_villages.require("commanding_sceptre")
working_villages.require("deprecated")
--job helpers
working_villages.require("jobs/util")
working_villages.require("jobs/empty")
--base jobs
working_villages.require("jobs/builder")
working_villages.require("jobs/follow_player")
working_villages.require("jobs/guard")
working_villages.require("jobs/plant_collector")
working_villages.require("jobs/farmer")
working_villages.require("jobs/woodcutter")
--testing jobs
working_villages.require("jobs/torcher")
working_villages.require("jobs/snowclearer")
if working_villages.setting_enabled("spawn",false) then
working_villages.require("spawn")
end
if working_villages.setting_enabled("debug_tools",false) then
working_villages.require("util_test")
end
--ready
local time_to_load= os.clock() - init
log.action("loaded init in %.4f s", time_to_load)
| {
"content_hash": "bb0e9a376c548fc2e52ba2ed6974ea54",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 77,
"avg_line_length": 27.64179104477612,
"alnum_prop": 0.7570194384449244,
"repo_name": "theFox6/working_villages",
"id": "c4503df9acfb4f676451288b9f8dca45cc7166de",
"size": "1852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "working_villagers/init.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "170270"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e10031becf8fc23e9fefc06b7ed98b76",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e2a02d1b8471b84b18471854f3f44c60f82ffc3a",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Dendrophthoe/Dendrophthoe pendulus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
export const loadStyle = (url, resolve) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
document.head.appendChild(link);
resolve(link);
};
| {
"content_hash": "7845a4db4cfb3bb5909b73650fc58805",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 46,
"avg_line_length": 27.571428571428573,
"alnum_prop": 0.6735751295336787,
"repo_name": "AntonLapshin/droplet.js",
"id": "a4fe66f44de54c1a2f493e191457c8d07c3b8ba1",
"size": "193",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/loaders/style.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "63"
},
{
"name": "JavaScript",
"bytes": "18464"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "da138267e33cbcddf4abe12fb51d03f6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "99f02f65e8e17352a968f6e35b737a56b3eede05",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Woodsiaceae/Cystopteris/Cystopteris regia/Cystopteris regia latilobum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import store from 'kolibri.coreVue.vuex.store';
import router from 'kolibri.coreVue.router';
import { ClassesPageNames, PageNames } from '../constants';
import { showLessonPlaylist, showLessonResourceViewer } from '../modules/lessonPlaylist/handlers';
import { showClassAssignmentsPage } from '../modules/classAssignments/handlers';
import { showAllClassesPage } from '../modules/classes/handlers';
import { showExam } from '../modules/examViewer/handlers';
import { showExamReport } from '../modules/examReportViewer/handlers';
function noClassesGuard() {
const { memberships } = store.state;
const { canAccessUnassignedContent } = store.getters;
if (memberships.length === 0 && canAccessUnassignedContent) {
// If there are no memberships and it is allowed, redirect to topics page
return router.replace({ name: PageNames.TOPICS_ROOT });
}
// Otherwise return nothing
return;
}
export default [
{
name: ClassesPageNames.ALL_CLASSES,
path: '/classes',
handler: () => {
return noClassesGuard() || showAllClassesPage(store);
},
},
{
name: ClassesPageNames.CLASS_ASSIGNMENTS,
path: '/classes/:classId',
handler: toRoute => {
const { classId } = toRoute.params;
return noClassesGuard() || showClassAssignmentsPage(store, classId);
},
},
{
name: ClassesPageNames.LESSON_PLAYLIST,
path: '/classes/:classId/lesson/:lessonId',
handler: toRoute => {
const { classId, lessonId } = toRoute.params;
return noClassesGuard() || showLessonPlaylist(store, { classId, lessonId });
},
},
{
name: ClassesPageNames.LESSON_RESOURCE_VIEWER,
path: '/classes/:classId/lesson/:lessonId/item/:resourceNumber',
handler: toRoute => {
if (noClassesGuard()) {
return noClassesGuard();
}
const { lessonId, resourceNumber } = toRoute.params;
showLessonResourceViewer(store, { lessonId, resourceNumber });
},
},
{
name: ClassesPageNames.EXAM_VIEWER,
path: '/classes/:classId/exam/:examId/:questionNumber',
handler: (toRoute, fromRoute) => {
if (noClassesGuard()) {
return noClassesGuard();
}
const alreadyOnQuiz =
fromRoute.name === ClassesPageNames.EXAM_VIEWER &&
toRoute.params.examId === fromRoute.params.examId &&
toRoute.params.classId === fromRoute.params.classId;
showExam(store, toRoute.params, alreadyOnQuiz);
},
},
{
name: ClassesPageNames.EXAM_REPORT_VIEWER,
path: '/classes/:classId/examReport/:examId/:questionNumber/:questionInteraction',
handler: toRoute => {
if (noClassesGuard()) {
return noClassesGuard();
}
showExamReport(store, toRoute.params);
},
},
];
| {
"content_hash": "1efef73e0283ceea79a17d04d0905076",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 98,
"avg_line_length": 34.1,
"alnum_prop": 0.6689882697947214,
"repo_name": "indirectlylit/kolibri",
"id": "3efd1c028ef843d7d3b6d78b7d38aa62754284b1",
"size": "2728",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "kolibri/plugins/learn/assets/src/routes/classesRoutes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2554964"
},
{
"name": "Dockerfile",
"bytes": "4114"
},
{
"name": "Gherkin",
"bytes": "365088"
},
{
"name": "HTML",
"bytes": "24294"
},
{
"name": "JavaScript",
"bytes": "1613945"
},
{
"name": "Makefile",
"bytes": "11953"
},
{
"name": "Python",
"bytes": "2860587"
},
{
"name": "SCSS",
"bytes": "5225"
},
{
"name": "Shell",
"bytes": "5245"
},
{
"name": "Vue",
"bytes": "1604613"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Stagonospora vincetoxici Fautrey & Roum.
### Remarks
null | {
"content_hash": "b941c8942d9adb98dbec8e0258470e5c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 40,
"avg_line_length": 11.153846153846153,
"alnum_prop": 0.7172413793103448,
"repo_name": "mdoering/backbone",
"id": "e9f325490e9cb4cf8549a0505ca51c69aedf8bb3",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phaeosphaeriaceae/Stagonospora/Stagonospora vincetoxici/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'capistrano/notify' | {
"content_hash": "6372a34635bc1b4f9003e6bd9b08b742",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 27,
"avg_line_length": 27,
"alnum_prop": 0.8518518518518519,
"repo_name": "leejones/capistrano-notify",
"id": "7cdf850cd64c44492f672b7f3ab8b0507cb9ac93",
"size": "27",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/capistrano-notify.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2643"
}
],
"symlink_target": ""
} |
namespace remoting {
namespace protocol {
namespace {
const char kTcpProtocol[] = "tcp";
// Maps value returned by Recv() and Send() Pepper methods to net::Error.
int PPErrorToNetError(int result) {
if (result > 0)
return result;
switch (result) {
case PP_OK:
return net::OK;
case PP_OK_COMPLETIONPENDING:
return net::ERR_IO_PENDING;
case PP_ERROR_NOTSUPPORTED:
case PP_ERROR_NOINTERFACE:
return net::ERR_NOT_IMPLEMENTED;
default:
return net::ERR_FAILED;
}
}
} // namespace
PepperTransportSocketAdapter::PepperTransportSocketAdapter(
pp::Transport_Dev* transport,
const std::string& name,
Observer* observer)
: name_(name),
observer_(observer),
transport_(transport),
connected_(false),
get_address_pending_(false) {
callback_factory_.Initialize(this);
}
PepperTransportSocketAdapter::~PepperTransportSocketAdapter() {
observer_->OnChannelDeleted();
}
void PepperTransportSocketAdapter::AddRemoteCandidate(
const std::string& candidate) {
DCHECK(CalledOnValidThread());
if (transport_.get())
transport_->ReceiveRemoteAddress(candidate);
}
int PepperTransportSocketAdapter::Read(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
DCHECK(CalledOnValidThread());
DCHECK(read_callback_.is_null());
DCHECK(!read_buffer_);
if (!transport_.get())
return net::ERR_SOCKET_NOT_CONNECTED;
int result = PPErrorToNetError(transport_->Recv(
buf->data(), buf_len,
callback_factory_.NewOptionalCallback(
&PepperTransportSocketAdapter::OnRead)));
if (result == net::ERR_IO_PENDING) {
read_callback_ = callback;
read_buffer_ = buf;
}
return result;
}
int PepperTransportSocketAdapter::Write(
net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
DCHECK(CalledOnValidThread());
DCHECK(write_callback_.is_null());
DCHECK(!write_buffer_);
if (!transport_.get())
return net::ERR_SOCKET_NOT_CONNECTED;
int result = PPErrorToNetError(transport_->Send(
buf->data(), buf_len,
callback_factory_.NewOptionalCallback(
&PepperTransportSocketAdapter::OnWrite)));
if (result == net::ERR_IO_PENDING) {
write_callback_ = callback;
write_buffer_ = buf;
}
return result;
}
bool PepperTransportSocketAdapter::SetReceiveBufferSize(int32 size) {
DCHECK(CalledOnValidThread());
// TODO(sergeyu): Implement this: crbug.com/91439.
NOTIMPLEMENTED();
return false;
}
bool PepperTransportSocketAdapter::SetSendBufferSize(int32 size) {
DCHECK(CalledOnValidThread());
// TODO(sergeyu): Implement this: crbug.com/91439.
NOTIMPLEMENTED();
return false;
}
int PepperTransportSocketAdapter::Connect(
const net::CompletionCallback& callback) {
DCHECK(CalledOnValidThread());
if (!transport_.get())
return net::ERR_UNEXPECTED;
connect_callback_ = callback;
// This will return false when GetNextAddress() returns an
// error. This helps to detect when the P2P Transport API is not
// supported.
int result = ProcessCandidates();
if (result != net::OK)
return result;
result = transport_->Connect(
callback_factory_.NewCallback(&PepperTransportSocketAdapter::OnConnect));
DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
return net::ERR_IO_PENDING;
}
void PepperTransportSocketAdapter::Disconnect() {
DCHECK(CalledOnValidThread());
transport_.reset();
}
bool PepperTransportSocketAdapter::IsConnected() const {
DCHECK(CalledOnValidThread());
return connected_;
}
bool PepperTransportSocketAdapter::IsConnectedAndIdle() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return false;
}
int PepperTransportSocketAdapter::GetPeerAddress(
net::AddressList* address) const {
DCHECK(CalledOnValidThread());
// We don't have a meaningful peer address, but we can't return an
// error, so we return a INADDR_ANY instead.
net::IPAddressNumber ip_address(4);
*address = net::AddressList::CreateFromIPAddress(ip_address, 0);
return net::OK;
}
int PepperTransportSocketAdapter::GetLocalAddress(
net::IPEndPoint* address) const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return net::ERR_FAILED;
}
const net::BoundNetLog& PepperTransportSocketAdapter::NetLog() const {
DCHECK(CalledOnValidThread());
return net_log_;
}
void PepperTransportSocketAdapter::SetSubresourceSpeculation() {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
}
void PepperTransportSocketAdapter::SetOmniboxSpeculation() {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
}
bool PepperTransportSocketAdapter::WasEverUsed() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return true;
}
bool PepperTransportSocketAdapter::UsingTCPFastOpen() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return true;
}
int64 PepperTransportSocketAdapter::NumBytesRead() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return 0;
}
base::TimeDelta PepperTransportSocketAdapter::GetConnectTimeMicros() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return base::TimeDelta();
}
net::NextProto PepperTransportSocketAdapter::GetNegotiatedProtocol() const {
DCHECK(CalledOnValidThread());
NOTIMPLEMENTED();
return net::kProtoUnknown;
}
int PepperTransportSocketAdapter::ProcessCandidates() {
DCHECK(CalledOnValidThread());
DCHECK(!get_address_pending_);
DCHECK(transport_.get());
while (true) {
pp::Var address;
int result = transport_->GetNextAddress(
&address, callback_factory_.NewOptionalCallback(
&PepperTransportSocketAdapter::OnNextAddress));
if (result == PP_OK_COMPLETIONPENDING) {
get_address_pending_ = true;
break;
}
if (result == PP_OK) {
observer_->OnChannelNewLocalCandidate(address.AsString());
} else {
LOG(ERROR) << "GetNextAddress() returned an error " << result;
return PPErrorToNetError(result);
}
}
return net::OK;
}
void PepperTransportSocketAdapter::OnNextAddress(int32_t result) {
DCHECK(CalledOnValidThread());
get_address_pending_ = false;
ProcessCandidates();
}
void PepperTransportSocketAdapter::OnConnect(int result) {
DCHECK(CalledOnValidThread());
DCHECK(!connect_callback_.is_null());
if (result == PP_OK)
connected_ = true;
net::CompletionCallback callback = connect_callback_;
connect_callback_.Reset();
callback.Run(PPErrorToNetError(result));
}
void PepperTransportSocketAdapter::OnRead(int32_t result) {
DCHECK(CalledOnValidThread());
DCHECK(!read_callback_.is_null());
DCHECK(read_buffer_);
net::CompletionCallback callback = read_callback_;
read_callback_.Reset();
read_buffer_ = NULL;
callback.Run(PPErrorToNetError(result));
}
void PepperTransportSocketAdapter::OnWrite(int32_t result) {
DCHECK(CalledOnValidThread());
DCHECK(!write_callback_.is_null());
DCHECK(write_buffer_);
net::CompletionCallback callback = write_callback_;
write_callback_.Reset();
write_buffer_ = NULL;
callback.Run(PPErrorToNetError(result));
}
} // namespace protocol
} // namespace remoting
| {
"content_hash": "55bb2ee5cbc98bf9ceddbf7e52a4aadf",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 79,
"avg_line_length": 25.525,
"alnum_prop": 0.7147054708269204,
"repo_name": "yitian134/chromium",
"id": "e4e47d551560536d9bdee844d0b410f98c3deb8f",
"size": "7638",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "remoting/protocol/pepper_transport_socket_adapter.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Assembly",
"bytes": "64286"
},
{
"name": "Batchfile",
"bytes": "12391"
},
{
"name": "C",
"bytes": "3177008"
},
{
"name": "C++",
"bytes": "110667033"
},
{
"name": "CSS",
"bytes": "441900"
},
{
"name": "Go",
"bytes": "18556"
},
{
"name": "HTML",
"bytes": "24278542"
},
{
"name": "Java",
"bytes": "62764"
},
{
"name": "JavaScript",
"bytes": "8873424"
},
{
"name": "Makefile",
"bytes": "49910"
},
{
"name": "NSIS",
"bytes": "3518"
},
{
"name": "Objective-C",
"bytes": "809365"
},
{
"name": "Objective-C++",
"bytes": "4643562"
},
{
"name": "PHP",
"bytes": "97796"
},
{
"name": "PLpgSQL",
"bytes": "98455"
},
{
"name": "Perl",
"bytes": "63993"
},
{
"name": "Protocol Buffer",
"bytes": "161124"
},
{
"name": "Python",
"bytes": "4653412"
},
{
"name": "Rebol",
"bytes": "524"
},
{
"name": "Shell",
"bytes": "259655"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "8497"
}
],
"symlink_target": ""
} |
// RTM.Tools
// RTM.Component.StereoImaging
// App.xaml.cs
//
// Created by Bartosz Rachwal.
// Copyright (c) 2015 Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved.
using System.Windows;
namespace RTM.Component.StereoImaging
{
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var bootstrapper = new StereoImagingBootstrapper();
bootstrapper.Run();
}
}
} | {
"content_hash": "b0b5dc04cf80d426cd94b0bfaed3ff06",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 137,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.668488160291439,
"repo_name": "rachwal/RTM-Tools",
"id": "bfa603a4c5f46fd2caa9dad4be837400169b7f00",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RTM.Component.StereoImaging/App.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "253753"
}
],
"symlink_target": ""
} |
#import "DefaultOperationHttpChannel.h"
#import "HttpRequestCreator.h"
#import "KaaLogging.h"
#import "KaaExceptions.h"
#define TAG @"DefaultOperationHttpChannel >>>"
#define CHANNEL_ID @"default_operations_http_channel"
#define URL_SUFFIX @"/EP/Sync"
@interface DefaultOperationHttpChannel ()
/**
* <TransportType, ChannelDirection> as key-value
*/
@property (nonatomic, strong) NSDictionary *supportedTypes;
@end
@implementation DefaultOperationHttpChannel
- (instancetype)initWithClient:(AbstractKaaClient *)client
state:(id<KaaClientState>)state
failoverManager:(id<FailoverManager>)manager {
self = [super initWithClient:client state:state failoverManager:manager];
if (self) {
self.supportedTypes = @{@(TRANSPORT_TYPE_EVENT) : @(CHANNEL_DIRECTION_UP),
@(TRANSPORT_TYPE_LOGGING) : @(CHANNEL_DIRECTION_UP)};
}
return self;
}
- (void)processTypes:(NSDictionary *)types {
NSData *requestBodyRaw = [[self getMultiplexer] compileRequestForTypes:types];
@synchronized(self) {
MessageEncoderDecoder *encoderDecoder = [[self getHttpClient] getEncoderDecoder];
NSDictionary *requestEntity = [HttpRequestCreator createOperationHttpRequest:requestBodyRaw
withEncoderDecoder:encoderDecoder];
__weak typeof(self) weakSelf = self;
[[self getHttpClient] executeHttpRequest:@""
entity:requestEntity
verifyResponse:NO
success:^(NSData *response){
NSData *decodedResponse = [encoderDecoder decodeData:response];
[[weakSelf getDemultiplexer] processResponse:decodedResponse];
[weakSelf connectionEstablished];
}
failure:^(NSInteger responseCode) {
DDLogError(@"%@ Failed to receive response from the operation server: %i", TAG, (int)responseCode);
[weakSelf connectionFailedWithStatus:(int)responseCode];
}];
}
}
- (NSString *)getId {
return CHANNEL_ID;
}
- (ServerType)getServerType {
return SERVER_OPERATIONS;
}
- (NSDictionary *)getSupportedTransportTypes {
return self.supportedTypes;
}
- (NSString *)getURLSuffix {
return URL_SUFFIX;
}
@end | {
"content_hash": "9b54b41f5ab51d888251e427a48e58b8",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 144,
"avg_line_length": 36.23287671232877,
"alnum_prop": 0.5754253308128544,
"repo_name": "aglne/kaa",
"id": "1fb1c74e57eeca355423c991dedf63c37e2013c2",
"size": "3251",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "client/client-multi/client-objective-c/Kaa/channel/impl/channels/DefaultOperationHttpChannel.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "19815"
},
{
"name": "Arduino",
"bytes": "22520"
},
{
"name": "Batchfile",
"bytes": "21336"
},
{
"name": "C",
"bytes": "6219408"
},
{
"name": "C++",
"bytes": "1729698"
},
{
"name": "CMake",
"bytes": "74157"
},
{
"name": "CSS",
"bytes": "23111"
},
{
"name": "HTML",
"bytes": "6338"
},
{
"name": "Java",
"bytes": "10478878"
},
{
"name": "JavaScript",
"bytes": "4669"
},
{
"name": "Makefile",
"bytes": "15221"
},
{
"name": "Objective-C",
"bytes": "305678"
},
{
"name": "Python",
"bytes": "128276"
},
{
"name": "Shell",
"bytes": "185517"
},
{
"name": "Thrift",
"bytes": "21163"
},
{
"name": "XSLT",
"bytes": "4062"
}
],
"symlink_target": ""
} |
import re
import nltk
from . import tokenizers as tok
from . import summary as summ
# mod = moderate
def mod_max_unit_func(unit_num):
return 5 * unit_num ** (1/12)
class Document(object):
def __init__(self, filename=None, text=None,
max_unit_func=lambda x: 5*x**(1/12)):
self.filename = filename
self.text = text
# original text
self.words = None
self.sentences = None
self.paragraphs = None
self.num_words = None
self.num_paragraphs = None
self.num_sentences = None
self.genre = None
self.summary = None
self.max_unit_func = max_unit_func
self.recursive = False
def build(self):
self.load()
self.tokenize()
self.get_count()
self.get_summary()
def load(self):
if self.filename:
self.text = summ.file_to_doc(self.filename)
else:
pass
def tokenize(self):
regex = re.compile(r"\((Applause|APPLAUSE|Laughter|LAUGHTER)\.\) ?",
re.IGNORECASE)
cleaned_text = regex.sub("", self.text)
self.words = cleaned_text.split()
self.sentences = tok.tokenize_to_sentences(
cleaned_text.replace("\n", " "))
self.paragraphs = tok.tokenize_to_paragraphs(cleaned_text)
def get_count(self):
self.num_words = len(self.words)
self.num_sentences = len(self.sentences)
self.num_paragraphs = len(self.paragraphs)
# both unit_type and num_units must be given to get a fixed summary
def get_summary(self, unit_type=None, max_units=None, stem=True):
if unit_type is not None and max_units is not None:
print("Hello!")
if unit_type == 0:
units = self.sentences
divider = " "
else:
units = self.paragraphs
# for proper printing
divider = "\n"
else:
if self.num_words > 500 and self.num_paragraphs > 5:
units = self.paragraphs
unit_type = 1
unit_count = self.num_paragraphs
divider = "\n"
else:
units = self.sentences
unit_type = 0
unit_count = self.num_sentences
divider = " "
max_units = round(self.max_unit_func(unit_count))
summary_units = summ.get_tfidf_summary_units(units, max_units, stem)
# for long paragraphs
if unit_type == 1:
for i, unit in enumerate(summary_units):
doc = Document(text=unit,)
doc.max_unit_func = lambda x: 3*x**(1/12)
doc.recursive = True
doc.build()
summary_units[i] = doc.summary
self.summary = divider.join(summary_units)
degree = 1
while len(self.summary.split()) > 500:
self.shorten_summary(degree)
degree += 1
def shorten_summary(self, degree):
doc = Document(text=self.summary,
max_unit_func=lambda x: (5-degree)*x**(1/12))
doc.build()
self.summary = doc.summary
def pprint(self):
print("********* {} *********\n".format(self.filename))
print("TEXT STATISTICS:")
print("Word #: {}; Sentence #: {}; Paragraph #: {};\n".format(
self.num_words, self.num_sentences, self.num_paragraphs))
print("SUMMARY:\n")
summary_paragraphs = tok.tokenize_to_paragraphs(self.summary)
for sent in summary_paragraphs:
print(sent)
print("\n")
print("SUMMARY STATISTICS:")
print("Word #: {}: Sentence #: {}; Paragraph #: {};\n".format(
len(self.summary.split()),
len(tok.tokenize_to_sentences(self.summary)),
len(summary_paragraphs),))
| {
"content_hash": "304505903601d16e0590f4d5ece9ecf8",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 89,
"avg_line_length": 31.094488188976378,
"alnum_prop": 0.5292479108635098,
"repo_name": "euirim/maple",
"id": "550d577e5244d5d6bb583b62ee1d267452031720",
"size": "3949",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/documents_old.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "60"
},
{
"name": "Python",
"bytes": "24822"
}
],
"symlink_target": ""
} |
module Furnace::AVM2::ABC
class AS3InitProperty < PropertyOpcode
instruction 0x68
write_barrier :memory
implicit_operand false
consume 1
produce 0
end
end | {
"content_hash": "1c1c9d4003cb318ff3e4a64b9ea961d3",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 40,
"avg_line_length": 17.9,
"alnum_prop": 0.7206703910614525,
"repo_name": "whitequark/furnace-avm2",
"id": "ae82f32567bc64aefd983b09448e047d4f70e865",
"size": "179",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/furnace-avm2/abc/opcodes/property/as3_initproperty.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "7197"
},
{
"name": "Ruby",
"bytes": "241465"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Game Store</title>
<meta charset="UTF-8">
<link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header>
<nav class="navbar navbar-toggleable-md navbar-light bg-warning">
<div class="container">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">SoftUni Store</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Cart</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<!--Body of the store-->
<main>
<div class="container">
<div class="row">
<div class="col-12">
<div class="text-center"><h1 class="display-3">SoftUni Store</h1></div>
<form class="form-inline">
Filter:
<input type="submit" name="filter" class="btn btn-link" value="All"/>
<input type="submit" name="filter" class="btn btn-link" value="Owned"/>
</form>
<div class="card-group">
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
</div>
<div class="card-group">
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
</div>
<div class="card-group">
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
<div class="card col-4 thumbnail">
<img
class="card-image-top img-fluid img-thumbnail"
onerror="this.src='https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg';"
src="https://i.ytimg.com/vi/BqJyluskTfM/maxresdefault.jpg">
<div class="card-block">
<h4 class="card-title">Mass Effect Andromeda</h4>
<p class="card-text"><strong>Price</strong> - 60€</p>
<p class="card-text"><strong>Size</strong> - 62.5 GB</p>
<p class="card-text">Mass Effect: Andromeda is an action role-playing game in which the player takes control of either Scott or Sara Ryder from a third-person perspective.</p>
</div>
<div class="card-footer">
<a class="card-button btn btn-outline-primary" name="info" href="#">Info</a>
<a class="card-button btn btn-primary" name="buy" href="#">Buy</a>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<br/>
<!--Footer-->
<footer>
<div class="container modal-footer">
<p>© 2017 - Software University Foundation</p>
</div>
</footer>
<script src="/scripts/jquery-3.1.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html> | {
"content_hash": "477d944c23eee2ccdc7c0f78137552ea",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 203,
"avg_line_length": 52.314655172413794,
"alnum_prop": 0.45859767652632444,
"repo_name": "vanncho/Java-Web-Development-Basics",
"id": "675b7172af5849eff29bab27093c5c9a5169c358",
"size": "12137",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "exam/softuniGameStore/web/html/user-home.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "310308"
},
{
"name": "HTML",
"bytes": "188856"
},
{
"name": "Java",
"bytes": "292980"
}
],
"symlink_target": ""
} |
package jdbreport.source;
import java.util.EventListener;
/**
* @version 1.1 03/09/08
* @author Andrey Kholmanskih
*
*/
public interface DataSetListener extends EventListener {
void cursorChange(CursorChangedEvent evt);
}
| {
"content_hash": "1f947f23924698dd2e5bfdaba53cc94f",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 56,
"avg_line_length": 15.533333333333333,
"alnum_prop": 0.7467811158798283,
"repo_name": "andreikh/jdbreport",
"id": "86b9f0a276276223ba029389f6539d14f5298953",
"size": "870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jdbreport-rt/src/main/java/jdbreport/source/DataSetListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2065847"
}
],
"symlink_target": ""
} |
class: middle, center
background-image: url('./slides/images/slide-bg-1.png')
background-size: contain
# Docker Nashville
<p style="font-size: 32pt;">Welcome<br />
<!--<br />Wifi: BuiltWifi<br />Pass: Buil7Gues7--></p>
---
class: center
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Community Code of Conduct!
We are dedicated to providing a harassment free experience for everyone
<table>
<tbody>
<tr>
<td style="text-align: left; vertical-align: top">
<ul>
<li>Be professional.</li>
<li>Be responsible.</li>
<li>Be welcoming.</li>
<li>Be kind.</li>
<li>Be respectful of other viewpoints and ideas.</li>
<li>Be supportive and look out for each other.</li>
</ul>
</td>
</tr>
</tbody>
</table>
---
class: center
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Thank you to our host!
.center[<img src="./slides/images/datablue.jpeg" style="width: 30%; position: relative;">]
<div style="width: 80%; position: fixed; bottom: 15.5%"><p>Please let us know if your company is interested in hosting or sponsoring a future meetup!</p></div>
---
class: center
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Thank you to our sponsor!
.center[<img src="./slides/images/famc.png" style="width: 50%; position: relative;">]
We're Hiring!
---
class: top
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Housekeeping
- Free Docker Training! https://training.play-with-docker.com
- Topic idea for future meetups? https://bit.ly/DockerNashvilleIdeas
- Slides available at http://bit.ly/DockerNashvilleSlides
- Connect with local Nashville tech community in NashDev Slack: http://nashdev.com/
- Join the `#docker` channel!
- Join the Docker Community Slack instance: https://dockr.ly/community
---
class: top
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Upcoming Meetups
<table>
<tbody>
<tr>
<td style="vertical-align: top">
<span>March 19th</span>
<span style="text-decoration: underline">Docker 5th Birthday</span><br/>
<b>Speaker:</b> TBA<br />
<b>Games / Prizes / SWAG</b><br />
</td>
<td style="vertical-align: top">
<span>April 16th</span>
<span style="text-decoration: underline">Kubernetes Intro</span><br/>
<b>Speaker:</b> Jason Greathouse<br/>
<b>Topic:</b> Getting Started with Kubernetes Workshop
</td>
</tr>
<tr>
<td style="vertical-align: top">
<span>May 14th</span>
<span style="text-decoration: underline">OpenFaaS</span><br/>
<b>Speaker:</b> Kevin Crawley<br />
<b>Topic:</b> Deep Dive into Serverless with Docker
</td>
</tr>
</tbody>
</table>
---
class: top
background-image: url('./slides/images/slide-bg-2.png')
background-size: contain
## Upcoming Local Conferences
* Music City Tech -- CFP Closes March 1st
* Scenic City Summit -- CFP Closes March 16th
If you're aware of any other conferences please DM @kevin on NashDev or submit a PR.
| {
"content_hash": "9778623ce42d867f33c4686e3577b70d",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 159,
"avg_line_length": 27.654867256637168,
"alnum_prop": 0.67168,
"repo_name": "DockerNashvilleMeetup/Slides",
"id": "5104e0b1f19d1bb4eaccc2558e4c9588052a6df2",
"size": "3125",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "0000-00-00-Intro/slides/slides.md",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5146"
},
{
"name": "Go",
"bytes": "2475"
},
{
"name": "HTML",
"bytes": "1096"
}
],
"symlink_target": ""
} |
require File.join(File.dirname(__FILE__), 'lib', 'pin-it-button') | {
"content_hash": "6e6847e369e762fcd24ed66fbeeac389",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 65,
"avg_line_length": 65,
"alnum_prop": 0.676923076923077,
"repo_name": "willrax/pin-it-button",
"id": "31d432ccc3506ddc7dcfa22fe5b93606135c6357",
"size": "65",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "init.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2046"
}
],
"symlink_target": ""
} |
package org.onosproject.net.device;
import java.util.Collections;
import java.util.List;
import org.onosproject.net.Device;
import org.onosproject.net.Device.Type;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import com.google.common.collect.FluentIterable;
/**
* Test adapter for device service.
*/
public class DeviceServiceAdapter implements DeviceService {
private List<Port> portList;
/**
* Constructor with port list.
*
* @param portList port list
*/
public DeviceServiceAdapter(List<Port> portList) {
this.portList = portList;
}
/**
* Default constructor.
*/
public DeviceServiceAdapter() {
}
@Override
public int getDeviceCount() {
return 0;
}
@Override
public Iterable<Device> getDevices() {
return Collections.emptyList();
}
@Override
public Iterable<Device> getAvailableDevices() {
return FluentIterable.from(getDevices())
.filter(input -> isAvailable(input.id()));
}
@Override
public Device getDevice(DeviceId deviceId) {
return null;
}
@Override
public MastershipRole getRole(DeviceId deviceId) {
return MastershipRole.NONE;
}
@Override
public List<Port> getPorts(DeviceId deviceId) {
return portList;
}
@Override
public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
return null;
}
@Override
public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
return null;
}
@Override
public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
return null;
}
@Override
public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
return null;
}
@Override
public Port getPort(DeviceId deviceId, PortNumber portNumber) {
return getPorts(deviceId).stream()
.filter(port -> deviceId.equals(port.element().id()))
.filter(port -> portNumber.equals(port.number()))
.findFirst().orElse(null);
}
@Override
public boolean isAvailable(DeviceId deviceId) {
return false;
}
@Override
public void addListener(DeviceListener listener) {
}
@Override
public void removeListener(DeviceListener listener) {
}
@Override
public Iterable<Device> getDevices(Type type) {
return Collections.emptyList();
}
@Override
public Iterable<Device> getAvailableDevices(Type type) {
return Collections.emptyList();
}
@Override
public String localStatus(DeviceId deviceId) {
return null;
}
}
| {
"content_hash": "707ce34abf940c05a6518b6adc47f770",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 95,
"avg_line_length": 22.58730158730159,
"alnum_prop": 0.6549543218552354,
"repo_name": "sdnwiselab/onos",
"id": "026d253cd617b53c7a92d22728bf656f2222f07e",
"size": "3463",
"binary": false,
"copies": "1",
"ref": "refs/heads/onos-sdn-wise-1.10",
"path": "core/api/src/main/java/org/onosproject/net/device/DeviceServiceAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "222318"
},
{
"name": "HTML",
"bytes": "148718"
},
{
"name": "Java",
"bytes": "34889939"
},
{
"name": "JavaScript",
"bytes": "3818724"
},
{
"name": "Python",
"bytes": "492716"
},
{
"name": "Ruby",
"bytes": "4052"
},
{
"name": "Shell",
"bytes": "205831"
}
],
"symlink_target": ""
} |
<md:EntityDescriptor xmlns:idpdisc="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol"
xmlns:init="urn:oasis:names:tc:SAML:profiles:SSO:request-init"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi"
xmlns:mdui="urn:oasis:names:tc:SAML:metadata:ui" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
entityID="https://ecsg.dch-rp.eu/shibboleth">
<md:Extensions>
<mdrpi:RegistrationInfo registrationAuthority="http://www.idem.garr.it/" registrationInstant="2013-06-10T15:00:00Z">
<mdrpi:RegistrationPolicy xml:lang="en">https://www.idem.garr.it/idem-metadata-registration-practice-statement</mdrpi:RegistrationPolicy>
</mdrpi:RegistrationInfo>
</md:Extensions>
<md:SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:1.0:protocol">
<md:Extensions>
<mdui:UIInfo>
<mdui:DisplayName xml:lang="en">
e-Culture Science Gateway
</mdui:DisplayName>
<mdui:DisplayName xml:lang="it">
e-Culture Science Gateway
</mdui:DisplayName>
<mdui:Description xml:lang="en">
This service allows to use on a Grid infrastructure the applications of the DCH-RP Project which provides tools to store and preserve digital cultural heritage.
</mdui:Description>
<mdui:Description xml:lang="it">
Questo servizio permette l'accesso e l'uso delle applicazioni/servizi sviluppati per il progetto europeo DCH-RP che ha come obiettivo quello di fornire strumenti per la memo
rizzazione ed il mantenimento del patrimonio culturale
</mdui:Description>
</mdui:UIInfo>
<init:RequestInitiator Binding="urn:oasis:names:tc:SAML:profiles:SSO:request-init" Location="https://earthserver-sg.consorzio-cometa.it/Shibboleth.sso/DS"/>
<idpdisc:DiscoveryResponse Binding="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/DS" index="1"/>
</md:Extensions>
<md:KeyDescriptor>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>
MIIF0TCCBLmgAwIBAgIRAJjvs9uxU/ydSPVPqQh6szEwDQYJKoZIhvcNAQEFBQAw
NjELMAkGA1UEBhMCTkwxDzANBgNVBAoTBlRFUkVOQTEWMBQGA1UEAxMNVEVSRU5B
IFNTTCBDQTAeFw0xMzAxMDcwMDAwMDBaFw0xNjAxMDcyMzU5NTlaMIHFMQswCQYD
VQQGEwJJVDEOMAwGA1UEERMFOTUxMjMxDjAMBgNVBAgTBUl0YWx5MRAwDgYDVQQH
EwdDYXRhbmlhMRkwFwYDVQQJExBWaWEgUy5Tb2ZpYSBuLjY0MS4wLAYDVQQKEyVJ
c3RpdHV0byBOYXppb25hbGUgZGkgRmlzaWNhIE51Y2xlYXJlMQ8wDQYDVQQLEwZD
T01FVEExKDAmBgNVBAMTH3d3dy5jYXRhbmlhLXNjaWVuY2UtZ2F0ZXdheXMuaXQw
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDMR2RMw4cNImWSKdvZjDhz
3JuO7/pMOnGw4hF6uu09cqX8qqBpkU/gd33xq7J254ojywwiIlLT7QaTce4YQU2W
O5mPyqdHjnpA+C0fJWrQgRyJEXsOzwpxyUG42tim/9jgNNDaUuNSGgrMLGlzl0sU
i3Cq04AY0hukrtFGe6DFvDsm8xoNwfV8jmO3IipWJdJdezRnCGDgTZqgIWj3yrHo
LjfgLbs85AJ31plMahcEni1jDZYgzu7FurbKpO4FGSLUEI8VUxncdYx3IWidqYBD
TjxFGIiRIcD59DTIBxZYT4IgGHhG1whnUtE7nZhtuxFvnxfH4gPi7mPcRwidNHg9
AgMBAAGjggJIMIICRDAfBgNVHSMEGDAWgBQMvZNoDPPeq6NJays3V0fqkOO57TAd
BgNVHQ4EFgQU+qOkofxo+Ei3aGD2lLEkM4L7LS0wDgYDVR0PAQH/BAQDAgWgMAwG
A1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMCIGA1Ud
IAQbMBkwDQYLKwYBBAGyMQECAh0wCAYGZ4EMAQICMDoGA1UdHwQzMDEwL6AtoCuG
KWh0dHA6Ly9jcmwudGNzLnRlcmVuYS5vcmcvVEVSRU5BU1NMQ0EuY3JsMG0GCCsG
AQUFBwEBBGEwXzA1BggrBgEFBQcwAoYpaHR0cDovL2NydC50Y3MudGVyZW5hLm9y
Zy9URVJFTkFTU0xDQS5jcnQwJgYIKwYBBQUHMAGGGmh0dHA6Ly9vY3NwLnRjcy50
ZXJlbmEub3JnMIH1BgNVHREEge0wgeqCH3d3dy5jYXRhbmlhLXNjaWVuY2UtZ2F0
ZXdheXMuaXSCFWFnaW5mcmEtc2cuY3QuaW5mbi5pdIIVY29naXRvLW1lZC5jdC5p
bmZuLml0giJlYXJ0aHNlcnZlci1zZy5jb25zb3J6aW8tY29tZXRhLml0gg5lY3Nn
LmRjaC1ycC5ldYISZ2Fyci1zZy5jdC5pbmZuLml0ghBrbGlvcy5jdC5pbmZuLml0
ghNsaWZlcmF5Mi5jdC5pbmZuLml0ghNzZ3cuYWZyaWNhLWdyaWQub3JnghV3d3cu
cHJvZ2V0dG8taWNhcm8uaXQwDQYJKoZIhvcNAQEFBQADggEBAIzikPZKDI8rXlUU
iF8KUeEVYZMyBfRtl0sQYBZCprDoVpCr74CPTxQ72Jrh2mD8oAz0ZYVgOA19AbM8
PskJlhx4bmDJvWU/C2FrOgYDNg9Tl7dqLnr18GDt7DuC0KXCDupgtBmwy7mayNgA
n2jbIaYsfMI7k1msS1XoaVX7kBMgmeGY3V11Om9Te7iMWKFOhpavI2hbf741ODtV
zBen58Q2WzjVEKVQYbY7UgtcYzOM44GhMcdS65lLsBviK7HzyB6I5Iu3TR0bcpFE
2V4bd6L5foq3Qn+WO9wqOwnOk3qfD/TQId7NWv0ZE2vp8fPPaaRF2XcA7Qh5xltt
j/MCNlE=
</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:ArtifactResolutionService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/Artifact/SOAP" index="1"/>
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SLO/SOAP"/>
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SLO/Redirect"/>
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SLO/POST"/>
<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SLO/Artifact"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML2/POST" index="1"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML2/POST-SimpleSign" index="2"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML2/Artifact" index="3"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:PAOS" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML2/ECP" index="4"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML/POST" index="5"/>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:1.0:profiles:artifact-01" Location="https://ecsg.dch-rp.eu/Shibboleth.sso/SAML/Artifact" index="6"/>
<md:AttributeConsumingService index="1">
<md:ServiceName xml:lang="en">e-Culture Science Gateway</md:ServiceName>
<md:ServiceDescription xml:lang="en">
This service allows to use on a Grid infrastructure the applications of the DCH-RP Project which provides tools to store and preserve digital cultural heritage.
</md:ServiceDescription>
<md:RequestedAttribute FriendlyName="mail" Name="urn:oid:0.9.2342.19200300.100.1.3" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" isRequired="true"/>
</md:AttributeConsumingService>
</md:SPSSODescriptor>
<md:Organization>
<md:OrganizationName xml:lang="en">INFN Catania</md:OrganizationName>
<md:OrganizationDisplayName xml:lang="en">INFN Catania</md:OrganizationDisplayName>
<md:OrganizationURL xml:lang="en">http://www.ct.infn.it/</md:OrganizationURL>
</md:Organization>
<md:ContactPerson contactType="technical">
<md:GivenName>Marco</md:GivenName>
<md:SurName>Fargetta</md:SurName>
<md:EmailAddress>mailto:marco.fargetta@ct.infn.it</md:EmailAddress>
<md:EmailAddress>mailto:credentials-admin@ct.infn.it</md:EmailAddress>
</md:ContactPerson>
<md:ContactPerson contactType="administrative">
<md:GivenName>Roberto</md:GivenName>
<md:SurName>Barbera</md:SurName>
<md:EmailAddress>mailto:roberto.barbera@ct.infn.it</md:EmailAddress>
<md:EmailAddress>mailto:credentials-admin@ct.infn.it</md:EmailAddress>
</md:ContactPerson>
</md:EntityDescriptor>
| {
"content_hash": "4f99617ad5f622061a02e40b59bf31ce",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 197,
"avg_line_length": 73.58878504672897,
"alnum_prop": 0.7672085344170688,
"repo_name": "OpenConext/OpenConext-teams",
"id": "76151c8fbe3f1dfe4964049e8fac8f28188c4a81",
"size": "7874",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/stoker/349a07fbdcc6a75442bb2c4455e0a5f9.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17097"
},
{
"name": "FreeMarker",
"bytes": "16892"
},
{
"name": "HTML",
"bytes": "7331"
},
{
"name": "Java",
"bytes": "444334"
},
{
"name": "JavaScript",
"bytes": "92080"
}
],
"symlink_target": ""
} |
package org.apache.spark;
import com.linkedin.drelephant.math.Statistics;
import org.apache.commons.io.FileUtils;
import com.linkedin.drelephant.analysis.HadoopApplicationData;
import com.linkedin.drelephant.analysis.HadoopMetricsAggregator;
import com.linkedin.drelephant.analysis.HadoopAggregatedData;
import com.linkedin.drelephant.configurations.aggregator.AggregatorConfigurationData;
import com.linkedin.drelephant.spark.data.SparkApplicationData;
import com.linkedin.drelephant.spark.data.SparkExecutorData;
import com.linkedin.drelephant.util.MemoryFormatUtils;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SparkMetricsAggregator implements HadoopMetricsAggregator {
private static final Logger logger = LoggerFactory.getLogger(SparkMetricsAggregator.class);
private AggregatorConfigurationData _aggregatorConfigurationData;
private double _storageMemWastageBuffer = 0.5;
private static final String SPARK_EXECUTOR_MEMORY = "spark.executor.memory";
private static final String STORAGE_MEM_WASTAGE_BUFFER = "storage_mem_wastage_buffer";
private HadoopAggregatedData _hadoopAggregatedData = new HadoopAggregatedData();
public SparkMetricsAggregator(AggregatorConfigurationData _aggregatorConfigurationData) {
this._aggregatorConfigurationData = _aggregatorConfigurationData;
String configValue = _aggregatorConfigurationData.getParamMap().get(STORAGE_MEM_WASTAGE_BUFFER);
if(configValue != null) {
_storageMemWastageBuffer = Double.parseDouble(configValue);
}
}
@Override
public void aggregate(HadoopApplicationData data) {
long resourceUsed = 0;
long resourceWasted = 0;
SparkApplicationData applicationData = (SparkApplicationData) data;
long perExecutorMem =
MemoryFormatUtils.stringToBytes(applicationData.getEnvironmentData().getSparkProperty(SPARK_EXECUTOR_MEMORY, "0"));
Iterator<String> executorIds = applicationData.getExecutorData().getExecutors().iterator();
while(executorIds.hasNext()) {
String executorId = executorIds.next();
SparkExecutorData.ExecutorInfo executorInfo = applicationData.getExecutorData().getExecutorInfo(executorId);
// store the resourceUsed in MBSecs
resourceUsed += (executorInfo.duration / Statistics.SECOND_IN_MS) * (perExecutorMem / FileUtils.ONE_MB);
// maxMem is the maximum available storage memory
// memUsed is how much storage memory is used.
// any difference is wasted after a buffer of 50% is wasted
long excessMemory = (long) (executorInfo.maxMem - (executorInfo.memUsed * (1.0 + _storageMemWastageBuffer)));
if( excessMemory > 0) {
resourceWasted += (executorInfo.duration / Statistics.SECOND_IN_MS) * (excessMemory / FileUtils.ONE_MB);
}
}
_hadoopAggregatedData.setResourceUsed(resourceUsed);
_hadoopAggregatedData.setResourceWasted(resourceWasted);
// TODO: to find a way to calculate the delay
_hadoopAggregatedData.setTotalDelay(0L);
}
@Override
public HadoopAggregatedData getResult() {
return _hadoopAggregatedData;
}
}
| {
"content_hash": "1a872a6ce2d7bd76932323571cb821ed",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 123,
"avg_line_length": 41.666666666666664,
"alnum_prop": 0.77824,
"repo_name": "qubole/dr-elephant",
"id": "ef8566b41dc4f8b8a58ba69a8721a5fa9be1fc41",
"size": "3718",
"binary": false,
"copies": "1",
"ref": "refs/heads/q-master",
"path": "app/org/apache/spark/SparkMetricsAggregator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28725"
},
{
"name": "HTML",
"bytes": "201309"
},
{
"name": "Java",
"bytes": "718627"
},
{
"name": "JavaScript",
"bytes": "171333"
},
{
"name": "Scala",
"bytes": "39148"
},
{
"name": "Shell",
"bytes": "10430"
}
],
"symlink_target": ""
} |
import React from 'react'
import Link from 'gatsby-link'
const IndexPage = () => (
<div>
<h1>Hi people,</h1>
<p>Welcome to the Code Nut, a blog about software engineering</p>
</div>
)
export default IndexPage
| {
"content_hash": "36a34b3cbd67e6f7291540dd77e21bcc",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 69,
"avg_line_length": 20.272727272727273,
"alnum_prop": 0.6636771300448431,
"repo_name": "thecodenutproject/thecodenut",
"id": "c2075bf0c34e1739b5f448b7ede1d95d2773a800",
"size": "223",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pages/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11497"
},
{
"name": "JavaScript",
"bytes": "7485"
}
],
"symlink_target": ""
} |
<?php
namespace HeyDoc;
use Symfony\Component\HttpFoundation\Request as BaseRequest;
class Request extends BaseRequest
{
/**
* Get path without base url
*
* @return string
*/
public function getPath()
{
return str_replace($this->getBaseUrl(), '', $this->getRequestUri());
}
}
| {
"content_hash": "aaf90f4ec1070b2b8bd63c88053b0437",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 76,
"avg_line_length": 17.944444444444443,
"alnum_prop": 0.6253869969040248,
"repo_name": "nicolas-brousse/HeyDoc",
"id": "de9155d229a24c5b0d3f8fde21180e3787866897",
"size": "323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HeyDoc/Request.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1451"
},
{
"name": "PHP",
"bytes": "51036"
}
],
"symlink_target": ""
} |
{-# LANGUAGE CPP,MagicHash,UnboxedTuples #-}
-- | This module defines the algebraic type-classes used in subhask.
-- The class hierarchies are significantly more general than those in the standard Prelude.
module SubHask.Algebra
(
-- * Comparisons
Logic
, ValidLogic
, ClassicalLogic
, Eq_ (..)
, Eq
, ValidEq
, law_Eq_reflexive
, law_Eq_symmetric
, law_Eq_transitive
, defn_Eq_noteq
, POrd_ (..)
, POrd
, law_POrd_commutative
, law_POrd_associative
, theorem_POrd_idempotent
, Lattice_ (..)
, Lattice
, isChain
, isAntichain
, POrdering (..)
, law_Lattice_commutative
, law_Lattice_associative
, theorem_Lattice_idempotent
, law_Lattice_infabsorption
, law_Lattice_supabsorption
, law_Lattice_reflexivity
, law_Lattice_antisymmetry
, law_Lattice_transitivity
, defn_Lattice_greaterthan
, MinBound_ (..)
, MinBound
, law_MinBound_inf
, Bounded (..)
, law_Bounded_sup
, supremum
, supremum_
, infimum
, infimum_
, Complemented (..)
, law_Complemented_not
, Heyting (..)
, modusPonens
, law_Heyting_maxbound
, law_Heyting_infleft
, law_Heyting_infright
, law_Heyting_distributive
, Boolean (..)
, law_Boolean_infcomplement
, law_Boolean_supcomplement
, law_Boolean_infdistributivity
, law_Boolean_supdistributivity
-- , defn_Latticelessthaninf
-- , defn_Latticelessthansup
, Ord_ (..)
, law_Ord_totality
, law_Ord_min
, law_Ord_max
, Ord
, Ordering (..)
, min
, max
, maximum
, maximum_
, minimum
, minimum_
, argmin
, argmax
-- , argminimum_
-- , argmaximum_
, Graded (..)
, law_Graded_fromEnum
, law_Graded_pred
, defn_Graded_predN
, Enum (..)
, law_Enum_toEnum
, law_Enum_succ
, defn_Enum_succN
-- ** Boolean helpers
, (||)
, (&&)
, true
, false
, and
, or
-- * Set-like
, Elem
, SetElem
, Container (..)
, law_Container_preservation
, Constructible (..)
, Constructible0
, law_Constructible_singleton
, defn_Constructible_cons
, defn_Constructible_snoc
, defn_Constructible_fromList
, defn_Constructible_fromListN
, theorem_Constructible_cons
, fromString
, fromList
, fromListN
, generate
, insert
, empty
, isEmpty
, Foldable (..)
, law_Foldable_sum
, theorem_Foldable_tofrom
, defn_Foldable_foldr
, defn_Foldable_foldr'
, defn_Foldable_foldl
, defn_Foldable_foldl'
, defn_Foldable_foldr1
, defn_Foldable_foldr1'
, defn_Foldable_foldl1
, defn_Foldable_foldl1'
, foldtree1
, length
, reduce
, concat
, headMaybe
, tailMaybe
, lastMaybe
, initMaybe
-- *** indexed containers
, Index
, SetIndex
, IxContainer (..)
, law_IxContainer_preservation
, defn_IxContainer_bang
, defn_IxContainer_findWithDefault
, defn_IxContainer_hasIndex
, (!?)
, Sliceable (..)
, law_Sliceable_restorable
, law_Sliceable_preservation
, IxConstructible (..)
, law_IxConstructible_lookup
, defn_IxConstructible_consAt
, defn_IxConstructible_snocAt
, defn_IxConstructible_fromIxList
, theorem_IxConstructible_preservation
, insertAt
-- * Types
, CanError (..)
, Maybe' (..)
, justs'
, Labeled' (..)
-- * Number-like
-- ** Classes with one operator
, Semigroup (..)
, law_Semigroup_associativity
, defn_Semigroup_plusequal
, Actor
, Action (..)
, law_Action_compatibility
, defn_Action_dotplusequal
, (+.)
, Cancellative (..)
, law_Cancellative_rightminus1
, law_Cancellative_rightminus2
, defn_Cancellative_plusequal
, Monoid (..)
, isZero
, notZero
, law_Monoid_leftid
, law_Monoid_rightid
, defn_Monoid_isZero
, Abelian (..)
, law_Abelian_commutative
, Group (..)
, law_Group_leftinverse
, law_Group_rightinverse
, defn_Group_negateminus
-- ** Classes with two operators
, Rg(..)
, law_Rg_multiplicativeAssociativity
, law_Rg_multiplicativeCommutivity
, law_Rg_annihilation
, law_Rg_distributivityLeft
, theorem_Rg_distributivityRight
, defn_Rg_timesequal
, Rig(..)
, isOne
, notOne
, law_Rig_multiplicativeId
, Rng
, defn_Ring_fromInteger
, Ring(..)
, indicator
, Integral(..)
, law_Integral_divMod
, law_Integral_quotRem
, law_Integral_toFromInverse
, roundUpToNearest
-- , roundUpToNearestBase2
, fromIntegral
, Field(..)
, OrdField(..)
, RationalField(..)
, convertRationalField
, toFloat
, toDouble
, BoundedField(..)
, infinity
, negInfinity
, ExpRing (..)
, (^)
, ExpField (..)
, Real (..)
, QuotientField(..)
-- ** Sizes
, Normed (..)
, abs
, Metric (..)
, isFartherThan
, lb2distanceUB
, law_Metric_nonnegativity
, law_Metric_indiscernables
, law_Metric_symmetry
, law_Metric_triangle
-- ** Linear algebra
, Scalar
, IsScalar
, HasScalar
, type (><)
, Cone (..)
, Module (..)
, law_Module_multiplication
, law_Module_addition
, law_Module_action
, law_Module_unital
, defn_Module_dotstarequal
, (*.)
, FreeModule (..)
, law_FreeModule_commutative
, law_FreeModule_associative
, law_FreeModule_id
, defn_FreeModule_dotstardotequal
, FiniteModule (..)
, VectorSpace (..)
, Banach (..)
, Hilbert (..)
, innerProductDistance
, innerProductNorm
, TensorAlgebra (..)
-- * Spatial programming
, Any (..)
, All
-- * Helper functions
, simpleMutableDefn
, module SubHask.Mutable
)
where
import qualified Prelude as P
import qualified Data.Number.Erf as P
import qualified Math.Gamma as P
import qualified Data.List as L
import Prelude (Ordering (..))
import Control.Monad hiding (liftM)
import Control.Monad.ST
import Data.Ratio
import Data.Typeable
import Test.QuickCheck (Arbitrary (..), frequency)
import Control.Concurrent
import Control.Parallel
import Control.Parallel.Strategies
import System.IO.Unsafe -- used in the parallel function
import GHC.Prim hiding (Any)
import GHC.Types
import GHC.Magic
import SubHask.Internal.Prelude
import SubHask.Category
import SubHask.Mutable
import SubHask.SubType
-------------------------------------------------------------------------------
-- Helper functions
-- | Creates a quickcheck property for a simple mutable operator defined using "immutable2mutable"
simpleMutableDefn :: (Eq_ a, IsMutable a)
=> (Mutable (ST s) a -> b -> ST s ()) -- ^ mutable function
-> (a -> b -> a) -- ^ create a mutable function using "immutable2mutable"
-> (a -> b -> Logic a) -- ^ the output property
simpleMutableDefn mf f a b = unsafeRunMutableProperty $ do
ma1 <- thaw a
ma2 <- thaw a
mf ma1 b
immutable2mutable f ma2 b
a1 <- freeze ma1
a2 <- freeze ma2
return $ a1==a2
-------------------------------------------------------------------------------
-- relational classes
-- | Every type has an associated logic.
-- Most types use classical logic, which corresponds to the Bool type.
-- But types can use any logical system they want.
-- Functions, for example, use an infinite logic.
-- You probably want your logic to be an instance of "Boolean", but this is not required.
--
-- See wikipedia's articles on <https://en.wikipedia.org/wiki/Algebraic_logic algebraic logic>,
-- and <https://en.wikipedia.org/wiki/Infinitary_logic infinitary logic> for more details.
type family Logic a :: *
type instance Logic Bool = Bool
type instance Logic Char = Bool
type instance Logic Int = Bool
type instance Logic Integer = Bool
type instance Logic Rational = Bool
type instance Logic Float = Bool
type instance Logic Double = Bool
type instance Logic (a->b) = a -> Logic b
type instance Logic () = ()
-- FIXME:
-- This type is only needed to due an apparent ghc bug.
-- See [#10592](https://ghc.haskell.org/trac/ghc/ticket/10592).
-- But there seems to be a workaround now.
type ValidLogic a = Complemented (Logic a)
-- | Classical logic is implemented using the Prelude's Bool type.
type ClassicalLogic a = Logic a ~ Bool
-- | Defines equivalence classes over the type.
-- The values need not have identical representations in the machine to be equal.
--
-- See <https://en.wikipedia.org/wiki/Equivalence_class wikipedia>
-- and <http://ncatlab.org/nlab/show/equivalence+class ncatlab> for more details.
class Eq_ a where
infix 4 ==
(==) :: a -> a -> Logic a
-- | In order to have the "not equals to" relation, your logic must have a notion of "not", and therefore must be "Boolean".
{-# INLINE (/=) #-}
infix 4 /=
(/=) :: ValidLogic a => a -> a -> Logic a
(/=) = not (==)
law_Eq_reflexive :: Eq a => a -> Logic a
law_Eq_reflexive a = a==a
law_Eq_symmetric :: Eq a => a -> a -> Logic a
law_Eq_symmetric a1 a2 = (a1==a2)==(a2==a1)
law_Eq_transitive :: Eq a => a -> a -> a -> Logic a
law_Eq_transitive a1 a2 a3 = (a1==a2&&a2==a3) ==> (a1==a3)
defn_Eq_noteq :: (Complemented (Logic a), Eq a) => a -> a -> Logic a
defn_Eq_noteq a1 a2 = (a1/=a2) == (not $ a1==a2)
instance Eq_ () where
{-# INLINE (==) #-}
() == () = ()
{-# INLINE (/=) #-}
() /= () = ()
instance Eq_ Bool where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Char where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Int where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Integer where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Rational where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Float where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ Double where (==) = (P.==); (/=) = (P./=); {-# INLINE (==) #-}; {-# INLINE (/=) #-}
instance Eq_ b => Eq_ (a -> b) where
{-# INLINE (==) #-}
(f==g) a = f a == g a
type Eq a = (Eq_ a, Logic a~Bool)
type ValidEq a = (Eq_ a, ValidLogic a)
-- class (Eq_ a, Logic a ~ Bool) => Eq a
-- instance (Eq_ a, Logic a ~ Bool) => Eq a
--
-- class (Eq_ a, ValidLogic a) => ValidEq a
-- instance (Eq_ a, ValidLogic a) => ValidEq a
--------------------
-- | This is more commonly known as a "meet" semilattice
class Eq_ b => POrd_ b where
inf :: b -> b -> b
{-# INLINE (<=) #-}
infix 4 <=
(<=) :: b -> b -> Logic b
b1 <= b2 = inf b1 b2 == b1
{-# INLINE (<) #-}
infix 4 <
(<) :: Complemented (Logic b) => b -> b -> Logic b
b1 < b2 = inf b1 b2 == b1 && b1 /= b2
type POrd a = (Eq a, POrd_ a)
-- class (Eq b, POrd_ b) => POrd b
-- instance (Eq b, POrd_ b) => POrd b
law_POrd_commutative :: (Eq b, POrd_ b) => b -> b -> Bool
law_POrd_commutative b1 b2 = inf b1 b2 == inf b2 b1
law_POrd_associative :: (Eq b, POrd_ b) => b -> b -> b -> Bool
law_POrd_associative b1 b2 b3 = inf (inf b1 b2) b3 == inf b1 (inf b2 b3)
theorem_POrd_idempotent :: (Eq b, POrd_ b) => b -> Bool
theorem_POrd_idempotent b = inf b b == b
#define mkPOrd_(x) \
instance POrd_ x where \
inf = (P.min) ;\
(<=) = (P.<=) ;\
(<) = (P.<) ;\
{-# INLINE inf #-} ;\
{-# INLINE (<=) #-} ;\
{-# INLINE (<) #-}
mkPOrd_(Bool)
mkPOrd_(Char)
mkPOrd_(Int)
mkPOrd_(Integer)
mkPOrd_(Float)
mkPOrd_(Double)
mkPOrd_(Rational)
instance POrd_ () where
{-# INLINE inf #-}
inf () () = ()
instance POrd_ b => POrd_ (a -> b) where
{-# INLINE inf #-}
inf f g = \x -> inf (f x) (g x)
{-# INLINE (<) #-}
(f<=g) a = f a <= g a
-------------------
-- | Most Lattice literature only considers 'Bounded' lattices, but here we have both upper and lower bounded lattices.
--
-- prop> minBound <= b || not (minBound > b)
--
class POrd_ b => MinBound_ b where
minBound :: b
type MinBound a = (Eq a, MinBound_ a)
-- class (Eq b, MinBound_ b) => MinBound b
-- instance (Eq b, MinBound_ b) => MinBound b
law_MinBound_inf :: (Eq b, MinBound_ b) => b -> Bool
law_MinBound_inf b = inf b minBound == minBound
-- | "false" is an upper bound because `a && false = false` for all a.
{-# INLINE false #-}
false :: MinBound_ b => b
false = minBound
instance MinBound_ () where minBound = () ; {-# INLINE minBound #-}
instance MinBound_ Bool where minBound = False ; {-# INLINE minBound #-}
instance MinBound_ Char where minBound = P.minBound ; {-# INLINE minBound #-}
instance MinBound_ Int where minBound = P.minBound ; {-# INLINE minBound #-}
instance MinBound_ Float where minBound = -1/0 ; {-# INLINE minBound #-}
instance MinBound_ Double where minBound = -1/0 ; {-# INLINE minBound #-}
-- FIXME: should be a primop for this
instance MinBound_ b => MinBound_ (a -> b) where minBound = \x -> minBound ; {-# INLINE minBound #-}
-------------------
-- | Represents all the possible ordering relations in a classical logic (i.e. Logic a ~ Bool)
data POrdering
= PLT
| PGT
| PEQ
| PNA
deriving (Read,Show)
type instance Logic POrdering = Bool
instance Arbitrary POrdering where
arbitrary = frequency
[ (1, P.return PLT)
, (1, P.return PGT)
, (1, P.return PEQ)
, (1, P.return PNA)
]
instance Eq_ POrdering where
{-# INLINE (==) #-}
PLT == PLT = True
PGT == PGT = True
PEQ == PEQ = True
PNA == PNA = True
_ == _ = False
-- | FIXME: there are many semigroups over POrdering;
-- how should we represent the others? newtypes?
instance Semigroup POrdering where
{-# INLINE (+) #-}
PEQ + x = x
PLT + _ = PLT
PGT + _ = PGT
PNA + _ = PNA
type instance Logic Ordering = Bool
instance Eq_ Ordering where
{-# INLINE (==) #-}
EQ == EQ = True
LT == LT = True
GT == GT = True
_ == _ = False
instance Semigroup Ordering where
{-# INLINE (+) #-}
EQ + x = x
LT + _ = LT
GT + _ = GT
instance Monoid POrdering where
{-# INLINE zero #-}
zero = PEQ
instance Monoid Ordering where
{-# INLINE zero #-}
zero = EQ
-- |
--
--
-- See <https://en.wikipedia.org/wiki/Lattice_%28order%29 wikipedia> for more details.
class POrd_ b => Lattice_ b where
sup :: b -> b -> b
{-# INLINE (>=) #-}
infix 4 >=
(>=) :: b -> b -> Logic b
b1 >= b2 = sup b1 b2 == b1
{-# INLINE (>) #-}
infix 4 >
(>) :: Boolean (Logic b) => b -> b -> Logic b
b1 > b2 = sup b1 b2 == b1 && b1 /= b2
-- | This function does not make sense on non-classical logics
--
-- FIXME: there are probably related functions for all these other logics;
-- is there a nice way to represent them all?
{-# INLINABLE pcompare #-}
pcompare :: Logic b ~ Bool => b -> b -> POrdering
pcompare a b = if a==b
then PEQ
else if a < b
then PLT
else if a > b
then PGT
else PNA
type Lattice a = (Eq a, Lattice_ a)
-- class (Eq b, Lattice_ b) => Lattice b
-- instance (Eq b, Lattice_ b) => Lattice b
law_Lattice_commutative :: (Eq b, Lattice_ b) => b -> b -> Bool
law_Lattice_commutative b1 b2 = sup b1 b2 == sup b2 b1
law_Lattice_associative :: (Eq b, Lattice_ b) => b -> b -> b -> Bool
law_Lattice_associative b1 b2 b3 = sup (sup b1 b2) b3 == sup b1 (sup b2 b3)
theorem_Lattice_idempotent :: (Eq b, Lattice_ b) => b -> Bool
theorem_Lattice_idempotent b = sup b b == b
law_Lattice_infabsorption :: (Eq b, Lattice b) => b -> b -> Bool
law_Lattice_infabsorption b1 b2 = inf b1 (sup b1 b2) == b1
law_Lattice_supabsorption :: (Eq b, Lattice b) => b -> b -> Bool
law_Lattice_supabsorption b1 b2 = sup b1 (inf b1 b2) == b1
law_Lattice_reflexivity :: Lattice a => a -> Logic a
law_Lattice_reflexivity a = a<=a
law_Lattice_antisymmetry :: Lattice a => a -> a -> Logic a
law_Lattice_antisymmetry a1 a2
| a1 <= a2 && a2 <= a1 = a1 == a2
| otherwise = true
law_Lattice_transitivity :: Lattice a => a -> a -> a -> Logic a
law_Lattice_transitivity a1 a2 a3
| a1 <= a2 && a2 <= a3 = a1 <= a3
| a1 <= a3 && a3 <= a2 = a1 <= a2
| a2 <= a1 && a1 <= a3 = a2 <= a3
| a2 <= a3 && a3 <= a1 = a2 <= a1
| a3 <= a2 && a2 <= a1 = a3 <= a1
| a3 <= a1 && a1 <= a2 = a3 <= a2
| otherwise = true
defn_Lattice_greaterthan :: Lattice a => a -> a -> Logic a
defn_Lattice_greaterthan a1 a2
| a1 < a2 = a2 >= a1
| a1 > a2 = a2 <= a1
| otherwise = true
#define mkLattice_(x)\
instance Lattice_ x where \
sup = (P.max) ;\
(>=) = (P.>=) ;\
(>) = (P.>) ;\
{-# INLINE sup #-} ;\
{-# INLINE (>=) #-} ;\
{-# INLINE (>) #-}
mkLattice_(Bool)
mkLattice_(Char)
mkLattice_(Int)
mkLattice_(Integer)
mkLattice_(Float)
mkLattice_(Double)
mkLattice_(Rational)
instance Lattice_ () where
{-# INLINE sup #-}
sup () () = ()
instance Lattice_ b => Lattice_ (a -> b) where
{-# INLINE sup #-}
sup f g = \x -> sup (f x) (g x)
{-# INLINE (>=) #-}
(f>=g) a = f a >= g a
{-# INLINE (&&) #-}
infixr 3 &&
(&&) :: Lattice_ b => b -> b -> b
(&&) = inf
{-# INLINE (||) #-}
infixr 2 ||
(||) :: Lattice_ b => b -> b -> b
(||) = sup
-- | A chain is a collection of elements all of which can be compared
{-# INLINABLE isChain #-}
isChain :: Lattice a => [a] -> Logic a
isChain [] = true
isChain (x:xs) = all (/=PNA) (map (pcompare x) xs) && isChain xs
-- | An antichain is a collection of elements none of which can be compared
--
-- See <http://en.wikipedia.org/wiki/Antichain wikipedia> for more details.
--
-- See also the article on <http://en.wikipedia.org/wiki/Dilworth%27s_theorem Dilward's Theorem>.
{-# INLINABLE isAntichain #-}
isAntichain :: Lattice a => [a] -> Logic a
isAntichain [] = true
isAntichain (x:xs) = all (==PNA) (map (pcompare x) xs) && isAntichain xs
-------------------
-- | An element of a graded lattice has a unique predecessor.
--
-- See <https://en.wikipedia.org/wiki/Graded_poset wikipedia> for more details.
class Lattice b => Graded b where
-- | Algebrists typically call this function the "rank" of the element in the poset;
-- however we use the name from the standard prelude instead
fromEnum :: b -> Int
-- | The predecessor in the ordering
pred :: b -> b
-- | Repeatedly apply the "pred" function
predN :: Int -> b -> b
predN i b
| i < 0 = error $ "predN called on negative number "++show i
| i == 0 = b
| i > 0 = predN (i-1) $ pred b
law_Graded_fromEnum :: (Lattice b, Graded b) => b -> b -> Bool
law_Graded_fromEnum b1 b2
| b1 < b2 = fromEnum b1 < fromEnum b2
| b1 > b2 = fromEnum b1 > fromEnum b2
| b1 == b2 = fromEnum b1 == fromEnum b2
| otherwise = True
law_Graded_pred :: Graded b => b -> b -> Bool
law_Graded_pred b1 b2 = fromEnum (pred b1) == fromEnum b1-1
|| fromEnum (pred b1) == fromEnum b1
defn_Graded_predN :: Graded b => Int -> b -> Bool
defn_Graded_predN i b
| i < 0 = true
| otherwise = go i b == predN i b
where
go 0 b = b
go i b = go (i-1) $ pred b
instance Graded Bool where
{-# INLINE pred #-}
pred True = False
pred False = False
{-# INLINE fromEnum #-}
fromEnum True = 1
fromEnum False = 0
instance Graded Int where
{-# INLINE pred #-}
pred i = if i == minBound
then i
else i-1
{-# INLINE predN #-}
predN n i = if i-n <= i
then i-n
else minBound
{-# INLINE fromEnum #-}
fromEnum = id
instance Graded Char where
{-# INLINE pred #-}
pred c = if c=='\NUL'
then '\NUL'
else P.pred c
{-# INLINE fromEnum #-}
fromEnum = P.fromEnum
instance Graded Integer where
{-# INLINE pred #-}
pred = P.pred
{-# INLINE predN #-}
predN n i = i - toInteger n
{-# INLINE fromEnum #-}
fromEnum = P.fromEnum
{-# INLINE (<.) #-}
(<.) :: (Lattice b, Graded b) => b -> b -> Bool
b1 <. b2 = b1 == pred b2
-- | In a well founded ordering, every element (except possibly the "maxBound" if it exists) has a successor element.
-- We use the "Enum" to represent well founded orderings to maintain consistency with the standard Prelude.
--
-- See <ncatlab http://ncatlab.org/nlab/show/well-founded+relation> for more info.
class (Graded b, Ord_ b) => Enum b where
-- | The next element in the ordering
succ :: b -> b
-- | Advance many elements into the ordering.
-- This value may be negative to move backwards.
succN :: Int -> b -> b
succN i b = toEnum $ fromEnum b + i
-- | Given an index (also called a rank) of an element, return the element
toEnum :: Int -> b
law_Enum_toEnum :: Enum b => b -> Bool
law_Enum_toEnum b = toEnum (fromEnum b) == b
law_Enum_succ :: Enum b => b -> b -> Bool
law_Enum_succ b1 b2 = fromEnum (succ b1) == fromEnum b1+1
|| fromEnum (succ b1) == fromEnum b1
defn_Enum_succN :: Enum b => Int -> b -> Logic b
defn_Enum_succN i b = succN i b == toEnum (fromEnum b + i)
instance Enum Bool where
{-# INLINE succ #-}
succ True = True
succ False = True
{-# INLINE toEnum #-}
toEnum i
| i > 0 = True
| otherwise = False
instance Enum Int where
{-# INLINE succ #-}
succ i = if i == maxBound
then i
else i+1
{-# INLINE toEnum #-}
toEnum = id
instance Enum Char where
{-# INLINE succ #-}
succ = P.succ
{-# INLINE toEnum #-}
toEnum i = if i < 0
then P.toEnum 0
else P.toEnum i
instance Enum Integer where
{-# INLINE succ #-}
succ = P.succ
{-# INLINE toEnum #-}
toEnum = P.toEnum
{-# INLINE (>.) #-}
(>.) :: (Lattice b, Enum b) => b -> b -> Bool
b1 >. b2 = b1 == succ b2
---------------------------------------
-- | This is the class of total orderings.
--
-- See https://en.wikipedia.org/wiki/Total_order
class Lattice_ a => Ord_ a where
compare :: (Logic a~Bool, Ord_ a) => a -> a -> Ordering
compare a1 a2 = case pcompare a1 a2 of
PLT -> LT
PGT -> GT
PEQ -> EQ
PNA -> error "PNA given by pcompare on a totally ordered type"
law_Ord_totality :: Ord a => a -> a -> Bool
law_Ord_totality a1 a2 = a1 <= a2 || a2 <= a1
law_Ord_min :: Ord a => a -> a -> Bool
law_Ord_min a1 a2 = min a1 a2 == a1
|| min a1 a2 == a2
law_Ord_max :: Ord a => a -> a -> Bool
law_Ord_max a1 a2 = max a1 a2 == a1
|| max a1 a2 == a2
{-# INLINE min #-}
min :: Ord_ a => a -> a -> a
min = inf
{-# INLINE max #-}
max :: Ord_ a => a -> a -> a
max = sup
type Ord a = (Eq a, Ord_ a)
instance Ord_ ()
instance Ord_ Char where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Int where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Integer where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Float where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Double where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Rational where compare = P.compare ; {-# INLINE compare #-}
instance Ord_ Bool where compare = P.compare ; {-# INLINE compare #-}
-------------------
-- | A Bounded lattice is a lattice with both a minimum and maximum element
--
class (Lattice_ b, MinBound_ b) => Bounded b where
maxBound :: b
law_Bounded_sup :: (Eq b, Bounded b) => b -> Bool
law_Bounded_sup b = sup b maxBound == maxBound
-- | "true" is an lower bound because `a && true = true` for all a.
{-# INLINE true #-}
true :: Bounded b => b
true = maxBound
instance Bounded () where maxBound = () ; {-# INLINE maxBound #-}
instance Bounded Bool where maxBound = True ; {-# INLINE maxBound #-}
instance Bounded Char where maxBound = P.maxBound ; {-# INLINE maxBound #-}
instance Bounded Int where maxBound = P.maxBound ; {-# INLINE maxBound #-}
instance Bounded Float where maxBound = 1/0 ; {-# INLINE maxBound #-}
instance Bounded Double where maxBound = 1/0 ; {-# INLINE maxBound #-}
-- FIXME: should be a primop for infinity
instance Bounded b => Bounded (a -> b) where
{-# INLINE maxBound #-}
maxBound = \x -> maxBound
--------------------
class Bounded b => Complemented b where
not :: b -> b
law_Complemented_not :: (ValidLogic b, Complemented b) => b -> Logic b
law_Complemented_not b = not (true `asTypeOf` b) == false
&& not (false `asTypeOf` b) == true
instance Complemented () where
{-# INLINE not #-}
not () = ()
instance Complemented Bool where
{-# INLINE not #-}
not = P.not
instance Complemented b => Complemented (a -> b) where
{-# INLINE not #-}
not f = \x -> not $ f x
-- | Heyting algebras are lattices that support implication, but not necessarily the law of excluded middle.
--
-- FIXME:
-- Is every Heyting algebra a cancellative Abelian semigroup?
-- If so, should we make that explicit in the class hierarchy?
--
-- ==== Laws
-- There is a single, simple law that Heyting algebras must satisfy:
--
-- prop> a ==> b = c ===> a && c < b
--
-- ==== Theorems
-- From the laws, we automatically get the properties of:
--
-- distributivity
--
-- See <https://en.wikipedia.org/wiki/Heyting_algebra wikipedia> for more details.
class Bounded b => Heyting b where
-- | FIXME: think carefully about infix
infixl 3 ==>
(==>) :: b -> b -> b
law_Heyting_maxbound :: (Eq b, Heyting b) => b -> Bool
law_Heyting_maxbound b = (b ==> b) == maxBound
law_Heyting_infleft :: (Eq b, Heyting b) => b -> b -> Bool
law_Heyting_infleft b1 b2 = (b1 && (b1 ==> b2)) == (b1 && b2)
law_Heyting_infright :: (Eq b, Heyting b) => b -> b -> Bool
law_Heyting_infright b1 b2 = (b2 && (b1 ==> b2)) == b2
law_Heyting_distributive :: (Eq b, Heyting b) => b -> b -> b -> Bool
law_Heyting_distributive b1 b2 b3 = (b1 ==> (b2 && b3)) == ((b1 ==> b2) && (b1 ==> b3))
-- | FIXME: add the axioms for intuitionist logic, which are theorems based on these laws
--
-- | Modus ponens gives us a default definition for "==>" in a "Boolean" algebra.
-- This formula is guaranteed to not work in a "Heyting" algebra that is not "Boolean".
--
-- See <https://en.wikipedia.org/wiki/Modus_ponens wikipedia> for more details.
modusPonens :: Boolean b => b -> b -> b
modusPonens b1 b2 = not b1 || b2
instance Heyting () where
{-# INLINE (==>) #-}
() ==> () = ()
instance Heyting Bool where
{-# INLINE (==>) #-}
(==>) = modusPonens
instance Heyting b => Heyting (a -> b) where
{-# INLINE (==>) #-}
(f==>g) a = f a ==> g a
-- | Generalizes Boolean variables.
--
-- See <https://en.wikipedia.org/wiki/Boolean_algebra_%28structure%29 wikipedia> for more details.
class (Complemented b, Heyting b) => Boolean b where
law_Boolean_infcomplement :: (Eq b, Boolean b) => b -> Bool
law_Boolean_infcomplement b = (b || not b) == true
law_Boolean_supcomplement :: (Eq b, Boolean b) => b -> Bool
law_Boolean_supcomplement b = (b && not b) == false
law_Boolean_infdistributivity :: (Eq b, Boolean b) => b -> b -> b -> Bool
law_Boolean_infdistributivity b1 b2 b3 = (b1 || (b2 && b3)) == ((b1 || b2) && (b1 || b3))
law_Boolean_supdistributivity :: (Eq b, Boolean b) => b -> b -> b -> Bool
law_Boolean_supdistributivity b1 b2 b3 = (b1 && (b2 || b3)) == ((b1 && b2) || (b1 && b3))
instance Boolean ()
instance Boolean Bool
instance Boolean b => Boolean (a -> b)
-------------------------------------------------------------------------------
-- numeric classes
class IsMutable g => Semigroup g where
{-# MINIMAL (+) | (+=) #-}
{-# INLINE (+) #-}
infixl 6 +
(+) :: g -> g -> g
(+) = mutable2immutable (+=)
{-# INLINE (+=) #-}
infixr 5 +=
(+=) :: (PrimBase m) => Mutable m g -> g -> m ()
(+=) = immutable2mutable (+)
law_Semigroup_associativity :: (Eq g, Semigroup g ) => g -> g -> g -> Logic g
law_Semigroup_associativity g1 g2 g3 = g1 + (g2 + g3) == (g1 + g2) + g3
defn_Semigroup_plusequal :: (Eq_ g, Semigroup g, IsMutable g) => g -> g -> Logic g
defn_Semigroup_plusequal = simpleMutableDefn (+=) (+)
-- | Measures the degree to which a Semigroup obeys the associative law.
--
-- FIXME: Less-than-perfect associativity should be formalized in the class laws somehow.
associator :: (Semigroup g, Metric g) => g -> g -> g -> Scalar g
associator g1 g2 g3 = distance ((g1+g2)+g3) (g1+(g2+g3))
-- | A generalization of 'Data.List.cycle' to an arbitrary 'Semigroup'.
-- May fail to terminate for some values in some semigroups.
cycle :: Semigroup m => m -> m
cycle xs = xs' where xs' = xs + xs'
instance Semigroup Int where (+) = (P.+) ; {-# INLINE (+) #-}
instance Semigroup Integer where (+) = (P.+) ; {-# INLINE (+) #-}
instance Semigroup Float where (+) = (P.+) ; {-# INLINE (+) #-}
instance Semigroup Double where (+) = (P.+) ; {-# INLINE (+) #-}
instance Semigroup Rational where (+) = (P.+) ; {-# INLINE (+) #-}
instance Semigroup () where
{-# INLINE (+) #-}
()+() = ()
instance Semigroup b => Semigroup (a -> b) where
{-# INLINE (+) #-}
f+g = \a -> f a + g a
---------------------------------------
-- | This type class is only used by the "Action" class.
-- It represents the semigroup that acts on our type.
type family Actor s
-- | Semigroup actions let us apply a semigroup to a set.
-- The theory of Modules is essentially the theory of Ring actions.
-- (See <http://mathoverflow.net/questions/100565/why-are-ring-actions-much-harder-to-find-than-group-actions mathoverflow.)
-- That is why the two classes use similar notation.
--
-- See <https://en.wikipedia.org/wiki/Semigroup_action wikipedia> for more detail.
--
-- FIXME: These types could probably use a more expressive name.
--
-- FIXME: We would like every Semigroup to act on itself, but this results in a class cycle.
class (IsMutable s, Semigroup (Actor s)) => Action s where
{-# MINIMAL (.+) | (.+=) #-}
{-# INLINE (.+) #-}
infixl 6 .+
(.+) :: s -> Actor s -> s
(.+) = mutable2immutable (.+=)
{-# INLINE (.+=) #-}
infixr 5 .+=
(.+=) :: (PrimBase m) => Mutable m s -> Actor s -> m ()
(.+=) = immutable2mutable (.+)
law_Action_compatibility :: (Eq_ s, Action s) => Actor s -> Actor s -> s -> Logic s
law_Action_compatibility a1 a2 s = (a1+a2) +. s == a1 +. a2 +. s
defn_Action_dotplusequal :: (Eq_ s, Action s, Logic (Actor s)~Logic s) => s -> Actor s -> Logic s
defn_Action_dotplusequal = simpleMutableDefn (.+=) (.+)
-- | > s .+ a = a +. s
{-# INLINE (+.) #-}
infixr 6 +.
(+.) :: Action s => Actor s -> s -> s
a +. s = s .+ a
type instance Actor Int = Int
type instance Actor Integer = Integer
type instance Actor Float = Float
type instance Actor Double = Double
type instance Actor Rational = Rational
type instance Actor () = ()
type instance Actor (a->b) = a->Actor b
instance Action Int where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action Integer where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action Float where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action Double where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action Rational where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action () where (.+) = (+) ; {-# INLINE (.+) #-}
instance Action b => Action (a->b) where
{-# INLINE (.+) #-}
f.+g = \x -> f x.+g x
---------------------------------------
class Semigroup g => Monoid g where
zero :: g
-- | FIXME: this should be in the Monoid class, but putting it there requires a lot of changes to Eq
isZero :: (Monoid g, ValidEq g) => g -> Logic g
isZero = (==zero)
-- | FIXME: this should be in the Monoid class, but putting it there requires a lot of changes to Eq
notZero :: (Monoid g, ValidEq g) => g -> Logic g
notZero = (/=zero)
law_Monoid_leftid :: (Monoid g, Eq g) => g -> Bool
law_Monoid_leftid g = zero + g == g
law_Monoid_rightid :: (Monoid g, Eq g) => g -> Bool
law_Monoid_rightid g = g + zero == g
defn_Monoid_isZero :: (Monoid g, Eq g) => g -> Bool
defn_Monoid_isZero g = (isZero $ zero `asTypeOf` g)
&& (g /= zero ==> not isZero g)
---------
instance Monoid Int where zero = 0 ; {-# INLINE zero #-}
instance Monoid Integer where zero = 0 ; {-# INLINE zero #-}
instance Monoid Float where zero = 0 ; {-# INLINE zero #-}
instance Monoid Double where zero = 0 ; {-# INLINE zero #-}
instance Monoid Rational where zero = 0 ; {-# INLINE zero #-}
instance Monoid () where
{-# INLINE zero #-}
zero = ()
instance Monoid b => Monoid (a -> b) where
{-# INLINE zero #-}
zero = \a -> zero
---------------------------------------
-- | In a cancellative semigroup,
--
-- 1)
--
-- > a + b = a + c ==> b = c
-- so
-- > (a + b) - b = a + (b - b) = a
--
-- 2)
--
-- > b + a = c + a ==> b = c
-- so
-- > -b + (b + a) = (-b + b) + a = a
--
-- This allows us to define "subtraction" in the semigroup.
-- If the semigroup is embeddable in a group, subtraction can be thought of as performing the group subtraction and projecting the result back into the domain of the cancellative semigroup.
-- It is an open problem to fully characterize which cancellative semigroups can be embedded into groups.
--
-- See <http://en.wikipedia.org/wiki/Cancellative_semigroup wikipedia> for more details.
class Semigroup g => Cancellative g where
{-# MINIMAL (-) | (-=) #-}
{-# INLINE (-) #-}
infixl 6 -
(-) :: g -> g -> g
(-) = mutable2immutable (-=)
{-# INLINE (-=) #-}
infixr 5 -=
(-=) :: (PrimBase m) => Mutable m g -> g -> m ()
(-=) = immutable2mutable (-)
law_Cancellative_rightminus1 :: (Eq g, Cancellative g) => g -> g -> Bool
law_Cancellative_rightminus1 g1 g2 = (g1 + g2) - g2 == g1
law_Cancellative_rightminus2 :: (Eq g, Cancellative g) => g -> g -> Bool
law_Cancellative_rightminus2 g1 g2 = g1 + (g2 - g2) == g1
defn_Cancellative_plusequal :: (Eq_ g, Cancellative g) => g -> g -> Logic g
defn_Cancellative_plusequal = simpleMutableDefn (-=) (-)
instance Cancellative Int where (-) = (P.-) ; {-# INLINE (-) #-}
instance Cancellative Integer where (-) = (P.-) ; {-# INLINE (-) #-}
instance Cancellative Float where (-) = (P.-) ; {-# INLINE (-) #-}
instance Cancellative Double where (-) = (P.-) ; {-# INLINE (-) #-}
instance Cancellative Rational where (-) = (P.-) ; {-# INLINE (-) #-}
instance Cancellative () where
{-# INLINE (-) #-}
()-() = ()
instance Cancellative b => Cancellative (a -> b) where
{-# INLINE (-) #-}
f-g = \a -> f a - g a
---------------------------------------
class (Cancellative g, Monoid g) => Group g where
{-# INLINE negate #-}
negate :: g -> g
negate g = zero - g
defn_Group_negateminus :: (Eq g, Group g) => g -> g -> Bool
defn_Group_negateminus g1 g2 = g1 + negate g2 == g1 - g2
law_Group_leftinverse :: (Eq g, Group g) => g -> Bool
law_Group_leftinverse g = negate g + g == zero
law_Group_rightinverse :: (Eq g, Group g) => g -> Bool
law_Group_rightinverse g = g + negate g == zero
instance Group Int where negate = P.negate ; {-# INLINE negate #-}
instance Group Integer where negate = P.negate ; {-# INLINE negate #-}
instance Group Float where negate = P.negate ; {-# INLINE negate #-}
instance Group Double where negate = P.negate ; {-# INLINE negate #-}
instance Group Rational where negate = P.negate ; {-# INLINE negate #-}
instance Group () where
{-# INLINE negate #-}
negate () = ()
instance Group b => Group (a -> b) where
{-# INLINE negate #-}
negate f = negate . f
---------------------------------------
class Semigroup m => Abelian m
law_Abelian_commutative :: (Abelian g, Eq g) => g -> g -> Bool
law_Abelian_commutative g1 g2 = g1 + g2 == g2 + g1
instance Abelian Int
instance Abelian Integer
instance Abelian Float
instance Abelian Double
instance Abelian Rational
instance Abelian ()
instance Abelian b => Abelian (a -> b)
---------------------------------------
-- | A Rg is a Ring without multiplicative identity or negative numbers.
-- (Hence the removal of the i and n from the name.)
--
-- There is no standard terminology for this structure.
-- They might also be called \"semirings without identity\", \"pre-semirings\", or \"hemirings\".
-- See <http://math.stackexchange.com/questions/359437/name-for-a-semiring-minus-multiplicative-identity-requirement this stackexchange question> for a discussion on naming.
--
class (Abelian r, Monoid r) => Rg r where
{-# MINIMAL (*) | (*=) #-}
{-# INLINE (*) #-}
infixl 7 *
(*) :: r -> r -> r
(*) = mutable2immutable (*=)
{-# INLINE (*=) #-}
infixr 5 *=
(*=) :: (PrimBase m) => Mutable m r -> r -> m ()
(*=) = immutable2mutable (*)
law_Rg_multiplicativeAssociativity :: (Eq r, Rg r) => r -> r -> r -> Bool
law_Rg_multiplicativeAssociativity r1 r2 r3 = (r1 * r2) * r3 == r1 * (r2 * r3)
law_Rg_multiplicativeCommutivity :: (Eq r, Rg r) => r -> r -> Bool
law_Rg_multiplicativeCommutivity r1 r2 = r1*r2 == r2*r1
law_Rg_annihilation :: (Eq r, Rg r) => r -> Bool
law_Rg_annihilation r = r * zero == zero
law_Rg_distributivityLeft :: (Eq r, Rg r) => r -> r -> r -> Bool
law_Rg_distributivityLeft r1 r2 r3 = r1*(r2+r3) == r1*r2+r1*r3
theorem_Rg_distributivityRight :: (Eq r, Rg r) => r -> r -> r -> Bool
theorem_Rg_distributivityRight r1 r2 r3 = (r2+r3)*r1 == r2*r1+r3*r1
defn_Rg_timesequal :: (Eq_ g, Rg g) => g -> g -> Logic g
defn_Rg_timesequal = simpleMutableDefn (*=) (*)
instance Rg Int where (*) = (P.*) ; {-# INLINE (*) #-}
instance Rg Integer where (*) = (P.*) ; {-# INLINE (*) #-}
instance Rg Float where (*) = (P.*) ; {-# INLINE (*) #-}
instance Rg Double where (*) = (P.*) ; {-# INLINE (*) #-}
instance Rg Rational where (*) = (P.*) ; {-# INLINE (*) #-}
instance Rg b => Rg (a -> b) where
{-# INLINE (*) #-}
f*g = \a -> f a * g a
---------------------------------------
-- | A Rig is a Rg with multiplicative identity.
-- They are also known as semirings.
--
-- See <https://en.wikipedia.org/wiki/Semiring wikipedia>
-- and <http://ncatlab.org/nlab/show/rig ncatlab>
-- for more details.
class (Monoid r, Rg r) => Rig r where
-- | the multiplicative identity
one :: r
-- | FIXME: this should be in the Rig class, but putting it there requires a lot of changes to Eq
isOne :: (Rig g, ValidEq g) => g -> Logic g
isOne = (==one)
-- | FIXME: this should be in the Rig class, but putting it there requires a lot of changes to Eq
notOne :: (Rig g, ValidEq g) => g -> Logic g
notOne = (/=one)
law_Rig_multiplicativeId :: (Eq r, Rig r) => r -> Bool
law_Rig_multiplicativeId r = r * one == r && one * r == r
instance Rig Int where one = 1 ; {-# INLINE one #-}
instance Rig Integer where one = 1 ; {-# INLINE one #-}
instance Rig Float where one = 1 ; {-# INLINE one #-}
instance Rig Double where one = 1 ; {-# INLINE one #-}
instance Rig Rational where one = 1 ; {-# INLINE one #-}
instance Rig b => Rig (a -> b) where
{-# INLINE one #-}
one = \a -> one
---------------------------------------
-- | A "Ring" without identity.
type Rng r = (Rg r, Group r)
-- |
--
-- It is not part of the standard definition of rings that they have a "fromInteger" function.
-- It follows from the definition, however, that we can construct such a function.
-- The "slowFromInteger" function is this standard construction.
--
-- See <https://en.wikipedia.org/wiki/Ring_%28mathematics%29 wikipedia>
-- and <http://ncatlab.org/nlab/show/ring ncatlab>
-- for more details.
--
-- FIXME:
-- We can construct a "Module" from any ring by taking (*)=(.*.).
-- Thus, "Module" should be a superclass of "Ring".
-- Currently, however, this creates a class cycle, so we can't do it.
-- A number of type signatures are therefore more complicated than they need to be.
class (Rng r, Rig r) => Ring r where
fromInteger :: Integer -> r
fromInteger = slowFromInteger
defn_Ring_fromInteger :: (Eq r, Ring r) => r -> Integer -> Bool
defn_Ring_fromInteger r i = fromInteger i `asTypeOf` r
== slowFromInteger i
-- | Here we construct an element of the Ring based on the additive and multiplicative identities.
-- This function takes O(n) time, where n is the size of the Integer.
-- Most types should be able to compute this value significantly faster.
--
-- FIXME: replace this with peasant multiplication.
slowFromInteger :: forall r. (Rng r, Rig r) => Integer -> r
slowFromInteger i = if i>0
then foldl' (+) zero $ P.map (const (one::r)) [1.. i]
else negate $ foldl' (+) zero $ P.map (const (one::r)) [1.. negate i]
instance Ring Int where fromInteger = P.fromInteger ; {-# INLINE fromInteger #-}
instance Ring Integer where fromInteger = P.fromInteger ; {-# INLINE fromInteger #-}
instance Ring Float where fromInteger = P.fromInteger ; {-# INLINE fromInteger #-}
instance Ring Double where fromInteger = P.fromInteger ; {-# INLINE fromInteger #-}
instance Ring Rational where fromInteger = P.fromInteger ; {-# INLINE fromInteger #-}
instance Ring b => Ring (a -> b) where
{-# INLINE fromInteger #-}
fromInteger i = \a -> fromInteger i
{-# INLINABLE indicator #-}
indicator :: Ring r => Bool -> r
indicator True = 1
indicator False = 0
---------------------------------------
-- | 'Integral' numbers can be formed from a wide class of things that behave
-- like integers, but intuitively look nothing like integers.
--
-- FIXME: All Fields are integral domains; should we make it a subclass? This wouuld have the (minor?) problem of making the Integral class have to be an approximate embedding.
-- FIXME: Not all integral domains are homomorphic to the integers (e.g. a field)
--
-- See wikipedia on <https://en.wikipedia.org/wiki/Integral_element integral elements>,
-- <https://en.wikipedia.org/wiki/Integral_domain integral domains>,
-- and the <https://en.wikipedia.org/wiki/Ring_of_integers ring of integers>.
class Ring a => Integral a where
toInteger :: a -> Integer
infixl 7 `quot`, `rem`
-- | truncates towards zero
{-# INLINE quot #-}
quot :: a -> a -> a
quot a1 a2 = fst (quotRem a1 a2)
{-# INLINE rem #-}
rem :: a -> a -> a
rem a1 a2 = snd (quotRem a1 a2)
quotRem :: a -> a -> (a,a)
infixl 7 `div`, `mod`
-- | truncates towards negative infinity
{-# INLINE div #-}
div :: a -> a -> a
div a1 a2 = fst (divMod a1 a2)
{-# INLINE mod #-}
mod :: a -> a -> a
mod a1 a2 = snd (divMod a1 a2)
divMod :: a -> a -> (a,a)
law_Integral_divMod :: (Eq a, Integral a) => a -> a -> Bool
law_Integral_divMod a1 a2 = if a2 /= 0
then a2 * (a1 `div` a2) + (a1 `mod` a2) == a1
else True
law_Integral_quotRem :: (Eq a, Integral a) => a -> a -> Bool
law_Integral_quotRem a1 a2 = if a2 /= 0
then a2 * (a1 `quot` a2) + (a1 `rem` a2) == a1
else True
law_Integral_toFromInverse :: (Eq a, Integral a) => a -> Bool
law_Integral_toFromInverse a = fromInteger (toInteger a) == a
{-# INLINE[1] fromIntegral #-}
fromIntegral :: (Integral a, Ring b) => a -> b
fromIntegral = fromInteger . toInteger
-- | FIXME:
-- This should be moved into the class hierarchy and generalized.
--
-- FIXME:
-- There are more efficient implementations available if you restrict m to powers of 2.
-- Is GHC smart enough to convert `rem` into bit shifts?
-- See for more possibilities:
-- http://stackoverflow.com/questions/3407012/c-rounding-up-to-the-nearest-multiple-of-a-number
{-# INLINE roundUpToNearest #-}
roundUpToNearest :: Int -> Int -> Int
roundUpToNearest m x = x + m - 1 - (x-1)`rem`m
-- roundUpToNearest m x = if s==0
-- then
-- else x+r
-- where
-- s = x`rem`m
-- r = if s==0 then 0 else m-s
-- FIXME:
-- need more RULES; need tests
{-# RULES
"subhask/fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
#-}
instance Integral Int where
{-# INLINE div #-}
{-# INLINE mod #-}
{-# INLINE divMod #-}
{-# INLINE quot #-}
{-# INLINE rem #-}
{-# INLINE quotRem #-}
{-# INLINE toInteger #-}
div = P.div
mod = P.mod
divMod = P.divMod
quot = P.quot
rem = P.rem
quotRem = P.quotRem
toInteger = P.toInteger
instance Integral Integer where
{-# INLINE div #-}
{-# INLINE mod #-}
{-# INLINE divMod #-}
{-# INLINE quot #-}
{-# INLINE rem #-}
{-# INLINE quotRem #-}
{-# INLINE toInteger #-}
div = P.div
mod = P.mod
divMod = P.divMod
quot = P.quot
rem = P.rem
quotRem = P.quotRem
toInteger = P.toInteger
instance Integral b => Integral (a -> b) where
{-# INLINE div #-}
{-# INLINE mod #-}
{-# INLINE divMod #-}
{-# INLINE quot #-}
{-# INLINE rem #-}
{-# INLINE quotRem #-}
{-# INLINE toInteger #-}
quot f1 f2 = \a -> quot (f1 a) (f2 a)
rem f1 f2 = \a -> rem (f1 a) (f2 a)
quotRem f1 f2 = (quot f1 f2, rem f1 f2)
div f1 f2 = \a -> div (f1 a) (f2 a)
mod f1 f2 = \a -> mod (f1 a) (f2 a)
divMod f1 f2 = (div f1 f2, mod f1 f2)
-- FIXME
toInteger = error "toInteger shouldn't be in the integral class b/c of bad function instance"
---------------------------------------
-- | Fields are Rings with a multiplicative inverse.
--
-- See <https://en.wikipedia.org/wiki/Field_%28mathematics%29 wikipedia>
-- and <http://ncatlab.org/nlab/show/field ncatlab>
-- for more details.
class Ring r => Field r where
{-# INLINE reciprocal #-}
reciprocal :: r -> r
reciprocal r = one/r
{-# INLINE (/) #-}
infixl 7 /
(/) :: r -> r -> r
n/d = n * reciprocal d
-- infixr 5 /=
-- (/=) :: (PrimBase m) => Mutable m g -> g -> m ()
-- (/=) = immutable2mutable (/)
{-# INLINE fromRational #-}
fromRational :: Rational -> r
fromRational r = fromInteger (numerator r) / fromInteger (denominator r)
#define mkField(x) \
instance Field x where \
(/) = (P./) ;\
fromRational=P.fromRational ;\
{-# INLINE fromRational #-} ;\
{-# INLINE (/) #-}
mkField(Float)
mkField(Double)
mkField(Rational)
instance Field b => Field (a -> b) where
{-# INLINE fromRational #-}
reciprocal f = reciprocal . f
----------------------------------------
-- | Ordered fields are generalizations of the rational numbers that maintain most of the nice properties.
-- In particular, all finite fields and the complex numbers are NOT ordered fields.
--
-- See <http://en.wikipedia.org/wiki/Ordered_field wikipedia> for more details.
class (Field r, Ord r, Normed r, IsScalar r) => OrdField r
instance OrdField Float
instance OrdField Double
instance OrdField Rational
---------------------------------------
-- | The prototypical example of a bounded field is the extended real numbers.
-- Other examples are the extended hyperreal numbers and the extended rationals.
-- Each of these fields has been extensively studied, but I don't know of any studies of this particular abstraction of these fields.
--
-- See <https://en.wikipedia.org/wiki/Extended_real_number_line wikipedia> for more details.
class (OrdField r, Bounded r) => BoundedField r where
{-# INLINE nan #-}
nan :: r
nan = 0/0
isNaN :: r -> Bool
{-# INLINE infinity #-}
infinity :: BoundedField r => r
infinity = maxBound
{-# INLINE negInfinity #-}
negInfinity :: BoundedField r => r
negInfinity = minBound
instance BoundedField Float where isNaN = P.isNaN ; {-# INLINE isNaN #-}
instance BoundedField Double where isNaN = P.isNaN ; {-# INLINE isNaN #-}
----------------------------------------
-- | A Rational field is a field with only a single dimension.
--
-- FIXME: this isn't part of standard math; why is it here?
class Field r => RationalField r where
toRational :: r -> Rational
instance RationalField Float where toRational=P.toRational ; {-# INLINE toRational #-}
instance RationalField Double where toRational=P.toRational ; {-# INLINE toRational #-}
instance RationalField Rational where toRational=P.toRational ; {-# INLINE toRational #-}
{-# INLINE convertRationalField #-}
convertRationalField :: (RationalField a, RationalField b) => a -> b
convertRationalField = fromRational . toRational
-- |
--
-- FIXME:
-- These functions don't work for Int's, but they should
toFloat :: RationalField a => a -> Float
toFloat = convertRationalField
toDouble :: RationalField a => a -> Double
toDouble = convertRationalField
---------------------------------------
-- | A 'QuotientField' is a field with an 'IntegralDomain' as a subring.
-- There may be many such subrings (for example, every field has itself as an integral domain subring).
-- This is especially true in Haskell because we have different data types that represent essentially the same ring (e.g. "Int" and "Integer").
-- Therefore this is a multiparameter type class.
-- The 'r' parameter represents the quotient field, and the 's' parameter represents the subring.
-- The main purpose of this class is to provide functions that map elements in 'r' to elements in 's' in various ways.
--
-- FIXME: Need examples. Is there a better representation?
--
-- See <http://en.wikipedia.org/wiki/Field_of_fractions wikipedia> for more details.
--
class (Ring r, Integral s) => QuotientField r s where
truncate :: r -> s
round :: r -> s
ceiling :: r -> s
floor :: r -> s
(^^) :: r -> s -> r
#define mkQuotientField(r,s) \
instance QuotientField r s where \
truncate = P.truncate; \
round = P.round; \
ceiling = P.ceiling; \
floor = P.floor; \
(^^) = (P.^^); \
{-# INLINE truncate #-} ;\
{-# INLINE round #-} ;\
{-# INLINE ceiling #-} ;\
{-# INLINE floor #-} ;\
{-# INLINE (^^) #-} ;\
mkQuotientField(Float,Int)
mkQuotientField(Float,Integer)
mkQuotientField(Double,Int)
mkQuotientField(Double,Integer)
mkQuotientField(Rational,Int)
mkQuotientField(Rational,Integer)
-- mkQuotientField(Integer,Integer)
-- mkQuotientField(Int,Int)
instance QuotientField b1 b2 => QuotientField (a -> b1) (a -> b2) where
truncate f = \a -> truncate $ f a
round f = \a -> round $ f a
ceiling f = \a -> ceiling $ f a
floor f = \a -> floor $ f a
(^^) f1 f2 = \a -> (^^) (f1 a) (f2 a)
---------------------------------------
-- | Rings augmented with the ability to take exponents.
--
-- Not all rings have this ability.
-- Consider the ring of rational numbers (represented by "Rational" in Haskell).
-- Raising any rational to an integral power results in another rational.
-- But raising to a fractional power results in an irrational number.
-- For example, the square root of 2.
--
-- See <http://en.wikipedia.org/wiki/Exponential_field#Exponential_rings wikipedia> for more detail.
--
-- FIXME:
-- This class hierarchy doesn't give a nice way exponentiate the integers.
-- We need to add instances for all the quotient groups.
class Ring r => ExpRing r where
(**) :: r -> r -> r
infixl 8 **
logBase :: r -> r -> r
-- | An alternate form of "(**)" that some people find more convenient.
(^) :: ExpRing r => r -> r -> r
(^) = (**)
instance ExpRing Float where
{-# INLINE (**) #-}
(**) = (P.**)
{-# INLINE logBase #-}
logBase = P.logBase
instance ExpRing Double where
{-# INLINE (**) #-}
(**) = (P.**)
{-# INLINE logBase #-}
logBase = P.logBase
---------------------------------------
-- | Fields augmented with exponents and logarithms.
--
-- Technically, there are fields for which only a subset of the functions below are meaningful.
-- But these fields don't have any practical computational uses that I'm aware of.
-- So I've combined them all into a single class for simplicity.
--
-- See <http://en.wikipedia.org/wiki/Exponential_field wikipedia> for more detail.
class (ExpRing r, Field r) => ExpField r where
sqrt :: r -> r
sqrt r = r**(1/2)
exp :: r -> r
log :: r -> r
instance ExpField Float where
sqrt = P.sqrt
log = P.log
exp = P.exp
instance ExpField Double where
sqrt = P.sqrt
log = P.log
exp = P.exp
---------------------------------------
-- | This is a catch-all class for things the real numbers can do but don't exist in other classes.
--
-- FIXME:
-- Factor this out into a more appropriate class hierarchy.
-- For example, some (all?) trig functions need to move to a separate class in order to support trig in finite fields (see <en.wikipedia.org/wiki/Trigonometry_in_Galois_fields wikipedia>).
--
-- FIXME:
-- This class is misleading/incorrect for complex numbers.
--
-- FIXME:
-- There's a lot more functions that need adding.
class ExpField r => Real r where
gamma :: r -> r
lnGamma :: r -> r
erf :: r -> r
pi :: r
sin :: r -> r
cos :: r -> r
tan :: r -> r
asin :: r -> r
acos :: r -> r
atan :: r -> r
sinh :: r -> r
cosh :: r -> r
tanh :: r -> r
asinh :: r -> r
acosh :: r -> r
atanh :: r -> r
instance Real Float where
gamma = P.gamma
lnGamma = P.lnGamma
erf = P.erf
pi = P.pi
sin = P.sin
cos = P.cos
tan = P.tan
asin = P.asin
acos = P.acos
atan = P.atan
sinh = P.sinh
cosh = P.cosh
tanh = P.tanh
asinh = P.asinh
acosh = P.acosh
atanh = P.atanh
instance Real Double where
gamma = P.gamma
lnGamma = P.lnGamma
erf = P.erf
pi = P.pi
sin = P.sin
cos = P.cos
tan = P.tan
asin = P.asin
acos = P.acos
atan = P.atan
sinh = P.sinh
cosh = P.cosh
tanh = P.tanh
asinh = P.asinh
acosh = P.acosh
atanh = P.atanh
---------------------------------------
type family Scalar m
infixr 8 ><
type family (><) (a::k1) (b::k2) :: *
type instance Int >< Int = Int
type instance Integer >< Integer = Integer
type instance Float >< Float = Float
type instance Double >< Double = Double
type instance Rational >< Rational = Rational
-- type instance (a,b) >< Scalar b = (a,b)
-- type instance (a,b,c) >< Scalar b = (a,b,c)
type instance (a -> b) >< c = a -> (b><c)
-- type instance c >< (a -> b) = a -> (c><b)
-- | A synonym that covers everything we intuitively thing scalar variables should have.
type IsScalar r = (Ring r, Ord_ r, Scalar r~r, Normed r, ClassicalLogic r, r~(r><r))
-- | A (sometimes) more convenient version of "IsScalar".
type HasScalar a = IsScalar (Scalar a)
type instance Scalar Int = Int
type instance Scalar Integer = Integer
type instance Scalar Float = Float
type instance Scalar Double = Double
type instance Scalar Rational = Rational
type instance Scalar (a,b) = Scalar a
type instance Scalar (a,b,c) = Scalar a
type instance Scalar (a,b,c,d) = Scalar a
type instance Scalar (a -> b) = Scalar b
---------------------------------------
-- | FIXME: What constraint should be here? Semigroup?
--
-- See <http://ncatlab.org/nlab/show/normed%20group ncatlab>
class
( Ord_ (Scalar g)
, Scalar (Scalar g) ~ Scalar g
, Ring (Scalar g)
) => Normed g where
size :: g -> Scalar g
sizeSquared :: g -> Scalar g
sizeSquared g = s*s
where
s = size g
abs :: IsScalar g => g -> g
abs = size
instance Normed Int where size = P.abs
instance Normed Integer where size = P.abs
instance Normed Float where size = P.abs
instance Normed Double where size = P.abs
instance Normed Rational where size = P.abs
---------------------------------------
-- | A Cone is an \"almost linear\" subspace of a module.
-- Examples include the cone of positive real numbers and the cone of positive semidefinite matrices.
--
-- See <http://en.wikipedia.org/wiki/Cone_%28linear_algebra%29 wikipedia for more details.
--
-- FIXME:
-- There are many possible laws for cones (as seen in the wikipedia article).
-- I need to explicitly formulate them here.
-- Intuitively, the laws should apply the module operations and then project back into the "closest point" in the cone.
--
-- FIXME:
-- We're using the definition of a cone from linear algebra.
-- This definition is closely related to the definition from topology.
-- What is needed to ensure our definition generalizes to topological cones?
-- See <http://en.wikipedia.org/wiki/Cone_(topology) wikipedia>
-- and <http://ncatlab.org/nlab/show/cone ncatlab> for more details.
class (Cancellative m, HasScalar m, Rig (Scalar m)) => Cone m where
infixl 7 *..
(*..) :: Scalar m -> m -> m
infixl 7 ..*..
(..*..) :: m -> m -> m
---------------------------------------
class
( Abelian v
, Group v
, HasScalar v
, v ~ (v><Scalar v)
-- , v ~ (Scalar v><v)
) => Module v
where
{-# MINIMAL (.*) | (.*=) #-}
-- | Scalar multiplication.
{-# INLINE (.*) #-}
infixl 7 .*
(.*) :: v -> Scalar v -> v
(.*) = mutable2immutable (.*=)
{-# INLINE (.*=) #-}
infixr 5 .*=
(.*=) :: (PrimBase m) => Mutable m v -> Scalar v -> m ()
(.*=) = immutable2mutable (.*)
law_Module_multiplication :: (Eq_ m, Module m) => m -> m -> Scalar m -> Logic m
law_Module_multiplication m1 m2 s = s *. (m1 + m2) == s*.m1 + s*.m2
law_Module_addition :: (Eq_ m, Module m) => m -> Scalar m -> Scalar m -> Logic m
law_Module_addition m s1 s2 = (s1+s2)*.m == s1*.m + s2*.m
law_Module_action :: (Eq_ m, Module m) => m -> Scalar m -> Scalar m -> Logic m
law_Module_action m s1 s2 = s1*.(s2*.m) == (s1*s2)*.m
law_Module_unital :: (Eq_ m, Module m) => m -> Logic m
law_Module_unital m = 1 *. m == m
defn_Module_dotstarequal :: (Eq_ m, Module m) => m -> Scalar m -> Logic m
defn_Module_dotstarequal = simpleMutableDefn (.*=) (.*)
{-# INLINE (*.) #-}
infixl 7 *.
(*.) :: Module v => Scalar v -> v -> v
r *. v = v .* r
instance Module Int where (.*) = (*)
instance Module Integer where (.*) = (*)
instance Module Float where (.*) = (*)
instance Module Double where (.*) = (*)
instance Module Rational where (.*) = (*)
instance
( Module b
) => Module (a -> b)
where
f .* b = \a -> f a .* b
---------------------------------------
-- | Free modules have a basis.
-- This means it makes sense to perform operations elementwise on the basis coefficients.
--
-- See <https://en.wikipedia.org/wiki/Free_module wikipedia> for more detail.
class Module v => FreeModule v where
{-# MINIMAL ones, ((.*.) | (.*.=)) #-}
-- | Multiplication of the components pointwise.
-- For matrices, this is commonly called Hadamard multiplication.
--
-- See <http://en.wikipedia.org/wiki/Hadamard_product_%28matrices%29 wikipedia> for more detail.
--
-- FIXME: This is only valid for modules with a basis.
{-# INLINE (.*.) #-}
infixl 7 .*.
(.*.) :: v -> v -> v
(.*.) = mutable2immutable (.*.=)
{-# INLINE (.*.=) #-}
infixr 5 .*.=
(.*.=) :: (PrimBase m) => Mutable m v -> v -> m ()
(.*.=) = immutable2mutable (.*.)
-- | The identity for Hadamard multiplication.
-- Intuitively, this object has the value "one" in every column.
ones :: v
law_FreeModule_commutative :: (Eq_ m, FreeModule m) => m -> m -> Logic m
law_FreeModule_commutative m1 m2 = m1.*.m2 == m2.*.m1
law_FreeModule_associative :: (Eq_ m, FreeModule m) => m -> m -> m -> Logic m
law_FreeModule_associative m1 m2 m3 = m1.*.(m2.*.m3) == (m1.*.m2).*.m3
law_FreeModule_id :: (Eq_ m, FreeModule m) => m -> Logic m
law_FreeModule_id m = m == m.*.ones
defn_FreeModule_dotstardotequal :: (Eq_ m, FreeModule m) => m -> m -> Logic m
defn_FreeModule_dotstardotequal = simpleMutableDefn (.*.=) (.*.)
instance FreeModule Int where (.*.) = (*); ones = one
instance FreeModule Integer where (.*.) = (*); ones = one
instance FreeModule Float where (.*.) = (*); ones = one
instance FreeModule Double where (.*.) = (*); ones = one
instance FreeModule Rational where (.*.) = (*); ones = one
instance
( FreeModule b
) => FreeModule (a -> b)
where
g .*. f = \a -> g a .*. f a
ones = \a -> ones
---------------------------------------
-- | If our "FreeModule" has a finite basis, then we can:
--
-- * index into the modules basis coefficients
--
-- * provide a dense construction method that's a bit more convenient than "fromIxList".
class
( FreeModule v
, IxContainer v
, Elem v~Scalar v
, Index v~Int
, v ~ SetElem v (Elem v)
) => FiniteModule v
where
-- | Returns the dimension of the object.
-- For some objects, this may be known statically, and so the parameter will not be "seq"ed.
-- But for others, this may not be known statically, and so the parameter will be "seq"ed.
dim :: v -> Int
unsafeToModule :: [Scalar v] -> v
type instance Elem Int = Int
type instance Elem Integer = Integer
type instance Elem Float = Float
type instance Elem Double = Double
type instance Elem Rational = Rational
type instance SetElem Int a = Int
type instance SetElem Integer a = Integer
type instance SetElem Float a = Float
type instance SetElem Double a = Double
type instance SetElem Rational a = Rational
type instance Index Int = Int
type instance Index Integer = Int
type instance Index Float = Int
type instance Index Double = Int
type instance Index Rational = Int
type instance SetIndex Int a = Int
type instance SetIndex Integer a = Int
type instance SetIndex Float a = Int
type instance SetIndex Double a = Int
type instance SetIndex Rational a = Int
instance FiniteModule Int where dim _ = 1; unsafeToModule [x] = x
instance FiniteModule Integer where dim _ = 1; unsafeToModule [x] = x
instance FiniteModule Float where dim _ = 1; unsafeToModule [x] = x
instance FiniteModule Double where dim _ = 1; unsafeToModule [x] = x
instance FiniteModule Rational where dim _ = 1; unsafeToModule [x] = x
---------------------------------------
class (FreeModule v, Field (Scalar v)) => VectorSpace v where
{-# MINIMAL (./.) | (./.=) #-}
{-# INLINE (./) #-}
infixl 7 ./
(./) :: v -> Scalar v -> v
v ./ r = v .* reciprocal r
{-# INLINE (./.) #-}
infixl 7 ./.
(./.) :: v -> v -> v
(./.) = mutable2immutable (./.=)
{-# INLINE (./=) #-}
infixr 5 ./=
(./=) :: (PrimBase m) => Mutable m v -> Scalar v -> m ()
(./=) = immutable2mutable (./)
{-# INLINE (./.=) #-}
infixr 5 ./.=
(./.=) :: (PrimBase m) => Mutable m v -> v -> m ()
(./.=) = immutable2mutable (./.)
instance VectorSpace Float where (./) = (/); (./.) = (/)
instance VectorSpace Double where (./) = (/); (./.) = (/)
instance VectorSpace Rational where (./) = (/); (./.) = (/)
instance VectorSpace b => VectorSpace (a -> b) where g ./. f = \a -> g a ./. f a
---------------------------------------
-- | A Reisz space is a vector space obeying nice partial ordering laws.
--
-- See <http://en.wikipedia.org/wiki/Riesz_space wikipedia> for more details.
class (VectorSpace v, Lattice_ v) => Reisz v where
--
-- | An element of a reisz space can always be split into positive and negative components.
reiszSplit :: v -> (v,v)
---------------------------------------
-- | A Banach space is a Vector Space equipped with a compatible Norm and Metric.
--
-- See <http://en.wikipedia.org/wiki/Banach_space wikipedia> for more details.
class (VectorSpace v, Normed v, Metric v) => Banach v where
{-# INLINE normalize #-}
normalize :: v -> v
normalize v = v ./ size v
-- | These laws correspond to the actual math class, but they don't
-- actually hold for 'Float' and 'Double'.
--
-- FIXME:
-- Find a way to actually test these laws and add them to
-- "SubHask.TemplateHaskell.Test".
law_Banach_distance :: Banach v => v -> v -> Logic (Scalar v)
law_Banach_distance v1 v2 = size (v1 - v2) == distance v1 v2
law_Banach_size :: Banach v => v -> Logic (Scalar v)
law_Banach_size v
= isZero v
|| size (normalize v) == 1
instance Banach Float
instance Banach Double
instance Banach Rational
---------------------------------------
-- | Hilbert spaces are a natural generalization of Euclidean space that allows for infinite dimension.
--
-- See <http://en.wikipedia.org/wiki/Hilbert_space wikipedia> for more details.
--
-- FIXME:
-- The result of a dot product must always be an ordered field.
-- This is true even when the Hilbert space is over a non-ordered field like the complex numbers.
-- But the "OrdField" constraint currently prevents us from doing scalar multiplication on Complex Hilbert spaces.
-- See <http://math.stackexchange.com/questions/49348/inner-product-spaces-over-finite-fields> and <http://math.stackexchange.com/questions/47916/banach-spaces-over-fields-other-than-mathbbc> for some technical details.
class ( Banach v , TensorAlgebra v , Real (Scalar v), OrdField (Scalar v) ) => Hilbert v where
infix 8 <>
(<>) :: v -> v -> Scalar v
instance Hilbert Float where (<>) = (*)
instance Hilbert Double where (<>) = (*)
{-# INLINE squaredInnerProductNorm #-}
squaredInnerProductNorm :: Hilbert v => v -> Scalar v
squaredInnerProductNorm v = v<>v
{-# INLINE innerProductNorm #-}
innerProductNorm :: Hilbert v => v -> Scalar v
innerProductNorm = undefined -- sqrt . squaredInnerProductNorm
{-# INLINE innerProductDistance #-}
innerProductDistance :: Hilbert v => v -> v -> Scalar v
innerProductDistance v1 v2 = undefined --innerProductNorm $ v1-v2
---------------------------------------
-- | Tensor algebras generalize the outer product of vectors to construct a matrix.
--
-- See <https://en.wikipedia.org/wiki/Tensor_algebra wikipedia> for details.
--
-- FIXME:
-- This needs to be replaced by the Tensor product in the Monoidal category Vect
class
( VectorSpace v
, VectorSpace (v><v)
, Scalar (v><v) ~ Scalar v
, Normed (v><v) -- the size represents the determinant
, Field (v><v)
) => TensorAlgebra v
where
-- | Take the tensor product of two vectors
(><) :: v -> v -> (v><v)
-- | "left multiplication" of a square matrix
vXm :: v -> (v><v) -> v
-- | "right multiplication" of a square matrix
mXv :: (v><v) -> v -> v
instance TensorAlgebra Float where (><) = (*); vXm = (*); mXv = (*)
instance TensorAlgebra Double where (><) = (*); vXm = (*); mXv = (*)
instance TensorAlgebra Rational where (><) = (*); vXm = (*); mXv = (*)
---------------------------------------
{-
-- | Bregman divergences generalize the squared Euclidean distance and the KL-divergence.
-- They are closely related to exponential family distributions.
--
-- Mark Reid has a <http://mark.reid.name/blog/meet-the-bregman-divergences.html good tutorial>.
--
-- FIXME:
-- The definition of divergence requires taking the derivative.
-- How should this relate to categories?
class
( Hilbert v
) => Bregman v
where
divergence :: v -> v -> Scalar v
divergence v1 v2 = f v1 - f v2 - (derivative f v2 <> v1 - v2)
where
f = bregmanFunction
bregmanFunction :: v -> Scalar v
law_Bregman_nonnegativity :: v -> v -> Logic v
law_Bregman_nonnegativity v1 v2 = divergence v1 v2 > 0
law_Bregman_triangle ::
-}
---------------------------------------
-- | Metric spaces give us the most intuitive notion of distance between objects.
--
-- FIXME: There are many other notions of distance and we should make a whole hierarchy.
class
( HasScalar v
, Eq_ v
, Boolean (Logic v)
, Logic (Scalar v) ~ Logic v
) => Metric v
where
distance :: v -> v -> Scalar v
-- | If the distance between two datapoints is less than or equal to the upper bound,
-- then this function will return the distance.
-- Otherwise, it will return some number greater than the upper bound.
{-# INLINE distanceUB #-}
distanceUB :: v -> v -> Scalar v -> Scalar v
distanceUB v1 v2 _ = {-# SCC distanceUB #-} distance v1 v2
-- | Calling this function will be faster on some 'Metric's than manually checking if distance is greater than the bound.
{-# INLINE isFartherThan #-}
isFartherThan :: Metric v => v -> v -> Scalar v -> Logic v
isFartherThan s1 s2 b = {-# SCC isFartherThan #-} distanceUB s1 s2 b > b
-- | This function constructs an efficient default implementation for 'distanceUB' given a function that lower bounds the distance metric.
{-# INLINE lb2distanceUB #-}
lb2distanceUB ::
( Metric a
, ClassicalLogic a
) => (a -> a -> Scalar a)
-> (a -> a -> Scalar a -> Scalar a)
lb2distanceUB lb p q b = if lbpq > b
then lbpq
else distance p q
where
lbpq = lb p q
law_Metric_nonnegativity :: Metric v => v -> v -> Logic v
law_Metric_nonnegativity v1 v2 = distance v1 v2 >= 0
law_Metric_indiscernables :: (Eq v, Metric v) => v -> v -> Logic v
law_Metric_indiscernables v1 v2 = if v1 == v2
then distance v1 v2 == 0
else distance v1 v2 > 0
law_Metric_symmetry :: Metric v => v -> v -> Logic v
law_Metric_symmetry v1 v2 = distance v1 v2 == distance v2 v1
law_Metric_triangle :: Metric v => v -> v -> v -> Logic v
law_Metric_triangle m1 m2 m3
= distance m1 m2 <= distance m1 m3 + distance m2 m3
&& distance m1 m3 <= distance m1 m2 + distance m2 m3
&& distance m2 m3 <= distance m1 m3 + distance m2 m1
instance Metric Int where distance x1 x2 = abs $ x1 - x2
instance Metric Integer where distance x1 x2 = abs $ x1 - x2
instance Metric Float where distance x1 x2 = abs $ x1 - x2
instance Metric Double where distance x1 x2 = abs $ x1 - x2
instance Metric Rational where distance x1 x2 = abs $ x1 - x2
---------
class CanError a where
errorVal :: a
isError :: a -> Bool
isJust :: a -> Bool
isJust = not isError
instance CanError (Maybe a) where
{-# INLINE isError #-}
isError Nothing = True
isError _ = False
{-# INLINE errorVal #-}
errorVal = Nothing
instance CanError (Maybe' a) where
{-# INLINE isError #-}
isError Nothing' = True
isError _ = False
{-# INLINE errorVal #-}
errorVal = Nothing'
instance CanError [a] where
{-# INLINE isError #-}
isError [] = True
isError _ = False
{-# INLINE errorVal #-}
errorVal = []
instance CanError Float where
{-# INLINE isError #-}
{-# INLINE errorVal #-}
isError = isNaN
errorVal = 0/0
instance CanError Double where
{-# INLINE isError #-}
{-# INLINE errorVal #-}
isError = isNaN
errorVal = 0/0
-------------------------------------------------------------------------------
-- set-like
type Item s = Elem s
type family Elem s
type family SetElem s t
type ValidSetElem s = SetElem s (Elem s) ~ s
-- | Two sets are disjoint if their infimum is the empty set.
-- This function generalizes the notion of disjointness for any lower bounded lattice.
-- FIXME: add other notions of disjoint
infDisjoint :: (Constructible s, MinBound s, Monoid s) => s -> s -> Logic s
infDisjoint s1 s2 = isEmpty $ inf s1 s2
sizeDisjoint :: (Normed s, Constructible s) => s -> s -> Logic (Scalar s)
sizeDisjoint s1 s2 = size s1 + size s2 == size (s1+s2)
type Constructible0 x = (Monoid x, Constructible x)
-- | This is the class for any type that gets "constructed" from smaller types.
-- It is a massive generalization of the notion of a constructable set in topology.
--
-- See <https://en.wikipedia.org/wiki/Constructible_set_%28topology%29 wikipedia> for more details.
class Semigroup s => Constructible s where
{-# MINIMAL singleton | cons | fromList1 #-}
-- | creates the smallest value containing the given element
singleton :: Elem s -> s
singleton x = fromList1N 1 x []
-- | inserts an element on the left
cons :: Elem s -> s -> s
cons x xs = singleton x + xs
-- | inserts an element on the right;
-- in a non-abelian 'Constructible', this may not insert the element;
-- this occurs, for example, in the Map type.
snoc :: s -> Elem s -> s
snoc xs x = xs + singleton x
-- | Construct the type from a list.
-- Since lists may be empty (but not all 'Constructible's can be empty) we explicitly pass in an Elem s.
fromList1 :: Elem s -> [Elem s] -> s
fromList1 x xs = foldl' snoc (singleton x) xs
-- | Like "fromList1" but passes in the size of the list for more efficient construction.
fromList1N :: Int -> Elem s -> [Elem s] -> s
fromList1N _ = fromList1
defn_Constructible_fromList :: (Eq_ s, Constructible s) => s -> Elem s -> [Elem s] -> Logic s
defn_Constructible_fromList s e es = fromList1 e es `asTypeOf` s == foldl' snoc (singleton e) es
defn_Constructible_fromListN :: (Eq_ s, Constructible s) => s -> Elem s -> [Elem s] -> Logic s
defn_Constructible_fromListN s e es = (fromList1 e es `asTypeOf` s)==fromList1N (size es+1) e es
defn_Constructible_cons :: (Eq_ s, Constructible s) => s -> Elem s -> Logic s
defn_Constructible_cons s e = cons e s == singleton e + s
defn_Constructible_snoc :: (Eq_ s, Constructible s) => s -> Elem s -> Logic s
defn_Constructible_snoc s e = snoc s e == s + singleton e
-- | A more suggestive name for inserting an element into a container that does not remember location
insert :: Constructible s => Elem s -> s -> s
insert = cons
-- | A slightly more suggestive name for a container's monoid identity
empty :: (Monoid s, Constructible s) => s
empty = zero
-- | A slightly more suggestive name for checking if a container is empty
isEmpty :: (ValidEq s, Monoid s, Constructible s) => s -> Logic s
isEmpty = isZero
-- | This function needed for the OverloadedStrings language extension
fromString :: (Monoid s, Constructible s, Elem s ~ Char) => String -> s
fromString = fromList
-- | FIXME: if -XOverloadedLists is enabled, this causes an infinite loop for some reason
{-# INLINABLE fromList #-}
fromList :: (Monoid s, Constructible s) => [Elem s] -> s
fromList [] = zero
fromList (x:xs) = fromList1 x xs
{-# INLINABLE fromListN #-}
fromListN :: (Monoid s, Constructible s) => Int -> [Elem s] -> s
fromListN 0 [] = zero
fromListN i (x:xs) = fromList1N i x xs
{-# INLINABLE generate #-}
generate :: (Monoid v, Constructible v) => Int -> (Int -> Elem v) -> v
generate n f = if n <= 0
then zero
else fromList1N n (f 0) (map f [1..n-1])
-- | This is a generalization of a "set".
-- We do not require a container to be a boolean algebra, just a semigroup.
class (ValidLogic s, Constructible s, ValidSetElem s) => Container s where
elem :: Elem s -> s -> Logic s
notElem :: Elem s -> s -> Logic s
notElem = not elem
law_Container_preservation :: (Heyting (Logic s), Container s) => s -> s -> Elem s -> Logic s
law_Container_preservation s1 s2 e = (e `elem` s1 || e `elem` s2) ==> (e `elem` (s1+s2))
law_Constructible_singleton :: Container s => s -> Elem s -> Logic s
law_Constructible_singleton s e = elem e $ singleton e `asTypeOf` s
theorem_Constructible_cons :: Container s => s -> Elem s -> Logic s
theorem_Constructible_cons s e = elem e (cons e s)
-- | The dual of a monoid, obtained by swapping the arguments of 'mappend'.
newtype DualSG a = DualSG { getDualSG :: a }
deriving (Read,Show)
instance Semigroup a => Semigroup (DualSG a) where
(DualSG x)+(DualSG y) = DualSG (x+y)
instance Monoid a => Monoid (DualSG a) where
zero = DualSG zero
-- | The monoid of endomorphisms under composition.
newtype Endo a = Endo { appEndo :: a -> a }
instance Semigroup (Endo a) where
(Endo f)+(Endo g) = Endo (f.g)
instance Monoid (Endo a) where
zero = Endo id
-- | Provides inverse operations for "Constructible".
--
-- FIXME:
-- should this class be broken up into smaller pieces?
class (Constructible s, Monoid s, Normed s, Scalar s~Int) => Foldable s where
{-# MINIMAL foldMap | foldr #-}
-- | Convert the container into a list.
toList :: Foldable s => s -> [Elem s]
toList s = foldr (:) [] s
-- | Remove an element from the left of the container.
uncons :: s -> Maybe (Elem s,s)
uncons s = case toList s of
[] -> Nothing
(x:xs) -> Just (x,fromList xs)
-- | Remove an element from the right of the container.
unsnoc :: s -> Maybe (s,Elem s)
unsnoc s = case unsnoc (toList s) of
Nothing -> Nothing
Just (xs,x) -> Just (fromList xs,x)
-- | Add all the elements of the container together.
{-# INLINABLE sum #-}
sum :: Monoid (Elem s) => s -> Elem s
sum xs = foldl' (+) zero $ toList xs
-- | the default summation uses kahan summation
-- sum :: (Abelian (Elem s), Group (Elem s)) => s -> Elem s
-- sum = snd . foldl' go (zero,zero)
-- where
-- go (c,t) i = ((t'-t)-y,t')
-- where
-- y = i-c
-- t' = t+y
-- the definitions below are copied from Data.Foldable
foldMap :: Monoid a => (Elem s -> a) -> s -> a
foldMap f = foldr ((+) . f) zero
foldr :: (Elem s -> a -> a) -> a -> s -> a
foldr f z t = appEndo (foldMap (Endo . f) t) z
foldr' :: (Elem s -> a -> a) -> a -> s -> a
foldr' f z0 xs = foldl f' id xs z0
where f' k x z = k $! f x z
foldl :: (a -> Elem s -> a) -> a -> s -> a
foldl f z t = appEndo (getDualSG (foldMap (DualSG . Endo . flip f) t)) z
foldl' :: (a -> Elem s -> a) -> a -> s -> a
foldl' f z0 xs = foldr f' id xs z0
where f' x k z = k $! f z x
-- the following definitions are simpler (IMO) than those in Data.Foldable
foldr1 :: (Elem s -> Elem s -> Elem s) -> s -> Elem s
foldr1 f s = foldr1 f (toList s)
foldr1' :: (Elem s -> Elem s -> Elem s) -> s -> Elem s
foldr1' f s = foldr1' f (toList s)
foldl1 :: (Elem s -> Elem s -> Elem s) -> s -> Elem s
foldl1 f s = foldl1 f (toList s)
foldl1' :: (Elem s -> Elem s -> Elem s) -> s -> Elem s
foldl1' f s = foldl1' f (toList s)
defn_Foldable_foldr ::
( Eq_ a
, a~Elem s
, Logic a ~ Logic (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> Elem s -> s -> Logic (Elem s)
defn_Foldable_foldr f a s = foldr f a s == foldr f a (toList s)
defn_Foldable_foldr' ::
( Eq_ a
, a~Elem s
, Logic a ~ Logic (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> Elem s -> s -> Logic (Elem s)
defn_Foldable_foldr' f a s = foldr' f a s == foldr' f a (toList s)
defn_Foldable_foldl ::
( Eq_ a
, a~Elem s
, Logic a ~ Logic (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> Elem s -> s -> Logic (Elem s)
defn_Foldable_foldl f a s = foldl f a s == foldl f a (toList s)
defn_Foldable_foldl' ::
( Eq_ a
, a~Elem s
, Logic a ~ Logic (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> Elem s -> s -> Logic (Elem s)
defn_Foldable_foldl' f a s = foldl' f a s == foldl' f a (toList s)
defn_Foldable_foldr1 ::
( Eq_ (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> s -> Logic (Elem s)
defn_Foldable_foldr1 f s = (length s > 0) ==> (foldr1 f s == foldr1 f (toList s))
defn_Foldable_foldr1' ::
( Eq_ (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> s -> Logic (Elem s)
defn_Foldable_foldr1' f s = (length s > 0) ==> (foldr1' f s == foldr1' f (toList s))
defn_Foldable_foldl1 ::
( Eq_ (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> s -> Logic (Elem s)
defn_Foldable_foldl1 f s = (length s > 0) ==> (foldl1 f s == foldl1 f (toList s))
defn_Foldable_foldl1' ::
( Eq_ (Elem s)
, Logic (Scalar s) ~ Logic (Elem s)
, Boolean (Logic (Elem s))
, Foldable s
) => (Elem s -> Elem s -> Elem s) -> s -> Logic (Elem s)
defn_Foldable_foldl1' f s = (length s > 0) ==> (foldl1' f s == foldl1' f (toList s))
-- |
--
-- Note:
-- The inverse \"theorem\" of @(toList . fromList) xs == xs@ is actually not true.
-- See the "Set" type for a counter example.
theorem_Foldable_tofrom :: (Eq_ s, Foldable s) => s -> Logic s
theorem_Foldable_tofrom s = fromList (toList s) == s
-- |
-- FIXME:
-- This law can't be automatically included in the current test system because it breaks parametricity by requiring @Monoid (Elem s)@
law_Foldable_sum ::
( Logic (Scalar s)~Logic s
, Logic (Elem s)~Logic s
, Heyting (Logic s)
, Monoid (Elem s)
, Eq_ (Elem s)
, Foldable s
) => s -> s -> Logic s
law_Foldable_sum s1 s2 = sizeDisjoint s1 s2 ==> (sum (s1+s2) == sum s1 + sum s2)
-- | This fold is not in any of the standard libraries.
foldtree1 :: Monoid a => [a] -> a
foldtree1 as = case go as of
[] -> zero
[a] -> a
as -> foldtree1 as
where
go [] = []
go [a] = [a]
go (a1:a2:as) = (a1+a2):go as
{-# INLINE[1] convertUnfoldable #-}
convertUnfoldable :: (Monoid t, Foldable s, Constructible t, Elem s ~ Elem t) => s -> t
convertUnfoldable = fromList . toList
{-# INLINE reduce #-}
reduce :: (Monoid (Elem s), Foldable s) => s -> Elem s
reduce s = foldl' (+) zero s
-- | For anything foldable, the norm must be compatible with the folding structure.
{-# INLINE length #-}
length :: Normed s => s -> Scalar s
length = size
{-# INLINE and #-}
and :: (Foldable bs, Elem bs~b, Boolean b) => bs -> b
and = foldl' inf true
{-# INLINE or #-}
or :: (Foldable bs, Elem bs~b, Boolean b) => bs -> b
or = foldl' sup false
{-# INLINE argmin #-}
argmin :: Ord b => a -> a -> (a -> b) -> a
argmin a1 a2 f = if f a1 < f a2 then a1 else a2
{-# INLINE argmax #-}
argmax :: Ord b => a -> a -> (a -> b) -> a
argmax a1 a2 f = if f a1 > f a2 then a1 else a2
-- {-# INLINE argminimum_ #-}
-- argminimum_ :: Ord_ b => a -> [a] -> (a -> b) -> a
-- argminimum_ a as f = fstHask $ foldl' go (a,f a) as
-- where
-- go (a1,fa1) a2 = if fa1 < fa2
-- then (a1,fa1)
-- else (a2,fa2)
-- where fa2 = f a2
--
-- {-# INLINE argmaximum_ #-}
-- argmaximum_ :: Ord_ b => a -> [a] -> (a -> b) -> a
-- argmaximum_ a as f = fstHask $ foldl' go (a,f a) as
-- where
-- go (a1,fa1) a2 = if fa1 > fa2
-- then (a1,fa1)
-- else (a2,fa2)
-- where fa2 = f a2
{-# INLINE maximum #-}
maximum :: (ValidLogic b, Bounded b) => [b] -> b
maximum = supremum
{-# INLINE maximum_ #-}
maximum_ :: (ValidLogic b, Ord_ b) => b -> [b] -> b
maximum_ = supremum_
{-# INLINE minimum #-}
minimum :: (ValidLogic b, Bounded b) => [b] -> b
minimum = infimum
{-# INLINE minimum_ #-}
minimum_ :: (ValidLogic b, Ord_ b) => b -> [b] -> b
minimum_ = infimum_
{-# INLINE supremum #-}
supremum :: (Foldable bs, Elem bs~b, Bounded b) => bs -> b
supremum = supremum_ minBound
{-# INLINE supremum_ #-}
supremum_ :: (Foldable bs, Elem bs~b, Lattice_ b) => b -> bs -> b
supremum_ = foldl' sup
{-# INLINE infimum #-}
infimum :: (Foldable bs, Elem bs~b, Bounded b) => bs -> b
infimum = infimum_ maxBound
{-# INLINE infimum_ #-}
infimum_ :: (Foldable bs, Elem bs~b, POrd_ b) => b -> bs -> b
infimum_ = foldl' inf
{-# INLINE concat #-}
concat :: (Monoid (Elem s), Foldable s) => s -> Elem s
concat = foldl' (+) zero
{-# INLINE headMaybe #-}
headMaybe :: Foldable s => s -> Maybe (Elem s)
headMaybe = P.fmap fst . uncons
{-# INLINE tailMaybe #-}
tailMaybe :: Foldable s => s -> Maybe s
tailMaybe = P.fmap snd . uncons
{-# INLINE lastMaybe #-}
lastMaybe :: Foldable s => s -> Maybe (Elem s)
lastMaybe = P.fmap snd . unsnoc
{-# INLINE initMaybe #-}
initMaybe :: Foldable s => s -> Maybe s
initMaybe = P.fmap fst . unsnoc
-- |
--
-- FIXME:
-- This is a correct definition of topologies, but is it useful?
-- How can this relate to continuous functions?
class (Boolean (Logic s), Boolean s, Container s) => Topology s where
open :: s -> Logic s
closed :: s -> Logic s
closed s = open $ not s
clopen :: s -> Logic s
clopen = open && closed
----------------------------------------
type family Index s
type family SetIndex s a
-- | FIXME:
-- This type is a hack designed to work around the lack of injective type families.
type ValidSetIndex s = SetIndex s (Index s) ~ s
-- | An indexed constructible container associates an 'Index' with each 'Elem'.
-- This class generalizes the map abstract data type.
--
-- There are two differences in the indexed hierarchy of containers from the standard hierarchy.
-- 1. 'IxConstructible' requires a 'Monoid' constraint whereas 'Constructible' requires a 'Semigroup' constraint because there are no valid 'IxConstructible's (that I know of at least) that are not also 'Monoid's.
-- 2. Many regular containers are indexed containers, but not the other way around.
-- So the class hierarchy is in a different order.
--
class (ValidLogic s, Monoid s, ValidSetElem s{-, ValidSetIndex s-}) => IxContainer s where
lookup :: Index s -> s -> Maybe (Elem s)
{-# INLINABLE (!) #-}
(!) :: s -> Index s -> Elem s
(!) s i = case lookup i s of
Just x -> x
Nothing -> error "used (!) on an invalid index"
{-# INLINABLE findWithDefault #-}
findWithDefault :: Elem s -> Index s -> s -> Elem s
findWithDefault def i s = case s !? i of
Nothing -> def
Just e -> e
{-# INLINABLE hasIndex #-}
hasIndex :: s -> Index s -> Logic s
hasIndex s i = case s !? i of
Nothing -> false
Just _ -> true
-- | FIXME: should the functions below be moved to other classes?
type ValidElem s e :: Constraint
type ValidElem s e = ()
imap :: (ValidElem s (Elem s), ValidElem s b) => (Index s -> Elem s -> b) -> s -> SetElem s b
toIxList :: s -> [(Index s, Elem s)]
indices :: s -> [Index s]
indices = map fst . toIxList
values :: s -> [Elem s]
values = map snd . toIxList
law_IxContainer_preservation ::
( Logic (Elem s)~Logic s
, ValidLogic s
, Eq_ (Elem s)
, IxContainer s
) => s -> s -> Index s -> Logic s
law_IxContainer_preservation s1 s2 i = case s1 !? i of
Just e -> (s1+s2) !? i == Just e
Nothing -> true
defn_IxContainer_bang ::
( Eq_ (Elem s)
, ValidLogic (Elem s)
, IxContainer s
) => s -> Index s -> Logic (Elem s)
defn_IxContainer_bang s i = case s !? i of
Nothing -> true
Just e -> s!i == e
defn_IxContainer_findWithDefault ::
( Eq_ (Elem s)
, IxContainer s
) => s -> Index s -> Elem s -> Logic (Elem s)
defn_IxContainer_findWithDefault s i e = case s !? i of
Nothing -> findWithDefault e i s == e
Just e' -> findWithDefault e i s == e'
defn_IxContainer_hasIndex ::
( Eq_ (Elem s)
, IxContainer s
) => s -> Index s -> Logic s
defn_IxContainer_hasIndex s i = case s !? i of
Nothing -> not $ hasIndex s i
Just _ -> hasIndex s i
-- FIXME:
-- It would be interesting to make the "Index" of scalars be ().
-- Is it worth it?
#define mkIxContainer(t) \
type instance Index t = Int; \
type instance Elem t = t; \
instance IxContainer t where \
lookup 0 x = Just x; \
lookup _ _ = Nothing
mkIxContainer(Int)
mkIxContainer(Integer)
mkIxContainer(Float)
mkIxContainer(Double)
mkIxContainer(Rational)
-- | Sliceable containers generalize the notion of a substring to any IxContainer.
-- Sliceables place a stronger guarantee on the way the Semigroup and IxContainer class interact to make the containers more array-like.
--
-- FIXME:
-- Slice should probably be redefined in terms of "drop" and "take" (which also need to be included into the class hierarchy properly).
class (IxContainer s, Scalar s~Index s, HasScalar s, Normed s) => Sliceable s where
-- | Extract a subcontainer
slice
:: Index s -- ^ starting index
-> Index s -- ^ number of elements
-> s -- ^ container
-> s
law_Sliceable_restorable ::
( Sliceable s
, Eq s
) => s -> Index s -> Logic s
law_Sliceable_restorable s i
| i >= 0 && i < length s = slice 0 i s + slice i (length s-i) s == s
| otherwise = True
law_Sliceable_preservation ::
( ValidLogic s
, Logic (Elem s) ~ Logic s
, Eq_ (Elem s)
, Eq_ s
, Sliceable s
) => s -> s -> Index s -> Logic s
law_Sliceable_preservation s1 s2 i = case s1 !? i of
Just e -> (s1+s2) !? i == Just e
Nothing -> case s2 !? (i - length s1) of
Just e -> (s1+s2) !? i == Just e
Nothing -> true
-- | This is the class for Map-like containers.
-- Every element in these containers must contain both an index and an element.
--
-- Some containers that use indices are not typically constructed with those indices (e.g. Arrays).
-- They belong to the "Sliceable" and "Constructable" classes, but not to this class.
class IxContainer s => IxConstructible s where
{-# MINIMAL singletonAt | consAt #-}
-- | Construct a container with only the single (index,element) pair.
-- This function is equivalent to 'singleton' in the 'Constructible' class.
singletonAt :: Index s -> Elem s -> s
singletonAt i e = consAt i e zero
-- | Insert an element, overwriting the previous value if the index already exists.
-- This function is equivalent to 'cons' in the 'Constructible' class.
{-# INLINABLE consAt #-}
consAt :: Index s -> Elem s -> s -> s
consAt i e s = singletonAt i e + s
-- | Insert an element only if the index does not already exist.
-- If the index already exists, the container is unmodified.
-- This function is equivalent to 'snoc' in the 'Constructible' class.
{-# INLINABLE snocAt #-}
snocAt :: s -> Index s -> Elem s -> s
snocAt s i e = s + singletonAt i e
-- | This function is the equivalent of 'fromList' in the 'Constructible' class.
-- We do not require all the variants of 'fromList' because of our 'Monoid' constraint.
{-# INLINABLE fromIxList #-}
fromIxList :: [(Index s, Elem s)] -> s
fromIxList xs = foldl' (\s (i,e) -> snocAt s i e) zero xs
law_IxConstructible_lookup ::
( ValidLogic (Elem s)
, Eq_ (Elem s)
, IxConstructible s
) => s -> Index s -> Elem s -> Logic (Elem s)
law_IxConstructible_lookup s i e = case lookup i (consAt i e s) of
Just e' -> e'==e
Nothing -> false
defn_IxConstructible_consAt :: (Eq_ s, IxConstructible s) => s -> Index s -> Elem s -> Logic s
defn_IxConstructible_consAt s i e = consAt i e s == singletonAt i e + s
defn_IxConstructible_snocAt :: (Eq_ s, IxConstructible s) => s -> Index s -> Elem s -> Logic s
defn_IxConstructible_snocAt s i e = snocAt s i e == s + singletonAt i e
defn_IxConstructible_fromIxList :: (Eq_ s, IxConstructible s) => s -> [(Index s, Elem s)] -> Logic s
defn_IxConstructible_fromIxList t es
= fromIxList es `asTypeOf` t == foldl' (\s (i,e) -> snocAt s i e) zero es
-- | Follows from "law_IxConstructible_lookup" but is closely related to "law_IxContainer_preservation" and "law_Sliceable_preservation"
theorem_IxConstructible_preservation ::
( ValidLogic s
, Logic (Elem s) ~ Logic s
, Eq_ (Elem s)
, IxContainer s
, Scalar s ~ Int
) => s -> s -> Index s -> Logic s
theorem_IxConstructible_preservation s1 s2 i = case s1 !? i of
Just e -> (s1+s2) !? i == Just e
Nothing -> case s2 !? i of
Just e -> (s1+s2) !? i == Just e
Nothing -> true
insertAt :: IxConstructible s => Index s -> Elem s -> s -> s
insertAt = consAt
-- | An infix operator equivalent to 'lookup'
-- FIXME: what should the precedence be?
{-# INLINABLE (!?) #-}
(!?) :: IxContainer s => s -> Index s -> Maybe (Elem s)
(!?) s i = lookup i s
--------------------------------------------------------------------------------
type instance Scalar [a] = Int
type instance Logic [a] = Logic a
type instance Elem [a] = a
type instance SetElem [a] b = [b]
type instance Index [a] = Int
instance ValidEq a => Eq_ [a] where
(x:xs)==(y:ys) = x==y && xs==ys
(x:xs)==[] = false
[] ==(y:ts) = false
[] ==[] = true
instance Eq a => POrd_ [a] where
inf [] _ = []
inf _ [] = []
inf (x:xs) (y:ys) = if x==y
then x:inf xs ys
else []
instance Eq a => MinBound_ [a] where
minBound = []
instance Normed [a] where
size = P.length
instance Semigroup [a] where
(+) = (P.++)
instance Monoid [a] where
zero = []
instance ValidEq a => Container [a] where
elem _ [] = false
elem x (y:ys) = x==y || elem x ys
notElem = not elem
instance Constructible [a] where
singleton a = [a]
cons x xs = x:xs
fromList1 x xs = x:xs
fromList1N _ x xs = x:xs
instance Foldable [a] where
toList = id
uncons [] = Nothing
uncons (x:xs) = Just (x,xs)
unsnoc [] = Nothing
unsnoc xs = Just (P.init xs,P.last xs)
foldMap f s = concat $ map f s
foldr = L.foldr
foldr' = L.foldr
foldr1 = L.foldr1
foldr1' = L.foldr1
foldl = L.foldl
foldl' = L.foldl'
foldl1 = L.foldl1
foldl1' = L.foldl1'
instance ValidLogic a => IxContainer [a] where
lookup 0 (x:xs) = Just x
lookup i (x:xs) = lookup (i-1) xs
lookup _ [] = Nothing
imap f xs = map (uncurry f) $ P.zip [0..] xs
toIxList xs = P.zip [0..] xs
----------------------------------------
type instance Scalar (Maybe a) = Scalar a
type instance Logic (Maybe a) = Logic a
instance ValidEq a => Eq_ (Maybe a) where
Nothing == Nothing = true
Nothing == _ = false
_ == Nothing = false
(Just a1) == (Just a2) = a1==a2
instance Semigroup a => Semigroup (Maybe a) where
(Just a1) + (Just a2) = Just $ a1+a2
Nothing + a2 = a2
a1 + Nothing = a1
instance Semigroup a => Monoid (Maybe a) where
zero = Nothing
----------
data Maybe' a = Nothing' | Just' { fromJust' :: !a }
justs' :: [Maybe' a] -> [a]
justs' [] = []
justs' (Nothing':xs) = justs' xs
justs' (Just' x:xs) = x:justs' xs
type instance Scalar (Maybe' a) = Scalar a
type instance Logic (Maybe' a) = Logic a
instance NFData a => NFData (Maybe' a) where
rnf Nothing' = ()
rnf (Just' a) = rnf a
instance ValidEq a => Eq_ (Maybe' a) where
(Just' a1) == (Just' a2) = a1==a2
Nothing' == Nothing' = true
_ == _ = false
instance Semigroup a => Semigroup (Maybe' a) where
(Just' a1) + (Just' a2) = Just' $ a1+a2
Nothing' + a2 = a2
a1 + Nothing' = a1
instance Semigroup a => Monoid (Maybe' a) where
zero = Nothing'
----------------------------------------
type instance Logic (a,b) = Logic a
type instance Logic (a,b,c) = Logic a
instance (ValidEq a, ValidEq b, Logic a ~ Logic b) => Eq_ (a,b) where
(a1,b1)==(a2,b2) = a1==a2 && b1==b2
instance (ValidEq a, ValidEq b, ValidEq c, Logic a ~ Logic b, Logic b~Logic c) => Eq_ (a,b,c) where
(a1,b1,c1)==(a2,b2,c2) = a1==a2 && b1==b2 && c1==c2
instance (Semigroup a, Semigroup b) => Semigroup (a,b) where
(a1,b1)+(a2,b2) = (a1+a2,b1+b2)
instance (Semigroup a, Semigroup b, Semigroup c) => Semigroup (a,b,c) where
(a1,b1,c1)+(a2,b2,c2) = (a1+a2,b1+b2,c1+c2)
instance (Monoid a, Monoid b) => Monoid (a,b) where
zero = (zero,zero)
instance (Monoid a, Monoid b, Monoid c) => Monoid (a,b,c) where
zero = (zero,zero,zero)
instance (Cancellative a, Cancellative b) => Cancellative (a,b) where
(a1,b1)-(a2,b2) = (a1-a2,b1-b2)
instance (Cancellative a, Cancellative b, Cancellative c) => Cancellative (a,b,c) where
(a1,b1,c1)-(a2,b2,c2) = (a1-a2,b1-b2,c1-c2)
instance (Group a, Group b) => Group (a,b) where
negate (a,b) = (negate a,negate b)
instance (Group a, Group b, Group c) => Group (a,b,c) where
negate (a,b,c) = (negate a,negate b,negate c)
instance (Abelian a, Abelian b) => Abelian (a,b)
instance (Abelian a, Abelian b, Abelian c) => Abelian (a,b,c)
-- instance (Module a, Module b, Scalar a ~ Scalar b) => Module (a,b) where
-- (a,b) .* r = (r*.a, r*.b)
-- (a1,b1).*.(a2,b2) = (a1.*.a2,b1.*.b2)
--
-- instance (Module a, Module b, Module c, Scalar a ~ Scalar b, Scalar c~Scalar b) => Module (a,b,c) where
-- (a,b,c) .* r = (r*.a, r*.b,r*.c)
-- (a1,b1,c1).*.(a2,b2,c2) = (a1.*.a2,b1.*.b2,c1.*.c2)
--
-- instance (VectorSpace a,VectorSpace b, Scalar a ~ Scalar b) => VectorSpace (a,b) where
-- (a,b) ./ r = (a./r,b./r)
-- (a1,b1)./.(a2,b2) = (a1./.a2,b1./.b2)
--
-- instance (VectorSpace a,VectorSpace b, VectorSpace c, Scalar a ~ Scalar b, Scalar c~Scalar b) => VectorSpace (a,b,c) where
-- (a,b,c) ./ r = (a./r,b./r,c./r)
-- (a1,b1,c1)./.(a2,b2,c2) = (a1./.a2,b1./.b2,c1./.c2)
--------------------------------------------------------------------------------
data Labeled' x y = Labeled' { xLabeled' :: !x, yLabeled' :: !y }
deriving (Read,Show,Typeable)
instance (NFData x, NFData y) => NFData (Labeled' x y) where
rnf (Labeled' x y) = deepseq x $ rnf y
instance (Arbitrary x, Arbitrary y) => Arbitrary (Labeled' x y) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Labeled' x y
instance (CoArbitrary x, CoArbitrary y) => CoArbitrary (Labeled' x y) where
coarbitrary (Labeled' x y) = coarbitrary (x,y)
type instance Scalar (Labeled' x y) = Scalar x
type instance Actor (Labeled' x y) = x
type instance Logic (Labeled' x y) = Logic x
type instance Elem (Labeled' x y) = Elem x
-----
instance Eq_ x => Eq_ (Labeled' x y) where
(Labeled' x1 y1) == (Labeled' x2 y2) = x1==x2
instance (ClassicalLogic x, Ord_ x) => POrd_ (Labeled' x y) where
inf (Labeled' x1 y1) (Labeled' x2 y2) = if x1 < x2
then Labeled' x1 y1
else Labeled' x2 y2
(Labeled' x1 _)< (Labeled' x2 _) = x1< x2
(Labeled' x1 _)<=(Labeled' x2 _) = x1<=x2
instance (ClassicalLogic x, Ord_ x) => Lattice_ (Labeled' x y) where
sup (Labeled' x1 y1) (Labeled' x2 y2) = if x1 >= x2
then Labeled' x1 y1
else Labeled' x2 y2
(Labeled' x1 _)> (Labeled' x2 _) = x1> x2
(Labeled' x1 _)>=(Labeled' x2 _) = x1>=x2
instance (ClassicalLogic x, Ord_ x) => Ord_ (Labeled' x y) where
-----
instance Semigroup x => Action (Labeled' x y) where
(Labeled' x y) .+ x' = Labeled' (x'+x) y
-----
instance Metric x => Metric (Labeled' x y) where
distance (Labeled' x1 y1) (Labeled' x2 y2) = distance x1 x2
distanceUB (Labeled' x1 y1) (Labeled' x2 y2) = distanceUB x1 x2
instance Normed x => Normed (Labeled' x y) where
size (Labeled' x _) = size x
--------------------------------------------------------------------------------
-- spatial programming
--
-- FIXME:
-- This is broken, partly due to type system limits.
-- It's being exported just for basic testing.
-- | The type of all containers satisfying the @cxt@ constraint with elements of type @x@.
type All cxt x = forall xs. (cxt xs, Elem xs~x) => xs
data Any cxt x where
Any :: forall cxt x xs. (cxt xs, Elem xs~x) => xs -> Any cxt x
-- Any :: All cxt x -> Any cxt x
instance Show x => Show (Any Foldable x) where
show (Any xs) = show $ toList xs
type instance Elem (Any cxt x) = x
type instance Scalar (Any cxt x) = Int
instance Semigroup (Any Foldable x) where
(Any x1)+(Any x2)=Any (x1+(fromList.toList)x2)
instance Constructible (Any Foldable x) where
instance Normed (Any Foldable x) where
size (Any xs) = size xs
instance Monoid (Any Foldable x) where
zero = Any []
instance Foldable (Any Foldable x) where
toList (Any xs) = toList xs
mkMutable [t| forall cxt x. Any cxt x |]
--------------------------------------------------------------------------------
mkMutable [t| POrdering |]
mkMutable [t| Ordering |]
mkMutable [t| forall a. Endo a |]
mkMutable [t| forall a. DualSG a |]
mkMutable [t| forall a. Maybe a |]
mkMutable [t| forall a. Maybe' a |]
mkMutable [t| forall a b. Labeled' a b |]
| {
"content_hash": "1e9542c174d6690e1186ed0eeed0196f",
"timestamp": "",
"source": "github",
"line_count": 3249,
"max_line_length": 219,
"avg_line_length": 30.74453678054786,
"alnum_prop": 0.591626705643264,
"repo_name": "mredaelli/subhask",
"id": "90632902db22272aa8d703b2837005f602cace53",
"size": "99889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SubHask/Algebra.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "9337"
},
{
"name": "Haskell",
"bytes": "402748"
},
{
"name": "Makefile",
"bytes": "235"
},
{
"name": "SourcePawn",
"bytes": "1166"
},
{
"name": "TeX",
"bytes": "6537"
}
],
"symlink_target": ""
} |
package com.trifluxsoftware.set.enemies;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Vector2;
import com.trifluxsoftware.set.entities.BaseEnt;
import com.trifluxsoftware.set.util.Collision;
import com.trifluxsoftware.set.util.Gravity;
public class BurgerBois extends BaseEnt {
private TiledMapTileLayer collisionLayer;
Vector2 vel = new Vector2();
float sideSpeed = -20;
int _SPEED = 60;
public BurgerBois(Sprite sprite, TiledMapTileLayer collisionLayer){
super(sprite);
this.collisionLayer = collisionLayer;
}
@Override
public void draw(Batch batch){
update(Gdx.graphics.getDeltaTime());
super.draw(batch);
}
public void update(float delta){
vel.x = sideSpeed;
setSideSpeed(sideSpeed);
setGrav(vel, _SPEED, 60*2f, delta);
EntCol(vel, _SPEED, delta, collisionLayer);
}
public TiledMapTileLayer getCollisionLayer() {
return collisionLayer;
}
}
| {
"content_hash": "625b30406e2b4db66363c9bcac9fbf87",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 71,
"avg_line_length": 28.974358974358974,
"alnum_prop": 0.7088495575221239,
"repo_name": "SubjectAlpha/SETPlatformer",
"id": "f8929836da33b11a89486905af3615a7f85a0ac5",
"size": "1130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/com/trifluxsoftware/set/enemies/BurgerBois.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1069"
},
{
"name": "HTML",
"bytes": "1559"
},
{
"name": "Java",
"bytes": "28290"
},
{
"name": "JavaScript",
"bytes": "24"
}
],
"symlink_target": ""
} |
using System.Web;
using System.Web.Http;
namespace Arbor.Ginkgo.Tests.Integration.WebApp
{
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
} | {
"content_hash": "5077018ac74d2b8d7e678131c5cfd742",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 65,
"avg_line_length": 22.153846153846153,
"alnum_prop": 0.6736111111111112,
"repo_name": "niklaslundberg/Arbor.Ginkgo",
"id": "3aa0a50b6ee20919a1b99be18ac7ec9775e7904b",
"size": "290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Arbor.Ginkgo.Tests.Integration.WebApp/Global.asax.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "Batchfile",
"bytes": "2290"
},
{
"name": "C#",
"bytes": "55673"
}
],
"symlink_target": ""
} |
<?php
namespace lgladdy\CubeSensors;
use lgladdy\CubeSensors\OAuth;
/**
** CubeSensors for PHP **
**
** A PHP Library to provide CubeSensors API access
**
** Liam Gladdy (@lgladdy) liam@gladdy.co.uk
*/
require_once('OAuth.php');
class CubeSensors {
public $base_url = "http://api.cubesensors.com/";
public $api_base = "v1/";
public $user_agent = 'CubeSensors for PHP v2.0.1';
public $request_token_url = 'http://api.cubesensors.com/auth/request_token';
public $authorize_url = 'http://api.cubesensors.com/auth/authorize';
public $access_token_url = 'http://api.cubesensors.com/auth/access_token';
function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->sha1_method = new OAuth\OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuth\OAuthConsumer($consumer_key, $consumer_secret);
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new OAuth\OAuthConsumer($oauth_token, $oauth_token_secret);
} else {
$this->token = NULL;
}
}
function getOAuthRequestToken($callback) {
$params = array();
$params['oauth_callback'] = $callback;
$url = $this->signOAuthRequest($this->request_token_url, $params, 'GET');
$call = $this->call($url);
if (json_decode($call,true)) {
//If we're here, it means we got a JSON failure object back from CubeSensors, and that's bad.
return json_decode($call,true);
} else {
$token = OAuth\OAuthUtil::parse_parameters($call);
return $token;
}
}
function getOAuthAuthorizeURL($token) {
if (is_array($token)) $token = $token['oauth_token'];
return $this->authorize_url."?oauth_token={$token}";
}
function getOAuthAccessToken($oauth_verifier) {
$params = array();
$params['oauth_verifier'] = $oauth_verifier;
$url = $this->signOAuthRequest($this->access_token_url, $params, 'GET');
$call = $this->call($url);
if (json_decode($call,true)) {
//If we're here, it means we got a JSON failure object back from CubeSensors, and that's bad.
return json_decode($call,true);
} else {
$token = OAuth\OAuthUtil::parse_parameters($call);
return $token;
}
}
function get($url, $parameters = array()) {
$url = $this->base_url.$this->api_base.$url;
$url = $this->signOAuthRequest($url, $parameters);
//echo "[".time()."] Making a GET request to ".$url."<br />";
$call = $this->call($url);
return json_decode($call,true);
}
function call($url) {
if (is_array($url) && isset($url['url']) && isset($url['data'])) {
//We've got an array containing url and data...
$params = $url['data'];
$url = $url['url'];
}
$this->last_response = array();
$curl_object = curl_init();
curl_setopt($curl_object, CURLOPT_USERAGENT, $this->user_agent);
curl_setopt($curl_object, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_object, CURLOPT_HEADERFUNCTION, array($this, 'processHeader'));
curl_setopt($curl_object, CURLOPT_HEADER, FALSE);
curl_setopt($curl_object, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl_object, CURLOPT_URL, $url);
if (isset($params)) {
//Just incase we ever need POST
curl_setopt($curl_object, CURLOPT_POST, TRUE);
curl_setopt($curl_object, CURLOPT_POSTFIELDS, $params);
}
$response = curl_exec($curl_object);
$this->last_response_code = curl_getinfo($curl_object, CURLINFO_HTTP_CODE);
$this->last_response = array_merge($this->last_response, curl_getinfo($curl_object));
$this->url = $url;
curl_close ($curl_object);
return $response;
}
function processHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->response_headers[$key] = $value;
}
return strlen($header);
}
function signOAuthRequest($url, $parameters, $method = 'GET') {
$request = OAuth\OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
$request->sign_request($this->sha1_method, $this->consumer, $this->token);
if ($method == "POST") {
$r['url'] = $request->get_normalized_http_url();
$r['data'] = $request->to_postdata();
return $r;
} else {
return $request->to_url();
}
}
}
?>
| {
"content_hash": "cd7206fd25f7bc1bf680ca79f5d8b060",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 118,
"avg_line_length": 33.161764705882355,
"alnum_prop": 0.617960088691796,
"repo_name": "lgladdy/cubesensors-for-php",
"id": "5653fe3fbbb6842e77d498257874a61cad0c4290",
"size": "4510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CubeSensors.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "34661"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./snakegame.css">
<script type="text/javascript" src="snakegame.js"></script>
</head>
<body>
<script type="text/javascript">
// var myPlayArea = new PlayArea(13, 10);
var myRuleBook = new RuleBook();
</script>
</body>
</html> | {
"content_hash": "b809b8ef2ad4a9005a6caa548986a450",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 64,
"avg_line_length": 24.5,
"alnum_prop": 0.641399416909621,
"repo_name": "graynun/WebDevCurriculum",
"id": "5e1c13ce4cc425499b83c72e5c5de5556040f694",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Part 2. JavaScript/Quest 08. Midterm project/snakeGame/snakegame.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22313"
},
{
"name": "HTML",
"bytes": "85030"
},
{
"name": "JavaScript",
"bytes": "148743"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<title>1.15. generalization</title>
<!-- Loaded before other Sphinx assets -->
<link href="../../_static/styles/theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link href="../../_static/styles/pydata-sphinx-theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link rel="stylesheet"
href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">
<link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
<link rel="stylesheet" href="../../_static/styles/sphinx-book-theme.css?digest=62ba249389abaaa9ffc34bf36a076bdc1d65ee18" type="text/css" />
<link rel="stylesheet" type="text/css" href="../../_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="../../_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="../../_static/design-style.b7bb847fb20b106c3d81b95245e65545.min.css" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf">
<script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/clipboard.min.js"></script>
<script src="../../_static/copybutton.js"></script>
<script src="../../_static/scripts/sphinx-book-theme.js?digest=f31d14ad54b65d19161ba51d4ffff3a77ae00456"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="../../_static/togglebutton.js"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script src="../../_static/design-tabs.js"></script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"
const thebe_selector = ".thebe,.cell"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output, .cell_output"
</script>
<script async="async" src="../../_static/sphinx-thebe.js"></script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="2. cs" href="../cs/cs.html" />
<link rel="prev" title="1.14. interpretability" href="ovw_interp.html" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="docsearch:language" content="None">
<!-- Google Analytics -->
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="60">
<!-- Checkboxes to toggle the left sidebar -->
<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle navigation sidebar">
<label class="overlay overlay-navbar" for="__navigation">
<div class="visually-hidden">Toggle navigation sidebar</div>
</label>
<!-- Checkboxes to toggle the in-page toc -->
<input type="checkbox" class="sidebar-toggle" name="__page-toc" id="__page-toc" aria-label="Toggle in-page Table of Contents">
<label class="overlay overlay-pagetoc" for="__page-toc">
<div class="visually-hidden">Toggle in-page Table of Contents</div>
</label>
<!-- Headers at the top -->
<div class="announcement header-item noprint"></div>
<div class="header header-item noprint"></div>
<div class="container-fluid" id="banner"></div>
<div class="container-xl">
<div class="row">
<!-- Sidebar -->
<div class="bd-sidebar noprint" id="site-navigation">
<div class="bd-sidebar__content">
<div class="bd-sidebar__top"><div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="../../index.html">
<!-- `logo` is deprecated in Sphinx 4.0, so remove this when we stop supporting 3 -->
<img src="../../_static/logo.png" class="logo" alt="logo">
</a>
</div><form class="bd-search d-flex align-items-center" action="../../search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form><nav class="bd-links" id="bd-docs-nav" aria-label="Main">
<div class="bd-toc-item active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="../../intro.html">
overview 👋
</a>
</li>
</ul>
<ul class="current nav bd-sidenav">
<li class="toctree-l1 current active has-children">
<a class="reference internal" href="research_ovws.html">
1. research_ovws
</a>
<input checked="" class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>
<label for="toctree-checkbox-1">
<i class="fas fa-chevron-down">
</i>
</label>
<ul class="current">
<li class="toctree-l2">
<a class="reference internal" href="ovw_comp_neuro.html">
1.1. comp neuro
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_transfer_learning.html">
1.2. transfer learning
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_disentanglement.html">
1.3. disentanglement
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_omics.html">
1.4. omics
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_complexity.html">
1.5. complexity
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_interesting_science.html">
1.6. interesting science
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_dl_theory.html">
1.7. dl theory
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_scat.html">
1.8. scattering transform
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_ml_medicine.html">
1.9. ml in medicine
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_transformers.html">
1.10. transformers
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_causal_inference.html">
1.11. causal inference
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_dl_for_neuro.html">
1.12. dl for neuro
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_uncertainty.html">
1.13. uncertainty
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="ovw_interp.html">
1.14. interpretability
</a>
</li>
<li class="toctree-l2 current active">
<a class="current reference internal" href="#">
1.15. generalization
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../cs/cs.html">
2. cs
</a>
<input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>
<label for="toctree-checkbox-2">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../cs/retrieval.html">
2.1. info retrieval
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/data_structures.html">
2.2. data structures
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/languages.html">
2.3. languages
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/software.html">
2.4. software engineering
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/quantum.html">
2.5. quantum
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/algo.html">
2.6. algorithms
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/graphs.html">
2.7. graphs
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/os.html">
2.8. os
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/arch.html">
2.9. architecture
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/reproducibility.html">
2.10. reproducibility
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../cs/comp_theory.html">
2.11. cs theory
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../math/math.html">
3. math
</a>
<input class="toctree-checkbox" id="toctree-checkbox-3" name="toctree-checkbox-3" type="checkbox"/>
<label for="toctree-checkbox-3">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../math/differential_equations.html">
3.1. differential equations
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/proofs.html">
3.2. proofs
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/analysis.html">
3.3. real analysis
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/linear_algebra.html">
3.4. linear algebra
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/signals.html">
3.5. signals
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/optimization.html">
3.6. optimization
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/calculus.html">
3.7. calculus
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/chaos.html">
3.8. chaos
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../math/math_basics.html">
3.9. math basics
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../stat/stat.html">
4. stat
</a>
<input class="toctree-checkbox" id="toctree-checkbox-4" name="toctree-checkbox-4" type="checkbox"/>
<label for="toctree-checkbox-4">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../stat/graphical_models.html">
4.1. graphical models
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/data_analysis.html">
4.2. data analysis
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/testing.html">
4.3. testing
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/causal_inference.html">
4.4. causal inference
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/info_theory.html">
4.5. info theory
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/linear_models.html">
4.6. linear models
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/time_series.html">
4.7. time series
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../stat/game_theory.html">
4.8. game theory
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../ml/ml.html">
5. ml
</a>
<input class="toctree-checkbox" id="toctree-checkbox-5" name="toctree-checkbox-5" type="checkbox"/>
<label for="toctree-checkbox-5">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../ml/kernels.html">
5.1. kernels
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/nlp.html">
5.2. nlp
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/comp_vision.html">
5.3. computer vision
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/structure_ml.html">
5.4. structure learning
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/classification.html">
5.5. classification
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/unsupervised.html">
5.6. unsupervised
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/deep_learning.html">
5.7. deep learning
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/feature_selection.html">
5.8. feature selection
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/learning_theory.html">
5.9. learning theory
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ml/evaluation.html">
5.10. evaluation
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../ai/ai.html">
6. ai
</a>
<input class="toctree-checkbox" id="toctree-checkbox-6" name="toctree-checkbox-6" type="checkbox"/>
<label for="toctree-checkbox-6">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../ai/search.html">
6.1. search
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/decisions_rl.html">
6.2. decisions, rl
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/fairness_sts.html">
6.3. fairness, sts
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/cogsci.html">
6.4. cogsci
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/ai_futures.html">
6.5. ai futures
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/logic.html">
6.6. logic
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/philosophy.html">
6.7. philosophy
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/psychology.html">
6.8. psychology
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../ai/knowledge_rep.html">
6.9. representations
</a>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../neuro/neuro.html">
7. neuro
</a>
<input class="toctree-checkbox" id="toctree-checkbox-7" name="toctree-checkbox-7" type="checkbox"/>
<label for="toctree-checkbox-7">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/disease.html">
7.1. disease
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/brain_basics.html">
7.2. brain basics
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/vissci.html">
7.3. vision
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/comp_neuro.html">
7.4. comp neuro
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/sensory_input.html">
7.5. sensory input
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/memory.html">
7.6. memory
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/motor.html">
7.7. motor system
</a>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../neuro/development.html">
7.8. development
</a>
</li>
</ul>
</li>
</ul>
</div>
</nav></div>
<div class="bd-sidebar__bottom">
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
</div>
<div id="rtd-footer-container"></div>
</div>
<!-- A tiny helper pixel to detect if we've scrolled -->
<div class="sbt-scroll-pixel-helper"></div>
<!-- Main content -->
<div class="col py-0 content-container">
<div class="header-article row sticky-top noprint">
<div class="col py-1 d-flex header-article-main">
<div class="header-article__left">
<label for="__navigation"
class="headerbtn"
data-toggle="tooltip"
data-placement="right"
title="Toggle navigation"
>
<span class="headerbtn__icon-container">
<i class="fas fa-bars"></i>
</span>
</label>
</div>
<div class="header-article__right">
<button onclick="toggleFullScreen()"
class="headerbtn"
data-toggle="tooltip"
data-placement="bottom"
title="Fullscreen mode"
>
<span class="headerbtn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<a href="https://github.com/csinva/csinva.github.io"
class="headerbtn"
data-toggle="tooltip"
data-placement="bottom"
title="Source repository"
>
<span class="headerbtn__icon-container">
<i class="fab fa-github"></i>
</span>
</a>
<div class="menu-dropdown menu-dropdown-download-buttons">
<button class="headerbtn menu-dropdown__trigger"
aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<div class="menu-dropdown__content">
<ul>
<li>
<a href="../../_sources/notes/research_ovws/ovw_generalization.md"
class="headerbtn"
data-toggle="tooltip"
data-placement="left"
title="Download source file"
>
<span class="headerbtn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="headerbtn__text-container">.md</span>
</a>
</li>
<li>
<button onclick="printPdf(this)"
class="headerbtn"
data-toggle="tooltip"
data-placement="left"
title="Print to PDF"
>
<span class="headerbtn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="headerbtn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
</div>
<label for="__page-toc"
class="headerbtn headerbtn-page-toc"
>
<span class="headerbtn__icon-container">
<i class="fas fa-list"></i>
</span>
</label>
</div>
</div>
<!-- Table of contents -->
<div class="col-md-3 bd-toc show noprint">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav" aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#basics">
1.15.1. basics
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#uniform-stability">
1.15.2. uniform stability
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#trees">
1.15.3. trees
</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="article row">
<div class="col pl-md-3 pl-lg-5 content-container">
<!-- Table of contents that is only displayed when printing the page -->
<div id="jb-print-docs-body" class="onlyprint">
<h1>generalization</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#basics">
1.15.1. basics
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#uniform-stability">
1.15.2. uniform stability
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#trees">
1.15.3. trees
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<main id="main-content" role="main">
<div>
<p><strong>some notes on generalization bounds in machine learning with an emphasis on stability</strong></p>
<section class="tex2jax_ignore mathjax_ignore" id="generalization">
<h1><span class="section-number">1.15. </span>generalization<a class="headerlink" href="#generalization" title="Permalink to this headline">#</a></h1>
<section id="basics">
<h2><span class="section-number">1.15.1. </span>basics<a class="headerlink" href="#basics" title="Permalink to this headline">#</a></h2>
<ul class="simple">
<li><p>Risk: <span class="math notranslate nohighlight">\(R\left(A_{S}\right)=\mathbb{E}_{(X, Y) \sim P} \ell\left(A_{S}(X), Y\right)\)</span></p></li>
<li><p>Empirical risk: <span class="math notranslate nohighlight">\(R_{\mathrm{emp}}\left(A_{S}\right)=\frac{1}{n} \sum_{i=1}^{n} \ell\left(A_{S}\left(X_{i}\right), Y_{i}\right)\)</span></p></li>
<li><p>Generalization error: <span class="math notranslate nohighlight">\(R\left(A_{S}\right)-R_{\mathrm{emp}}\left(A_{S}\right)\)</span></p></li>
</ul>
</section>
<section id="uniform-stability">
<h2><span class="section-number">1.15.2. </span>uniform stability<a class="headerlink" href="#uniform-stability" title="Permalink to this headline">#</a></h2>
<ul class="simple">
<li><p><a class="reference external" href="http://proceedings.mlr.press/v125/bousquet20b.html">Sharper Bounds for Uniformly Stable Algorithms</a></p>
<ul>
<li><p>uniformly stable with prameter <span class="math notranslate nohighlight">\(\gamma\)</span> if <span class="math notranslate nohighlight">\(\left|\ell\left(A_{S}(x), y\right)-\ell\left(A_{S^{i}}(x), y\right)\right| \leq \gamma\)</span></p>
<ul>
<li><p>where <span class="math notranslate nohighlight">\(A_{S^i}\)</span> can alter one point in the training data</p></li>
</ul>
</li>
<li><p>stability approach can provide bounds even when empirical risk is 0 (e.g. 1-nearest-neighbor, devroye & wagner 1979)</p></li>
<li><p><span class="math notranslate nohighlight">\(n\underbrace{\left(R\left(A_{S}\right)-R_{\mathrm{emp}}\left(A_{S}\right)\right)}_{\text{generalization error}} \lesssim(n \sqrt{n} \gamma+L \sqrt{n}) \sqrt{\log \left(\frac{1}{\delta}\right)}\)</span> (bousegeuet & elisseef, 2002)</p></li>
</ul>
</li>
</ul>
</section>
<section id="trees">
<h2><span class="section-number">1.15.3. </span>trees<a class="headerlink" href="#trees" title="Permalink to this headline">#</a></h2>
<ul class="simple">
<li><p><a class="reference external" href="https://arxiv.org/abs/2110.09626">A cautionary tale on fitting decision trees to data from additive models: generalization lower bounds</a> (tan, agarwal, & yu, 2021)</p>
<ul>
<li><p>(generalized) additive models: <span class="math notranslate nohighlight">\(y = f(X_1) + f(X_2) + ... f(X_p)\)</span> (as opposed to linear models)</p></li>
<li><p>main result</p>
<ul>
<li><p>lower bound: can’t peform better than <span class="math notranslate nohighlight">\(\Omega (n^{-\frac{2}{s+2}})\)</span> in <span class="math notranslate nohighlight">\(\ell_2\)</span> risk (as defined above)</p>
<ul>
<li><p>best tree (ALA tree) can’t do better than this bound (e.g. risk <span class="math notranslate nohighlight">\(\geq \frac{1}{n^{s+2}}\)</span> times some stuff)</p></li>
</ul>
</li>
</ul>
</li>
<li><p>generative assumption simplifies calculations by avoiding some of the complex dependencies be- tween splits that may accumulate during recursive splitting</p></li>
<li><p>ALA tree</p>
<ul>
<li><p>learns axis-aligned splits</p></li>
<li><p>makes predictions as leaf averages</p></li>
<li><p>honest trees: val split is used to estimate leaf averages</p></li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
</section>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./notes/research_ovws"
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</main>
<footer class="footer-article noprint">
<!-- Previous / next buttons -->
<div class='prev-next-area'>
<a class='left-prev' id="prev-link" href="ovw_interp.html" title="previous page">
<i class="fas fa-angle-left"></i>
<div class="prev-next-info">
<p class="prev-next-subtitle">previous</p>
<p class="prev-next-title"><span class="section-number">1.14. </span>interpretability</p>
</div>
</a>
<a class='right-next' id="next-link" href="../cs/cs.html" title="next page">
<div class="prev-next-info">
<p class="prev-next-subtitle">next</p>
<p class="prev-next-title"><span class="section-number">2. </span>cs</p>
</div>
<i class="fas fa-angle-right"></i>
</a>
</div>
</footer>
</div>
</div>
<div class="footer-content row">
<footer class="col footer"><p>
By Chandan Singh<br/>
© Copyright None.<br/>
<div class="extra_footer">
<p>
Many of these images are taken from resources on the web.
</p>
</div>
</p>
</footer>
</div>
</div>
</div>
</div>
<!-- Scripts loaded after <body> so the DOM is not blocked -->
<script src="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf"></script>
</body>
</html> | {
"content_hash": "549f75f68203499b2f4c16449bf65b8d",
"timestamp": "",
"source": "github",
"line_count": 881,
"max_line_length": 296,
"avg_line_length": 31.362088535754825,
"alnum_prop": 0.6020267824828085,
"repo_name": "csinva/csinva.github.io",
"id": "6f9e561b8349a2373d4efff3b6300cb972d48b64",
"size": "27638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_blog/compiled_notes/_build/html/notes/research_ovws/ovw_generalization.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "319714"
},
{
"name": "HTML",
"bytes": "18384466"
},
{
"name": "JavaScript",
"bytes": "848763"
},
{
"name": "Jupyter Notebook",
"bytes": "4535"
},
{
"name": "Python",
"bytes": "49755"
},
{
"name": "Shell",
"bytes": "765"
}
],
"symlink_target": ""
} |
package com.elmakers.mine.bukkit.action.builtin;
import java.util.Collection;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.action.CheckAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
public class CheckModifiersAction extends CheckAction {
private Collection<String> required;
private Collection<String> blocked;
@Override
public void prepare(CastContext context, ConfigurationSection parameters)
{
super.prepare(context, parameters);
required = ConfigurationUtils.getStringList(parameters, "required");
blocked = ConfigurationUtils.getStringList(parameters, "blocked");
}
@Override
protected boolean isAllowed(CastContext context) {
Entity targetEntity = context.getTargetEntity();
Mage mage = context.getController().getRegisteredMage(targetEntity);
if (blocked != null && mage != null) {
for (String check : blocked) {
if (mage.hasModifier(check)) {
return false;
}
}
}
if (required != null) {
if (mage == null) {
return false;
}
for (String check : required) {
if (mage.hasModifier(check)) {
return true;
}
}
}
return required == null || required.isEmpty();
}
@Override
public boolean requiresTarget() {
return true;
}
@Override
public boolean requiresTargetEntity() {
return true;
}
@Override
public void getParameterNames(Spell spell, Collection<String> parameters) {
super.getParameterNames(spell, parameters);
parameters.add("required");
parameters.add("blocked");
}
}
| {
"content_hash": "9704be102f2e6cf0905962d90335bb5e",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 79,
"avg_line_length": 29.26086956521739,
"alnum_prop": 0.6319960376423972,
"repo_name": "elBukkit/MagicPlugin",
"id": "f0e3e84dc3e79c19a493a66423f773661fd3f70c",
"size": "2019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Magic/src/main/java/com/elmakers/mine/bukkit/action/builtin/CheckModifiersAction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3373"
},
{
"name": "Java",
"bytes": "7781583"
},
{
"name": "PHP",
"bytes": "54448"
},
{
"name": "Shell",
"bytes": "342"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_40) on Wed Apr 13 18:09:35 UTC 2016 -->
<title>MorePartitions (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MorePartitions (apache-cassandra API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":17,"i1":17,"i2":6};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MorePartitions.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/db/transform/FilteredRows.html" title="class in org.apache.cassandra.db.transform"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/db/transform/MoreRows.html" title="interface in org.apache.cassandra.db.transform"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/transform/MorePartitions.html" target="_top">Frames</a></li>
<li><a href="MorePartitions.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.db.transform</div>
<h2 title="Interface MorePartitions" class="title">Interface MorePartitions<I extends <a href="../../../../../org/apache/cassandra/db/partitions/BasePartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">BasePartitionIterator</a><?>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <span class="typeNameLabel">MorePartitions<I extends <a href="../../../../../org/apache/cassandra/db/partitions/BasePartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">BasePartitionIterator</a><?>></span></pre>
<div class="block">An interface for providing new partitions for a partitions iterator.
The new contents are produced as a normal arbitrary PartitionIterator or UnfilteredPartitionIterator (as appropriate)
The transforming iterator invokes this method when any current source is exhausted, then then inserts the
new contents as the new source.
If the new source is itself a product of any transformations, the two transforming iterators are merged
so that control flow always occurs at the outermost point</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html#extend-org.apache.cassandra.db.partitions.PartitionIterator-org.apache.cassandra.db.transform.MorePartitions-">extend</a></span>(<a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a> iterator,
<a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html" title="interface in org.apache.cassandra.db.transform">MorePartitions</a><? super <a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a>> more)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html#extend-org.apache.cassandra.db.partitions.UnfilteredPartitionIterator-org.apache.cassandra.db.transform.MorePartitions-">extend</a></span>(<a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a> iterator,
<a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html" title="interface in org.apache.cassandra.db.transform">MorePartitions</a><? super <a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a>> more)</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>I</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html#moreContents--">moreContents</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="extend-org.apache.cassandra.db.partitions.UnfilteredPartitionIterator-org.apache.cassandra.db.transform.MorePartitions-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>extend</h4>
<pre>static <a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a> extend(<a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a> iterator,
<a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html" title="interface in org.apache.cassandra.db.transform">MorePartitions</a><? super <a href="../../../../../org/apache/cassandra/db/partitions/UnfilteredPartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">UnfilteredPartitionIterator</a>> more)</pre>
</li>
</ul>
<a name="extend-org.apache.cassandra.db.partitions.PartitionIterator-org.apache.cassandra.db.transform.MorePartitions-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>extend</h4>
<pre>static <a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a> extend(<a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a> iterator,
<a href="../../../../../org/apache/cassandra/db/transform/MorePartitions.html" title="interface in org.apache.cassandra.db.transform">MorePartitions</a><? super <a href="../../../../../org/apache/cassandra/db/partitions/PartitionIterator.html" title="interface in org.apache.cassandra.db.partitions">PartitionIterator</a>> more)</pre>
</li>
</ul>
<a name="moreContents--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>moreContents</h4>
<pre>I moreContents()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MorePartitions.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/db/transform/FilteredRows.html" title="class in org.apache.cassandra.db.transform"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/db/transform/MoreRows.html" title="interface in org.apache.cassandra.db.transform"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/transform/MorePartitions.html" target="_top">Frames</a></li>
<li><a href="MorePartitions.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "36a572d00d9c420ab836c7631b500917",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 659,
"avg_line_length": 50.49808429118774,
"alnum_prop": 0.6691198786039454,
"repo_name": "elisska/cloudera-cassandra",
"id": "ee9e8a89fcb68cc53f927882b0eac1477ec7d601",
"size": "13180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DATASTAX_CASSANDRA-3.5.0/javadoc/org/apache/cassandra/db/transform/MorePartitions.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "75145"
},
{
"name": "CSS",
"bytes": "4112"
},
{
"name": "HTML",
"bytes": "331372"
},
{
"name": "PowerShell",
"bytes": "77673"
},
{
"name": "Python",
"bytes": "979128"
},
{
"name": "Shell",
"bytes": "143685"
},
{
"name": "Thrift",
"bytes": "80564"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<preference name="loglevel" value="DEBUG" />
<allow-intent href="market:*" />
<name>Control Mobile</name>
<description>
A Mobile Component for Control Suite
</description>
<author email="me@henrymascot.com" href="http://github.com/henrino/control-app">
MEST Control Team
</author>
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<feature name="Whitelist">
<param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />
<param name="onload" value="true" />
</feature>
</widget>
| {
"content_hash": "f9f27c5fd05205bb126c97e21bfd99d0",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 135,
"avg_line_length": 40.5,
"alnum_prop": 0.6172839506172839,
"repo_name": "henrino3/control-mobile",
"id": "4ab554d9cb8a7aaa045756d08f6e1ae0e975f8ab",
"size": "972",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platforms/android/res/xml/config.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "16341"
},
{
"name": "C",
"bytes": "1025"
},
{
"name": "CSS",
"bytes": "2235570"
},
{
"name": "HTML",
"bytes": "1515990"
},
{
"name": "Java",
"bytes": "261366"
},
{
"name": "JavaScript",
"bytes": "2265638"
},
{
"name": "Objective-C",
"bytes": "222947"
},
{
"name": "PHP",
"bytes": "1584"
},
{
"name": "Shell",
"bytes": "1927"
}
],
"symlink_target": ""
} |
package com.kinancity.core.generator.impl;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.kinancity.api.model.AccountData;
import com.kinancity.core.generator.account.SequenceAccountGenerator;
public class SequenceAccountGeneratorTest {
@Test
public void sequenceTest() {
// Given
SequenceAccountGenerator generator = new SequenceAccountGenerator();
generator.setBaseEmail("myname@domain.fr");
generator.setUsernamePattern("pref*****suf");
generator.setStartFrom(1234);
generator.setNbAccounts(3);
AccountData data;
data = generator.next();
assertThat(data).isNotNull();
assertThat(data.getUsername()).isEqualTo("pref01234suf");
data = generator.next();
assertThat(data).isNotNull();
assertThat(data.getUsername()).isEqualTo("pref01235suf");
data = generator.next();
assertThat(data).isNotNull();
assertThat(data.getUsername()).isEqualTo("pref01236suf");
data = generator.next();
assertThat(data).isNull();
}
}
| {
"content_hash": "83c4e14f5256095be5547ba9308809f5",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 70,
"avg_line_length": 26.05128205128205,
"alnum_prop": 0.7470472440944882,
"repo_name": "drallieiv/KinanCity",
"id": "6abb4df6d87f8ac2beff963952558f675041c150",
"size": "1016",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "KinanCity-core/src/test/java/com/kinancity/core/generator/impl/SequenceAccountGeneratorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "312"
},
{
"name": "Dockerfile",
"bytes": "1174"
},
{
"name": "HTML",
"bytes": "32898"
},
{
"name": "Java",
"bytes": "265364"
},
{
"name": "JavaScript",
"bytes": "4008"
},
{
"name": "Shell",
"bytes": "311"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using LibNLPCSharp.util;
namespace LibNLPCSharp.gui
{
public partial class TextNoticeForm : Form
{
////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Variables
////////////////////////////////////////////////////////////////
PersistentProperties pp;
string id;
////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////
private TextNoticeForm(PersistentProperties pp, string title, string message, string id)
{
InitializeComponent();
this.pp = pp;
this.Text = title;
this.id = id;
this.textBox1.Text = message;
}
////////////////////////////////////////////////////////////////
// Properties
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////////
public static void Show(PersistentProperties pp, DirectoryInfo dir, string id)
{
FileInfo fi = new FileInfo(Util.AddSeparatorChar(dir.FullName) + id + ".xml");
if (fi.Exists) Show(pp, fi);
else GUIToolkit.ShowErrorMessage("No data for message " + id + "!", (string)null);
}
public static void Show(PersistentProperties pp, FileInfo file)
{
XmlSerializer ser = new XmlSerializer(typeof(TextNoticeIO));
TextNoticeIO textNotice = (TextNoticeIO)(ser.Deserialize(new XmlTextReader(file.FullName)));
if (Util.Equals(pp[textNotice.ID], "hide")) return;
Show(pp, textNotice.Title, textNotice.Message, textNotice.ID);
}
public static void Show(PersistentProperties pp, string title, string message, string messageID)
{
TextNoticeForm form = new TextNoticeForm(pp, title, message, messageID);
form.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked) {
pp[id] = "hide";
if (pp.File != null) pp.Save();
}
Close();
}
}
}
| {
"content_hash": "97203b908a90fe7ef98da15c97b0240c",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 98,
"avg_line_length": 27.910112359550563,
"alnum_prop": 0.4915458937198068,
"repo_name": "SeNeReKo/LibNLPCommon_CSharp",
"id": "b8bb27d00bc30859ff36135a46e19e711ce942f8",
"size": "2486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gui/TextNoticeForm.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "337844"
}
],
"symlink_target": ""
} |
[CmdletBinding()]
param (
[Parameter()]
[string]
$Version
)
Invoke-psake -buildFile .\psakefile.ps1 -taskList Publish -parameters @{Version = $Version }
| {
"content_hash": "f20a00b75e0e19c60dfad6a6fabaec07",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 92,
"avg_line_length": 20.75,
"alnum_prop": 0.6686746987951807,
"repo_name": "tiksn/TIKSN-Framework",
"id": "e624401f60b8745dc894c5d31ab778962e5b2c9f",
"size": "166",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "publish.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "899203"
},
{
"name": "PowerShell",
"bytes": "10679"
}
],
"symlink_target": ""
} |
//
// AppDelegate.h
// SmartHomeSampleriOS
//
// Created by Ibrahim Adnan on 2/10/15.
// Copyright (c) 2015 LG Electronics.
//
// 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.
//
#define UIAppDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])
#import <UIKit/UIKit.h>
#import "PHBridgeSelectionViewController.h"
#import "PHBridgePushLinkViewController.h"
#import <HueSDK_iOS/HueSDK.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAlertViewDelegate, PHBridgeSelectionViewControllerDelegate, PHBridgePushLinkViewControllerDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navigationController;
@property (strong, nonatomic) PHHueSDK *phHueSDK;
@property (strong, nonatomic) NSMutableDictionary *connectedDevices;
@property (strong, nonatomic) NSMutableDictionary *wemoDevices;
@property (strong, nonatomic) NSMutableDictionary *winkDevices;
@property (strong, nonatomic) NSString *plistPath;
#pragma mark - HueSDK
/**
Starts the local heartbeat
*/
- (void)enableLocalHeartbeat;
/**
Stops the local heartbeat
*/
- (void)disableLocalHeartbeat;
/**
Starts a search for a bridge
*/
- (void)searchForBridgeLocal;
@end
| {
"content_hash": "fa4ff35b2f7857fbad1fca57cbaf510f",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 162,
"avg_line_length": 31.727272727272727,
"alnum_prop": 0.766189111747851,
"repo_name": "ConnectSDK/SmartHomeSampleriOS",
"id": "003548ed5e0a87947e8af1d8595402413b42c840",
"size": "1745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SmartHomeSampleriOS/AppDelegate.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "27929"
},
{
"name": "Objective-C",
"bytes": "191151"
},
{
"name": "Shell",
"bytes": "1357"
}
],
"symlink_target": ""
} |
package fr.jmini.asciidoctorj.converter.html.reference;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.impl.DocumentImpl;
import fr.jmini.asciidoctorj.converter.html.testing.AbstractListingTesting;
import fr.jmini.asciidoctorj.testcases.HtmlUtility;
/**
* Reference test for {@link fr.jmini.asciidoctorj.testcases.ListingTestCase} (ruby engine) .
*/
public class ListingReferenceTest extends AbstractListingTesting {
@Override
protected Document createAstDocument(String asciiDoc, Map<String, Object> options) {
Asciidoctor asciidoctor = org.asciidoctor.Asciidoctor.Factory.create();
Document document = asciidoctor.load(asciiDoc, options);
assertThat(document).isInstanceOf(DocumentImpl.class);
return document;
}
@Override
protected String convertToHtml(Document astDocument) {
String html = astDocument.convert();
return HtmlUtility.normalizeHtml(html);
}
}
| {
"content_hash": "6de4943f9d872ccdac9337ef3e645e0f",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 93,
"avg_line_length": 32.60606060606061,
"alnum_prop": 0.7639405204460966,
"repo_name": "jmini/asciidoctorj-experiments",
"id": "e4c026af8d508fac7aad15f2ea40894c6099d84c",
"size": "1076",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html-converter/html-j-reference-test/src/test/java/fr/jmini/asciidoctorj/converter/html/reference/ListingReferenceTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4209747"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Tue Apr 03 18:35:29 EST 2001 -->
<TITLE>
: Uses of Class com.kutsyy.lvspod.OrdinalSpatialStEM
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<!--mstheme--><link rel="stylesheet" type="text/css" href="../../../../../../_themes/blocks-modified/bloc1111.css"><meta name="Microsoft Theme" content="blocks-modified 1111, default">
<meta name="Microsoft Border" content="tl, default">
</HEAD>
<BODY><!--msnavigation--><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td>
<p align="center"><font size="6"><strong></strong></font><br>
</p>
<p align="center"> </p>
</td></tr><!--msnavigation--></table><!--msnavigation--><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td valign="top" width="1%">
</td><td valign="top" width="24"></td><!--msnavigation--><td valign="top">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/kutsyy/lvspod/OrdinalSpatialStEM.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="OrdinalSpatialStEM.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.kutsyy.lvspod.OrdinalSpatialStEM</B></H2>
</CENTER>
No usage of com.kutsyy.lvspod.OrdinalSpatialStEM
<P>
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/kutsyy/lvspod/OrdinalSpatialStEM.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="OrdinalSpatialStEM.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<!--msnavigation--></td></tr><!--msnavigation--></table><script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-4172521-1");
pageTracker._initData();
pageTracker._trackPageview();
</script></body>
</HTML>
| {
"content_hash": "a910dd36bfa0bd2bca87cb37483e9d9c",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 184,
"avg_line_length": 48.92173913043478,
"alnum_prop": 0.6206896551724138,
"repo_name": "kutsyy/com.kutsyy.lvspod",
"id": "21485d51d6bc3bb906465cd4a944c5a453227356",
"size": "5626",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/com/kutsyy/lvspod/class-use/OrdinalSpatialStEM.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "388359"
}
],
"symlink_target": ""
} |
/**
* base namespace of cocostuidio
* @namespace
*/
var ccs = ccs || {};
/**
* that same as cc.Class
* @class
*/
ccs.Class = ccs.Class || cc.Class;
ccs.Class.extend = ccs.Class.extend || cc.Class.extend;
/**
* that same as cc.NodeRGBA
* @class
* @extends ccs.Class
*/
ccs.Node = ccs.Node || cc.Node;
ccs.Node.extend = ccs.Node.extend || cc.Node.extend;
/**
* that same as cc.NodeRGBA
* @class
* @extends ccs.Class
*/
ccs.NodeRGBA = ccs.NodeRGBA || cc.NodeRGBA;
ccs.NodeRGBA.extend = ccs.NodeRGBA.extend || cc.NodeRGBA.extend;
/**
* that same as cc.Sprite
* @class
* @extends ccs.Class
*/
ccs.Sprite = ccs.Sprite || cc.Sprite;
ccs.Sprite.extend = ccs.Sprite.extend || cc.Sprite.extend;
/**
* that same as cc.Component
* @class
* @extends ccs.Class
*/
ccs.Component = ccs.Component || cc.Component;
ccs.Component.extend = ccs.Component.extend || cc.Component.extend;
/**
* cocostudio version
* @type {string}
*/
ccs.CocoStudioVersion = "1.3"; | {
"content_hash": "570eb05d81f884ae24693f03545cdb2a",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 67,
"avg_line_length": 19.058823529411764,
"alnum_prop": 0.654320987654321,
"repo_name": "honghaier2020/web_app",
"id": "0590d5d90e2c6452a66f89b036bc136512c5f88e",
"size": "2233",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "sample/extensions/CocoStudio/CocoStudio.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
lang: PT-BR
title: Mais Pequenos Pedaços de Análises
answer: [3-9]
load: livros = {"O Arco-Íris da Gravidade" => :esplendido}
ok: Veja, o método length trabalha com strings, arrays e hashes
error:
---
Vá em frente, preencha a lista com análises. E, se você quiser ver toda a lista, apenas digite: __puts livros__
Denovo, as classificações são: :esplendido, :muito\_bom, :mediocre, :nao\_tao\_bom e :lixo
Essas classificações não são strings. Quando você coloca dois pontos a frente de uma simples palavra, você obtém um __symbol__ (símbolo).
Símbolos são mais baratos que strings (em termos de custo de memória). Se você usar uma palavra várias e várias vezes no seu programa,
troque por um símbolo. Ao invés de ter milhares de cópias desta palavra na memória, o computador irá armazenar o símbolo apenas __uma vez__.
Mais importante, um símbolo diz a você que isso não é apenas uma palavra, mas algo que tem significado para o seu programa.
Entre com mais duas análises de livros, use __livros.length__ para ver quantas análises já existem no hash:
livros["Até o Fim"] = :lixo
livros["Cores Vivas"] = :mediocre
puts livros
puts livros.length
| {
"content_hash": "456151ee7c9547d1fa6a4ca87bb44134",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 140,
"avg_line_length": 45.11538461538461,
"alnum_prop": 0.7391304347826086,
"repo_name": "ricardovsilva/TryRuby",
"id": "a124926a72d8565ed58d73146743af6f815526e9",
"size": "1215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "translations/pt-br/try_ruby_210.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3251"
},
{
"name": "HTML",
"bytes": "2076"
},
{
"name": "JavaScript",
"bytes": "85"
},
{
"name": "Ruby",
"bytes": "17453"
}
],
"symlink_target": ""
} |
package live
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
// SetClientProperty Set Property by Reflect
func SetClientProperty(client *Client, propertyName string, propertyValue interface{}) {
v := reflect.ValueOf(client).Elem()
if v.FieldByName(propertyName).IsValid() && v.FieldByName(propertyName).CanSet() {
v.FieldByName(propertyName).Set(reflect.ValueOf(propertyValue))
}
}
// SetEndpointDataToClient Set EndpointMap and ENdpointType
func SetEndpointDataToClient(client *Client) {
SetClientProperty(client, "EndpointMap", GetEndpointMap())
SetClientProperty(client, "EndpointType", GetEndpointType())
}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
SetEndpointDataToClient(client)
return
}
// NewClientWithProvider creates a sdk client with providers
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
SetEndpointDataToClient(client)
return
}
// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential
// this is the common api to create a sdk client
func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
SetEndpointDataToClient(client)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
SetEndpointDataToClient(client)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
SetEndpointDataToClient(client)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
SetEndpointDataToClient(client)
return
}
| {
"content_hash": "7a97ee7ca72586104b8c1e6f207de6f8",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 155,
"avg_line_length": 41.007751937984494,
"alnum_prop": 0.7843100189035916,
"repo_name": "aliyun/alibaba-cloud-sdk-go",
"id": "9aaa98a136cfe57b594a9f92996719e3828f2a3b",
"size": "5290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services/live/client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "734307"
},
{
"name": "Makefile",
"bytes": "183"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "8b16b034c6f283a6dee8c792b23e9d4f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "11c21fb5ccd0bae6114fbe41f4d7fffa674a8fe9",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Willemetia/Willemetia stipitata/ Syn. Zollikoferia peltidium/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include "test_utils.hpp"
#include "cassandra.h"
#include <boost/format.hpp>
#include <boost/test/unit_test.hpp>
#define TOTAL_NUMBER_OF_BATCHES 100
struct NamedParametersTests : public test_utils::SingleSessionTest {
private:
/**
* Helper method to create the table name for the create CQL statement
*
* @param value_type CassValueType to use for value
* @param is_prepared True if prepared statement should be used; false
* otherwise
* @param suffix Suffix to apply to table name
*/
std::string table_name_builder(CassValueType value_type, bool is_prepared, std::string suffix = "") {
std::string table_name = "named_parameters_" + std::string(test_utils::get_value_type(value_type)) + "_";
table_name += is_prepared ? "prepared" : "simple";
table_name += suffix.empty() ? "" : "_" + suffix;
return table_name;
}
public:
NamedParametersTests() : test_utils::SingleSessionTest(1, 0) {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT) % test_utils::SIMPLE_KEYSPACE % "1"));
test_utils::execute_query(session, str(boost::format("USE %s") % test_utils::SIMPLE_KEYSPACE));
}
/**
* Insert and validate a datatype
*
* @param value_type CassValueType to use for value
* @param value Value to use
* @param is_prepared True if prepared statement should be used; false
* otherwise
*/
template <class T>
void insert_primitive_value(CassValueType value_type, T value, bool is_prepared) {
// Create the table for the test
std::string table_name = table_name_builder(value_type, is_prepared);
std::string create_table = "CREATE TABLE " + table_name + "(key timeuuid PRIMARY KEY, value " + test_utils::get_value_type(value_type) + ")";
test_utils::execute_query(session, create_table.c_str());
// Bind and insert the named value parameter into Cassandra
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
std::string insert_query = "INSERT INTO " + table_name + "(key, value) VALUES(:named_key, :named_value)";
test_utils::CassStatementPtr statement(cass_statement_new(insert_query.c_str(), 2));
if (is_prepared) {
test_utils::CassPreparedPtr prepared = test_utils::prepare(session, insert_query.c_str());
statement = test_utils::CassStatementPtr(cass_prepared_bind(prepared.get()));
}
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "named_key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<T>::bind_by_name(statement.get(), "named_value", value), CASS_OK);
test_utils::wait_and_check_error(test_utils::CassFuturePtr(cass_session_execute(session, statement.get())).get());
// Ensure the named parameter value can be read using a named parameter
std::string select_query = "SELECT value FROM " + table_name + " WHERE key = :named_key";
statement = test_utils::CassStatementPtr(cass_statement_new(select_query.c_str(), 1));
if (is_prepared) {
test_utils::CassPreparedPtr prepared = test_utils::prepare(session, select_query.c_str());
statement = test_utils::CassStatementPtr(cass_prepared_bind(prepared.get()));
}
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "named_key", key), CASS_OK);
test_utils::CassFuturePtr future = test_utils::CassFuturePtr(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 1);
BOOST_REQUIRE_EQUAL(cass_result_column_count(result.get()), 1);
const CassRow* row = cass_result_first_row(result.get());
const CassValue* row_value = cass_row_get_column(row, 0);
T result_value;
BOOST_REQUIRE(cass_value_type(row_value) == value_type);
BOOST_REQUIRE_EQUAL(test_utils::Value<T>::get(row_value, &result_value), CASS_OK);
BOOST_REQUIRE(test_utils::Value<T>::equal(result_value, value));
}
/**
* Insert and validate a batch
*
* @param value_type CassValueType to use for value
* @param value Value to use
* @param total Total number of batches to insert and validate
*/
template <class T>
void insert_primitive_batch_value(CassValueType value_type, T value, unsigned int total) {
// Create the table for the test
std::string table_name = table_name_builder(value_type, true, "batch");
std::string create_table = "CREATE TABLE " + table_name + "(key timeuuid PRIMARY KEY, value " + test_utils::get_value_type(value_type) + ")";
test_utils::execute_query(session, create_table.c_str());
// Bind and insert the named value parameter into Cassandra
test_utils::CassBatchPtr batch(cass_batch_new(CASS_BATCH_TYPE_LOGGED));
std::string insert_query = "INSERT INTO " + table_name + "(key, value) VALUES(:named_key , :named_value)";
test_utils::CassPreparedPtr prepared = test_utils::prepare(session, insert_query.c_str());
std::vector<CassUuid> uuids;
for (unsigned int i = 0; i < total; ++i) {
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
uuids.push_back(key);
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "named_key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<T>::bind_by_name(statement.get(), "named_value", value), CASS_OK);
cass_batch_add_statement(batch.get(), statement.get());
}
test_utils::wait_and_check_error(test_utils::CassFuturePtr(cass_session_execute_batch(session, batch.get())).get());
// Ensure the named parameter can be read using a named parameter
std::string select_query = "SELECT value FROM " + table_name + " WHERE key=:named_key";
prepared = test_utils::prepare(session, select_query.c_str());
for (std::vector<CassUuid>::iterator iterator = uuids.begin(); iterator != uuids.end(); ++iterator) {
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "named_key", *iterator), CASS_OK);
test_utils::CassFuturePtr future = test_utils::CassFuturePtr(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 1);
BOOST_REQUIRE_EQUAL(cass_result_column_count(result.get()), 1);
const CassRow* row = cass_result_first_row(result.get());
const CassValue* row_value = cass_row_get_column(row, 0);
T result_value;
BOOST_REQUIRE(cass_value_type(row_value) == value_type);
BOOST_REQUIRE_EQUAL(test_utils::Value<T>::get(row_value, &result_value), CASS_OK);
BOOST_REQUIRE(test_utils::Value<T>::equal(result_value, value));
}
}
};
BOOST_AUTO_TEST_SUITE(named_parameters)
/**
* Ordered and Unordered Named Parameters
*
* This test ensures named parameters can be read/written using Cassandra v2.1+
* whether the are ordered or unordered.
*
* @since 2.1.0-beta
* @jira_ticket CPP-263
* @test_category queries:named_parameters
* @cassandra_version 2.1.x
*/
BOOST_AUTO_TEST_CASE(ordered_unordered_read_write) {
CassVersion version = test_utils::get_version();
if ((version.major >= 2 && version.minor >= 1) || version.major >= 3) {
NamedParametersTests tester;
std::string create_table = "CREATE TABLE ordered_unordered_read_write(key int PRIMARY KEY, value_text text, value_uuid uuid, value_blob blob, value_list_floats list<float>)";
std::string insert_query = "INSERT INTO ordered_unordered_read_write(key, value_text, value_uuid, value_blob, value_list_floats) VALUES (:key, :one_text, :two_uuid, :three_blob, :four_list_floats)";
std::string select_query = "SELECT value_text, value_uuid, value_blob, value_list_floats FROM ordered_unordered_read_write WHERE key=?";
// Create the table and statement for the test
test_utils::execute_query(tester.session, create_table.c_str());
// Insert and read elements in the order of their named query parameters
{
// Create and insert values for the insert statement
test_utils::CassStatementPtr statement(cass_statement_new(insert_query.c_str(), 5));
CassString text("Named parameters - In Order");
CassUuid uuid = test_utils::generate_random_uuid(tester.uuid_gen);
CassBytes blob = test_utils::bytes_from_string(text.data);
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_int32_t>::bind_by_name(statement.get(), "key", 1), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::bind_by_name(statement.get(), "one_text", text), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::bind_by_name(statement.get(), "two_uuid", uuid), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::bind_by_name(statement.get(), "three_blob", blob), CASS_OK);
test_utils::CassCollectionPtr list(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 1));
test_utils::Value<cass_float_t>::append(list.get(), 0.01f);
BOOST_REQUIRE_EQUAL(cass_statement_bind_collection_by_name(statement.get(), "four_list_floats", list.get()), CASS_OK);
test_utils::wait_and_check_error(test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get())).get());
// Ensure the named query parameters can be read
statement = test_utils::CassStatementPtr(cass_statement_new(select_query.c_str(), 1));
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32(statement.get(), 0, 1), CASS_OK);
test_utils::CassFuturePtr future = test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 1);
BOOST_REQUIRE_EQUAL(cass_result_column_count(result.get()), 4);
const CassRow* row = cass_result_first_row(result.get());
CassString value_text;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::get(cass_row_get_column(row, 0), &value_text), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassString>::equal(value_text, text));
CassUuid value_uuid;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::get(cass_row_get_column(row, 1), &value_uuid), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassUuid>::equal(value_uuid, uuid));
CassBytes value_blob;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::get(cass_row_get_column(row, 2), &value_blob), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassBytes>::equal(value_blob, blob));
test_utils::CassIteratorPtr iterator(cass_iterator_from_collection(cass_row_get_column(row, 3)));
cass_iterator_next(iterator.get());
cass_float_t value_float;
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_float_t>::get(cass_iterator_get_value(iterator.get()), &value_float), CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_float_t>::equal(value_float, 0.01f));
}
// Insert and read elements out of the order of their named query parameters
{
// Create and insert values for the insert statement
test_utils::CassStatementPtr statement(cass_statement_new(insert_query.c_str(), 5));
CassString text("Named parameters - Out of Order");
CassUuid uuid = test_utils::generate_random_uuid(tester.uuid_gen);
CassBytes blob = test_utils::bytes_from_string(text.data);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::bind_by_name(statement.get(), "three_blob", blob), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::bind_by_name(statement.get(), "one_text", text), CASS_OK);
test_utils::CassCollectionPtr list(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 1));
test_utils::Value<cass_float_t>::append(list.get(), 0.02f);
BOOST_REQUIRE_EQUAL(cass_statement_bind_collection_by_name(statement.get(), "four_list_floats", list.get()), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_int32_t>::bind_by_name(statement.get(), "key", 2), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::bind_by_name(statement.get(), "two_uuid", uuid), CASS_OK);
test_utils::wait_and_check_error(test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get())).get());
// Ensure the named query parameters can be read
statement = test_utils::CassStatementPtr(cass_statement_new(select_query.c_str(), 1));
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32(statement.get(), 0, 2), CASS_OK);
test_utils::CassFuturePtr future = test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 1);
BOOST_REQUIRE_EQUAL(cass_result_column_count(result.get()), 4);
const CassRow* row = cass_result_first_row(result.get());
CassBytes value_blob;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::get(cass_row_get_column(row, 2), &value_blob), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassBytes>::equal(value_blob, blob));
CassString value_text;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::get(cass_row_get_column(row, 0), &value_text), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassString>::equal(value_text, text));
test_utils::CassIteratorPtr iterator(cass_iterator_from_collection(cass_row_get_column(row, 3)));
cass_iterator_next(iterator.get());
cass_float_t value_float;
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_float_t>::get(cass_iterator_get_value(iterator.get()), &value_float), CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_float_t>::equal(value_float, 0.02f));
CassUuid value_uuid;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::get(cass_row_get_column(row, 1), &value_uuid), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassUuid>::equal(value_uuid, uuid));
}
// Insert and read elements using prepared statement named query parameters
{
// Create and insert values for the insert statement
test_utils::CassPreparedPtr prepared = test_utils::prepare(tester.session, insert_query);
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassString text("Named parameters - Prepared Statement");
CassUuid uuid = test_utils::generate_random_uuid(tester.uuid_gen);
CassBytes blob = test_utils::bytes_from_string(text.data);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::bind_by_name(statement.get(), "three_blob", blob), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::bind_by_name(statement.get(), "one_text", text), CASS_OK);
test_utils::CassCollectionPtr list(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 1));
test_utils::Value<cass_float_t>::append(list.get(), 0.03f);
BOOST_REQUIRE_EQUAL(cass_statement_bind_collection_by_name(statement.get(), "four_list_floats", list.get()), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_int32_t>::bind_by_name(statement.get(), "key", 3), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::bind_by_name(statement.get(), "two_uuid", uuid), CASS_OK);
test_utils::wait_and_check_error(test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get())).get());
// Ensure the named query parameters can be read
statement = test_utils::CassStatementPtr(cass_statement_new(select_query.c_str(), 1));
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32(statement.get(), 0, 3), CASS_OK);
test_utils::CassFuturePtr future = test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 1);
BOOST_REQUIRE_EQUAL(cass_result_column_count(result.get()), 4);
const CassRow* row = cass_result_first_row(result.get());
CassBytes value_blob;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassBytes>::get(cass_row_get_column(row, 2), &value_blob), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassBytes>::equal(value_blob, blob));
CassString value_text;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::get(cass_row_get_column(row, 0), &value_text), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassString>::equal(value_text, text));
test_utils::CassIteratorPtr iterator(cass_iterator_from_collection(cass_row_get_column(row, 3)));
cass_iterator_next(iterator.get());
cass_float_t value_float;
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_float_t>::get(cass_iterator_get_value(iterator.get()), &value_float), CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_float_t>::equal(value_float, 0.03f));
CassUuid value_uuid;
BOOST_REQUIRE_EQUAL(test_utils::Value<CassUuid>::get(cass_row_get_column(row, 1), &value_uuid), CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassUuid>::equal(value_uuid, uuid));
}
} else {
boost::unit_test::unit_test_log_t::instance().set_threshold_level(boost::unit_test::log_messages);
BOOST_TEST_MESSAGE("Unsupported Test for Cassandra v" << version.to_string() << ": Skipping named_parameters/ordered_unordered_read_write");
BOOST_REQUIRE(true);
}
}
/**
* Bound/Prepared Statements Using All Primitive Datatype for named parameters
*
* This test ensures named parameters can be read/written using Cassandra v2.1+
* for all primitive datatypes either bound or prepared statements
*
* @since 2.1.0-beta
* @jira_ticket CPP-263
* @test_category queries:named_parameters
* @cassandra_version 2.1.x
*/
BOOST_AUTO_TEST_CASE(all_primitives) {
CassVersion version = test_utils::get_version();
if ((version.major >= 2 && version.minor >= 1) || version.major >= 3) {
NamedParametersTests tester;
for (unsigned int i = 0; i < 2; ++i) {
bool is_prepared = i == 0 ? false : true;
{
CassString value("Test Value");
tester.insert_primitive_value<CassString>(CASS_VALUE_TYPE_ASCII, value, is_prepared);
tester.insert_primitive_value<CassString>(CASS_VALUE_TYPE_VARCHAR, value, is_prepared); // NOTE: text is alias for varchar
}
{
cass_int64_t value = 1234567890;
tester.insert_primitive_value<cass_int64_t>(CASS_VALUE_TYPE_BIGINT, value, is_prepared);
tester.insert_primitive_value<cass_int64_t>(CASS_VALUE_TYPE_TIMESTAMP, value, is_prepared);
}
{
CassBytes value = test_utils::bytes_from_string("012345678900123456789001234567890012345678900123456789001234567890");
tester.insert_primitive_value<CassBytes>(CASS_VALUE_TYPE_BLOB, value, is_prepared);
tester.insert_primitive_value<CassBytes>(CASS_VALUE_TYPE_VARINT, value, is_prepared);
}
tester.insert_primitive_value<cass_bool_t>(CASS_VALUE_TYPE_BOOLEAN, cass_true, is_prepared);
{
const cass_uint8_t pi[] = { 57, 115, 235, 135, 229, 215, 8, 125, 13, 43, 1, 25, 32, 135, 129, 180,
112, 176, 158, 120, 246, 235, 29, 145, 238, 50, 108, 239, 219, 100, 250,
84, 6, 186, 148, 76, 230, 46, 181, 89, 239, 247 };
const cass_int32_t pi_scale = 100;
CassDecimal value = CassDecimal(pi, sizeof(pi), pi_scale);
tester.insert_primitive_value<CassDecimal>(CASS_VALUE_TYPE_DECIMAL, value, is_prepared);
}
tester.insert_primitive_value<cass_double_t>(CASS_VALUE_TYPE_DOUBLE, 3.141592653589793, is_prepared);
tester.insert_primitive_value<cass_float_t>(CASS_VALUE_TYPE_FLOAT, 3.1415926f, is_prepared);
tester.insert_primitive_value<cass_int32_t>(CASS_VALUE_TYPE_INT, 123, is_prepared);
if ((version.major >= 2 && version.minor >= 2) || version.major >= 3) {
tester.insert_primitive_value<cass_int16_t>(CASS_VALUE_TYPE_SMALL_INT, 123, is_prepared);
tester.insert_primitive_value<cass_int8_t>(CASS_VALUE_TYPE_TINY_INT, 123, is_prepared);
}
{
CassUuid value = test_utils::generate_random_uuid(tester.uuid_gen);
tester.insert_primitive_value<CassUuid>(CASS_VALUE_TYPE_UUID, value, is_prepared);
}
{
CassInet value = test_utils::inet_v4_from_int(16777343); // 127.0.0.1
tester.insert_primitive_value<CassInet>(CASS_VALUE_TYPE_INET, value, is_prepared);
}
{
CassUuid value = test_utils::generate_time_uuid(tester.uuid_gen);
tester.insert_primitive_value<CassUuid>(CASS_VALUE_TYPE_TIMEUUID, value, is_prepared);
}
}
} else {
boost::unit_test::unit_test_log_t::instance().set_threshold_level(boost::unit_test::log_messages);
BOOST_TEST_MESSAGE("Unsupported Test for Cassandra v" << version.to_string() << ": Skipping named_parameters/all_primitives");
BOOST_REQUIRE(true);
}
}
/**
* Batch Statements Using All Primitive Datatype for named parameters
*
* This test ensures named parameters can be read/written using Cassandra v2.1+
* for all primitive datatypes using batched statements
*
* @since 2.1.0-beta
* @jira_ticket CPP-263
* @test_category queries:named_parameters
* @cassandra_version 2.1.x
*/
BOOST_AUTO_TEST_CASE(all_primitives_batched) {
CassVersion version = test_utils::get_version();
if ((version.major >= 2 && version.minor >= 1) || version.major >= 3) {
NamedParametersTests tester;
{
CassString value("Test Value");
tester.insert_primitive_batch_value<CassString>(CASS_VALUE_TYPE_ASCII, value, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<CassString>(CASS_VALUE_TYPE_VARCHAR, value, TOTAL_NUMBER_OF_BATCHES); // NOTE: text is alias for varchar
}
{
cass_int64_t value = 1234567890;
tester.insert_primitive_batch_value<cass_int64_t>(CASS_VALUE_TYPE_BIGINT, value, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<cass_int64_t>(CASS_VALUE_TYPE_TIMESTAMP, value, TOTAL_NUMBER_OF_BATCHES);
}
{
CassBytes value = test_utils::bytes_from_string("012345678900123456789001234567890012345678900123456789001234567890");
tester.insert_primitive_batch_value<CassBytes>(CASS_VALUE_TYPE_BLOB, value, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<CassBytes>(CASS_VALUE_TYPE_VARINT, value, TOTAL_NUMBER_OF_BATCHES);
}
tester.insert_primitive_batch_value<cass_bool_t>(CASS_VALUE_TYPE_BOOLEAN, cass_true, TOTAL_NUMBER_OF_BATCHES);
{
const cass_uint8_t pi[] = { 57, 115, 235, 135, 229, 215, 8, 125, 13, 43, 1, 25, 32, 135, 129, 180,
112, 176, 158, 120, 246, 235, 29, 145, 238, 50, 108, 239, 219, 100, 250,
84, 6, 186, 148, 76, 230, 46, 181, 89, 239, 247 };
const cass_int32_t pi_scale = 100;
CassDecimal value = CassDecimal(pi, sizeof(pi), pi_scale);
tester.insert_primitive_batch_value<CassDecimal>(CASS_VALUE_TYPE_DECIMAL, value, TOTAL_NUMBER_OF_BATCHES);
}
tester.insert_primitive_batch_value<cass_double_t>(CASS_VALUE_TYPE_DOUBLE, 3.141592653589793, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<cass_float_t>(CASS_VALUE_TYPE_FLOAT, 3.1415926f, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<cass_int32_t>(CASS_VALUE_TYPE_INT, 123, TOTAL_NUMBER_OF_BATCHES);
if ((version.major >= 2 && version.minor >= 2) || version.major >= 3) {
tester.insert_primitive_batch_value<cass_int16_t>(CASS_VALUE_TYPE_SMALL_INT, 123, TOTAL_NUMBER_OF_BATCHES);
tester.insert_primitive_batch_value<cass_int8_t>(CASS_VALUE_TYPE_TINY_INT, 123, TOTAL_NUMBER_OF_BATCHES);
}
{
CassUuid value = test_utils::generate_random_uuid(tester.uuid_gen);
tester.insert_primitive_batch_value<CassUuid>(CASS_VALUE_TYPE_UUID, value, TOTAL_NUMBER_OF_BATCHES);
}
{
CassInet value = test_utils::inet_v4_from_int(16777343); // 127.0.0.1
tester.insert_primitive_batch_value<CassInet>(CASS_VALUE_TYPE_INET, value, TOTAL_NUMBER_OF_BATCHES);
}
{
CassUuid value = test_utils::generate_time_uuid(tester.uuid_gen);
tester.insert_primitive_batch_value<CassUuid>(CASS_VALUE_TYPE_TIMEUUID, value, TOTAL_NUMBER_OF_BATCHES);
}
} else {
boost::unit_test::unit_test_log_t::instance().set_threshold_level(boost::unit_test::log_messages);
BOOST_TEST_MESSAGE("Unsupported Test for Cassandra v" << version.to_string() << ": Skipping named_parameters/all_primitives");
BOOST_REQUIRE(true);
}
}
/**
* Bound/Prepared Statements Using invalid named parameters
*
* This test ensures invalid named parameters return errors when prepared or
* executed.
*
* @since 2.1.0-beta
* @jira_ticket CPP-263
* @test_category queries:named_parameters
* @cassandra_version 2.1.x
*/
BOOST_AUTO_TEST_CASE(invalid_name) {
CassVersion version = test_utils::get_version();
if ((version.major >= 2 && version.minor >= 1) || version.major >= 3) {
NamedParametersTests tester;
std::string create_table = "CREATE TABLE named_parameter_invalid(key int PRIMARY KEY, value text)";
std::string insert_query = "INSERT INTO named_parameter_invalid(key, value) VALUES (:key_name, :value_name)";
// Create the table and statement for the test
test_utils::execute_query(tester.session, create_table.c_str());
// Invalid name
{
// Simple
test_utils::CassStatementPtr statement(cass_statement_new(insert_query.c_str(), 2));
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_int32_t>::bind_by_name(statement.get(), "invalid_key_name", 0), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::bind_by_name(statement.get(), "invalid_value_name", CassString("invalid")), CASS_OK);
BOOST_REQUIRE_EQUAL(test_utils::wait_and_return_error(test_utils::CassFuturePtr(cass_session_execute(tester.session, statement.get())).get()),
CASS_ERROR_SERVER_INVALID_QUERY);
// Prepared
test_utils::CassPreparedPtr prepared = test_utils::prepare(tester.session, insert_query.c_str());
statement = test_utils::CassStatementPtr(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE_EQUAL(test_utils::Value<cass_int32_t>::bind_by_name(statement.get(), "invalid_key_name", 0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
BOOST_REQUIRE_EQUAL(test_utils::Value<CassString>::bind_by_name(statement.get(), "invalid_value_name", CassString("invalid")), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
}
} else {
boost::unit_test::unit_test_log_t::instance().set_threshold_level(boost::unit_test::log_messages);
BOOST_TEST_MESSAGE("Unsupported Test for Cassandra v" << version.to_string() << ": Skipping named_parameters/invalid");
BOOST_REQUIRE(true);
}
}
BOOST_AUTO_TEST_SUITE_END()
| {
"content_hash": "337e2fac0efa139813a1da84c7fcad7e",
"timestamp": "",
"source": "github",
"line_count": 484,
"max_line_length": 202,
"avg_line_length": 56.03512396694215,
"alnum_prop": 0.6896500866487224,
"repo_name": "tempbottle/cpp-driver",
"id": "eb3040c68358e3521847cfb4a8eb84277cb0bfbe",
"size": "27700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/integration_tests/src/test_named_parameters.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "66579"
},
{
"name": "C",
"bytes": "196726"
},
{
"name": "C++",
"bytes": "1439290"
},
{
"name": "CMake",
"bytes": "44907"
},
{
"name": "Makefile",
"bytes": "1051"
},
{
"name": "Ruby",
"bytes": "572"
},
{
"name": "Shell",
"bytes": "2555"
}
],
"symlink_target": ""
} |
import { declare } from "@babel/helper-plugin-utils";
import { template, types as t } from "@babel/core";
export default declare((api, options) => {
api.assertVersion(7);
const { loose } = options;
let helperName = "taggedTemplateLiteral";
if (loose) helperName += "Loose";
/**
* This function groups the objects into multiple calls to `.concat()` in
* order to preserve execution order of the primitive conversion, e.g.
*
* "".concat(obj.foo, "foo", obj2.foo, "foo2")
*
* would evaluate both member expressions _first_ then, `concat` will
* convert each one to a primitive, whereas
*
* "".concat(obj.foo, "foo").concat(obj2.foo, "foo2")
*
* would evaluate the member, then convert it to a primitive, then evaluate
* the second member and convert that one, which reflects the spec behavior
* of template literals.
*/
function buildConcatCallExpressions(items) {
let avail = true;
return items.reduce(function (left, right) {
let canBeInserted = t.isLiteral(right);
if (!canBeInserted && avail) {
canBeInserted = true;
avail = false;
}
if (canBeInserted && t.isCallExpression(left)) {
left.arguments.push(right);
return left;
}
return t.callExpression(
t.memberExpression(left, t.identifier("concat")),
[right],
);
});
}
return {
name: "transform-template-literals",
visitor: {
TaggedTemplateExpression(path) {
const { node } = path;
const { quasi } = node;
const strings = [];
const raws = [];
// Flag variable to check if contents of strings and raw are equal
let isStringsRawEqual = true;
for (const elem of (quasi.quasis: Array)) {
const { raw, cooked } = elem.value;
const value =
cooked == null
? path.scope.buildUndefinedNode()
: t.stringLiteral(cooked);
strings.push(value);
raws.push(t.stringLiteral(raw));
if (raw !== cooked) {
// false even if one of raw and cooked are not equal
isStringsRawEqual = false;
}
}
const scope = path.scope.getProgramParent();
const templateObject = scope.generateUidIdentifier("templateObject");
const helperId = this.addHelper(helperName);
const callExpressionInput = [t.arrayExpression(strings)];
// only add raw arrayExpression if there is any difference between raws and strings
if (!isStringsRawEqual) {
callExpressionInput.push(t.arrayExpression(raws));
}
const lazyLoad = template.ast`
function ${templateObject}() {
const data = ${t.callExpression(helperId, callExpressionInput)};
${t.cloneNode(templateObject)} = function() { return data };
return data;
}
`;
scope.path.unshiftContainer("body", lazyLoad);
path.replaceWith(
t.callExpression(node.tag, [
t.callExpression(t.cloneNode(templateObject), []),
...quasi.expressions,
]),
);
},
TemplateLiteral(path) {
const nodes = [];
const expressions = path.get("expressions");
let index = 0;
for (const elem of (path.node.quasis: Array)) {
if (elem.value.cooked) {
nodes.push(t.stringLiteral(elem.value.cooked));
}
if (index < expressions.length) {
const expr = expressions[index++];
const node = expr.node;
if (!t.isStringLiteral(node, { value: "" })) {
nodes.push(node);
}
}
}
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
const considerSecondNode = !loose || !t.isStringLiteral(nodes[1]);
if (!t.isStringLiteral(nodes[0]) && considerSecondNode) {
nodes.unshift(t.stringLiteral(""));
}
let root = nodes[0];
if (loose) {
for (let i = 1; i < nodes.length; i++) {
root = t.binaryExpression("+", root, nodes[i]);
}
} else if (nodes.length > 1) {
root = buildConcatCallExpressions(nodes);
}
path.replaceWith(root);
},
},
};
});
| {
"content_hash": "9128a08c8ccae6905058c0ac4fa25c5c",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 91,
"avg_line_length": 30.622377622377623,
"alnum_prop": 0.5693080612011875,
"repo_name": "jridgewell/babel",
"id": "abdf7087f8fc388fc62bed0cf0761cc396d5514b",
"size": "4379",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/babel-plugin-transform-template-literals/src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3207"
},
{
"name": "JavaScript",
"bytes": "4554602"
},
{
"name": "Makefile",
"bytes": "8151"
},
{
"name": "Shell",
"bytes": "10381"
},
{
"name": "TypeScript",
"bytes": "26134"
}
],
"symlink_target": ""
} |
# Flight
[](http://travis-ci.org/flightjs/flight)
[Flight](http://flightjs.github.io/) is a lightweight, component-based,
event-driven JavaScript framework that maps behavior to DOM nodes. It was
created at Twitter, and is used by the [twitter.com](https://twitter.com/) and
[TweetDeck](https://web.tweetdeck.com/) web applications.
* [Website](http://flightjs.github.io/)
* [API documentation](doc/README.md)
* [Flight example app](http://flightjs.github.io/example-app/)
* [Flight's Google Group](https://groups.google.com/forum/?fromgroups#!forum/twitter-flight)
* [Flight on Twitter](https://twitter.com/flight)
## Why Flight?
Flight is only ~5K minified and gzipped. It's built upon jQuery, and has
first-class support for AMD and [Bower](http://bower.io/).
Flight components are highly portable and easily testable. This is because a
Flight component (and its API) is entirely decoupled from other components.
Flight components communicate only by triggering and subscribing to events.
Flight also includes a simple and safe
[mixin](https://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/)
infrastructure, allowing components to be easily extended with minimal
boilerplate.
## Development tools
Flight has supporting projects that provide everything you need to setup,
write, and test your application.
* [Flight generator](https://github.com/flightjs/generator-flight/)
Recommended. One-step to setup everything you need to work with Flight.
* [Flight package generator](https://github.com/flightjs/generator-flight-package/)
Recommended. One-step to setup everything you need to write and test a
standalone Flight component.
* [Jasmine Flight](https://github.com/flightjs/jasmine-flight/)
Extensions for the Jasmine test framework.
* [Mocha Flight](https://github.com/flightjs/mocha-flight/)
Extensions for the Mocha test framework.
## Finding and writing standalone components
You can browse all the [Flight components](http://flight-components.jit.su)
available at this time. They can also be found by searching the Bower registry:
```
bower search flight
```
The easiest way to write a standalone Flight component is to use the [Flight
package generator](https://github.com/flightjs/generator-flight-package/):
```
yo flight-package foo
```
## Installation
If you prefer not to use the Flight generators, it's highly recommended that
you install Flight as an AMD package (including all the correct dependencies).
This is best done with [Bower](http://bower.io/), a package manager for the web.
```
npm install -g bower
bower install --save flight
```
You will have to reference Flight's installed dependencies –
[ES5-shim](https://github.com/kriskowal/es5-shim) and
[jQuery](http://jquery.com) – and use an AMD module loader like
[Require.js](http://requirejs.org/) or
[Loadrunner](https://github.com/danwrong/loadrunner).
```html
<script src="bower_components/es5-shim/es5-shim.js"></script>
<script src="bower_components/es5-shim/es5-sham.js"></script>
<script src="bower_components/jquery/jquery.js"></script>
<script data-main="main.js" src="bower_components/requirejs/require.js"></script>
...
```
## Standalone version
Alternatively, you can manually install the [standalone
version](http://flightjs.github.io/release/latest/flight.js) of Flight, also
available on [cdnjs](http://cdnjs.com/). It exposes all of its modules as
properties of a global variable, `flight`:
```html
...
<script src="flight.js"></script>
<script>
var MyComponent = flight.component(function() {
//...
});
</script>
```
N.B. You will also need to manually install the correct versions of Flight's
dependencies: ES5 Shim and jQuery.
## Example
A simple example of how to write and use a Flight component. Read the [API
documentation](doc) for a comprehensive overview.
```js
define(function (require) {
var defineComponent = require('flight/lib/component');
// define the component
return defineComponent(inbox);
function inbox() {
// define custom functions here
this.doSomething = function() {
//...
}
this.doSomethingElse = function() {
//...
}
// now initialize the component
this.after('initialize', function() {
this.on('click', doSomething);
this.on('mouseover', doSomethingElse);
});
}
});
```
```js
/* attach an inbox component to a node with id 'inbox' */
define(function (require) {
var Inbox = require('inbox');
Inbox.attachTo('#inbox', {
'nextPageSelector': '#nextPage',
'previousPageSelector': '#previousPage',
});
});
```
## Browser Support
Chrome, Firefox, Safari, Opera, IE 7+.
## Authors
+ [@angus-c](http://github.com/angus-c)
+ [@danwrong](http://github.com/danwrong)
+ [@kpk](http://github.com/kennethkufluk)
Thanks for assistance and contributions:
[@sayrer](https://github.com/sayrer),
[@shinypb](https://github.com/shinypb),
[@kloots](https://github.com/kloots),
[@marcelduran](https://github.com/marcelduran),
[@tbrd](https://github.com/tbrd),
[@necolas](https://github.com/necolas),
[@fat](https://github.com/fat),
[@mkuklis](https://github.com/mkuklis),
[@jrburke](https://github.com/jrburke),
[@garann](https://github.com/garann),
[@WebReflection](https://github.com/WebReflection),
[@coldhead](https://github.com/coldhead),
[@paulirish](https://github.com/paulirish),
[@nimbupani](https://github.com/nimbupani),
[@mootcycle](https://github.com/mootcycle).
Special thanks to the rest of the Twitter web team for their abundant
contributions and feedback.
## License
Copyright 2013 Twitter, Inc and other contributors.
Licensed under the MIT License
| {
"content_hash": "d67d50dbfd3f2ce41f147a7528fc7e7a",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 112,
"avg_line_length": 29.198979591836736,
"alnum_prop": 0.7289882928533986,
"repo_name": "pushiming/flight-package-sample",
"id": "6e5035719b9bfbf8058c3534618142672b4c32de",
"size": "5727",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bower_components/flight/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2145"
},
{
"name": "JavaScript",
"bytes": "322030"
}
],
"symlink_target": ""
} |
<?php
/*
Plugin Name: Toolbar Theme Switcher
Plugin URI: https://github.com/Rarst/toolbar-theme-switcher
Description: Adds toolbar menu that allows users to switch theme for themselves.
Author: Andrey "Rarst" Savchenko
Version: 1.5
Author URI: http://www.rarst.net/
Text Domain: toolbar-theme-switcher
Domain Path: /lang
License: MIT
*/
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
require __DIR__ . '/vendor/autoload.php';
}
Toolbar_Theme_Switcher::on_load();
| {
"content_hash": "130db1eb3cbd3ba08b8f62d12560a9b3",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 80,
"avg_line_length": 27.444444444444443,
"alnum_prop": 0.7004048582995951,
"repo_name": "Rarst/toolbar-theme-switcher",
"id": "583027b6818f58ef8751510608b1d6c1db9a8db2",
"size": "494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "toolbar-theme-switcher.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "7339"
}
],
"symlink_target": ""
} |
package tw.howie.load.config;
import org.apache.catalina.core.AprLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author howie
* @since 2015/4/15
*/
@Configuration
public class TomcatConfiguration implements EnvironmentAware {
private final Logger log = LoggerFactory.getLogger(TomcatConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "tomcat.");
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
String protocol = propertyResolver.getProperty("protocol");
log.info("Tomcat Protocol:{}", protocol);
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setProtocol(protocol);
factory.addContextLifecycleListeners(new AprLifecycleListener());
factory.setSessionTimeout(10, TimeUnit.MINUTES);
List<TomcatConnectorCustomizer> cs = new ArrayList();
cs.add(tomcatConnectorCustomizers());
factory.setTomcatConnectorCustomizers(cs);
return factory;
}
@Bean
public TomcatConnectorCustomizer tomcatConnectorCustomizers() {
String maxThreads = propertyResolver.getProperty("maxThreads");
String acceptCount = propertyResolver.getProperty("acceptCount");
return connector -> {
connector.setAttribute("maxThreads", maxThreads);
connector.setAttribute("acceptCount", acceptCount);
};
}
}
| {
"content_hash": "a966c9264e0c6db9da96719f40818d51",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 100,
"avg_line_length": 36.33870967741935,
"alnum_prop": 0.7665335108743897,
"repo_name": "howie/ServletContainerTest",
"id": "3e0b392bfe028c95854f768521a9d60b40cd592b",
"size": "2253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "load-tomcat/src/main/java/tw/howie/load/config/TomcatConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "18854"
}
],
"symlink_target": ""
} |
#include <permon/private/permonmatimpl.h>
PetscLogEvent Mat_GetColumnVectors, Mat_RestoreColumnVectors, Mat_MatMultByColumns, Mat_TransposeMatMultByColumns;
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_MatMult_Private(Mat A, PetscBool A_transpose, Mat B, Mat C);
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_MatFilterZeros_Private(Mat *C,PetscBool filter);
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_Private(Mat A, PetscBool A_transpose, Mat B, PetscBool filter, Mat *C_new);
static PetscErrorCode MatMatBlockDiagMultByColumns_Private(Mat B, PetscBool B_transpose, Mat R, PetscBool filter, Mat *Gt_new);
//TODO add an argument specifying whether values should be copied back during Restore
#undef __FUNCT__
#define __FUNCT__ "MatGetColumnVectors_Default"
static PetscErrorCode MatGetColumnVectors_Default(Mat A, Vec *cols_new[])
{
PetscInt i,j,nnz,ilo,ihi,N;
const PetscInt *nzi;
const PetscScalar *vals;
PetscScalar **A_cols_arrs;
Vec d,*cols;
PetscFunctionBegin;
N = A->cmap->N;
TRY( MatCreateVecs(A, PETSC_IGNORE, &d) );
TRY( VecDuplicateVecs(d, N, &cols) );
TRY( VecDestroy(&d) );
for (j=0; j<N; j++) {
TRY( VecZeroEntries(cols[j]) );
}
TRY( MatGetOwnershipRange(A, &ilo, &ihi) );
TRY( VecGetArrays(cols, N, &A_cols_arrs) );
for (i=ilo; i<ihi; i++) {
TRY( MatGetRow(A, i, &nnz, &nzi, &vals) );
for (j=0; j<nnz; j++) {
A_cols_arrs[nzi[j]][i-ilo] = vals[j];
}
TRY( MatRestoreRow(A, i, &nnz, &nzi, &vals) );
}
TRY( VecRestoreArrays(cols, N, &A_cols_arrs) );
*cols_new=cols;
PetscFunctionReturn(0);
}
//TODO add an argument specifying whether values should be copied back during Restore
#undef __FUNCT__
#define __FUNCT__ "MatRestoreColumnVectors_Default"
static PetscErrorCode MatRestoreColumnVectors_Default(Mat A, Vec *cols[])
{
PetscFunctionBegin;
TRY( VecDestroyVecs(A->cmap->N,cols) );
PetscFunctionReturn(0);
}
//TODO add an argument specifying whether values should be copied back during Restore
#undef __FUNCT__
#define __FUNCT__ "MatGetColumnVectors"
PetscErrorCode MatGetColumnVectors(Mat A, PetscInt *ncols, Vec *cols_new[])
{
static PetscBool registered = PETSC_FALSE;
PetscErrorCode (*f)(Mat,Vec*[]);
PetscFunctionBegin;
PetscValidHeaderSpecific(A,MAT_CLASSID,1);
PetscValidPointer(cols_new,3);
if (!registered) {
TRY( PetscLogEventRegister("MatGetColVecs",MAT_CLASSID,&Mat_GetColumnVectors) );
registered = PETSC_TRUE;
}
if (ncols) *ncols = A->cmap->N;
if (!A->cmap->N) {
*cols_new = NULL;
PetscFunctionReturn(0);
}
TRY( PetscObjectQueryFunction((PetscObject)A,"MatGetColumnVectors_C",&f) );
if (!f) f = MatGetColumnVectors_Default;
TRY( PetscLogEventBegin(Mat_GetColumnVectors,A,0,0,0) );
TRY( (*f)(A,cols_new) );
TRY( PetscLogEventEnd( Mat_GetColumnVectors,A,0,0,0) );
PetscFunctionReturn(0);
}
//TODO add an argument specifying whether values should be copied back during Restore
#undef __FUNCT__
#define __FUNCT__ "MatRestoreColumnVectors"
PetscErrorCode MatRestoreColumnVectors(Mat A, PetscInt *ncols, Vec *cols_new[])
{
static PetscBool registered = PETSC_FALSE;
PetscErrorCode (*f)(Mat,Vec*[]);
PetscFunctionBegin;
PetscValidHeaderSpecific(A,MAT_CLASSID,1);
PetscValidPointer(cols_new,3);
if (!registered) {
TRY( PetscLogEventRegister("MatResColVecs",MAT_CLASSID,&Mat_RestoreColumnVectors) );
registered = PETSC_TRUE;
}
if (ncols) *ncols = 0;
if (!A->cmap->N) {
*cols_new = NULL;
PetscFunctionReturn(0);
}
TRY( PetscObjectQueryFunction((PetscObject)A,"MatRestoreColumnVectors_C",&f) );
if (!f) f = MatRestoreColumnVectors_Default;
TRY( PetscLogEventBegin(Mat_RestoreColumnVectors,A,0,0,0) );
TRY( (*f)(A,cols_new) );
TRY( PetscLogEventEnd( Mat_RestoreColumnVectors,A,0,0,0) );
*cols_new = NULL;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatMatMultByColumns_MatMult_Private"
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_MatMult_Private(Mat A, PetscBool A_transpose, Mat B, Mat C)
{
PetscInt N,N1,j;
Vec *B_cols,*C_cols;
PetscErrorCode (*f)(Mat,Vec,Vec);
PetscFunctionBeginI;
f = A_transpose ? MatMultTranspose : MatMult;
N = B->cmap->N;
TRY( MatGetColumnVectors(B,&N1,&B_cols) ); FLLOP_ASSERT2(N1==N,"N1==N (%d != %d)",N1,N);
TRY( MatGetColumnVectors(C,&N1,&C_cols) ); FLLOP_ASSERT2(N1==N,"N1==N (%d != %d)",N1,N);
for (j=0; j<N; j++) {
TRY( f(A,B_cols[j],C_cols[j]) );
}
TRY( MatRestoreColumnVectors(B,&N1,&B_cols) );
TRY( MatRestoreColumnVectors(C,&N1,&C_cols) );
TRY( MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY) );
TRY( MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY) );
PetscFunctionReturnI(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatMatMultByColumns_MatFilterZeros_Private"
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_MatFilterZeros_Private(Mat *C,PetscBool filter)
{
Mat C_new;
FllopTracedFunctionBegin;
if (filter) {
FllopTraceBegin;
TRY( MatFilterZeros(*C,PETSC_MACHINE_EPSILON,&C_new) );
TRY( MatDestroy(C) );
*C = C_new;
PetscFunctionReturnI(0);
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatMatBlockDiagMultByColumns_Private"
static PetscErrorCode MatMatBlockDiagMultByColumns_Private(Mat B, PetscBool B_transpose, Mat R, PetscBool filter, Mat *Gt_new)
{
Mat Bt;
Mat Bt_loc;
Mat R_loc;
Mat Gt_loc;
Mat G_loc,G;
Vec lambda;
PetscFunctionBeginI;
/* get diagonal block */
TRY( MatGetDiagonalBlock(R, &R_loc) );
if (B_transpose) {
/* B_transpose is true => B is in fact B' */
Bt = B;
} else {
/* transpose matrix B */
TRY( PermonMatTranspose(B, MAT_TRANSPOSE_EXPLICIT, &Bt) );
}
TRY( MatNestPermonGetVecs(Bt,&lambda,NULL) );
/* get "local" part of matrix Bt */
TRY( PermonMatGetLocalMat(Bt, &Bt_loc) );
/* multiply Bt_loc' * R_loc = Gt_loc */
TRY( MatMatMultByColumns_Private(Bt_loc, PETSC_TRUE, R_loc, PETSC_FALSE, &Gt_loc) );
TRY( MatDestroy(&Bt_loc) );
if (!B_transpose) TRY( MatDestroy(&Bt) );
/* create global distributed G by vertical concatenating local sequential G_loc=Gt_loc' */
TRY( PermonMatTranspose(Gt_loc, MAT_TRANSPOSE_EXPLICIT, &G_loc) );
TRY( MatMatMultByColumns_MatFilterZeros_Private(&G_loc,filter) );
TRY( MatMergeAndDestroy(PetscObjectComm((PetscObject)B), &G_loc, lambda, &G) );
/* return Gt as implicit transpose of G */
TRY( PermonMatTranspose(G, MAT_TRANSPOSE_CHEAPEST, Gt_new) );
TRY( MatDestroy(&G) );
TRY( VecDestroy(&lambda) );
TRY( MatDestroy(&Gt_loc) );
PetscFunctionReturnI(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatMatMultByColumns_Private"
PETSC_STATIC_INLINE PetscErrorCode MatMatMultByColumns_Private(Mat A, PetscBool A_transpose, Mat B, PetscBool filter, Mat *C_new)
{
PetscBool flg;
PetscFunctionBeginI;
TRY( PetscObjectTypeCompare((PetscObject)B,MATBLOCKDIAG,&flg) );
if (flg) {
TRY( MatMatBlockDiagMultByColumns_Private(A,A_transpose,B,filter,C_new) );
} else {
TRY( PermonMatCreateDenseProductMatrix(A,A_transpose,B,C_new) );
TRY( MatMatMultByColumns_MatMult_Private(A,A_transpose,B,*C_new) );
TRY( MatMatMultByColumns_MatFilterZeros_Private(C_new,filter) );
}
PetscFunctionReturnI(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatMatMultByColumns"
PetscErrorCode MatMatMultByColumns(Mat A, Mat B, PetscBool filter, Mat *C_new)
{
static PetscBool registered = PETSC_FALSE;
PetscFunctionBeginI;
PetscValidHeaderSpecific(A,MAT_CLASSID,1);
PetscValidHeaderSpecific(B,MAT_CLASSID,2);
PetscValidLogicalCollectiveBool(A,filter,3);
PetscValidPointer(C_new,4);
if (!registered) {
TRY( PetscLogEventRegister("MatMatMultByCols",MAT_CLASSID,&Mat_MatMultByColumns) );
registered = PETSC_TRUE;
}
TRY( PetscLogEventBegin(Mat_MatMultByColumns,A,0,0,0) );
TRY( MatMatMultByColumns_Private(A,PETSC_FALSE,B,filter,C_new) );
TRY( PetscLogEventEnd( Mat_MatMultByColumns,A,0,0,0) );
PetscFunctionReturnI(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatTransposeMatMultByColumns"
PetscErrorCode MatTransposeMatMultByColumns(Mat A, Mat B, PetscBool filter, Mat *C_new)
{
static PetscBool registered = PETSC_FALSE;
PetscFunctionBeginI;
PetscValidHeaderSpecific(A,MAT_CLASSID,1);
PetscValidHeaderSpecific(B,MAT_CLASSID,2);
PetscValidLogicalCollectiveBool(A,filter,3);
PetscValidPointer(C_new,4);
if (!registered) {
TRY( PetscLogEventRegister("MatTrMatMultByCo",MAT_CLASSID,&Mat_TransposeMatMultByColumns) );
registered = PETSC_TRUE;
}
TRY( PetscLogEventBegin(Mat_TransposeMatMultByColumns,A,0,0,0) );
TRY( MatMatMultByColumns_Private(A,PETSC_TRUE,B,filter,C_new) );
TRY( PetscLogEventEnd( Mat_TransposeMatMultByColumns,A,0,0,0) );
PetscFunctionReturnI(0);
}
| {
"content_hash": "5627c4c79a47bfa6f96816680ee6ef6b",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 130,
"avg_line_length": 33.02264150943396,
"alnum_prop": 0.7087190035424523,
"repo_name": "It4innovations/permon",
"id": "5245f661e6ed994f298a82447941a74a6e752086",
"size": "8751",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mat/interface/permonmatmatmult.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "764633"
},
{
"name": "C++",
"bytes": "13364"
},
{
"name": "Makefile",
"bytes": "27627"
},
{
"name": "Python",
"bytes": "13390"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Saint-Savin est
une ville géographiquement positionnée dans le département de Gironde en Aquitaine. Elle comptait 2 545 habitants en 2008.</p>
<p>La ville compte quelques équipements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.</p>
<p>À Saint-Savin, le prix moyen à l'achat d'un appartement se situe à 2 676 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 651 € du m². À la location la valeur moyenne se situe à 10,33 € du m² mensuel.</p>
<p>Le nombre de logements, à Saint-Savin, était réparti en 2011 en 151 appartements et 1 115 maisons soit
un marché relativement équilibré.</p>
<p>À coté de Saint-Savin sont situées les communes de
<a href="{{VLROOT}}/immobilier/cubnezais_33142/">Cubnezais</a> située à 7 km, 1 137 habitants,
<a href="{{VLROOT}}/immobilier/saugon_33502/">Saugon</a> à 6 km, 370 habitants,
<a href="{{VLROOT}}/immobilier/cezac_33123/">Cézac</a> située à 5 km, 1 918 habitants,
<a href="{{VLROOT}}/immobilier/saint-girons-daiguevives_33416/">Saint-Girons-d'Aiguevives</a> à 7 km, 910 habitants,
<a href="{{VLROOT}}/immobilier/saint-yzan-de-soudiac_33492/">Saint-Yzan-de-Soudiac</a> localisée à 2 km, 1 762 habitants,
<a href="{{VLROOT}}/immobilier/cezac_46069/">Cézac</a> à 5 km, 160 habitants,
entre autres. De plus, Saint-Savin est située à seulement 29 km de <a href="{{VLROOT}}/immobilier/libourne_33243/">Libourne</a>.</p>
<p>À Saint-Savin le salaire moyen mensuel par personne se situe à environ 1 775 € net. Ceci est inférieur à la moyenne du pays.</p>
</div>
| {
"content_hash": "e193c5bdfed7d56e9dbf6e8e4c7a925d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 251,
"avg_line_length": 93.72222222222223,
"alnum_prop": 0.7350326022525193,
"repo_name": "donaldinou/frontend",
"id": "e29b6162444bc1a87a22283d3b6cdff2b08a902a",
"size": "1727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/33473.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": ""
} |
namespace paddle {
namespace platform {
inline ncclDataType_t ToNCCLDataType(framework::proto::VarType::Type type) {
if (type == framework::proto::VarType::FP32) {
return ncclFloat;
} else if (type == framework::proto::VarType::FP64) {
return ncclDouble;
} else if (type == framework::proto::VarType::INT32) {
return ncclInt;
} else if (type == framework::proto::VarType::INT64) {
return ncclInt64;
} else if (type == framework::proto::VarType::FP16) {
return ncclFloat16;
} else {
PADDLE_THROW("Not supported");
}
}
// NOTE(minqiyang): according to the ncclGroupEnd documentations:
// https://docs.nvidia.com/deeplearning/sdk/nccl-api/ncclapidoc.html,
// ncclGroupEnd will wait for all communicators to be initialized, which will
// cause blocking problem when a runtime_error was thrown, so try only guard
// NCCL actions when use it.
class NCCLGroupGuard {
public:
static std::mutex &NCCLMutex() {
static std::mutex mtx;
return mtx;
}
inline NCCLGroupGuard() {
NCCLMutex().lock();
PADDLE_ENFORCE(dynload::ncclGroupStart());
}
inline ~NCCLGroupGuard() {
PADDLE_ENFORCE(dynload::ncclGroupEnd());
NCCLMutex().unlock();
}
};
struct NCCLContext {
std::unique_ptr<CUDADeviceContext> ctx_;
ncclComm_t comm_;
explicit NCCLContext(int dev_id)
: ctx_(new CUDADeviceContext(CUDAPlace(dev_id))), comm_{nullptr} {}
cudaStream_t stream() const { return ctx_->stream(); }
ncclComm_t comm() const { return comm_; }
int device_id() const {
return boost::get<platform::CUDAPlace>(ctx_->GetPlace()).device;
}
};
struct NCCLContextMap {
std::unordered_map<int, NCCLContext> contexts_;
std::vector<int> order_;
explicit NCCLContextMap(const std::vector<platform::Place> &places,
ncclUniqueId *nccl_id = nullptr,
size_t num_trainers = 1, size_t trainer_id = 0) {
PADDLE_ENFORCE(!places.empty());
order_.reserve(places.size());
for (auto &p : places) {
int dev_id = boost::get<CUDAPlace>(p).device;
order_.emplace_back(dev_id);
contexts_.emplace(dev_id, NCCLContext(dev_id));
}
PADDLE_ENFORCE_EQ(
order_.size(), contexts_.size(),
"NCCL Context Map does not support contain two or more same device");
std::unique_ptr<ncclComm_t[]> comms(new ncclComm_t[order_.size()]);
// if num_trainers == 1, should create a new nccl id for local comms.
if (num_trainers == 1 && nccl_id == nullptr) {
std::lock_guard<std::mutex> guard(NCCLGroupGuard::NCCLMutex());
PADDLE_ENFORCE(platform::dynload::ncclCommInitAll(
comms.get(), static_cast<int>(order_.size()), order_.data()));
} else {
PADDLE_ENFORCE_NOT_NULL(nccl_id);
{
int nranks = num_trainers * order_.size();
NCCLGroupGuard gurad;
for (size_t i = 0; i < order_.size(); ++i) {
int gpu_id = order_[i];
int rank;
if (order_.size() > 1) {
rank = trainer_id * order_.size() + i;
} else {
rank = trainer_id;
}
VLOG(3) << "init nccl rank: " << rank << " nranks: " << nranks
<< " gpu id: " << gpu_id;
PADDLE_ENFORCE(cudaSetDevice(gpu_id));
PADDLE_ENFORCE(platform::dynload::ncclCommInitRank(
comms.get() + i, nranks, *nccl_id, rank));
}
}
}
int i = 0;
for (auto &dev_id : order_) {
contexts_.at(dev_id).comm_ = comms[i++];
}
}
NCCLContextMap(const NCCLContextMap &other) = delete;
NCCLContextMap &operator=(const NCCLContextMap &other) = delete;
CUDADeviceContext *DevCtx(int dev_id) const { return at(dev_id).ctx_.get(); }
CUDADeviceContext *DevCtx(platform::Place p) const {
return DevCtx(boost::get<CUDAPlace>(p).device);
}
const NCCLContext &at(platform::Place p) const {
return this->at(boost::get<CUDAPlace>(p).device);
}
const NCCLContext &at(int dev_id) const { return contexts_.at(dev_id); }
void WaitAll() {
for (auto &p : contexts_) {
p.second.ctx_->Wait();
}
}
};
} // namespace platform
} // namespace paddle
#endif
| {
"content_hash": "8eca9b5cc0276d10735cade283a43628",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 79,
"avg_line_length": 31.30827067669173,
"alnum_prop": 0.6162343900096061,
"repo_name": "baidu/Paddle",
"id": "b8b14b3d15efb47cbf53a393476f25158ebb5dff",
"size": "5183",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "paddle/fluid/platform/nccl_helper.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "217842"
},
{
"name": "C++",
"bytes": "2771237"
},
{
"name": "CMake",
"bytes": "113670"
},
{
"name": "Cuda",
"bytes": "424141"
},
{
"name": "M4",
"bytes": "40913"
},
{
"name": "Perl",
"bytes": "11412"
},
{
"name": "Python",
"bytes": "892636"
},
{
"name": "Shell",
"bytes": "64351"
}
],
"symlink_target": ""
} |
import { Resource } from '../api-resource';
/**
* @example <caption>Delete a channel</caption>
* ChannelResource.getModel(channel_id).delete()
*
* @example Only get the channels that are "available" (i.e. with resources on device)
* ChannelResource.getCollection().fetch({ available: true })
*/
export default class ChannelResource extends Resource {
static resourceName() {
return 'channel';
}
static usesContentCacheKey() {
return true;
}
}
| {
"content_hash": "70c6eadfbdc1a6fa9fa596a7df76e83a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 86,
"avg_line_length": 27.41176470588235,
"alnum_prop": 0.6995708154506438,
"repo_name": "benjaoming/kolibri",
"id": "937af409e8f956baa8594c2a7dce8feece9e95ec",
"size": "466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kolibri/core/assets/src/api-resources/channel.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "864"
},
{
"name": "CSS",
"bytes": "29176"
},
{
"name": "Dockerfile",
"bytes": "1872"
},
{
"name": "HTML",
"bytes": "12616"
},
{
"name": "JavaScript",
"bytes": "799257"
},
{
"name": "Makefile",
"bytes": "8232"
},
{
"name": "Python",
"bytes": "1241333"
},
{
"name": "Shell",
"bytes": "10412"
},
{
"name": "Vue",
"bytes": "815069"
}
],
"symlink_target": ""
} |
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**urn** | **String** | The design URN; returned when uploading the file to Forge The URN needs to be [Base64 (URL Safe) encoded](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/job-POST/#id3). |
**compressedUrn** | **Boolean** | Set this to `true` if the source file is compressed. If set to `true`, you need to define the `rootFilename`. | [optional] [default to false]
**rootFilename** | **String** | The root filename of the compressed file. Mandatory if the `compressedUrn` is set to `true`. | [optional]
| {
"content_hash": "ae659889817cb244fa8c9da50398dc09",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 222,
"avg_line_length": 97.85714285714286,
"alnum_prop": 0.637956204379562,
"repo_name": "hironaokato/genkeimodelsio",
"id": "c61b6267f86f3d52ba7b8cf96eb1c05946e6c799",
"size": "739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/forge-model-derivative/docs/JobPayloadInput.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16302"
},
{
"name": "HTML",
"bytes": "17382"
},
{
"name": "JavaScript",
"bytes": "334130"
}
],
"symlink_target": ""
} |
from decorator import decorate
def get_recorder(spy, attribute, context):
decorator_map = {
'function': FunctionRecorder(spy),
'instance_method': InstanceMethodRecorder(spy),
'class_method': ClassMethodRecorder(spy),
'static_method': StaticMethodRecorder(spy)
}
return decorate(attribute, context, decorator_map)
class Recorder(object):
def __init__(self, spy):
self.spy = spy
def record(self, fn, *args, **kwargs):
raise NotImplementedError
def __call__(self, fn, *args, **kwargs):
return self.record(fn, *args, **kwargs)
class FunctionRecorder(Recorder):
def record(self, fn, *args, **kwargs):
return_value = fn(*args, **kwargs)
self.spy.add_call(
fn,
args,
kwargs,
return_value
)
return return_value
class InstanceMethodRecorder(Recorder):
def record(self, fn, *args, **kwargs):
return_value = fn(*args, **kwargs)
self.spy.add_call(
fn,
args[1:], # discard 'self'
kwargs,
return_value
)
return return_value
class ClassMethodRecorder(InstanceMethodRecorder):
pass
class StaticMethodRecorder(FunctionRecorder):
pass
| {
"content_hash": "6b3eedee624cf367267157e89a35e7fd",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 55,
"avg_line_length": 21.89830508474576,
"alnum_prop": 0.5928792569659442,
"repo_name": "bywires/chara",
"id": "3c4345cabdf03f552ca311d2a4b36af04b12c7a9",
"size": "1292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chara/recorders.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "22110"
},
{
"name": "Shell",
"bytes": "77"
}
],
"symlink_target": ""
} |
$redis = Redis::Namespace.new("my_app", :redis => Redis.new) | {
"content_hash": "da7ab355c762d76be5afc9b229f00603",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 60,
"avg_line_length": 60,
"alnum_prop": 0.6666666666666666,
"repo_name": "ricardobaumann/who_are_you",
"id": "bbf7bda39af354399400f3fed35e98ba2510e0a0",
"size": "60",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/initializers/redis.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2432"
},
{
"name": "CoffeeScript",
"bytes": "844"
},
{
"name": "HTML",
"bytes": "8929"
},
{
"name": "JavaScript",
"bytes": "661"
},
{
"name": "Ruby",
"bytes": "42228"
}
],
"symlink_target": ""
} |
using UnityEngine;
namespace Pear.InteractionEngine.Converters
{
/// <summary>
/// Converts a vector3 to a float
/// </summary>
public class Vector3ToFloat : MonoBehaviour, IPropertyConverter<Vector3, float>
{
/// <summary>
/// Returns the magnitude of this vector
/// </summary>
/// <param name="convertFrom">Vector to use during the conversion</param>
/// <returns>Magnitude of vector 3</returns>
public float Convert(Vector3 convertFrom)
{
return convertFrom.magnitude;
}
}
}
| {
"content_hash": "14f276ae6698fb1a52d494b8b2c4e908",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 80,
"avg_line_length": 25.3,
"alnum_prop": 0.7035573122529645,
"repo_name": "PearMed/Pear-Interaction-Engine",
"id": "0356b28c09e5bed32260de2a83dca3e462340631",
"size": "508",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Scripts/Converters/Vector3ToFloat.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "155687"
},
{
"name": "GLSL",
"bytes": "6998"
},
{
"name": "ShaderLab",
"bytes": "11780"
}
],
"symlink_target": ""
} |
const argscheck = require('@remobile/react-native-cordova').argscheck,
utils = require('@remobile/react-native-cordova').utils,
exec = require('@remobile/react-native-cordova').exec,
Entry = require('./Entry'),
FileError = require('./FileError'),
DirectoryReader = require('./DirectoryReader');
/**
* An interface representing a directory on the file system.
*
* {boolean} isFile always false (readonly)
* {boolean} isDirectory always true (readonly)
* {DOMString} name of the directory, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the directory (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
const DirectoryEntry = function (name, fullPath, fileSystem, nativeURL) {
// add trailing slash if it is missing
if ((fullPath) && !/\/$/.test(fullPath)) {
fullPath += '/';
}
// add trailing slash if it is missing
if (nativeURL && !/\/$/.test(nativeURL)) {
nativeURL += '/';
}
DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);
};
utils.extend(DirectoryEntry, Entry);
/**
* Creates a new DirectoryReader to read entries from this directory
*/
DirectoryEntry.prototype.createReader = function () {
return new DirectoryReader(this.toInternalURL());
};
/**
* Creates or looks up a directory
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
* @param {Flags} options to create or exclusively create the directory
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {
argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
const fs = this.filesystem;
const win = successCallback && function (result) {
const entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
successCallback(entry);
};
const fail = errorCallback && function (code) {
errorCallback(new FileError(code));
};
exec(win, fail, 'File', 'getDirectory', [this.toInternalURL(), path, options]);
};
/**
* Deletes a directory and all of it's contents
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {
argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
const fail = errorCallback && function (code) {
errorCallback(new FileError(code));
};
exec(successCallback, fail, 'File', 'removeRecursively', [this.toInternalURL()]);
};
/**
* Creates or looks up a file
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
* @param {Flags} options to create or exclusively create the file
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {
argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
const fs = this.filesystem;
const win = successCallback && function (result) {
const FileEntry = require('./FileEntry');
const entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);
successCallback(entry);
};
const fail = errorCallback && function (code) {
errorCallback(new FileError(code));
};
exec(win, fail, 'File', 'getFile', [this.toInternalURL(), path, options]);
};
module.exports = DirectoryEntry;
| {
"content_hash": "63d727f58051a2edce2d9edab59510ac",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 123,
"avg_line_length": 39.855670103092784,
"alnum_prop": 0.702534919813761,
"repo_name": "remobile/react-native-file",
"id": "6a71f1465c542b68aa49694158478ea3edb479d6",
"size": "4678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/DirectoryEntry.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "116129"
},
{
"name": "JavaScript",
"bytes": "67327"
},
{
"name": "Objective-C",
"bytes": "94753"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.file.remote;
import java.io.File;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.component.file.GenericFileOperationFailedException;
import org.junit.Test;
/**
* @version
*/
public class FtpProducerTempFileExistIssueTest extends FtpServerTestSupport {
private String getFtpUrl() {
return "ftp://admin@localhost:" + getPort() + "/tempprefix/?password=admin";
}
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testIllegalConfiguration() throws Exception {
try {
context.getEndpoint(getFtpUrl() + "&fileExist=Append&tempPrefix=foo").createProducer();
} catch (IllegalArgumentException e) {
assertEquals("You cannot set both fileExist=Append and tempPrefix options", e.getMessage());
}
}
@Test
public void testWriteUsingTempPrefixButFileExist() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
template.sendBodyAndHeader(getFtpUrl() + "&tempPrefix=foo", "Bye World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
File file = new File(FTP_ROOT_DIR + "/tempprefix/hello.txt").getAbsoluteFile();
assertEquals(true, file.exists());
assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file));
}
@Test
public void testWriteUsingTempPrefixButBothFileExist() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "foohello.txt");
Thread.sleep(500);
template.sendBodyAndHeader(getFtpUrl() + "&tempPrefix=foo", "Bye World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
File file = new File(FTP_ROOT_DIR + "/tempprefix/hello.txt").getAbsoluteFile();
assertEquals(true, file.exists());
assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file));
}
@Test
public void testWriteUsingTempPrefixButFileExistOverride() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
template.sendBodyAndHeader(getFtpUrl() + "&tempPrefix=foo&fileExist=Override", "Bye World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
File file = new File(FTP_ROOT_DIR + "/tempprefix/hello.txt").getAbsoluteFile();
assertEquals(true, file.exists());
assertEquals("Bye World", context.getTypeConverter().convertTo(String.class, file));
}
@Test
public void testWriteUsingTempPrefixButFileExistIgnore() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
template.sendBodyAndHeader(getFtpUrl() + "&tempPrefix=foo&fileExist=Ignore", "Bye World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
File file = new File(FTP_ROOT_DIR + "/tempprefix/hello.txt").getAbsoluteFile();
// should not write new file as we should ignore
assertEquals("Hello World", context.getTypeConverter().convertTo(String.class, file));
}
@Test
public void testWriteUsingTempPrefixButFileExistFail() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
Thread.sleep(500);
try {
template.sendBodyAndHeader(getFtpUrl() + "&tempPrefix=foo&fileExist=Fail", "Bye World", Exchange.FILE_NAME, "hello.txt");
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
GenericFileOperationFailedException cause = assertIsInstanceOf(GenericFileOperationFailedException.class, e.getCause());
assertTrue(cause.getMessage().startsWith("File already exist"));
}
Thread.sleep(500);
File file = new File(FTP_ROOT_DIR + "/tempprefix/hello.txt").getAbsoluteFile();
// should not write new file as we should ignore
assertEquals("Hello World", context.getTypeConverter().convertTo(String.class, file));
}
} | {
"content_hash": "fda159e8d220d5a7fcc0d8776adf456f",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 133,
"avg_line_length": 38.13913043478261,
"alnum_prop": 0.6803465572275422,
"repo_name": "aaronwalker/camel",
"id": "8406b19887fca6ae51dc3661a804c08719e2f844",
"size": "5189",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerTempFileExistIssueTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "20202"
},
{
"name": "CSS",
"bytes": "221391"
},
{
"name": "Groovy",
"bytes": "2682"
},
{
"name": "Haskell",
"bytes": "5970"
},
{
"name": "Java",
"bytes": "27972791"
},
{
"name": "JavaScript",
"bytes": "3697148"
},
{
"name": "PHP",
"bytes": "88860"
},
{
"name": "Ruby",
"bytes": "9910"
},
{
"name": "Scala",
"bytes": "220463"
},
{
"name": "Shell",
"bytes": "12865"
},
{
"name": "TypeScript",
"bytes": "715"
},
{
"name": "XQuery",
"bytes": "1248"
},
{
"name": "XSLT",
"bytes": "53623"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2
Version: 3.7.0
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" dir="rtl">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title>Metronic | UI Features - Alerts & Dialogs API</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN THEME STYLES -->
<link href="../../assets/global/css/components-md-rtl.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/css/plugins-md-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout/css/layout-rtl.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="../../assets/admin/layout/css/themes/darkblue-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout/css/custom-rtl.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices -->
<!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default -->
<!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle -->
<!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar -->
<!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer -->
<!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side -->
<!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu -->
<body class="page-md page-header-fixed page-quick-sidebar-over-content ">
<!-- BEGIN HEADER -->
<div class="page-header md-shadow-z-1-i navbar navbar-fixed-top">
<!-- BEGIN HEADER INNER -->
<div class="page-header-inner">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../../assets/admin/layout/img/logo.png" alt="logo" class="logo-default"/>
</a>
<div class="menu-toggler sidebar-toggler hide">
<!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header -->
</div>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse">
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-default">
7 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3><span class="bold">12 pending</span> notifications</h3>
<a href="extra_profile.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span>
New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN INBOX DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-envelope-open"></i>
<span class="badge badge-default">
4 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have <span class="bold">7 New</span> Messages</h3>
<a href="page_inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message">
Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message">
Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message">
Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-default">
3 </span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have <span class="bold">12 pending</span> tasks</h3>
<a href="page_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-user">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<img alt="" class="img-circle" src="../../assets/admin/layout/img/avatar3_small.jpg"/>
<span class="username username-hide-on-mobile">
Nick </span>
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="extra_profile.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger">
3 </span>
</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-rocket"></i> My Tasks <span class="badge badge-success">
7 </span>
</a>
</li>
<li class="divider">
</li>
<li>
<a href="extra_lock.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="login.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
<!-- BEGIN QUICK SIDEBAR TOGGLER -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-quick-sidebar-toggler">
<a href="javascript:;" class="dropdown-toggle">
<i class="icon-logout"></i>
</a>
</li>
<!-- END QUICK SIDEBAR TOGGLER -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END HEADER INNER -->
</div>
<!-- END HEADER -->
<div class="clearfix">
</div>
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu page-sidebar-menu-light " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<!-- DOC: To remove the sidebar toggler from the sidebar you just need to completely remove the below "sidebar-toggler-wrapper" LI element -->
<li class="sidebar-toggler-wrapper">
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
<div class="sidebar-toggler">
</div>
<!-- END SIDEBAR TOGGLER BUTTON -->
</li>
<!-- DOC: To remove the search box from the sidebar you just need to completely remove the below "sidebar-search-wrapper" LI element -->
<li class="sidebar-search-wrapper">
<!-- BEGIN RESPONSIVE QUICK SEARCH FORM -->
<!-- DOC: Apply "sidebar-search-bordered" class the below search form to have bordered search box -->
<!-- DOC: Apply "sidebar-search-bordered sidebar-search-solid" class the below search form to have bordered & solid search box -->
<form class="sidebar-search " action="extra_search.html" method="POST">
<a href="javascript:;" class="remove">
<i class="icon-close"></i>
</a>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a>
</span>
</div>
</form>
<!-- END RESPONSIVE QUICK SEARCH FORM -->
</li>
<li class="start ">
<a href="javascript:;">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="index.html">
<i class="icon-bar-chart"></i>
Default Dashboard</a>
</li>
<li>
<a href="index_2.html">
<i class="icon-bulb"></i>
New Dashboard #1</a>
</li>
<li>
<a href="index_3.html">
<i class="icon-graph"></i>
New Dashboard #2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-basket"></i>
<span class="title">eCommerce</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="ecommerce_index.html">
<i class="icon-home"></i>
Dashboard</a>
</li>
<li>
<a href="ecommerce_orders.html">
<i class="icon-basket"></i>
Orders</a>
</li>
<li>
<a href="ecommerce_orders_view.html">
<i class="icon-tag"></i>
Order View</a>
</li>
<li>
<a href="ecommerce_products.html">
<i class="icon-handbag"></i>
Products</a>
</li>
<li>
<a href="ecommerce_products_edit.html">
<i class="icon-pencil"></i>
Product Edit</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-rocket"></i>
<span class="title">Page Layouts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="layout_horizontal_sidebar_menu.html">
Horizontal & Sidebar Menu</a>
</li>
<li>
<a href="index_horizontal_menu.html">
Dashboard & Mega Menu</a>
</li>
<li>
<a href="layout_horizontal_menu1.html">
Horizontal Mega Menu 1</a>
</li>
<li>
<a href="layout_horizontal_menu2.html">
Horizontal Mega Menu 2</a>
</li>
<li>
<a href="layout_fontawesome_icons.html">
<span class="badge badge-roundless badge-danger">new</span>Layout with Fontawesome Icons</a>
</li>
<li>
<a href="layout_glyphicons.html">
Layout with Glyphicon</a>
</li>
<li>
<a href="layout_full_height_portlet.html">
<span class="badge badge-roundless badge-success">new</span>Full Height Portlet</a>
</li>
<li>
<a href="layout_full_height_content.html">
<span class="badge badge-roundless badge-warning">new</span>Full Height Content</a>
</li>
<li>
<a href="layout_search_on_header1.html">
Search Box On Header 1</a>
</li>
<li>
<a href="layout_search_on_header2.html">
Search Box On Header 2</a>
</li>
<li>
<a href="layout_sidebar_search_option1.html">
Sidebar Search Option 1</a>
</li>
<li>
<a href="layout_sidebar_search_option2.html">
Sidebar Search Option 2</a>
</li>
<li>
<a href="layout_sidebar_reversed.html">
<span class="badge badge-roundless badge-warning">new</span>Right Sidebar Page</a>
</li>
<li>
<a href="layout_sidebar_fixed.html">
Sidebar Fixed Page</a>
</li>
<li>
<a href="layout_sidebar_closed.html">
Sidebar Closed Page</a>
</li>
<li>
<a href="layout_ajax.html">
Content Loading via Ajax</a>
</li>
<li>
<a href="layout_disabled_menu.html">
Disabled Menu Links</a>
</li>
<li>
<a href="layout_blank_page.html">
Blank Page</a>
</li>
<li>
<a href="layout_boxed_page.html">
Boxed Page</a>
</li>
<li>
<a href="layout_language_bar.html">
Language Switch Bar</a>
</li>
</ul>
</li>
<li class="active open">
<a href="javascript:;">
<i class="icon-diamond"></i>
<span class="title">UI Features</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
General Components</a>
</li>
<li>
<a href="ui_buttons.html">
Buttons</a>
</li>
<li>
<a href="ui_confirmations.html">
Popover Confirmations</a>
</li>
<li>
<a href="ui_icons.html">
<span class="badge badge-roundless badge-danger">new</span>Font Icons</a>
</li>
<li>
<a href="ui_colors.html">
Flat UI Colors</a>
</li>
<li>
<a href="ui_typography.html">
Typography</a>
</li>
<li>
<a href="ui_tabs_accordions_navs.html">
Tabs, Accordions & Navs</a>
</li>
<li>
<a href="ui_tree.html">
<span class="badge badge-roundless badge-danger">new</span>Tree View</a>
</li>
<li>
<a href="ui_page_progress_style_1.html">
<span class="badge badge-roundless badge-warning">new</span>Page Progress Bar</a>
</li>
<li>
<a href="ui_blockui.html">
Block UI</a>
</li>
<li>
<a href="ui_bootstrap_growl.html">
<span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a>
</li>
<li>
<a href="ui_notific8.html">
Notific8 Notifications</a>
</li>
<li>
<a href="ui_toastr.html">
Toastr Notifications</a>
</li>
<li class="active">
<a href="ui_alert_dialog_api.html">
<span class="badge badge-roundless badge-danger">new</span>Alerts & Dialogs API</a>
</li>
<li>
<a href="ui_session_timeout.html">
Session Timeout</a>
</li>
<li>
<a href="ui_idle_timeout.html">
User Idle Timeout</a>
</li>
<li>
<a href="ui_modals.html">
Modals</a>
</li>
<li>
<a href="ui_extended_modals.html">
Extended Modals</a>
</li>
<li>
<a href="ui_tiles.html">
Tiles</a>
</li>
<li>
<a href="ui_datepaginator.html">
<span class="badge badge-roundless badge-success">new</span>Date Paginator</a>
</li>
<li>
<a href="ui_nestable.html">
Nestable List</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-puzzle"></i>
<span class="title">UI Components</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="components_pickers.html">
Date & Time Pickers</a>
</li>
<li>
<a href="components_context_menu.html">
Context Menu</a>
</li>
<li>
<a href="components_dropdowns.html">
Custom Dropdowns</a>
</li>
<li>
<a href="components_form_tools.html">
Form Widgets & Tools</a>
</li>
<li>
<a href="components_form_tools2.html">
Form Widgets & Tools 2</a>
</li>
<li>
<a href="components_editors.html">
Markdown & WYSIWYG Editors</a>
</li>
<li>
<a href="components_ion_sliders.html">
Ion Range Sliders</a>
</li>
<li>
<a href="components_noui_sliders.html">
NoUI Range Sliders</a>
</li>
<li>
<a href="components_jqueryui_sliders.html">
jQuery UI Sliders</a>
</li>
<li>
<a href="components_knob_dials.html">
Knob Circle Dials</a>
</li>
</ul>
</li>
<!-- BEGIN ANGULARJS LINK -->
<li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo">
<a href="angularjs" target="_blank">
<i class="icon-paper-plane"></i>
<span class="title">
AngularJS Version </span>
</a>
</li>
<!-- END ANGULARJS LINK -->
<li class="heading">
<h3 class="uppercase">Features</h3>
</li>
<li>
<a href="javascript:;">
<i class="icon-settings"></i>
<span class="title">Form Stuff</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="form_controls_md.html">
<span class="badge badge-roundless badge-danger">new</span>Material Design<br>
Form Controls</a>
</li>
<li>
<a href="form_controls.html">
Bootstrap<br>
Form Controls</a>
</li>
<li>
<a href="form_icheck.html">
iCheck Controls</a>
</li>
<li>
<a href="form_layouts.html">
Form Layouts</a>
</li>
<li>
<a href="form_editable.html">
<span class="badge badge-roundless badge-warning">new</span>Form X-editable</a>
</li>
<li>
<a href="form_wizard.html">
Form Wizard</a>
</li>
<li>
<a href="form_validation.html">
Form Validation</a>
</li>
<li>
<a href="form_image_crop.html">
<span class="badge badge-roundless badge-danger">new</span>Image Cropping</a>
</li>
<li>
<a href="form_fileupload.html">
Multiple File Upload</a>
</li>
<li>
<a href="form_dropzone.html">
Dropzone File Upload</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-briefcase"></i>
<span class="title">Data Tables</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="table_basic.html">
Basic Datatables</a>
</li>
<li>
<a href="table_tree.html">
Tree Datatables</a>
</li>
<li>
<a href="table_responsive.html">
Responsive Datatables</a>
</li>
<li>
<a href="table_managed.html">
Managed Datatables</a>
</li>
<li>
<a href="table_editable.html">
Editable Datatables</a>
</li>
<li>
<a href="table_advanced.html">
Advanced Datatables</a>
</li>
<li>
<a href="table_ajax.html">
Ajax Datatables</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-wallet"></i>
<span class="title">Portlets</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="portlet_general.html">
General Portlets</a>
</li>
<li>
<a href="portlet_general2.html">
<span class="badge badge-roundless badge-danger">new</span>New Portlets #1</a>
</li>
<li>
<a href="portlet_general3.html">
<span class="badge badge-roundless badge-danger">new</span>New Portlets #2</a>
</li>
<li>
<a href="portlet_ajax.html">
Ajax Portlets</a>
</li>
<li>
<a href="portlet_draggable.html">
Draggable Portlets</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-bar-chart"></i>
<span class="title">Charts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="charts_amcharts.html">
amChart</a>
</li>
<li>
<a href="charts_flotcharts.html">
Flotchart</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-docs"></i>
<span class="title">Pages</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_timeline.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>New Timeline</a>
</li>
<li>
<a href="extra_profile.html">
<i class="icon-user-following"></i>
<span class="badge badge-success badge-roundless">new</span>New User Profile</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-check"></i>
Todo</a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope"></i>
<span class="badge badge-danger">4</span>Inbox</a>
</li>
<li>
<a href="extra_faq.html">
<i class="icon-question"></i>
FAQ</a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i>
<span class="badge badge-danger">14</span>Calendar</a>
</li>
<li>
<a href="page_coming_soon.html">
<i class="icon-flag"></i>
Coming Soon</a>
</li>
<li>
<a href="page_blog.html">
<i class="icon-speech"></i>
Blog</a>
</li>
<li>
<a href="page_blog_item.html">
<i class="icon-link"></i>
Blog Post</a>
</li>
<li>
<a href="page_news.html">
<i class="icon-eye"></i>
<span class="badge badge-success">9</span>News</a>
</li>
<li>
<a href="page_news_item.html">
<i class="icon-bell"></i>
News View</a>
</li>
<li>
<a href="page_timeline_old.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>Old Timeline</a>
</li>
<li>
<a href="extra_profile_old.html">
<i class="icon-user"></i>
Old User Profile</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-present"></i>
<span class="title">Extra</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_about.html">
About Us</a>
</li>
<li>
<a href="page_contact.html">
Contact Us</a>
</li>
<li>
<a href="extra_search.html">
Search Results</a>
</li>
<li>
<a href="extra_invoice.html">
Invoice</a>
</li>
<li>
<a href="page_portfolio.html">
Portfolio</a>
</li>
<li>
<a href="extra_pricing_table.html">
Pricing Tables</a>
</li>
<li>
<a href="extra_404_option1.html">
404 Page Option 1</a>
</li>
<li>
<a href="extra_404_option2.html">
404 Page Option 2</a>
</li>
<li>
<a href="extra_404_option3.html">
404 Page Option 3</a>
</li>
<li>
<a href="extra_500_option1.html">
500 Page Option 1</a>
</li>
<li>
<a href="extra_500_option2.html">
500 Page Option 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-folder"></i>
<span class="title">Multi Level Menu</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-settings"></i> Item 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-user"></i>
Sample Link 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-power"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-star"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#"><i class="icon-camera"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-link"></i> Sample Link 2</a>
</li>
<li>
<a href="#"><i class="icon-pointer"></i> Sample Link 3</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-globe"></i> Item 2 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-tag"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-pencil"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-graph"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="icon-bar-chart"></i>
Item 3 </a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-user"></i>
<span class="title">Login Options</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
Login Form 1</a>
</li>
<li>
<a href="login_2.html">
Login Form 2</a>
</li>
<li>
<a href="login_3.html">
Login Form 3</a>
</li>
<li>
<a href="login_soft.html">
Login Form 4</a>
</li>
<li>
<a href="extra_lock.html">
Lock Screen 1</a>
</li>
<li>
<a href="extra_lock2.html">
Lock Screen 2</a>
</li>
</ul>
</li>
<li class="heading">
<h3 class="uppercase">More</h3>
</li>
<li>
<a href="javascript:;">
<i class="icon-logout"></i>
<span class="title">Quick Sidebar</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="quick_sidebar_push_content.html">
Push Content</a>
</li>
<li>
<a href="quick_sidebar_over_content.html">
Over Content</a>
</li>
<li>
<a href="quick_sidebar_over_content_transparent.html">
Over Content & Transparent</a>
</li>
<li>
<a href="quick_sidebar_on_boxed_layout.html">
Boxed Layout</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-envelope-open"></i>
<span class="title">Email Templates</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="email_template1.html">
New Email Template 1</a>
</li>
<li>
<a href="email_template2.html">
New Email Template 2</a>
</li>
<li>
<a href="email_template3.html">
New Email Template 3</a>
</li>
<li>
<a href="email_template4.html">
New Email Template 4</a>
</li>
<li>
<a href="email_newsletter.html">
Old Email Template 1</a>
</li>
<li>
<a href="email_system.html">
Old Email Template 2</a>
</li>
</ul>
</li>
<li class="last ">
<a href="javascript:;">
<i class="icon-pointer"></i>
<span class="title">Maps</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="maps_google.html">
Google Maps</a>
</li>
<li>
<a href="maps_vector.html">
Vector Maps</a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Widget settings form goes here
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Save changes</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<!-- BEGIN STYLE CUSTOMIZER -->
<div class="theme-panel hidden-xs hidden-sm">
<div class="toggler">
</div>
<div class="toggler-close">
</div>
<div class="theme-options">
<div class="theme-option theme-colors clearfix">
<span>
THEME COLOR </span>
<ul>
<li class="color-default current tooltips" data-style="default" data-container="body" data-original-title="Default">
</li>
<li class="color-darkblue tooltips" data-style="darkblue" data-container="body" data-original-title="Dark Blue">
</li>
<li class="color-blue tooltips" data-style="blue" data-container="body" data-original-title="Blue">
</li>
<li class="color-grey tooltips" data-style="grey" data-container="body" data-original-title="Grey">
</li>
<li class="color-light tooltips" data-style="light" data-container="body" data-original-title="Light">
</li>
<li class="color-light2 tooltips" data-style="light2" data-container="body" data-html="true" data-original-title="Light 2">
</li>
</ul>
</div>
<div class="theme-option">
<span>
Layout </span>
<select class="layout-option form-control input-sm">
<option value="fluid" selected="selected">Fluid</option>
<option value="boxed">Boxed</option>
</select>
</div>
<div class="theme-option">
<span>
Header </span>
<select class="page-header-option form-control input-sm">
<option value="fixed" selected="selected">Fixed</option>
<option value="default">Default</option>
</select>
</div>
<div class="theme-option">
<span>
Top Menu Dropdown</span>
<select class="page-header-top-dropdown-style-option form-control input-sm">
<option value="light" selected="selected">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Mode</span>
<select class="sidebar-option form-control input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Menu </span>
<select class="sidebar-menu-option form-control input-sm">
<option value="accordion" selected="selected">Accordion</option>
<option value="hover">Hover</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Style </span>
<select class="sidebar-style-option form-control input-sm">
<option value="default" selected="selected">Default</option>
<option value="light">Light</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Position </span>
<select class="sidebar-pos-option form-control input-sm">
<option value="left" selected="selected">Left</option>
<option value="right">Right</option>
</select>
</div>
<div class="theme-option">
<span>
Footer </span>
<select class="page-footer-option form-control input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</div>
</div>
</div>
<!-- END STYLE CUSTOMIZER -->
<!-- BEGIN PAGE HEADER-->
<h3 class="page-title">
Alerts & Dialogs API <small>bootstrap modal dialogs and alerts api</small>
</h3>
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<i class="fa fa-home"></i>
<a href="index.html">Home</a>
<i class="fa fa-angle-right"></i>
</li>
<li>
<a href="#">UI Features</a>
<i class="fa fa-angle-right"></i>
</li>
<li>
<a href="#">Alerts & Dialogs API</a>
</li>
</ul>
<div class="page-toolbar">
<div class="btn-group pull-right">
<button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true">
Actions <i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li>
<a href="#">Action</a>
</li>
<li>
<a href="#">Another action</a>
</li>
<li>
<a href="#">Something else here</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">Separated link</a>
</li>
</ul>
</div>
</div>
</div>
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<div class="row">
<div class="col-md-12">
<div class="note note-success">
<h4 class="block">Bootbox</h4>
<p>
Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Twitter’s Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers. For more info please check out <a href="http://bootboxjs.com/" target="_blank">
the official documentation </a>
.
</p>
</div>
<!-- BEGIN PORTLET-->
<div class="portlet box yellow">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Bootbox Demo
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<table class="table table-hover table-striped table-bordered">
<tr>
<td>
Basic alert example
</td>
<td>
<a class="btn default" id="demo_1">
View Demo </a>
</td>
</tr>
<tr>
<td>
Alert with callback
</td>
<td>
<a class="btn default" id="demo_2">
View Demo </a>
</td>
</tr>
<tr>
<td>
Confirm example
</td>
<td>
<a class="btn default" id="demo_3">
View Demo </a>
</td>
</tr>
<tr>
<td>
Promt example
</td>
<td>
<a class="btn default" id="demo_4">
View Demo </a>
</td>
</tr>
<tr>
<td>
Advance dialog
</td>
<td>
<a class="btn default" id="demo_5">
View Demo </a>
</td>
</tr>
</table>
</div>
</div>
<!-- END PORTLET-->
<!-- BEGIN PORTLET-->
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Metronic's API for Bootstrap Alerts
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<div id="bootstrap_alerts_demo">
</div>
<form class="form-horizontal">
<div class="form-group">
<label class="col-md-3 control-label" for="title">Alert Message:</label>
<div class="col-md-7">
<input id="alert_message" type="text" class="form-control" value="some alert text goes here..." placeholder="enter a text ...">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Alert Type:</label>
<div class="col-md-5">
<select id="alert_type" class="form-control input-medium">
<option value="success">Success</option>
<option value="danger">Danger</option>
<option value="warning">Warning</option>
<option value="info">Info</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Container:</label>
<div class="col-md-5">
<select id="alert_container" class="form-control input-medium">
<option value="">Default(after the breadcrumb)</option>
<option value="#bootstrap_alerts_demo">#bootstrap_alerts_demo</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Placement:</label>
<div class="col-md-5">
<select id="alert_place" class="form-control input-medium">
<option value="append">Append</option>
<option value="prepend">Prepend</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Closable ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_close" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Close All Previouse Alerts ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_reset" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Auto Scroll/Focus ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_focus" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Auto Close In(seconds):</label>
<div class="col-md-5">
<select id="alert_close_in_seconds" class="form-control input-medium">
<option value="0">never close</option>
<option value="1">1 second</option>
<option value="5">5 seconds</option>
<option value="10">10 seconds</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Font Awesome Icon(fa-[*]):</label>
<div class="col-md-5">
<select id="alert_icon" class="form-control input-medium">
<option value="" selected="selected">none</option>
<option value="warning">warning</option>
<option value="check">check</option>
<option value="user">user</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title"></label>
<div class="col-md-5">
<a href="javascript:;" class="btn green btn-lg" id="alert_show">
Show Alert! </a>
</div>
</div>
</form>
</div>
</div>
<!-- END PORTLET-->
</div>
</div>
<!-- END PAGE CONTENT-->
</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler"><i class="icon-close"></i></a>
<div class="page-quick-sidebar-wrapper">
<div class="page-quick-sidebar">
<div class="nav-justified">
<ul class="nav nav-tabs nav-justified">
<li class="active">
<a href="#quick_sidebar_tab_1" data-toggle="tab">
Users <span class="badge badge-danger">2</span>
</a>
</li>
<li>
<a href="#quick_sidebar_tab_2" data-toggle="tab">
Alerts <span class="badge badge-success">7</span>
</a>
</li>
<li class="dropdown">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
More<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li>
<a href="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-bell"></i> Alerts </a>
</li>
<li>
<a href="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-info"></i> Notifications </a>
</li>
<li>
<a href="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-speech"></i> Activities </a>
</li>
<li class="divider">
</li>
<li>
<a href="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-settings"></i> Settings </a>
</li>
</ul>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1">
<div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list">
<h3 class="list-heading">Staff</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-success">8</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar3.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Bob Nilson</h4>
<div class="media-heading-sub">
Project Manager
</div>
</div>
</li>
<li class="media">
<img class="media-object" src="../../assets/admin/layout/img/avatar1.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Nick Larson</h4>
<div class="media-heading-sub">
Art Director
</div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">3</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar4.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Hubert</h4>
<div class="media-heading-sub">
CTO
</div>
</div>
</li>
<li class="media">
<img class="media-object" src="../../assets/admin/layout/img/avatar2.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ella Wong</h4>
<div class="media-heading-sub">
CEO
</div>
</div>
</li>
</ul>
<h3 class="list-heading">Customers</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-warning">2</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar6.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lara Kunis</h4>
<div class="media-heading-sub">
CEO, Loop Inc
</div>
<div class="media-heading-small">
Last seen 03:10 AM
</div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="label label-sm label-success">new</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar7.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ernie Kyllonen</h4>
<div class="media-heading-sub">
Project Manager,<br>
SmartBizz PTL
</div>
</div>
</li>
<li class="media">
<img class="media-object" src="../../assets/admin/layout/img/avatar8.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lisa Stone</h4>
<div class="media-heading-sub">
CTO, Keort Inc
</div>
<div class="media-heading-small">
Last seen 13:10 PM
</div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-success">7</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar9.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Portalatin</h4>
<div class="media-heading-sub">
CFO, H&D LTD
</div>
</div>
</li>
<li class="media">
<img class="media-object" src="../../assets/admin/layout/img/avatar10.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Irina Savikova</h4>
<div class="media-heading-sub">
CEO, Tizda Motors Inc
</div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">4</span>
</div>
<img class="media-object" src="../../assets/admin/layout/img/avatar11.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Maria Gomez</h4>
<div class="media-heading-sub">
Manager, Infomatic Inc
</div>
<div class="media-heading-small">
Last seen 03:10 AM
</div>
</div>
</li>
</ul>
</div>
<div class="page-quick-sidebar-item">
<div class="page-quick-sidebar-chat-user">
<div class="page-quick-sidebar-nav">
<a href="javascript:;" class="page-quick-sidebar-back-to-list"><i class="icon-arrow-left"></i>Back</a>
</div>
<div class="page-quick-sidebar-chat-user-messages">
<div class="post out">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body">
When could you send me the report ? </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:15</span>
<span class="body">
Its almost done. I will be sending it shortly </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body">
Alright. Thanks! :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:16</span>
<span class="body">
You are most welcome. Sorry for the delay. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body">
No probs. Just take your time :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body">
Alright. I just emailed it to you. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body">
Great! Thanks. Will check it right away. </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar2.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body">
Please let me know if you have any comment. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../../assets/admin/layout/img/avatar3.jpg"/>
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body">
Sure. I will check and buzz you if anything needs to be corrected. </span>
</div>
</div>
</div>
<div class="page-quick-sidebar-chat-user-form">
<div class="input-group">
<input type="text" class="form-control" placeholder="Type a message here...">
<div class="input-group-btn">
<button type="button" class="btn blue"><i class="icon-paper-clip"></i></button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2">
<div class="page-quick-sidebar-alerts-list">
<h3 class="list-heading">General</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 4 pending tasks. <span class="label label-sm label-warning ">
Take action <i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
Just now
</div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
Finance Report for year 2013 has been released.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
20 mins
</div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 5 pending membership that requires a quick review.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
24 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
New order received with <span class="label label-sm label-success">
Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
30 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 5 pending membership that requires a quick review.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
24 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
Web server hardware needs to be upgraded. <span class="label label-sm label-warning">
Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
2 hours
</div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
IPO Report for year 2013 has been released.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
20 mins
</div>
</div>
</a>
</li>
</ul>
<h3 class="list-heading">System</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 4 pending tasks. <span class="label label-sm label-warning ">
Take action <i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
Just now
</div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
Finance Report for year 2013 has been released.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
20 mins
</div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 5 pending membership that requires a quick review.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
24 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
New order received with <span class="label label-sm label-success">
Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
30 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
You have 5 pending membership that requires a quick review.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
24 mins
</div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-warning">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
Web server hardware needs to be upgraded. <span class="label label-sm label-default ">
Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
2 hours
</div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc">
IPO Report for year 2013 has been released.
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date">
20 mins
</div>
</div>
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3">
<div class="page-quick-sidebar-settings-list">
<h3 class="list-heading">General Settings</h3>
<ul class="list-items borderless">
<li>
Enable Notifications <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
<li>
Allow Tracking <input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
<li>
Log Errors <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
<li>
Auto Sumbit Issues <input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
<li>
Enable SMS Alerts <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
</ul>
<h3 class="list-heading">System Settings</h3>
<ul class="list-items borderless">
<li>
Security Level
<select class="form-control input-inline input-sm input-small">
<option value="1">Normal</option>
<option value="2" selected>Medium</option>
<option value="e">High</option>
</select>
</li>
<li>
Failed Email Attempts <input class="form-control input-inline input-sm input-small" value="5"/>
</li>
<li>
Secondary SMTP Port <input class="form-control input-inline input-sm input-small" value="3560"/>
</li>
<li>
Notify On System Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
<li>
Notify On SMTP Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF">
</li>
</ul>
<div class="inner-content">
<button class="btn btn-success"><i class="icon-settings"></i> Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="page-footer">
<div class="page-footer-inner">
2014 © Metronic by keenthemes.
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="../../assets/global/plugins/respond.min.js"></script>
<script src="../../assets/global/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="../../assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="../../assets/admin/layout/scripts/layout.js" type="text/javascript"></script>
<script src="../../assets/admin/layout/scripts/quick-sidebar.js" type="text/javascript"></script>
<script src="../../assets/admin/layout/scripts/demo.js" type="text/javascript"></script>
<script src="../../assets/admin/pages/scripts/ui-alert-dialog-api.js"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<script>
jQuery(document).ready(function() {
// initiate layout and plugins
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
QuickSidebar.init(); // init quick sidebar
Demo.init(); // init demo features
UIAlertDialogApi.init();
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html> | {
"content_hash": "ba04893fc069ff73cbc8bb8818a024ce",
"timestamp": "",
"source": "github",
"line_count": 2271,
"max_line_length": 331,
"avg_line_length": 33.11668868339938,
"alnum_prop": 0.5245585576002553,
"repo_name": "zzsoszz/metronicv37",
"id": "b6149827de6806a48ef011a63eb281955d215fdd",
"size": "75210",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "theme_rtl/templates/admin_material_design/ui_alert_dialog_api.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "580"
},
{
"name": "ApacheConf",
"bytes": "932"
},
{
"name": "CSS",
"bytes": "9993928"
},
{
"name": "CoffeeScript",
"bytes": "167262"
},
{
"name": "HTML",
"bytes": "155512809"
},
{
"name": "JavaScript",
"bytes": "12960293"
},
{
"name": "PHP",
"bytes": "599248"
},
{
"name": "Shell",
"bytes": "888"
}
],
"symlink_target": ""
} |
import forSelect from "../utils/for-select";
import h from "../utils/html";
const triggerHeight = 140,
minHeight = 100;
/**
*
* @param {HTMLElement|null} node
* @param {Settings} settings
*/
export default function (node, settings) {
node = node || document.body;
if (!settings.flag("new-lines")) {
forSelect(node, ".p-timeline-post .comment-text, .p-timeline-post .body .text", node => {
if (node.offsetHeight < triggerHeight) return;
var isComment = node.classList.contains("comment-text");
var cnt = null;
if (isComment) {
var d = node.nextSibling, n;
cnt = node.appendChild(h("span.be-fe-comm-controls"));
while (d) {
n = d.nextSibling;
cnt.appendChild(d);
d = n;
}
}
node.classList.add("be-fe-folded-text");
var link = h("a.be-fe-folded-text-read-more-link", "Read more\u2026");
var rm = node.appendChild(h(".be-fe-folded-text-read-more", link));
if (cnt) {
rm.appendChild(cnt.cloneNode(true));
}
link.addEventListener("click", () => node.classList.remove("be-fe-folded-text"));
});
} else {
forSelect(node, ".p-timeline-post .comment-text, .p-timeline-post .body .text", node => {
if (node.offsetHeight < triggerHeight) return;
var isComment = node.classList.contains("comment-text");
var lineHeight = isComment ? 18 : 21;
node.classList.add("be-fe-folded-text-nl");
var clipPara = null;
forSelect(node, ":scope > p", para => {
if (!clipPara && para.offsetTop + para.offsetHeight > triggerHeight) {
clipPara = para;
para.classList.add("be-fe-folded-text-para");
var nLines = Math.floor(para.offsetHeight / lineHeight);
var l;
for (l = 1; l <= nLines; l++) {
if (para.offsetTop + l * lineHeight > minHeight) {
break;
}
}
para.style.height = (l * lineHeight) + "px";
var link = h("a.be-fe-folded-text-read-more-link", "Read more\u2026");
var rm = para.appendChild(h(".be-fe-folded-text-read-more", link));
link.addEventListener("click", () => {
node.classList.remove("be-fe-folded-text-nl");
clipPara.style.height = "auto";
});
var cnt = node.querySelector(".be-fe-comm-controls");
if (cnt) {
rm.appendChild(cnt.cloneNode(true));
}
} else if (clipPara) {
para.classList.add("be-fe-folded-text-hidden");
}
});
});
}
};
| {
"content_hash": "d8788a4992f467d5c92a3f55cc234a2b",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 97,
"avg_line_length": 37.55555555555556,
"alnum_prop": 0.47764628533859305,
"repo_name": "davidmz/BetterFeed",
"id": "2360e2dfbf362346f4b3e5bd3ef2ef443134f29d",
"size": "3042",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/js/actions/fold-texts.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22834"
},
{
"name": "HTML",
"bytes": "18738"
},
{
"name": "JavaScript",
"bytes": "157627"
}
],
"symlink_target": ""
} |
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
//
require_once 'NotificationEnableArrayType.php';
require_once 'NotificationUserDataType.php';
require_once 'AbstractResponseType.php';
require_once 'ApplicationDeliveryPreferencesType.php';
require_once 'NotificationEventPropertyType.php';
/**
* Contains the requesting application's notification
* preferences.GetNotificationPreferences retrieves preferences that you
* havedeliberately set. For example, if you enable the EndOfAuction event andthen
* later disable it, the response shows the EndOfAuction eventpreference as
* Disabled. But if you have never set a preference for theEndOfAuction event, no
* EndOfAuction preference is returned at all.
*
* @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/GetNotificationPreferencesResponseType.html
*
*/
class GetNotificationPreferencesResponseType extends AbstractResponseType
{
/**
* @var ApplicationDeliveryPreferencesType
*/
protected $ApplicationDeliveryPreferences;
/**
* @var string
*/
protected $DeliveryURLName;
/**
* @var NotificationEnableArrayType
*/
protected $UserDeliveryPreferenceArray;
/**
* @var NotificationUserDataType
*/
protected $UserData;
/**
* @var NotificationEventPropertyType
*/
protected $EventProperty;
/**
* @return ApplicationDeliveryPreferencesType
*/
function getApplicationDeliveryPreferences()
{
return $this->ApplicationDeliveryPreferences;
}
/**
* @return void
* @param ApplicationDeliveryPreferencesType $value
*/
function setApplicationDeliveryPreferences($value)
{
$this->ApplicationDeliveryPreferences = $value;
}
/**
* @return string
*/
function getDeliveryURLName()
{
return $this->DeliveryURLName;
}
/**
* @return void
* @param string $value
*/
function setDeliveryURLName($value)
{
$this->DeliveryURLName = $value;
}
/**
* @return NotificationEnableArrayType
*/
function getUserDeliveryPreferenceArray()
{
return $this->UserDeliveryPreferenceArray;
}
/**
* @return void
* @param NotificationEnableArrayType $value
*/
function setUserDeliveryPreferenceArray($value)
{
$this->UserDeliveryPreferenceArray = $value;
}
/**
* @return NotificationUserDataType
*/
function getUserData()
{
return $this->UserData;
}
/**
* @return void
* @param NotificationUserDataType $value
*/
function setUserData($value)
{
$this->UserData = $value;
}
/**
* @return NotificationEventPropertyType
* @param integer $index
*/
function getEventProperty($index = null)
{
if ($index !== null) {
return $this->EventProperty[$index];
} else {
return $this->EventProperty;
}
}
/**
* @return void
* @param NotificationEventPropertyType $value
* @param $index
*/
function setEventProperty($value, $index = null)
{
if ($index !== null) {
$this->EventProperty[$index] = $value;
} else {
$this->EventProperty = $value;
}
}
/**
* @return void
* @param NotificationEventPropertyType $value
*/
function addEventProperty($value)
{
$this->EventProperty[] = $value;
}
/**
* @return
*/
function __construct()
{
parent::__construct('GetNotificationPreferencesResponseType', 'urn:ebay:apis:eBLBaseComponents');
if (!isset(self::$_elements[__CLASS__]))
self::$_elements[__CLASS__] = array_merge(self::$_elements[get_parent_class()],
array(
'ApplicationDeliveryPreferences' =>
array(
'required' => false,
'type' => 'ApplicationDeliveryPreferencesType',
'nsURI' => 'urn:ebay:apis:eBLBaseComponents',
'array' => false,
'cardinality' => '0..1'
),
'DeliveryURLName' =>
array(
'required' => false,
'type' => 'string',
'nsURI' => 'http://www.w3.org/2001/XMLSchema',
'array' => false,
'cardinality' => '0..1'
),
'UserDeliveryPreferenceArray' =>
array(
'required' => false,
'type' => 'NotificationEnableArrayType',
'nsURI' => 'urn:ebay:apis:eBLBaseComponents',
'array' => false,
'cardinality' => '0..1'
),
'UserData' =>
array(
'required' => false,
'type' => 'NotificationUserDataType',
'nsURI' => 'urn:ebay:apis:eBLBaseComponents',
'array' => false,
'cardinality' => '0..1'
),
'EventProperty' =>
array(
'required' => false,
'type' => 'NotificationEventPropertyType',
'nsURI' => 'urn:ebay:apis:eBLBaseComponents',
'array' => true,
'cardinality' => '0..*'
)
));
}
}
?>
| {
"content_hash": "e9922c59cb41c709e32096c57d462d68",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 116,
"avg_line_length": 23.713541666666668,
"alnum_prop": 0.6604436635185592,
"repo_name": "Kern-River-Corp/accelerator",
"id": "3dbec9bf9c9f498409e8e5d174c7526eaa257c91",
"size": "4553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GetNotificationPreferencesResponseType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "3764481"
}
],
"symlink_target": ""
} |
if (global.GENTLY) require = GENTLY.hijack(require);
var util = require('util'),
WriteStream = require('fs').WriteStream,
EventEmitter = require('events').EventEmitter,
crypto = require('crypto');
function File(properties) {
EventEmitter.call(this);
this.size = 0;
this.path = null;
this.name = null;
this.type = null;
this.hash = null;
this.lastModifiedDate = null;
this._writeStream = null;
for (var key in properties) {
this[key] = properties[key];
}
if(typeof this.hash === 'string') {
this.hash = crypto.createHash(properties.hash);
}
}
module.exports = File;
util.inherits(File, EventEmitter);
File.prototype.open = function() {
this._writeStream = new WriteStream(this.path);
};
File.prototype.toJSON = function() {
return {
size: this.size,
path: this.path,
name: this.name,
type: this.type,
mtime: this.lastModifiedDate,
length: this.length,
filename: this.filename,
mime: this.mime
};
};
File.prototype.write = function(buffer, cb) {
var self = this;
this._writeStream.write(buffer, function() {
if(self.hash) {
self.hash.update(buffer);
}
self.lastModifiedDate = new Date();
self.size += buffer.length;
self.emit('progress', self.size);
cb();
});
};
File.prototype.end = function(cb) {
var self = this;
this._writeStream.end(function() {
if(self.hash) {
self.hash = self.hash.digest('hex');
}
self.emit('end');
cb();
});
};
| {
"content_hash": "4f4d2fde2e3522277d7cbd6171002da9",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 52,
"avg_line_length": 21.32857142857143,
"alnum_prop": 0.6309444072337576,
"repo_name": "deanhunt/pantheon",
"id": "b214e6cc3cc75f84a9b22beaccd05a7f36974d7f",
"size": "1493",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16950"
},
{
"name": "JavaScript",
"bytes": "14839"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title>CURLOPT_IOCTLFUNCTION man page</title>
<meta name="generator" content="roffit">
<STYLE type="text/css">
pre {
overflow: auto;
margin: 0;
}
P.level0, pre.level0 {
padding-left: 2em;
}
P.level1, pre.level1 {
padding-left: 4em;
}
P.level2, pre.level2 {
padding-left: 6em;
}
span.emphasis {
font-style: italic;
}
span.bold {
font-weight: bold;
}
span.manpage {
font-weight: bold;
}
h2.nroffsh {
background-color: #e0e0e0;
}
span.nroffip {
font-weight: bold;
font-size: 120%;
font-family: monospace;
}
p.roffit {
text-align: center;
font-size: 80%;
}
</STYLE>
</head><body>
<p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2>
<p class="level0">CURLOPT_IOCTLFUNCTION - callback for I/O operations <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2>
<p class="level0"><pre class="level0">
#include <curl/curl.h>
typedef enum {
CURLIOE_OK, /* I/O operation successful */
CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
CURLIOE_FAILRESTART, /* failed to restart the read */
CURLIOE_LAST /* never use */
} curlioerr;
typedef enum {
CURLIOCMD_NOP, /* no operation */
CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
CURLIOCMD_LAST /* never use */
} curliocmd;
curlioerr ioctl_callback(CURL *handle, int cmd, void *clientp);
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_IOCTLFUNCTION, ioctl_callback);
</pre>
<a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2>
<p class="level0">Pass a pointer to your callback function, which should match the prototype shown above.
<p class="level0">This callback function gets called by libcurl when something special I/O-related needs to be done that the library can't do by itself. For now, rewinding the read data stream is the only action it can request. The rewinding of the read data stream may be necessary when doing a HTTP PUT or POST with a multi-pass authentication method.
<p class="level0">The callback MUST return <span Class="emphasis">CURLIOE_UNKNOWNCMD</span> if the input <span Class="emphasis">cmd</span> is not <span Class="emphasis">CURLIOCMD_RESTARTREAD</span>.
<p class="level0">The <span Class="emphasis">clientp</span> argument to the callback is set with the <a Class="emphasis" href="./CURLOPT_IOCTLDATA.html">CURLOPT_IOCTLDATA</a> option.
<p class="level0">This option is deprecated! Do not use it. Use <a Class="emphasis" href="./CURLOPT_SEEKFUNCTION.html">CURLOPT_SEEKFUNCTION</a> instead to provide seeking! If <a Class="emphasis" href="./CURLOPT_SEEKFUNCTION.html">CURLOPT_SEEKFUNCTION</a> is set, this parameter will be ignored when seeking. <a name="DEFAULT"></a><h2 class="nroffsh">DEFAULT</h2>
<p class="level0">By default, this parameter is set to NULL. Not used. <a name="PROTOCOLS"></a><h2 class="nroffsh">PROTOCOLS</h2>
<p class="level0">Used with HTTP <a name="EXAMPLE"></a><h2 class="nroffsh">EXAMPLE</h2>
<p class="level0">TODO <a name="AVAILABILITY"></a><h2 class="nroffsh">AVAILABILITY</h2>
<p class="level0">Added in 7.12.3 <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2>
<p class="level0">Returns CURLE_OK if the option is supported, and CURLE_UNKNOWN_OPTION if not. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2>
<p class="level0"><a Class="manpage" href="./CURLOPT_IOCTLDATA.html">CURLOPT_IOCTLDATA</a>, <a Class="manpage" href="./CURLOPT_SEEKFUNCTION.html">CURLOPT_SEEKFUNCTION</a><p class="roffit">
This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>.
</body></html>
| {
"content_hash": "8277f226274a87cf9b04865f188baf65",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 362,
"avg_line_length": 42.48863636363637,
"alnum_prop": 0.7090131051083177,
"repo_name": "phr34k/serpent",
"id": "94725dd75d27d5bdb2c9080e8d73741156e5a851",
"size": "3739",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "thirdparty/curl/docs/libcurl/opts/CURLOPT_IOCTLFUNCTION.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "503"
},
{
"name": "C++",
"bytes": "69304"
},
{
"name": "Makefile",
"bytes": "1096"
},
{
"name": "Python",
"bytes": "25175"
}
],
"symlink_target": ""
} |
<?php
/**
* ModelCommand generates a model class.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$
* @package system.cli.commands.shell
* @since 1.0
*/
class ModelCommand extends CConsoleCommand
{
/**
* @var string the directory that contains templates for the model command.
* Defaults to null, meaning using 'framework/cli/views/shell/model'.
* If you set this path and some views are missing in the directory,
* the default views will be used.
*/
public $templatePath;
/**
* @var string the directory that contains test fixtures.
* Defaults to null, meaning using 'protected/tests/fixtures'.
* If this is false, it means fixture file should NOT be generated.
*/
public $fixturePath;
/**
* @var string the directory that contains unit test classes.
* Defaults to null, meaning using 'protected/tests/unit'.
* If this is false, it means unit test file should NOT be generated.
*/
public $unitTestPath;
private $_schema;
private $_relations; // where we keep table relations
private $_tables;
private $_classes;
public function getHelp()
{
return <<<EOD
USAGE
model <class-name> [table-name]
DESCRIPTION
This command generates a model class with the specified class name.
PARAMETERS
* class-name: required, model class name. By default, the generated
model class file will be placed under the directory aliased as
'application.models'. To override this default, specify the class
name in terms of a path alias, e.g., 'application.somewhere.ClassName'.
If the model class belongs to a module, it should be specified
as 'ModuleID.models.ClassName'.
If the class name ends with '*', then a model class will be generated
for EVERY table in the database.
If the class name contains a regular expression deliminated by slashes,
then a model class will be generated for those tables whose name
matches the regular expression. If the regular expression contains
sub-patterns, the first sub-pattern will be used to generate the model
class name.
* table-name: optional, the associated database table name. If not given,
it is assumed to be the model class name.
Note, when the class name ends with '*', this parameter will be
ignored.
EXAMPLES
* Generates the Post model:
model Post
* Generates the Post model which is associated with table 'posts':
model Post posts
* Generates the Post model which should belong to module 'admin':
model admin.models.Post
* Generates a model class for every table in the current database:
model *
* Same as above, but the model class files should be generated
under 'protected/models2':
model application.models2.*
* Generates a model class for every table whose name is prefixed
with 'tbl_' in the current database. The model class will not
contain the table prefix.
model /^tbl_(.*)$/
* Same as above, but the model class files should be generated
under 'protected/models2':
model application.models2./^tbl_(.*)$/
EOD;
}
/**
* Checks if the given table is a "many to many" helper table.
* Their PK has 2 fields, and both of those fields are also FK to other separate tables.
* @param CDbTableSchema table to inspect
* @return boolean true if table matches description of helpter table.
*/
protected function isRelationTable($table)
{
$pk=$table->primaryKey;
return (count($pk) === 2 // we want 2 columns
&& isset($table->foreignKeys[$pk[0]]) // pk column 1 is also a foreign key
&& isset($table->foreignKeys[$pk[1]]) // pk column 2 is also a foriegn key
&& $table->foreignKeys[$pk[0]][0] !== $table->foreignKeys[$pk[1]][0]); // and the foreign keys point different tables
}
/**
* Generate code to put in ActiveRecord class's relations() function.
* @return array indexed by table names, each entry contains array of php code to go in appropriate ActiveRecord class.
* Empty array is returned if database couldn't be connected.
*/
protected function generateRelations()
{
$this->_relations=array();
$this->_classes=array();
foreach($this->_schema->getTables() as $table)
{
$tableName=$table->name;
if ($this->isRelationTable($table))
{
$pks=$table->primaryKey;
$fks=$table->foreignKeys;
$table0=$fks[$pks[1]][0];
$table1=$fks[$pks[0]][0];
$className0=$this->getClassName($table0);
$className1=$this->getClassName($table1);
$unprefixedTableName=$this->removePrefix($tableName,true);
$relationName=$this->generateRelationName($table0, $table1, true);
$this->_relations[$className0][$relationName]="array(self::MANY_MANY, '$className1', '$unprefixedTableName($pks[0], $pks[1])')";
$relationName=$this->generateRelationName($table1, $table0, true);
$this->_relations[$className1][$relationName]="array(self::MANY_MANY, '$className0', '$unprefixedTableName($pks[0], $pks[1])')";
}
else
{
$this->_classes[$tableName]=$className=$this->getClassName($tableName);
foreach ($table->foreignKeys as $fkName => $fkEntry)
{
// Put table and key name in variables for easier reading
$refTable=$fkEntry[0]; // Table name that current fk references to
$refKey=$fkEntry[1]; // Key in that table being referenced
$refClassName=$this->getClassName($refTable);
// Add relation for this table
$relationName=$this->generateRelationName($tableName, $fkName, false);
$this->_relations[$className][$relationName]="array(self::BELONGS_TO, '$refClassName', '$fkName')";
// Add relation for the referenced table
$relationType=$table->primaryKey === $fkName ? 'HAS_ONE' : 'HAS_MANY';
$relationName=$this->generateRelationName($refTable, $this->removePrefix($tableName), $relationType==='HAS_MANY');
$this->_relations[$refClassName][$relationName]="array(self::$relationType, '$className', '$fkName')";
}
}
}
}
protected function getClassName($tableName)
{
return isset($this->_tables[$tableName]) ? $this->_tables[$tableName] : $this->generateClassName($tableName);
}
/**
* Generates model class name based on a table name
* @param string the table name
* @return string the generated model class name
*/
protected function generateClassName($tableName)
{
return str_replace(' ','',
ucwords(
trim(
strtolower(
str_replace(array('-','_'),' ',
preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $tableName))))));
}
/**
* Generates the mapping table between table names and class names.
* @param CDbSchema the database schema
* @param string a regular expression that may be used to filter table names
*/
protected function generateClassNames($schema,$pattern=null)
{
$this->_tables=array();
foreach($schema->getTableNames() as $name)
{
if($pattern===null)
$this->_tables[$name]=$this->generateClassName($this->removePrefix($name));
else if(preg_match($pattern,$name,$matches))
{
if(count($matches)>1 && !empty($matches[1]))
$className=$this->generateClassName($matches[1]);
else
$className=$this->generateClassName($matches[0]);
$this->_tables[$name]=empty($className) ? $name : $className;
}
}
}
/**
* Generate a name for use as a relation name (inside relations() function in a model).
* @param string the name of the table to hold the relation
* @param string the foreign key name
* @param boolean whether the relation would contain multiple objects
*/
protected function generateRelationName($tableName, $fkName, $multiple)
{
if(strcasecmp(substr($fkName,-2),'id')===0 && strcasecmp($fkName,'id'))
$relationName=rtrim(substr($fkName, 0, -2),'_');
else
$relationName=$fkName;
$relationName[0]=strtolower($relationName);
$rawName=$relationName;
if($multiple)
$relationName=$this->pluralize($relationName);
$table=$this->_schema->getTable($tableName);
$i=0;
while(isset($table->columns[$relationName]))
$relationName=$rawName.($i++);
return $relationName;
}
/**
* Execute the action.
* @param array command line parameters specific for this command
*/
public function run($args)
{
if(!isset($args[0]))
{
echo "Error: model class name is required.\n";
echo $this->getHelp();
return;
}
$className=$args[0];
if(($db=Yii::app()->getDb())===null)
{
echo "Error: an active 'db' connection is required.\n";
echo "If you already added 'db' component in application configuration,\n";
echo "please quit and re-enter the yiic shell.\n";
return;
}
$db->active=true;
$this->_schema=$db->schema;
if(!preg_match('/^[\w\.\-\*]*(.*?)$/',$className,$matches))
{
echo "Error: model class name is invalid.\n";
return;
}
if(empty($matches[1])) // without regular expression
{
$this->generateClassNames($this->_schema);
if(($pos=strrpos($className,'.'))===false)
$basePath=Yii::getPathOfAlias('application.models');
else
{
$basePath=Yii::getPathOfAlias(substr($className,0,$pos));
$className=substr($className,$pos+1);
}
if($className==='*') // generate all models
$this->generateRelations();
else
{
$tableName=isset($args[1])?$args[1]:$className;
$tableName=$this->addPrefix($tableName);
$this->_tables[$tableName]=$className;
$this->generateRelations();
$this->_classes=array($tableName=>$className);
}
}
else // with regular expression
{
$pattern=$matches[1];
$pos=strrpos($className,$pattern);
if($pos>0) // only regexp is given
$basePath=Yii::getPathOfAlias(rtrim(substr($className,0,$pos),'.'));
else
$basePath=Yii::getPathOfAlias('application.models');
$this->generateClassNames($this->_schema,$pattern);
$classes=$this->_tables;
$this->generateRelations();
$this->_classes=$classes;
}
if(count($this->_classes)>1)
{
$entries=array();
$count=0;
foreach($this->_classes as $tableName=>$className)
$entries[]=++$count.". $className ($tableName)";
echo "The following model classes (tables) match your criteria:\n";
echo implode("\n",$entries);
echo "\n\nDo you want to generate the above classes? [Yes|No] ";
if(strncasecmp(trim(fgets(STDIN)),'y',1))
return;
}
$templatePath=$this->templatePath===null?YII_PATH.'/cli/views/shell/model':$this->templatePath;
$fixturePath=$this->fixturePath===null?Yii::getPathOfAlias('application.tests.fixtures'):$this->fixturePath;
$unitTestPath=$this->unitTestPath===null?Yii::getPathOfAlias('application.tests.unit'):$this->unitTestPath;
$list=array();
$files=array();
foreach ($this->_classes as $tableName=>$className)
{
$files[$className]=$classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
$list['models/'.$className.'.php']=array(
'source'=>$templatePath.DIRECTORY_SEPARATOR.'model.php',
'target'=>$classFile,
'callback'=>array($this,'generateModel'),
'params'=>array($className,$tableName),
);
if($fixturePath!==false)
{
$list['fixtures/'.$tableName.'.php']=array(
'source'=>$templatePath.DIRECTORY_SEPARATOR.'fixture.php',
'target'=>$fixturePath.DIRECTORY_SEPARATOR.$tableName.'.php',
'callback'=>array($this,'generateFixture'),
'params'=>$this->_schema->getTable($tableName),
);
}
if($unitTestPath!==false)
{
$fixtureName=$this->pluralize($className);
$fixtureName[0]=strtolower($fixtureName);
$list['unit/'.$className.'Test.php']=array(
'source'=>$templatePath.DIRECTORY_SEPARATOR.'test.php',
'target'=>$unitTestPath.DIRECTORY_SEPARATOR.$className.'Test.php',
'callback'=>array($this,'generateTest'),
'params'=>array($className,$fixtureName),
);
}
}
$this->copyFiles($list);
foreach($files as $className=>$file)
{
if(!class_exists($className,false))
include_once($file);
}
$classes=implode(", ", $this->_classes);
echo <<<EOD
The following model classes are successfully generated:
$classes
If you have a 'db' database connection, you can test these models now with:
\$model={$className}::model()->find();
print_r(\$model);
EOD;
}
public function generateModel($source,$params)
{
list($className,$tableName)=$params;
$rules=array();
$labels=array();
$relations=array();
if(($table=$this->_schema->getTable($tableName))!==null)
{
$required=array();
$integers=array();
$numerical=array();
$length=array();
$safe=array();
foreach($table->columns as $column)
{
$label=ucwords(trim(strtolower(str_replace(array('-','_'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $column->name)))));
$label=preg_replace('/\s+/',' ',$label);
if(strcasecmp(substr($label,-3),' id')===0)
$label=substr($label,0,-3);
$labels[$column->name]=$label;
if($column->isPrimaryKey && $table->sequenceName!==null)
continue;
$r=!$column->allowNull && $column->defaultValue===null;
if($r)
$required[]=$column->name;
if($column->type==='integer')
$integers[]=$column->name;
else if($column->type==='double')
$numerical[]=$column->name;
else if($column->type==='string' && $column->size>0)
$length[$column->size][]=$column->name;
else if(!$column->isPrimaryKey && !$r)
$safe[]=$column->name;
}
if($required!==array())
$rules[]="array('".implode(', ',$required)."', 'required')";
if($integers!==array())
$rules[]="array('".implode(', ',$integers)."', 'numerical', 'integerOnly'=>true)";
if($numerical!==array())
$rules[]="array('".implode(', ',$numerical)."', 'numerical')";
if($length!==array())
{
foreach($length as $len=>$cols)
$rules[]="array('".implode(', ',$cols)."', 'length', 'max'=>$len)";
}
if($safe!==array())
$rules[]="array('".implode(', ',$safe)."', 'safe')";
if(isset($this->_relations[$className]) && is_array($this->_relations[$className]))
$relations=$this->_relations[$className];
}
else
echo "Warning: the table '$tableName' does not exist in the database.\n";
if(!is_file($source)) // fall back to default ones
$source=YII_PATH.'/cli/views/shell/model/'.basename($source);
return $this->renderFile($source,array(
'className'=>$className,
'tableName'=>$this->removePrefix($tableName,true),
'columns'=>isset($table) ? $table->columns : array(),
'rules'=>$rules,
'labels'=>$labels,
'relations'=>$relations,
),true);
}
public function generateFixture($source,$table)
{
if(!is_file($source)) // fall back to default ones
$source=YII_PATH.'/cli/views/shell/model/'.basename($source);
return $this->renderFile($source, array(
'table'=>$table,
),true);
}
public function generateTest($source,$params)
{
list($className,$fixtureName)=$params;
if(!is_file($source)) // fall back to default ones
$source=YII_PATH.'/cli/views/shell/model/'.basename($source);
return $this->renderFile($source, array(
'className'=>$className,
'fixtureName'=>$fixtureName,
),true);
}
protected function removePrefix($tableName,$addBrackets=false)
{
$tablePrefix=Yii::app()->getDb()->tablePrefix;
if($tablePrefix!='' && !strncmp($tableName,$tablePrefix,strlen($tablePrefix)))
{
$tableName=substr($tableName,strlen($tablePrefix));
if($addBrackets)
$tableName='{{'.$tableName.'}}';
}
return $tableName;
}
protected function addPrefix($tableName)
{
$tablePrefix=Yii::app()->getDb()->tablePrefix;
if($tablePrefix!='' && strncmp($tableName,$tablePrefix,strlen($tablePrefix)))
$tableName=$tablePrefix.$tableName;
return $tableName;
}
} | {
"content_hash": "6bae3139a6c5f6e7130f7a767fcba6b4",
"timestamp": "",
"source": "github",
"line_count": 481,
"max_line_length": 132,
"avg_line_length": 32.25779625779626,
"alnum_prop": 0.6602861562258314,
"repo_name": "dwoodard/yii",
"id": "f9fa40376249270a11bac1ba4cf97671e7a76a4f",
"size": "15759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/cli/commands/shell/ModelCommand.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
layout: post
title: What I want from a computer
---
A loose collection of (very IMHO) ideas what a computer system built for
productivity should be like, everything goes, but nothing too crazy.
### Operating System
The OS itself is reduced to a minimal hardware abstraction layer:
- input
- audio
- filesystem
- networking
- 3D rendering API
- (and probably one or two essential things I forgot)
The OS APIs are exposed as C headers, because C is the lingua franca that all
other languages can talk to. That doesn't mean that the OS itself
has to be written in C.
There's only a simple window composer which can compose rectangles rendered
through the 3D API.
There is no UI framework built into the OS, applications
select their own 3rd-party UI framework (may the best win). Having
no standard UI framework sounds messy, but it is already a reality for
cross-platform apps, which are usually written with Qt or Electron.
Above this basic hardware abstraction layer there's a fork in the road,
one side leads to the dark side, a 'walled garden consumption OS', the
other side to an 'open productivity & creativity OS'. It doesn't make
any sense trying to combine the two ideologies, it only ends in pain
and suffering for everyone, as Windows 8 has shown.
This is about the creativity/productivity fork:
### Software Installation
A 'friendly' command line package manager like brew, coupled with a very
simple configuration system which allows me to automate system setup (what
software to install, config files, etc...).
Basically the opposite of Windows's sloppy installation system or the
Mac's restrictive App Shop.
The idea is that I want the entire configuration of my machine in a setup script
under version control. Resetting the machine to a clean slate, or setting up
an entirely new machine should not require any manual work.
### Filesystem
Instead of a rigid directory hierarchy I want to add custom attributes to
files (tags and key/value pairs). Some sort of hierarchical tags could be
used to simulate traditional directory hierarchies. The 'filename' is also
just a tag. File management tools and command line shells have realtime
fuzzy-search by file attributes (much like the incremental fuzzy search in
modern text editors works), while at it, drop the whole 'desktop metaphor'
bullshit once and for all.
There are no silly icons (except maybe for apps), only the
*file content* and tags are important.
I'm not sure about an integrated version control system, on one hand
it might make sense, on the other hand there is no consensus what a
good VCS looks like. So better to let the user decide.
### User Interaction
I want 'friendly, explorable, text-driven' interaction. I want to
start typing anywhere, anytime, and the system or current app should offer me
options through fuzzy-search (of apps to start, files to work on,
commands to execute and so on).
I want to easily navigate previous actions (through an ever-present context-
sensitive history), and possible next actions (through the fuzzy matching).
Look at the fish shell and Sublime Text's command palette for examples
how this would work.
Being mainly text-driven doesn't mean there can't be typical mouse- or
touch-driven apps like 3D-modelling or 2D-drawing tools.
### Scriptable UI Apps
All UI apps worth their salt should also offer a language-agnostic scripting
interface for automation tasks, similar to what the Amiga started
with AREXX scripting.
### Conclusion
> Netscape will soon reduce Windows to a poorly debugged set of device drivers
>
> *(Marc Andreessen, 1995)*
That's exactly what *all* operating systems should be IMHO, except for the
'poorly debugged' part of course :D
| {
"content_hash": "e47140fb3f17d68fa8714d190ed4cb9b",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 80,
"avg_line_length": 38.21649484536083,
"alnum_prop": 0.7836525492311842,
"repo_name": "floooh/floooh.github.io",
"id": "cf31f5ec6eff9306f2172deec73faac78315c3c0",
"size": "3711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2017-07-12-dream-computer.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "951218"
},
{
"name": "SCSS",
"bytes": "11448"
}
],
"symlink_target": ""
} |
class CWeaponWalther :
public CWeaponPistol
{
typedef CWeaponPistol inherited;
public:
CWeaponWalther(void);
virtual ~CWeaponWalther(void);
DECLARE_SCRIPT_REGISTER_FUNCTION
};
add_to_type_list(CWeaponWalther)
#undef script_type_list
#define script_type_list save_type_list(CWeaponWalther)
| {
"content_hash": "374c2592cb2a6e280055045733946f47",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 55,
"avg_line_length": 22.692307692307693,
"alnum_prop": 0.8033898305084746,
"repo_name": "OLR-xray/OLR-3.0",
"id": "032aa5c2fc40f59e7750a646ab9281488486ba35",
"size": "369",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/xray/xr_3da/xrGame/WeaponWalther.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "24445"
},
{
"name": "Batchfile",
"bytes": "25756"
},
{
"name": "C",
"bytes": "24938895"
},
{
"name": "C++",
"bytes": "47400139"
},
{
"name": "CMake",
"bytes": "6042"
},
{
"name": "Cuda",
"bytes": "36172"
},
{
"name": "Groff",
"bytes": "287360"
},
{
"name": "HTML",
"bytes": "67830"
},
{
"name": "MAXScript",
"bytes": "975"
},
{
"name": "Makefile",
"bytes": "16965"
},
{
"name": "Objective-C",
"bytes": "181404"
},
{
"name": "Pascal",
"bytes": "2978785"
},
{
"name": "Perl",
"bytes": "13337"
},
{
"name": "PostScript",
"bytes": "10774"
},
{
"name": "Python",
"bytes": "5517"
},
{
"name": "Shell",
"bytes": "956624"
},
{
"name": "TeX",
"bytes": "762124"
},
{
"name": "xBase",
"bytes": "151778"
}
],
"symlink_target": ""
} |
package org.apache.lucene.index;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.lucene.index.DocValuesUpdate.BinaryDocValuesUpdate;
import org.apache.lucene.index.DocValuesUpdate.NumericDocValuesUpdate;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.BytesRef;
/**
* {@link DocumentsWriterDeleteQueue} is a non-blocking linked pending deletes
* queue. In contrast to other queue implementation we only maintain the
* tail of the queue. A delete queue is always used in a context of a set of
* DWPTs and a global delete pool. Each of the DWPT and the global pool need to
* maintain their 'own' head of the queue (as a DeleteSlice instance per DWPT).
* The difference between the DWPT and the global pool is that the DWPT starts
* maintaining a head once it has added its first document since for its segments
* private deletes only the deletes after that document are relevant. The global
* pool instead starts maintaining the head once this instance is created by
* taking the sentinel instance as its initial head.
* <p>
* Since each {@link DeleteSlice} maintains its own head and the list is only
* single linked the garbage collector takes care of pruning the list for us.
* All nodes in the list that are still relevant should be either directly or
* indirectly referenced by one of the DWPT's private {@link DeleteSlice} or by
* the global {@link BufferedUpdates} slice.
* <p>
* Each DWPT as well as the global delete pool maintain their private
* DeleteSlice instance. In the DWPT case updating a slice is equivalent to
* atomically finishing the document. The slice update guarantees a "happens
* before" relationship to all other updates in the same indexing session. When a
* DWPT updates a document it:
*
* <ol>
* <li>consumes a document and finishes its processing</li>
* <li>updates its private {@link DeleteSlice} either by calling
* {@link #updateSlice(DeleteSlice)} or {@link #add(Term, DeleteSlice)} (if the
* document has a delTerm)</li>
* <li>applies all deletes in the slice to its private {@link BufferedUpdates}
* and resets it</li>
* <li>increments its internal document id</li>
* </ol>
*
* The DWPT also doesn't apply its current documents delete term until it has
* updated its delete slice which ensures the consistency of the update. If the
* update fails before the DeleteSlice could have been updated the deleteTerm
* will also not be added to its private deletes neither to the global deletes.
*
*/
final class DocumentsWriterDeleteQueue implements Accountable {
private volatile Node<?> tail;
@SuppressWarnings("rawtypes")
private static final AtomicReferenceFieldUpdater<DocumentsWriterDeleteQueue,Node> tailUpdater = AtomicReferenceFieldUpdater
.newUpdater(DocumentsWriterDeleteQueue.class, Node.class, "tail");
private final DeleteSlice globalSlice;
private final BufferedUpdates globalBufferedUpdates;
/* only acquired to update the global deletes */
private final ReentrantLock globalBufferLock = new ReentrantLock();
final long generation;
DocumentsWriterDeleteQueue() {
this(0);
}
DocumentsWriterDeleteQueue(long generation) {
this(new BufferedUpdates(), generation);
}
DocumentsWriterDeleteQueue(BufferedUpdates globalBufferedUpdates, long generation) {
this.globalBufferedUpdates = globalBufferedUpdates;
this.generation = generation;
/*
* we use a sentinel instance as our initial tail. No slice will ever try to
* apply this tail since the head is always omitted.
*/
tail = new Node<>(null); // sentinel
globalSlice = new DeleteSlice(tail);
}
void addDelete(Query... queries) {
add(new QueryArrayNode(queries));
tryApplyGlobalSlice();
}
void addDelete(Term... terms) {
add(new TermArrayNode(terms));
tryApplyGlobalSlice();
}
void addDocValuesUpdates(DocValuesUpdate... updates) {
add(new DocValuesUpdatesNode(updates));
tryApplyGlobalSlice();
}
/**
* invariant for document update
*/
void add(Term term, DeleteSlice slice) {
final TermNode termNode = new TermNode(term);
// System.out.println(Thread.currentThread().getName() + ": push " + termNode + " this=" + this);
add(termNode);
/*
* this is an update request where the term is the updated documents
* delTerm. in that case we need to guarantee that this insert is atomic
* with regards to the given delete slice. This means if two threads try to
* update the same document with in turn the same delTerm one of them must
* win. By taking the node we have created for our del term as the new tail
* it is guaranteed that if another thread adds the same right after us we
* will apply this delete next time we update our slice and one of the two
* competing updates wins!
*/
slice.sliceTail = termNode;
assert slice.sliceHead != slice.sliceTail : "slice head and tail must differ after add";
tryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe
// we can do it just every n times or so?
}
void add(Node<?> item) {
/*
* this non-blocking / 'wait-free' linked list add was inspired by Apache
* Harmony's ConcurrentLinkedQueue Implementation.
*/
while (true) {
final Node<?> currentTail = this.tail;
final Node<?> tailNext = currentTail.next;
if (tail == currentTail) {
if (tailNext != null) {
/*
* we are in intermediate state here. the tails next pointer has been
* advanced but the tail itself might not be updated yet. help to
* advance the tail and try again updating it.
*/
tailUpdater.compareAndSet(this, currentTail, tailNext); // can fail
} else {
/*
* we are in quiescent state and can try to insert the item to the
* current tail if we fail to insert we just retry the operation since
* somebody else has already added its item
*/
if (currentTail.casNext(null, item)) {
/*
* now that we are done we need to advance the tail while another
* thread could have advanced it already so we can ignore the return
* type of this CAS call
*/
tailUpdater.compareAndSet(this, currentTail, item);
return;
}
}
}
}
}
boolean anyChanges() {
globalBufferLock.lock();
try {
/*
* check if all items in the global slice were applied
* and if the global slice is up-to-date
* and if globalBufferedUpdates has changes
*/
return globalBufferedUpdates.any() || !globalSlice.isEmpty() || globalSlice.sliceTail != tail
|| tail.next != null;
} finally {
globalBufferLock.unlock();
}
}
void tryApplyGlobalSlice() {
if (globalBufferLock.tryLock()) {
/*
* The global buffer must be locked but we don't need to update them if
* there is an update going on right now. It is sufficient to apply the
* deletes that have been added after the current in-flight global slices
* tail the next time we can get the lock!
*/
try {
if (updateSlice(globalSlice)) {
// System.out.println(Thread.currentThread() + ": apply globalSlice");
globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT);
}
} finally {
globalBufferLock.unlock();
}
}
}
FrozenBufferedUpdates freezeGlobalBuffer(DeleteSlice callerSlice) {
globalBufferLock.lock();
/*
* Here we freeze the global buffer so we need to lock it, apply all
* deletes in the queue and reset the global slice to let the GC prune the
* queue.
*/
final Node<?> currentTail = tail; // take the current tail make this local any
// Changes after this call are applied later
// and not relevant here
if (callerSlice != null) {
// Update the callers slices so we are on the same page
callerSlice.sliceTail = currentTail;
}
try {
if (globalSlice.sliceTail != currentTail) {
globalSlice.sliceTail = currentTail;
globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT);
}
// System.out.println(Thread.currentThread().getName() + ": now freeze global buffer " + globalBufferedDeletes);
final FrozenBufferedUpdates packet = new FrozenBufferedUpdates(
globalBufferedUpdates, false);
globalBufferedUpdates.clear();
return packet;
} finally {
globalBufferLock.unlock();
}
}
DeleteSlice newSlice() {
return new DeleteSlice(tail);
}
boolean updateSlice(DeleteSlice slice) {
if (slice.sliceTail != tail) { // If we are the same just
slice.sliceTail = tail;
return true;
}
return false;
}
static class DeleteSlice {
// No need to be volatile, slices are thread captive (only accessed by one thread)!
Node<?> sliceHead; // we don't apply this one
Node<?> sliceTail;
DeleteSlice(Node<?> currentTail) {
assert currentTail != null;
/*
* Initially this is a 0 length slice pointing to the 'current' tail of
* the queue. Once we update the slice we only need to assign the tail and
* have a new slice
*/
sliceHead = sliceTail = currentTail;
}
void apply(BufferedUpdates del, int docIDUpto) {
if (sliceHead == sliceTail) {
// 0 length slice
return;
}
/*
* When we apply a slice we take the head and get its next as our first
* item to apply and continue until we applied the tail. If the head and
* tail in this slice are not equal then there will be at least one more
* non-null node in the slice!
*/
Node<?> current = sliceHead;
do {
current = current.next;
assert current != null : "slice property violated between the head on the tail must not be a null node";
current.apply(del, docIDUpto);
// System.out.println(Thread.currentThread().getName() + ": pull " + current + " docIDUpto=" + docIDUpto);
} while (current != sliceTail);
reset();
}
void reset() {
// Reset to a 0 length slice
sliceHead = sliceTail;
}
/**
* Returns <code>true</code> iff the given item is identical to the item
* hold by the slices tail, otherwise <code>false</code>.
*/
boolean isTailItem(Object item) {
return sliceTail.item == item;
}
boolean isEmpty() {
return sliceHead == sliceTail;
}
}
public int numGlobalTermDeletes() {
return globalBufferedUpdates.numTermDeletes.get();
}
void clear() {
globalBufferLock.lock();
try {
final Node<?> currentTail = tail;
globalSlice.sliceHead = globalSlice.sliceTail = currentTail;
globalBufferedUpdates.clear();
} finally {
globalBufferLock.unlock();
}
}
private static class Node<T> {
volatile Node<?> next;
final T item;
Node(T item) {
this.item = item;
}
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<Node,Node> nextUpdater = AtomicReferenceFieldUpdater
.newUpdater(Node.class, Node.class, "next");
void apply(BufferedUpdates bufferedDeletes, int docIDUpto) {
throw new IllegalStateException("sentinel item must never be applied");
}
boolean casNext(Node<?> cmp, Node<?> val) {
return nextUpdater.compareAndSet(this, cmp, val);
}
}
private static final class TermNode extends Node<Term> {
TermNode(Term term) {
super(term);
}
@Override
void apply(BufferedUpdates bufferedDeletes, int docIDUpto) {
bufferedDeletes.addTerm(item, docIDUpto);
}
@Override
public String toString() {
return "del=" + item;
}
}
private static final class QueryArrayNode extends Node<Query[]> {
QueryArrayNode(Query[] query) {
super(query);
}
@Override
void apply(BufferedUpdates bufferedUpdates, int docIDUpto) {
for (Query query : item) {
bufferedUpdates.addQuery(query, docIDUpto);
}
}
}
private static final class TermArrayNode extends Node<Term[]> {
TermArrayNode(Term[] term) {
super(term);
}
@Override
void apply(BufferedUpdates bufferedUpdates, int docIDUpto) {
for (Term term : item) {
bufferedUpdates.addTerm(term, docIDUpto);
}
}
@Override
public String toString() {
return "dels=" + Arrays.toString(item);
}
}
private static final class DocValuesUpdatesNode extends Node<DocValuesUpdate[]> {
DocValuesUpdatesNode(DocValuesUpdate... updates) {
super(updates);
}
@Override
void apply(BufferedUpdates bufferedUpdates, int docIDUpto) {
for (DocValuesUpdate update : item) {
switch (update.type) {
case NUMERIC:
bufferedUpdates.addNumericUpdate(new NumericDocValuesUpdate(update.term, update.field, (Long) update.value), docIDUpto);
break;
case BINARY:
bufferedUpdates.addBinaryUpdate(new BinaryDocValuesUpdate(update.term, update.field, (BytesRef) update.value), docIDUpto);
break;
default:
throw new IllegalArgumentException(update.type + " DocValues updates not supported yet!");
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("docValuesUpdates: ");
if (item.length > 0) {
sb.append("term=").append(item[0].term).append("; updates: [");
for (DocValuesUpdate update : item) {
sb.append(update.field).append(':').append(update.value).append(',');
}
sb.setCharAt(sb.length()-1, ']');
}
return sb.toString();
}
}
private boolean forceApplyGlobalSlice() {
globalBufferLock.lock();
final Node<?> currentTail = tail;
try {
if (globalSlice.sliceTail != currentTail) {
globalSlice.sliceTail = currentTail;
globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT);
}
return globalBufferedUpdates.any();
} finally {
globalBufferLock.unlock();
}
}
public int getBufferedUpdatesTermsSize() {
globalBufferLock.lock();
try {
forceApplyGlobalSlice();
return globalBufferedUpdates.terms.size();
} finally {
globalBufferLock.unlock();
}
}
@Override
public long ramBytesUsed() {
return globalBufferedUpdates.bytesUsed.get();
}
@Override
public String toString() {
return "DWDQ: [ generation: " + generation + " ]";
}
}
| {
"content_hash": "1726f3810e5f55760b12f636a4a7ca1f",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 134,
"avg_line_length": 33.17149220489978,
"alnum_prop": 0.6630186652343225,
"repo_name": "williamchengit/TestRepo",
"id": "d1c05a2385b37a61af687ad73394ce945b03ba84",
"size": "15691",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "solr-4.9.0/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.olat.core.gui.util.bandwidth;
import java.io.OutputStream;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.creator.ControllerCreator;
/**
* @author Felix Jost, http://www.goodsolutions.ch
*/
public class SlowBandWidthSimulatorImpl implements SlowBandWidthSimulator {
final CPSPauser cps = new CPSPauser(-1);
public SlowBandWidthSimulatorImpl() {
//
}
@Override
public ControllerCreator createAdminGUI() {
return new ControllerCreator() {
@Override
public Controller createController(UserRequest lureq, WindowControl lwControl) {
return new BandWidthAdminController(lureq, lwControl, cps);
}
};
}
@Override
public OutputStream wrapOutputStream(OutputStream outputStream) {
SlowOutputStream slos = new SlowOutputStream(outputStream, cps);
return slos;
}
}
| {
"content_hash": "592ab51948b067598a25da43003a7af1",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 83,
"avg_line_length": 25.63888888888889,
"alnum_prop": 0.7735644637053087,
"repo_name": "RLDevOps/Scholastic",
"id": "6ad167d781f56c2248fc38ea32688f23a5d8b4d1",
"size": "1718",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/org/olat/core/gui/util/bandwidth/SlowBandWidthSimulatorImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2279568"
},
{
"name": "Java",
"bytes": "20345916"
},
{
"name": "JavaScript",
"bytes": "31555977"
},
{
"name": "Perl",
"bytes": "4117"
},
{
"name": "Shell",
"bytes": "42296"
},
{
"name": "XSLT",
"bytes": "169404"
}
],
"symlink_target": ""
} |
//Created by Valerii Proskurin.
//Date: 30.01.2018
//parts of his code are taken from
//https://github.com/igrr/esp32-cam-demo
//by Ivan Grokhotkov
#include <WiFiClient.h>
#include <ESP32WebServer.h>
#include <WiFi.h>
#include "soc/soc.h"
#include "soc/gpio_sig_map.h"
#include "soc/i2s_reg.h"
#include "soc/i2s_struct.h"
#include "soc/io_mux_reg.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"
#include "rom/lldesc.h"
#include "Arduino.h"
#include "driver/ledc.h"
#define SAMPLES_COUNT 1000
/* wifi host id and password */
const char* ssid = "yourWifiName";
const char* password = "yourWifiPassword";
//#define DEBUG_LOG_ENABLE
const int XCLK = 32;
const int PCLK = 33;
const int D0 = 27;
const int D1 = 17;
const int D2 = 16;
const int D3 = 15;
const int D4 = 14;
const int D5 = 13;
const int D6 = 12;
const int D7 = 4;
#ifdef DEBUG_LOG_ENABLE
#define DEBUG_PRINTLN(a) Serial.println(a)
#define DEBUG_PRINT(a) Serial.print(a)
#define DEBUG_PRINTLNF(a, f) Serial.println(a, f)
#define DEBUG_PRINTF(a, f) Serial.print(a, f)
#else
#define DEBUG_PRINTLN(a)
#define DEBUG_PRINT(a)
#define DEBUG_PRINTLNF(a, f)
#define DEBUG_PRINTF(a, f)
#endif
//TODO: it looks like DMA processing is wrong. At least dma burst limit in 4096 uint32 words should be checked.
class DMABuffer
{
public:
lldesc_t descriptor;
unsigned char* buffer;
DMABuffer(uint32_t bytes)
{
buffer = (unsigned char *)malloc(bytes);
descriptor.length = bytes;
descriptor.size = descriptor.length;
descriptor.owner = 1;
descriptor.sosf = 1;
descriptor.buf = (uint8_t*) buffer;
descriptor.offset = 0;
descriptor.empty = 0;
descriptor.eof = 1;
descriptor.qe.stqe_next = 0;
}
void next(DMABuffer *next)
{
descriptor.qe.stqe_next = &(next->descriptor);
}
int sampleCount() const
{
return descriptor.length / 2;
}
~DMABuffer()
{
if(buffer)
delete(buffer);
}
};
bool ClockEnable(int pin, int Hz)
{
periph_module_enable(PERIPH_LEDC_MODULE);
ledc_timer_config_t timer_conf;
timer_conf.bit_num = (ledc_timer_bit_t)1;
timer_conf.freq_hz = Hz;
timer_conf.speed_mode = LEDC_HIGH_SPEED_MODE;
timer_conf.timer_num = LEDC_TIMER_0;
esp_err_t err = ledc_timer_config(&timer_conf);
if (err != ESP_OK) {
return false;
}
ledc_channel_config_t ch_conf;
ch_conf.channel = LEDC_CHANNEL_0;
ch_conf.timer_sel = LEDC_TIMER_0;
ch_conf.intr_type = LEDC_INTR_DISABLE;
ch_conf.duty = 1;
ch_conf.speed_mode = LEDC_HIGH_SPEED_MODE;
ch_conf.gpio_num = pin;
err = ledc_channel_config(&ch_conf);
if (err != ESP_OK) {
return false;
}
return true;
}
void ClockDisable()
{
periph_module_disable(PERIPH_LEDC_MODULE);
}
class I2C_AdcSampler
{
public:
static intr_handle_t i2sInterruptHandle;
static DMABuffer *dmaBuffer;
static unsigned char* frame;
static uint32_t frameLength;
static volatile bool stopSignal;
typedef enum {
/* camera sends byte sequence: s1, s2, s3, s4, ...
* fifo receives: 00 s1 00 s2, 00 s2 00 s3, 00 s3 00 s4, ...
*/
SM_0A0B_0B0C = 0,
/* camera sends byte sequence: s1, s2, s3, s4, ...
* fifo receives: 00 s1 00 s2, 00 s3 00 s4, ...
*/
SM_0A0B_0C0D = 1,
/* camera sends byte sequence: s1, s2, s3, s4, ...
* fifo receives: 00 s1 00 00, 00 s2 00 00, 00 s3 00 00, ...
*/
SM_0A00_0B00 = 3,
} i2s_sampling_mode_t;
static inline void i2sConfReset()
{
const uint32_t lc_conf_reset_flags = I2S_IN_RST_M | I2S_AHBM_RST_M | I2S_AHBM_FIFO_RST_M;
I2S0.lc_conf.val |= lc_conf_reset_flags;
I2S0.lc_conf.val &= ~lc_conf_reset_flags;
const uint32_t conf_reset_flags = I2S_RX_RESET_M | I2S_RX_FIFO_RESET_M | I2S_TX_RESET_M | I2S_TX_FIFO_RESET_M;
I2S0.conf.val |= conf_reset_flags;
I2S0.conf.val &= ~conf_reset_flags;
while (I2S0.state.rx_fifo_reset_back);
}
void start()
{
DEBUG_PRINTLN("Sampling started");
i2sRun();
}
void stop()
{
stopSignal = true;
while(stopSignal);
DEBUG_PRINTLN("Sampling stopped");
}
void oneFrame()
{
start();
stop();
}
static void i2sStop();
static void i2sRun();
static void dmaBufferInit(uint32_t bytes);
static void dmaBufferDeinit();
static void IRAM_ATTR i2sInterrupt(void* arg);
static bool i2sInit(const int PCLK, const int D0, const int D1, const int D2, const int D3, const int D4, const int D5, const int D6, const int D7);
static bool init(const uint32_t frameBytes, const int XCLK, const int PCLK, const int D0, const int D1, const int D2, const int D3, const int D4, const int D5, const int D6, const int D7);
};
//private variables
ESP32WebServer server(80);
intr_handle_t I2C_AdcSampler::i2sInterruptHandle = 0;
DMABuffer * I2C_AdcSampler::dmaBuffer = 0;
unsigned char* I2C_AdcSampler::frame = 0;
uint32_t I2C_AdcSampler::frameLength = 0;
volatile bool I2C_AdcSampler::stopSignal = false;
I2C_AdcSampler adcSampler;
void IRAM_ATTR I2C_AdcSampler::i2sInterrupt(void* arg)
{
I2S0.int_clr.val = I2S0.int_raw.val;
unsigned char* buf = dmaBuffer->buffer;
uint32_t framePointer = 0;
DEBUG_PRINTLN("I2S irq handler");
//stop i2s
if(stopSignal)
{
i2sStop();
stopSignal = false;
}
//compress data
for(uint32_t i = 0; i < frameLength * 2; i += 2)
{
frame[framePointer++] = buf[i];
}
}
void I2C_AdcSampler::i2sStop()
{
DEBUG_PRINTLN("I2S Stop");
esp_intr_disable(i2sInterruptHandle);
i2sConfReset();
I2S0.conf.rx_start = 0;
}
void I2C_AdcSampler::i2sRun()
{
DEBUG_PRINTLN("I2S Run");
esp_intr_disable(i2sInterruptHandle);
i2sConfReset();
DEBUG_PRINT("Sample count ");
DEBUG_PRINTLN(dmaBuffer->sampleCount());
I2S0.rx_eof_num = dmaBuffer->sampleCount();
I2S0.in_link.addr = (uint32_t)&(dmaBuffer->descriptor);
I2S0.in_link.start = 1;
I2S0.int_clr.val = I2S0.int_raw.val;
I2S0.int_ena.val = 0;
I2S0.int_ena.in_done = 1;
esp_intr_enable(i2sInterruptHandle);
I2S0.conf.rx_start = 1;
}
bool I2C_AdcSampler::init(const uint32_t frameBytes, const int XCLK, const int PCLK, const int D0, const int D1, const int D2, const int D3, const int D4, const int D5, const int D6, const int D7)
{
ClockEnable(XCLK, 40000000); //sampling clock is 40Msps
frameLength = frameBytes;
frame = (unsigned char*)malloc(frameBytes);
if(!frame)
{
DEBUG_PRINTLN("Not enough memory for frame buffer!");
return false;
}
i2sInit(PCLK, D0, D1, D2, D3, D4, D5, D6, D7);
dmaBufferInit(frameBytes * 2); //two bytes per dword packing
return true;
}
bool I2C_AdcSampler::i2sInit(const int PCLK, const int D0, const int D1, const int D2, const int D3, const int D4, const int D5, const int D6, const int D7)
{
int pins[] = {PCLK, D0, D1, D2, D3, D4, D5, D6, D7};
gpio_config_t conf = {
.pin_bit_mask = 0,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE
};
for (int i = 0; i < sizeof(pins) / sizeof(gpio_num_t); ++i) {
conf.pin_bit_mask = 1LL << pins[i];
gpio_config(&conf);
}
// Route input GPIOs to I2S peripheral using GPIO matrix, last parameter is invert
gpio_matrix_in(D0, I2S0I_DATA_IN0_IDX, false);
gpio_matrix_in(D1, I2S0I_DATA_IN1_IDX, false);
gpio_matrix_in(D2, I2S0I_DATA_IN2_IDX, false);
gpio_matrix_in(D3, I2S0I_DATA_IN3_IDX, false);
gpio_matrix_in(D4, I2S0I_DATA_IN4_IDX, false);
gpio_matrix_in(D5, I2S0I_DATA_IN5_IDX, false);
gpio_matrix_in(D6, I2S0I_DATA_IN6_IDX, false);
gpio_matrix_in(D7, I2S0I_DATA_IN7_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN8_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN9_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN10_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN11_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN12_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN13_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN14_IDX, false);
gpio_matrix_in(0x30, I2S0I_DATA_IN15_IDX, false);
//for i2s in parallel camera input mode data is receiver only when V_SYNC = H_SYNC = H_ENABLE = 1. We don't use these inputs so simply set them High
gpio_matrix_in(0x38, I2S0I_V_SYNC_IDX, false);
gpio_matrix_in(0x38, I2S0I_H_SYNC_IDX, false); //0x30 sends 0, 0x38 sends 1
gpio_matrix_in(0x38, I2S0I_H_ENABLE_IDX, false);
gpio_matrix_in(PCLK, I2S0I_WS_IN_IDX, false);
// Enable and configure I2S peripheral
periph_module_enable(PERIPH_I2S0_MODULE);
// Toggle some reset bits in LC_CONF register
// Toggle some reset bits in CONF register
i2sConfReset();
// Enable slave mode (sampling clock is external)
I2S0.conf.rx_slave_mod = 1;
// Enable parallel mode
I2S0.conf2.lcd_en = 1;
// Use HSYNC/VSYNC/HREF to control sampling
I2S0.conf2.camera_en = 1;
// Configure clock divider
I2S0.clkm_conf.clkm_div_a = 1;
I2S0.clkm_conf.clkm_div_b = 0;
I2S0.clkm_conf.clkm_div_num = 2;
// FIFO will sink data to DMA
I2S0.fifo_conf.dscr_en = 1;
// FIFO configuration
//two bytes per dword packing
I2S0.fifo_conf.rx_fifo_mod = SM_0A0B_0C0D; //pack two bytes in one UINT32
I2S0.fifo_conf.rx_fifo_mod_force_en = 1;
I2S0.conf_chan.rx_chan_mod = 1;
// Clear flags which are used in I2S serial mode
I2S0.sample_rate_conf.rx_bits_mod = 0;
I2S0.conf.rx_right_first = 0;
I2S0.conf.rx_msb_right = 0;
I2S0.conf.rx_msb_shift = 0;
I2S0.conf.rx_mono = 0;
I2S0.conf.rx_short_sync = 0;
I2S0.timing.val = 0;
// Allocate I2S interrupt, keep it disabled
esp_intr_alloc(ETS_I2S0_INTR_SOURCE, ESP_INTR_FLAG_INTRDISABLED | ESP_INTR_FLAG_LEVEL1 | ESP_INTR_FLAG_IRAM, &i2sInterrupt, NULL, &i2sInterruptHandle);
return true;
}
void I2C_AdcSampler::dmaBufferInit(uint32_t bytes)
{
dmaBuffer = (DMABuffer*) malloc(sizeof(DMABuffer*));
dmaBuffer = new DMABuffer(bytes);
}
void I2C_AdcSampler::dmaBufferDeinit()
{
if (!dmaBuffer) return;
delete(dmaBuffer);
dmaBuffer = 0;
}
/* my page */
char mainPage[] =
"<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<!-- Plotly.js -->\n\
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>\n\
</head>\n\
\n\
<body>\n\
<p style='text-align: left;'><strong>EspScope</strong></p>\n\
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>\n\
<hr />\n\
<p style='text-align: left;'>\n\
Open source <a href='github.com/easyvolts/espScope'>project</a> of esp32 based wireless oscilloscope. \n\
Trigger mode:\n\
<input type='radio' name='triggerSelection' value='auto'> Auto\n\
<input type='radio' name='triggerSelection' value='single'> Single\n\
<input type='radio' name='triggerSelection' value='none' onclick='startUpdate()'> None\n\
<input type='radio' name='triggerSelection' value='stop' onclick='stopUpdate()' checked='checked'> Stop\n\
</p>\n\
<script>\n\
<!-- JAVASCRIPT CODE GOES HERE -->\n\
var data = [\n\
{ y: [0,0,0,0],\n\
x: [0,1,2,3],\n\
type: 'lines+markers' } ];\n\
var counter = 1;\n\
var intervalID;\n\
\n\
Plotly.newPlot('myDiv', data);\n\
\n\
function httpGet(theUrl)\n\
{\n\
var xmlHttp = new XMLHttpRequest();\n\
xmlHttp.open( 'GET', theUrl, false ); /*false for synchronous request*/\n\
xmlHttp.send( null );\n\
return xmlHttp.responseText;\n\
}\n\
\n\
function plotUpdate() {\n\
/*alert('called');*/\n\
scopeData = httpGet('/scope?');\n\
/* remove the first trace*/\n\
Plotly.deleteTraces('myDiv', 0);\n\
scopeDataArray = scopeData.split(',');\n\
Plotly.addTraces('myDiv', {y: scopeDataArray});\n\
/*Plotly.extendTraces('myDiv', {y: [1,2,3,1]}, [0]);*/\n\
}\n\
function startUpdate() {\n\
intervalID = setInterval(plotUpdate, 300);\n\
}\n\
function stopUpdate() {\n\
clearInterval(intervalID);\n\
}\n\
\n\
</script>\n\
</body>\n\
</html>";
void handleRoot() {
server.send(200, "text/html", mainPage);
}
/* send data points in responce to "/scope?" request */
char str[50000];
void handleDataRequest() {
int samplePointer = 0;
int strPointer = 0;
DEBUG_PRINTLN("Answer to the request.");
adcSampler.oneFrame();
//convert bin data to str
for(samplePointer = 0; samplePointer < adcSampler.frameLength; samplePointer++) {
strPointer += sprintf(&str[strPointer], "%u,", adcSampler.frame[samplePointer]);
}
//char str[] = "1,12,24,23,33,2"; //send data bytes only
/* respond to the request */
server.send(200, "text/plain", str);
}
/* cannot handle request so return 404 */
void handleNotFound(){
String message = "File Not Found\n\n\n\n";
server.send(404, "text/plain", message);
}
void setup(void){
adcSampler.init(SAMPLES_COUNT, XCLK, PCLK, D0, D1, D2, D3, D4, D5, D6, D7);
Serial.begin(115200);
Serial.println("Application start");
WiFi.begin(ssid, password);
/* indication of connection process */
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
/* main page handler */
server.on("/", handleRoot);
/* this callback handle GPIO request and respond*/
server.on("/scope", handleDataRequest);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
| {
"content_hash": "31b22894ebc06a09f481cb95baf9f361",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 196,
"avg_line_length": 30.085653104925054,
"alnum_prop": 0.6293238434163702,
"repo_name": "Ebiroll/qemu_esp32",
"id": "bcd43ef9cb4e56477048e4bc878fcd25f8f20191",
"size": "14050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/37_espScope/main/espScope.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "421980"
},
{
"name": "C++",
"bytes": "141156"
},
{
"name": "CMake",
"bytes": "17409"
},
{
"name": "Dockerfile",
"bytes": "1079"
},
{
"name": "GDB",
"bytes": "3176"
},
{
"name": "Makefile",
"bytes": "699"
},
{
"name": "QMake",
"bytes": "1480"
},
{
"name": "Shell",
"bytes": "228"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en-us">
<head>
<link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title>
404: Page not found · Christopher Ahern
</title>
<!-- CSS -->
<link rel="stylesheet" href="/public/css/poole.css">
<link rel="stylesheet" href="/public/css/syntax.css">
<link rel="stylesheet" href="/public/css/lanyon.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<!-- Icons -->
<!-- <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="/public/favicon.ico"> -->
<!-- RSS -->
<link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>
<!-- <body class="layout-reverse sidebar-overlay">-->
<body class="layout-reverse sidebar-overlay">
<!-- Target for toggling the sidebar `.sidebar-checkbox` is for regular
styles, `#sidebar-checkbox` for behavior. -->
<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">
<!-- Toggleable sidebar -->
<div class="sidebar" id="sidebar">
<div class="sidebar-item">
<p></p>
</div>
<nav class="sidebar-nav">
<!--<a class="sidebar-nav-item" href="/">Home</a>-->
<a class="sidebar-nav-item" href="/projects/">Projects</a>
<a class="sidebar-nav-item" href="/publications/">Publications</a>
<!-- <a class="sidebar-nav-item" href="https://github.com/"><i class="fa fa-github"></i> GitHub </a> -->
<!-- <a class="sidebar-nav-item" href="/archive/v1.0.0.zip">Download</a> -->
<!-- <a class="sidebar-nav-item" href="">GitHub project</a> -->
<!--<span class="sidebar-nav-item">Currently v1.0.0</span> -->
</nav>
<div class="sidebar-item">
<p>
© 2016. All rights reserved.
</p>
</div>
</div>
<!-- Wrap is the content to shift when toggling the sidebar. We wrap the
content to avoid any CSS collisions with our real content. -->
<div class="wrap">
<div class="masthead">
<div class="container">
<h2 class="masthead-title">
<a href="/" title="">Christopher Ahern</a>
<!-- Add username for website to _config.yaml and create new loop -->
<a href="https://github.com/christopherahern" style="text-decoration : none">
<span class="fa">
<i class="fa fa-github-square"></i>
</span>
</a>
<a href="https://linkedin.com/in/christopherahern" style="text-decoration : none">
<span class="fa ">
<i class="fa fa-linkedin-square"></i>
</span>
</a>
<a href="mailto:christopher.ahern@gmail.com" style="text-decoration : none">
<span class="fa ">
<i class="fa fa-envelope-square"></i>
</span>
</a>
<br/>
<small>Post-doctoral researcher at University of Pennsylvania</small>
</h2>
</div>
</div>
<div class="container content">
<div class="page">
<h1 class="page-title">404: Page not found</h1>
<p class="lead">Sorry, we've misplaced that URL or it's pointing to something that doesn't exist. <a href="/">Head back home</a> to try finding it again.</p>
</div>
</div>
</div>
<label for="sidebar-checkbox" class="sidebar-toggle"></label>
<script>
(function(document) {
var toggle = document.querySelector('.sidebar-toggle');
var sidebar = document.querySelector('#sidebar');
var checkbox = document.querySelector('#sidebar-checkbox');
document.addEventListener('click', function(e) {
var target = e.target;
if(!checkbox.checked ||
sidebar.contains(target) ||
(target === checkbox || target === toggle)) return;
checkbox.checked = false;
}, false);
})(document);
</script>
</body>
</html>
| {
"content_hash": "71cc42c53aaa21f118d3eee4f6535860",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 159,
"avg_line_length": 27.64848484848485,
"alnum_prop": 0.5679526523454625,
"repo_name": "christopherahern/christopherahern.github.io",
"id": "e09923fced8fc33fef4be0a67804c379c3b41994",
"size": "4562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/404.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "46358"
},
{
"name": "HTML",
"bytes": "82837"
}
],
"symlink_target": ""
} |
Notes:
- Pull requests will not be accepted until the submitter has agreed to the [contributer agreement](https://github.com/ARMmbed/mbed-os/blob/master/CONTRIBUTING.md).
- This is just a template, so feel free to use/remove the unnecessary things
## Description
A few sentences describing the overall goals of the pull request's commits.
## Status
**READY/IN DEVELOPMENT/HOLD**
## Migrations
If this PR changes any APIs or behaviors, give a short description of what *API users* should do when this PR is merged.
YES | NO
## Related PRs
List related PRs against other branches:
branch | PR
------ | ------
other_pr_production | [link]()
other_pr_master | [link]()
## Todos
- [ ] Tests
- [ ] Documentation
## Deploy notes
Notes regarding the deployment of this PR. These should note any required changes in the build environment, tools, compilers and so on.
## Steps to test or reproduce
Outline the steps to test or reproduce the PR here.
| {
"content_hash": "ffb56af40b8fc50eda70ee9bfd725a4b",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 163,
"avg_line_length": 24.512820512820515,
"alnum_prop": 0.7353556485355649,
"repo_name": "infinnovation/mbed-os",
"id": "95211bb51169feb7ee9df23d673ced95994b6d35",
"size": "956",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": ".github/pull_request_template.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6681752"
},
{
"name": "Batchfile",
"bytes": "22"
},
{
"name": "C",
"bytes": "300399715"
},
{
"name": "C++",
"bytes": "8907452"
},
{
"name": "CMake",
"bytes": "5285"
},
{
"name": "HTML",
"bytes": "2063156"
},
{
"name": "Makefile",
"bytes": "103497"
},
{
"name": "Objective-C",
"bytes": "63900"
},
{
"name": "Perl",
"bytes": "2589"
},
{
"name": "Python",
"bytes": "38809"
},
{
"name": "Shell",
"bytes": "16862"
},
{
"name": "XSLT",
"bytes": "5596"
}
],
"symlink_target": ""
} |
<?php
require_once 'Interface.php';
require_once realpath(dirname(__FILE__)) . '/../Exception.php';
if ( !function_exists('json_decode') ) {
throw new Exception("Please install the PHP JSON extension");
}
if ( !function_exists('curl_init') ) {
throw new Exception("Please install the PHP cURL extension");
}
/**
* Services_Paymill cURL HTTP client
*/
class Services_Paymill_Apiclient_Curl implements Services_Paymill_Apiclient_Interface
{
/**
* Paymill API merchant key
*
* @var string
*/
private $_apiKey = null;
/**
* Paymill API base url
*
* @var string
*/
private $_apiUrl = '/' ;
const USER_AGENT = 'Paymill-php/0.0.2';
public static $lastRawResponse;
public static $lastRawCurlOptions;
/**
* cURL HTTP client constructor
*
* @param string $apiKey
* @param string $apiEndpoint
*/
public function __construct($apiKey, $apiEndpoint)
{
$this->_apiKey = $apiKey;
$this->_apiUrl = $apiEndpoint;
}
/**
* Perform API and handle exceptions
*
* @param $action
* @param array $params
* @param string $method
* @return mixed
* @throws Services_Paymill_Exception
* @throws Exception
*/
public function request($action, $params = array(), $method = 'POST')
{
if (!is_array($params)) $params = array();
try {
$response = $this->_requestApi($action, $params, $method);
$httpStatusCode = $response['header']['status'];
if ( $httpStatusCode != 200 ) {
$errorMessage = 'Client returned HTTP status code ' . $httpStatusCode;
if (isset($response['body']['error'])) {
$errorMessage = $response['body']['error'];
}
return array("data" => array("error" => $errorMessage));
}
return $response['body'];
} catch (Exception $e) {
return array("data" => array("error" => $e->getMessage()));
}
}
/**
* Perform HTTP request to REST endpoint
*
* @param string $action
* @param array $params
* @param string $method
* @return array
*/
private function _requestApi($action = '', $params = array(), $method = 'POST')
{
$curlOpts = array(
CURLOPT_URL => $this->_apiUrl . $action,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_USERAGENT => self::USER_AGENT,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSLVERSION => 3,
// CURLOPT_CAINFO => realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'paymill.crt',
);
if (Services_Paymill_Apiclient_Interface::HTTP_GET === $method) {
if (0 !== count($params)) {
$curlOpts[CURLOPT_URL] .= false === strpos($curlOpts[CURLOPT_URL], '?') ? '?' : '&';
$curlOpts[CURLOPT_URL] .= http_build_query($params, null, '&');
}
} else {
$curlOpts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
if ($this->_apiKey) {
$curlOpts[CURLOPT_USERPWD] = $this->_apiKey . ':';
}
$curl = curl_init();
curl_setopt_array($curl, $curlOpts);
$responseBody = curl_exec($curl);
self::$lastRawCurlOptions = $curlOpts;
self::$lastRawResponse = $responseBody;
$responseInfo = curl_getinfo($curl);
curl_close($curl);
if ('application/json' === $responseInfo['content_type']) {
$responseBody = json_decode($responseBody, true);
}
return array(
'header' => array(
'status' => $responseInfo['http_code'],
'reason' => null,
),
'body' => $responseBody
);
}
} | {
"content_hash": "a01ff93868a3ae831389108f7f6510d6",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 102,
"avg_line_length": 29.414814814814815,
"alnum_prop": 0.52253840342483,
"repo_name": "Saldum/Paymill-Codeigniter",
"id": "14ac04aec0d457ad0acece5c15bc5a0d38350d2d",
"size": "3971",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/libraries/Paymill/lib/Services/Paymill/Apiclient/Curl.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "73313"
}
],
"symlink_target": ""
} |
package com.swrve.sdk.messaging;
import android.util.Log;
import com.swrve.sdk.SwrveBase;
import com.swrve.sdk.SwrveHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/*
* Swrve campaign containing messages targeted for the current device and user id.
*/
public class SwrveCampaign {
protected static final String LOG_TAG = "SwrveMessagingSDK";
// Default campaign throttle limits
protected static int DEFAULT_DELAY_FIRST_MESSAGE = 180;
protected static int DEFAULT_MAX_IMPRESSIONS = 99999;
protected static int DEFAULT_MIN_DELAY_BETWEEN_MSGS = 60;
// Random number generator
protected static Random rnd = new Random();
protected final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss ZZZZ", Locale.US);
// Identifies the campaign
protected int id;
// SDK controller for this campaign
protected SwrveBase<?, ?> talkController;
// Start date of the campaign
protected Date startDate;
// End date of the campaign
protected Date endDate;
// List of messages contained in the campaign
protected List<SwrveMessage> messages;
// List of triggers for the campaign
protected Set<String> triggers;
// Indicates if the campaign serves messages randomly or using round robin
protected boolean randomOrder;
// Next message to be shown if round robin campaign
protected int next;
// Number of impressions of this campaign. Used to disable the campaign if
// it reaches total impressions
protected int impressions;
// Number of maximum impressions of the campaign
protected int maxImpressions;
// Minimum delay we want between messages
protected int minDelayBetweenMessage;
// Time we can show the first message after launch
protected Date showMessagesAfterLaunch;
// Time we can show the next message
// Will be based on time previous message was shown + minDelayBetweenMessage
protected Date showMessagesAfterDelay;
// Amount of seconds to wait for the first message
protected int delayFirstMessage;
public SwrveCampaign() {
this.messages = new ArrayList<SwrveMessage>();
this.triggers = new HashSet<String>();
}
/**
* Load a campaign from JSON data.
*
* @param controller SwrveTalk object that will manage the data from the campaign.
* @param campaignData JSON data containing the campaign details.
* @param assetsQueue Set where to save the resources to be loaded
* @return SwrveCampaign Loaded SwrveCampaign.
* @throws JSONException
*/
public SwrveCampaign(SwrveBase<?, ?> controller, JSONObject campaignData, Set<String> assetsQueue) throws JSONException {
this();
setId(campaignData.getInt("id"));
setTalkController(controller);
Log.i(LOG_TAG, "Loading campaign " + getId());
// Campaign rule defaults
this.maxImpressions = DEFAULT_MAX_IMPRESSIONS;
this.minDelayBetweenMessage = DEFAULT_MIN_DELAY_BETWEEN_MSGS;
this.showMessagesAfterLaunch = SwrveHelper.addTimeInterval(this.talkController.getInitialisedTime(), DEFAULT_DELAY_FIRST_MESSAGE, Calendar.SECOND);
assignCampaignTriggers(this, campaignData);
assignCampaignRules(this, campaignData);
assignCampaignDates(this, campaignData);
JSONArray jsonMessages = campaignData.getJSONArray("messages");
for (int k = 0, t = jsonMessages.length(); k < t; k++) {
JSONObject messageData = jsonMessages.getJSONObject(k);
SwrveMessage message = createMessage(controller, this, messageData);
// If the message has some format
if (message.getFormats().size() > 0) {
// Add assets to queue
if (assetsQueue != null) {
for (SwrveMessageFormat format : message.getFormats()) {
// Add all images to the download queue
for (SwrveButton button : format.getButtons()) {
if (!SwrveHelper.isNullOrEmpty(button.getImage())) {
assetsQueue.add(button.getImage());
}
}
for (SwrveImage image : format.getImages()) {
if (!SwrveHelper.isNullOrEmpty(image.getFile())) {
assetsQueue.add(image.getFile());
}
}
}
}
}
// Only add message if it has any format
if (message.getFormats().size() > 0) {
addMessage(message);
}
}
}
/**
* @return the campaign id.
*/
public int getId() {
return id;
}
protected void setId(int id) {
this.id = id;
}
protected void setTalkController(SwrveBase<?, ?> controller) {
this.talkController = controller;
}
/**
* @return the campaign messages.
*/
public List<SwrveMessage> getMessages() {
return messages;
}
protected void setMessages(List<SwrveMessage> messages) {
this.messages = messages;
}
protected void addMessage(SwrveMessage message) {
this.messages.add(message);
}
/**
* @return the next message to show.
*/
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
/**
* @return the set of triggers for this campaign.
*/
public Set<String> getTriggers() {
return triggers;
}
protected void setTriggers(Set<String> triggers) {
this.triggers = triggers;
}
/**
* @return if the campaign serves messages in random order and not round
* robin.
*/
public boolean isRandomOrder() {
return randomOrder;
}
protected void setRandomOrder(boolean randomOrder) {
this.randomOrder = randomOrder;
}
/**
* @return current impressions
*/
public int getImpressions() {
return impressions;
}
public void setImpressions(int impressions) {
this.impressions = impressions;
}
/**
* @return maximum impressions
*/
public int getMaxImpressions() {
return maxImpressions;
}
public void setMaxImpressions(int maxImpressions) {
this.maxImpressions = maxImpressions;
}
/**
* @return the campaign start date.
*/
public Date getStartDate() {
return startDate;
}
protected void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* @return the campaign end date.
*/
public Date getEndDate() {
return endDate;
}
protected void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* Check if the campaign contains messages for the given event.
*
* @param eventName
* @return true if the campaign has this event as a trigger
*/
public boolean hasMessageForEvent(String eventName) {
String lowerCaseEvent = eventName.toLowerCase(Locale.US);
return triggers != null && triggers.contains(lowerCaseEvent);
}
/**
* Search for a message with the given trigger event and that satisfies
* the specific rules for the campaign.
*
* @param event trigger event
* @param now device time
* @return SwrveMessage message setup to the given trigger or null
* otherwise.
*/
public SwrveMessage getMessageForEvent(String event, Date now) {
return getMessageForEvent(event, now, null);
}
/**
* Search for a message related to the given trigger event at the given
* time. This function will return null if too many messages were dismissed,
* the campaign start is in the future, the campaign end is in the past or
* the given event is not contained in the trigger set.
*
* @param event trigger event
* @param now device time
* @param campaignReasons will contain the reason the campaign returned no message
* @return SwrveMessage message setup to the given trigger or null
* otherwise.
*/
public SwrveMessage getMessageForEvent(String event, Date now, Map<Integer, String> campaignReasons) {
int messagesCount = messages.size();
if (!hasMessageForEvent(event)) {
Log.i(LOG_TAG, "There is no trigger in " + id + " that matches " + event);
return null;
}
if (messagesCount == 0) {
logAndAddReason(campaignReasons, "No messages in campaign " + id);
return null;
}
if (startDate.after(now)) {
logAndAddReason(campaignReasons, "Campaign " + id + " has not started yet");
return null;
}
if (endDate.before(now)) {
logAndAddReason(campaignReasons, "Campaign " + id + " has finished");
return null;
}
if (impressions >= maxImpressions) {
logAndAddReason(campaignReasons, "{Campaign throttle limit} Campaign " + id + " has been shown " + maxImpressions + " times already");
return null;
}
// Ignore delay after launch throttle limit for auto show messages
if (!event.equalsIgnoreCase(talkController.getAutoShowEventTrigger()) && isTooSoonToShowMessageAfterLaunch(now)) {
logAndAddReason(campaignReasons, "{Campaign throttle limit} Too soon after launch. Wait until " + timestampFormat.format(showMessagesAfterLaunch));
return null;
}
if (isTooSoonToShowMessageAfterDelay(now)) {
logAndAddReason(campaignReasons, "{Campaign throttle limit} Too soon after last message. Wait until " + timestampFormat.format(showMessagesAfterDelay));
return null;
}
Log.i(LOG_TAG, event + " matches a trigger in " + id);
return getNextMessage(messagesCount, campaignReasons);
}
protected boolean isTooSoonToShowMessageAfterLaunch(Date now) {
return now.before(showMessagesAfterLaunch);
}
protected boolean isTooSoonToShowMessageAfterDelay(Date now) {
if (showMessagesAfterDelay == null) {
return false;
}
return now.before(showMessagesAfterDelay);
}
protected void logAndAddReason(Map<Integer, String> campaignReasons, String reason) {
if (campaignReasons != null) {
campaignReasons.put(id, reason);
}
Log.i(LOG_TAG, reason);
}
/**
* Amount of seconds to wait for first message.
*
* @return time in seconds
*/
public int getDelayFirstMessage() {
return delayFirstMessage;
}
/**
* Search for a message with the given message id.
*
* @param messageId message id to look for
* @return SwrveMessage message with the given id. If not found returns
* null.
*/
public SwrveMessage getMessageForId(int messageId) {
int messagesCount = messages.size();
if (messagesCount == 0) {
Log.i(LOG_TAG, "No messages in campaign " + id);
return null;
}
Iterator<SwrveMessage> messageIt = messages.iterator();
while (messageIt.hasNext()) {
SwrveMessage message = messageIt.next();
if (message.getId() == messageId)
return message;
}
return null;
}
protected SwrveMessage getNextMessage(int messagesCount, Map<Integer, String> campaignReasons) {
if (randomOrder) {
List<SwrveMessage> randomMessages = new ArrayList<SwrveMessage>(messages);
Collections.shuffle(randomMessages);
Iterator<SwrveMessage> itRandom = randomMessages.iterator();
while (itRandom.hasNext()) {
SwrveMessage msg = itRandom.next();
if (msg.isDownloaded()) {
return msg;
}
}
} else if (next < messagesCount) {
SwrveMessage msg = messages.get(next);
if (msg.isDownloaded()) {
return messages.get(next);
}
}
logAndAddReason(campaignReasons, "Campaign " + this.getId() + " hasn't finished downloading.");
return null;
}
protected SwrveMessage createMessage(SwrveBase<?, ?> controller, SwrveCampaign swrveCampaign, JSONObject messageData) throws JSONException {
return new SwrveMessage(controller, swrveCampaign, messageData);
}
protected void assignCampaignTriggers(SwrveCampaign campaign, JSONObject campaignData) throws JSONException {
JSONArray jsonTriggers = campaignData.getJSONArray("triggers");
for (int i = 0, j = jsonTriggers.length(); i < j; i++) {
String trigger = jsonTriggers.getString(i);
campaign.getTriggers().add(trigger.toLowerCase(Locale.US));
}
}
protected void assignCampaignRules(SwrveCampaign campaign, JSONObject campaignData) throws JSONException {
JSONObject rules = campaignData.getJSONObject("rules");
campaign.setRandomOrder(rules.getString("display_order").equals("random"));
if (rules.has("dismiss_after_views")) {
int totalImpressions = rules.getInt("dismiss_after_views");
setMaxImpressions(totalImpressions);
}
if (rules.has("delay_first_message")) {
int delay = rules.getInt("delay_first_message");
this.delayFirstMessage = delay;
this.showMessagesAfterLaunch = SwrveHelper.addTimeInterval(this.talkController.getInitialisedTime(), this.delayFirstMessage, Calendar.SECOND);
}
if (rules.has("min_delay_between_messages")) {
this.minDelayBetweenMessage = rules.getInt("min_delay_between_messages");
}
}
protected void assignCampaignDates(SwrveCampaign campaign, JSONObject campaignData) throws JSONException {
campaign.setStartDate(new Date(campaignData.getLong("start_date")));
campaign.setEndDate(new Date(campaignData.getLong("end_date")));
}
/**
* Increment impressions by one.
*/
public void incrementImpressions() {
this.impressions++;
}
/**
* Serialize the campaign state.
*
* @return JSONObject Settings for the campaign.
* @throws JSONException
*/
public JSONObject createSettings() throws JSONException {
JSONObject settings = new JSONObject();
settings.put("next", next);
settings.put("impressions", impressions);
return settings;
}
/**
* Load campaign settings from JSON data.
*
* @param settings JSONObject containing the campaign settings.
* @throws JSONException
*/
public void loadSettings(JSONObject settings) throws JSONException {
try {
if (settings.has("next")) {
this.next = settings.getInt("next");
}
if (settings.has("impressions")) {
this.impressions = settings.getInt("impressions");
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error while trying to load campaign settings", e);
}
}
/**
* Ensures a new message cannot be shown until now + minDelayBetweenMessage
*/
private void setMessageMinDelayThrottle()
{
Date now = this.talkController.getNow();
this.showMessagesAfterDelay = SwrveHelper.addTimeInterval(now, this.minDelayBetweenMessage, Calendar.SECOND);
this.talkController.setMessageMinDelayThrottle();
}
/**
* Notify that a message was shown to the user.
*
* @param messageFormat SwrveMessageFormat shown to the user.
*/
public void messageWasShownToUser(SwrveMessageFormat messageFormat) {
incrementImpressions();
setMessageMinDelayThrottle();
// Set next message to be shown
if (!isRandomOrder()) {
int nextMessage = (getNext() + 1) % getMessages().size();
setNext(nextMessage);
Log.i(LOG_TAG, "Round Robin: Next message in campaign " + getId() + " is " + nextMessage);
} else {
Log.i(LOG_TAG, "Next message in campaign " + getId() + " is random");
}
}
/**
* Notify that a message was dismissed.
*/
public void messageDismissed() {
setMessageMinDelayThrottle();
}
}
| {
"content_hash": "b19434aa93c55e8d05459321005a2e38",
"timestamp": "",
"source": "github",
"line_count": 506,
"max_line_length": 164,
"avg_line_length": 33.36166007905138,
"alnum_prop": 0.6257923108820568,
"repo_name": "leandroz/cordova-swrve",
"id": "4c03a76ce935861848e7e8bb717a7cd3f396f04a",
"size": "16881",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/android/Swrve_Android_SDK/SwrveCommonSDK/src/main/java/com/swrve/sdk/messaging/SwrveCampaign.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "353"
},
{
"name": "Java",
"bytes": "322589"
},
{
"name": "JavaScript",
"bytes": "480"
},
{
"name": "Objective-C",
"bytes": "348817"
},
{
"name": "Ruby",
"bytes": "709"
}
],
"symlink_target": ""
} |
require 'spec_helper'
RSpec.describe Gitlab::Gpg::Commit do
describe '#signature' do
shared_examples 'returns the cached signature on second call' do
it 'returns the cached signature on second call' do
gpg_commit = described_class.new(commit)
expect(gpg_commit).to receive(:using_keychain).and_call_original
gpg_commit.signature
# consecutive call
expect(gpg_commit).not_to receive(:using_keychain).and_call_original
gpg_commit.signature
end
end
let!(:project) { create :project, :repository, path: 'sample-project' }
let!(:commit_sha) { '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }
context 'unsigned commit' do
let!(:commit) { create :commit, project: project, sha: commit_sha }
it 'returns nil' do
expect(described_class.new(commit).signature).to be_nil
end
end
context 'invalid signature' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User1.emails.first }
let!(:user) { create(:user, email: GpgHelpers::User1.emails.first) }
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
# Corrupt the key
GpgHelpers::User1.signed_commit_signature.tr('=', 'a'),
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns nil' do
expect(described_class.new(commit).signature).to be_nil
end
end
context 'known key' do
context 'user matches the key uid' do
context 'user email matches the email committer' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User1.emails.first }
let!(:user) { create(:user, email: GpgHelpers::User1.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns a valid signature' do
signature = described_class.new(commit).signature
expect(signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'verified'
)
expect(signature.persisted?).to be_truthy
end
it_behaves_like 'returns the cached signature on second call'
context 'read-only mode' do
before do
allow(Gitlab::Database).to receive(:read_only?).and_return(true)
end
it 'does not create a cached signature' do
signature = described_class.new(commit).signature
expect(signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'verified'
)
expect(signature.persisted?).to be_falsey
end
end
end
context 'valid key signed using recent version of Gnupg' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User1.emails.first }
let!(:user) { create(:user, email: GpgHelpers::User1.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
let!(:crypto) { instance_double(GPGME::Crypto) }
before do
fake_signature = [
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(fake_signature)
end
it 'returns a valid signature' do
verified_signature = double('verified-signature', fingerprint: GpgHelpers::User1.fingerprint, valid?: true)
allow(GPGME::Crypto).to receive(:new).and_return(crypto)
allow(crypto).to receive(:verify).and_return(verified_signature)
signature = described_class.new(commit).signature
expect(signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'verified'
)
end
end
context 'valid key signed using older version of Gnupg' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User1.emails.first }
let!(:user) { create(:user, email: GpgHelpers::User1.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
let!(:crypto) { instance_double(GPGME::Crypto) }
before do
fake_signature = [
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(fake_signature)
end
it 'returns a valid signature' do
keyid = GpgHelpers::User1.fingerprint.last(16)
verified_signature = double('verified-signature', fingerprint: keyid, valid?: true)
allow(GPGME::Crypto).to receive(:new).and_return(crypto)
allow(crypto).to receive(:verify).and_return(verified_signature)
signature = described_class.new(commit).signature
expect(signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'verified'
)
end
end
context 'commit signed with a subkey' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User3.emails.first }
let!(:user) { create(:user, email: GpgHelpers::User3.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User3.public_key, user: user
end
let(:gpg_key_subkey) do
gpg_key.subkeys.find_by(fingerprint: GpgHelpers::User3.subkey_fingerprints.last)
end
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User3.signed_commit_signature,
GpgHelpers::User3.signed_commit_base_data
]
)
end
it 'returns a valid signature' do
expect(described_class.new(commit).signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key_subkey,
gpg_key_primary_keyid: gpg_key_subkey.keyid,
gpg_key_user_name: GpgHelpers::User3.names.first,
gpg_key_user_email: GpgHelpers::User3.emails.first,
verification_status: 'verified'
)
end
it_behaves_like 'returns the cached signature on second call'
end
context 'user email does not match the committer email, but is the same user' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User2.emails.first }
let(:user) do
create(:user, email: GpgHelpers::User1.emails.first).tap do |user|
create :email, user: user, email: GpgHelpers::User2.emails.first
end
end
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns an invalid signature' do
expect(described_class.new(commit).signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'same_user_different_email'
)
end
it_behaves_like 'returns the cached signature on second call'
end
context 'user email does not match the committer email' do
let!(:commit) { create :commit, project: project, sha: commit_sha, committer_email: GpgHelpers::User2.emails.first }
let(:user) { create(:user, email: GpgHelpers::User1.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns an invalid signature' do
expect(described_class.new(commit).signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'other_user'
)
end
it_behaves_like 'returns the cached signature on second call'
end
end
context 'user does not match the key uid' do
let!(:commit) { create :commit, project: project, sha: commit_sha }
let(:user) { create(:user, email: GpgHelpers::User2.emails.first) }
let!(:gpg_key) do
create :gpg_key, key: GpgHelpers::User1.public_key, user: user
end
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns an invalid signature' do
expect(described_class.new(commit).signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: gpg_key,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: GpgHelpers::User1.names.first,
gpg_key_user_email: GpgHelpers::User1.emails.first,
verification_status: 'unverified_key'
)
end
it_behaves_like 'returns the cached signature on second call'
end
end
context 'unknown key' do
let!(:commit) { create :commit, project: project, sha: commit_sha }
before do
allow(Gitlab::Git::Commit).to receive(:extract_signature_lazily)
.with(Gitlab::Git::Repository, commit_sha)
.and_return(
[
GpgHelpers::User1.signed_commit_signature,
GpgHelpers::User1.signed_commit_base_data
]
)
end
it 'returns an invalid signature' do
expect(described_class.new(commit).signature).to have_attributes(
commit_sha: commit_sha,
project: project,
gpg_key: nil,
gpg_key_primary_keyid: GpgHelpers::User1.primary_keyid,
gpg_key_user_name: nil,
gpg_key_user_email: nil,
verification_status: 'unknown_key'
)
end
it_behaves_like 'returns the cached signature on second call'
end
context 'multiple commits with signatures' do
let(:first_signature) { create(:gpg_signature) }
let(:gpg_key) { create(:gpg_key, key: GpgHelpers::User2.public_key) }
let(:second_signature) { create(:gpg_signature, gpg_key: gpg_key) }
let!(:first_commit) { create(:commit, project: project, sha: first_signature.commit_sha) }
let!(:second_commit) { create(:commit, project: project, sha: second_signature.commit_sha) }
let(:commits) do
[first_commit, second_commit].map do |commit|
gpg_commit = described_class.new(commit)
allow(gpg_commit).to receive(:has_signature?).and_return(true)
gpg_commit
end
end
it 'does an aggregated sql request instead of 2 separate ones' do
recorder = ActiveRecord::QueryRecorder.new do
commits.each(&:signature)
end
expect(recorder.count).to eq(1)
end
end
end
end
| {
"content_hash": "6463bc080c9328633b824fd92dd2a76a",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 126,
"avg_line_length": 36.30099502487562,
"alnum_prop": 0.5788391694648118,
"repo_name": "mmkassem/gitlabhq",
"id": "55102554508a7ef38763137d6ceabeb5e6cc2101",
"size": "14624",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/lib/gitlab/gpg/commit_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113683"
},
{
"name": "CoffeeScript",
"bytes": "139197"
},
{
"name": "Cucumber",
"bytes": "119759"
},
{
"name": "HTML",
"bytes": "447030"
},
{
"name": "JavaScript",
"bytes": "29805"
},
{
"name": "Ruby",
"bytes": "2417833"
},
{
"name": "Shell",
"bytes": "14336"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v6.1.0: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v6.1.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1HeapGraphNode.html">HeapGraphNode</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::HeapGraphNode Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#ac3435611573e58b6614aeaab68442905">GetChild</a>(int index) const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#a0a49abe006755dd5536d15ae42f552d4">GetChildrenCount</a>() const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#a0faf2a07888af9ca938b3ac089500b4c">GetId</a>() const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#afd02d17040ae74f40d60d921795aacdb">GetName</a>() const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#a5f6f1e87efce0b297c3ffad0b50f34d5">GetShallowSize</a>() const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html#a5e07fc855bded52229e62b855fa08c5d">GetType</a>() const </td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kArray</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kClosure</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kCode</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kConsString</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kHeapNumber</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kHidden</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kNative</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kObject</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kRegExp</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kSimdValue</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kSlicedString</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kString</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kSymbol</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kSynthetic</b> enum value (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Type</b> enum name (defined in <a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a>)</td><td class="entry"><a class="el" href="classv8_1_1HeapGraphNode.html">v8::HeapGraphNode</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "f162b7dcd74bed2bc77835ef3819d38e",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 300,
"avg_line_length": 81.46456692913385,
"alnum_prop": 0.6742702493717379,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "c21fc5684462cdbe2b281121369cb60e5d72ae2d",
"size": "10346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "65b6574/html/classv8_1_1HeapGraphNode-members.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.navercorp.pinpoint.common.server.bo;
import com.navercorp.pinpoint.common.PinpointConstants;
import com.navercorp.pinpoint.common.util.BytesUtils;
import com.navercorp.pinpoint.common.server.util.RowKeyUtils;
import com.navercorp.pinpoint.common.util.TimeUtils;
/**
* @author emeroad
* @author jaehong.kim
*/
public class ApiMetaDataBo {
private String agentId;
private long startTime;
private int apiId;
private String apiInfo;
private int lineNumber = -1;
private MethodTypeEnum methodTypeEnum = MethodTypeEnum.DEFAULT;
public ApiMetaDataBo() {
}
public ApiMetaDataBo(String agentId, long startTime, int apiId) {
if (agentId == null) {
throw new NullPointerException("agentId must not be null");
}
this.agentId = agentId;
this.startTime = startTime;
this.apiId = apiId;
}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public int getApiId() {
return apiId;
}
public void setApiId(int apiId) {
this.apiId = apiId;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public String getApiInfo() {
return apiInfo;
}
public void setApiInfo(String apiInfo) {
this.apiInfo = apiInfo;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public MethodTypeEnum getMethodTypeEnum() {
return methodTypeEnum;
}
public void setMethodTypeEnum(MethodTypeEnum methodTypeEnum) {
if (methodTypeEnum == null) {
throw new NullPointerException("methodTypeEnum must not be null");
}
this.methodTypeEnum = methodTypeEnum;
}
public String getDescription() {
if (lineNumber != -1) {
return apiInfo + ":" + lineNumber;
}
return apiInfo;
}
public void readRowKey(byte[] bytes) {
this.agentId = BytesUtils.safeTrim(BytesUtils.toString(bytes, 0, PinpointConstants.AGENT_NAME_MAX_LEN));
this.startTime = TimeUtils.recoveryTimeMillis(readTime(bytes));
this.apiId = readKeyCode(bytes);
}
private static long readTime(byte[] rowKey) {
return BytesUtils.bytesToLong(rowKey, PinpointConstants.AGENT_NAME_MAX_LEN);
}
private static int readKeyCode(byte[] rowKey) {
return BytesUtils.bytesToInt(rowKey, PinpointConstants.AGENT_NAME_MAX_LEN + BytesUtils.LONG_BYTE_LENGTH);
}
public byte[] toRowKey() {
return RowKeyUtils.getMetaInfoRowKey(this.agentId, this.startTime, this.apiId);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ApiMetaDataBo{");
sb.append("agentId='").append(agentId).append('\'');
sb.append(", startTime=").append(startTime);
sb.append(", apiId=").append(apiId);
sb.append(", apiInfo='").append(apiInfo).append('\'');
sb.append(", lineNumber=").append(lineNumber);
sb.append(", methodTypeEnum=").append(methodTypeEnum);
sb.append('}');
return sb.toString();
}
} | {
"content_hash": "675d7f7b3b7a20e56329b6e11f53282b",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 113,
"avg_line_length": 26.566929133858267,
"alnum_prop": 0.6387077652637818,
"repo_name": "barneykim/pinpoint",
"id": "09f667eaba9cb6e0ff1329b5c68e250ebd4cea52",
"size": "3968",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApiMetaDataBo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23110"
},
{
"name": "CSS",
"bytes": "534460"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "783305"
},
{
"name": "Java",
"bytes": "16344627"
},
{
"name": "JavaScript",
"bytes": "4821525"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "31363"
},
{
"name": "TSQL",
"bytes": "4316"
},
{
"name": "Thrift",
"bytes": "15284"
},
{
"name": "TypeScript",
"bytes": "1384337"
}
],
"symlink_target": ""
} |
from bilanci.tree_dict_models import deep_sum
from bilanci.utils import couch, nearly_equal
from bilanci.utils.comuni import FLMapper
from django.test import TestCase
from django.core.management import BaseCommand
from django.conf import settings
from collections import OrderedDict
from optparse import make_option
import logging
__author__ = 'guglielmo'
class Command(BaseCommand, TestCase):
option_list = BaseCommand.option_list + (
make_option('--years',
dest='years',
default='',
help='Years to fetch. From 2002 to 2012. Use one of this formats: 2012 or 2003-2006 or 2002,2004,2006'),
make_option('--cities',
dest='cities',
default='',
help='Cities codes or slugs. Use comma to separate values: Roma,Napoli,Torino or "All"'),
make_option('--couchdb-server',
dest='couchdb_server',
default=settings.COUCHDB_DEFAULT_SERVER,
help='CouchDB server to connect to (defaults to staging).'),
)
help = 'Verify the bilanci_simple values and sums.'
logger = logging.getLogger('management')
comuni_dicts = {}
def handle(self, *args, **options):
verbosity = options['verbosity']
if verbosity == '0':
self.logger.setLevel(logging.ERROR)
elif verbosity == '1':
self.logger.setLevel(logging.WARNING)
elif verbosity == '2':
self.logger.setLevel(logging.INFO)
elif verbosity == '3':
self.logger.setLevel(logging.DEBUG)
cities_codes = options['cities']
if not cities_codes:
raise Exception("Missing city parameter")
mapper = FLMapper()
cities = mapper.get_cities(cities_codes)
if cities_codes.lower() != 'all':
self.logger.info("Processing cities: {0}".format(cities))
years = options['years']
if not years:
raise Exception("Missing years parameter")
if "-" in years:
(start_year, end_year) = years.split("-")
years = range(int(start_year), int(end_year)+1)
else:
years = [int(y.strip()) for y in years.split(",") if 2001 < int(y.strip()) < 2014]
if not years:
raise Exception("No suitable year found in {0}".format(years))
self.logger.info("Processing years: {0}".format(years))
couchdb_server_name = options['couchdb_server']
if couchdb_server_name not in settings.COUCHDB_SERVERS:
raise Exception("Unknown couchdb server name.")
###
# Couchdb connections
###
couchdb_server_alias = options['couchdb_server']
if couchdb_server_alias not in settings.COUCHDB_SERVERS:
raise Exception("Unknown couchdb server alias.")
# hook to simple DB
simple_db_name = 'bilanci_simple'
simple_db = couch.connect(
simple_db_name,
couchdb_server_settings=settings.COUCHDB_SERVERS[couchdb_server_alias]
)
self.logger.info("Hooked to simple DB: {0}".format(simple_db_name))
# hook to normalized DB (for comparisons)
norm_db_name = 'bilanci_voci'
norm_db = couch.connect(
norm_db_name,
couchdb_server_settings=settings.COUCHDB_SERVERS[couchdb_server_alias]
)
self.logger.info("Hooked to normalized DB: {0}".format(norm_db_name))
entrate_sections = OrderedDict([
('Accertamenti', 0),
('Riscossioni in conto competenza', 1),
('Riscossioni in conto residui', 2),
])
spese_sections = OrderedDict([
('Impegni', 0),
('Pagamenti in conto competenza', 1),
('Pagamenti in conto residui', 2),
])
# totali_* will hold a list of all voices to be compared
# norm refers to the normalized tree
# simp refers to the simple tree
totali_preventivo_entrate = [
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-tributarie',
'data', 'totale titolo i', 0),
'simp': ('preventivo', 'ENTRATE', 'Imposte e tasse', 'TOTALE')},
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-derivanti-da-contributi-e-trasferimenti-correnti-dello-stato-della-regione-e-di-altri-enti-pubblici-anche-in-rapporto-funzioni-delegate-dalla-regione',
'data', 'totale titolo ii', 0),
'simp': ('preventivo', 'ENTRATE', 'Contributi pubblici', 'TOTALE')},
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-extratributarie',
'data', 'totale titolo iii', 0),
'simp': ('preventivo', 'ENTRATE', 'Entrate extratributarie', 'TOTALE')},
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-derivanti-da-alienazione-da-trasferimenti-di-capitali-e-da-riscossioni-di-crediti',
'data', 'totale titolo iv', 0),
'simp': ('preventivo', 'ENTRATE', 'Vendite e trasferimenti di capitali', 'TOTALE')},
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-derivanti-da-accensioni-di-prestiti',
'data', 'totale titolo v', 0),
'simp': ('preventivo', 'ENTRATE', 'Prestiti')},
{'norm': ('preventivo', '02',
'quadro-2-entrate-entrate-derivanti-da-servizi-per-conto-di-terzi',
'data', 'totale titolo vi', 0),
'simp': ('preventivo', 'ENTRATE', 'Entrate per conto terzi')},
]
totali_consuntivo_entrate = []
for section_name, section_idx in entrate_sections.items():
totali_consuntivo_entrate.extend([
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-i-entrate-tributarie',
'data', 'totale entrate tributarie', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Imposte e tasse', 'TOTALE')},
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-ii-entrate-derivanti-da-contributi-e-trasferimenti-correnti',
'data', 'totale entrate derivanti da contributi e trasferimenti correnti', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Contributi pubblici', 'TOTALE')},
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-iii-entrate-extratributarie',
'data', 'totale entrate extratributarie', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Entrate extratributarie', 'TOTALE')},
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-iv-entrate-derivanti-da-alienazione-da-trasfer-di-capitali-e-da-riscossioni-di-crediti',
'data', 'totale entrate derivanti da alienazione, trasferimenti di capitali e da riscossioni di crediti', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Vendite e trasferimenti di capitali', 'TOTALE')},
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-v-entrate-derivanti-da-accensione-di-prestiti',
'data', 'totale entrate derivanti da accensione di prestiti', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Prestiti')},
{'norm': ('consuntivo', '02',
'quadro-2-entrate-titolo-vi-entrate-da-servizi-per-conto-di-terzi',
'data', 'totale entrate da servizi per conto di terzi', section_idx),
'simp': ('consuntivo', 'ENTRATE', section_name, 'Entrate per conto terzi')},
])
totali_consuntivo_spese = []
# quadro 3
# section_name and section_idx contains the Impegni/Competenze/Residui name and indexes
for section_name, section_idx in spese_sections.items():
totali_consuntivo_spese.extend([
{'norm': ('consuntivo', '03',
'quadro-3-riepilogo-generale-delle-spese',
'data', 'totale generale delle spese', section_idx),
'simp': ('consuntivo', 'SPESE', section_name, 'TOTALE')},
{'norm': ('consuntivo', '03',
'quadro-3-riepilogo-generale-delle-spese',
'data', 'titolo i - spese correnti', section_idx),
'simp': ('consuntivo', 'SPESE', section_name, 'Spese correnti', 'TOTALE')},
{'norm': ('consuntivo', '03',
'quadro-3-riepilogo-generale-delle-spese',
'data', 'titolo ii - spese in c/capitale', section_idx),
'simp': ('consuntivo', 'SPESE', section_name, 'Spese per investimenti', 'TOTALE')},
{'norm': ('consuntivo', '03',
'quadro-3-riepilogo-generale-delle-spese',
'data', 'titolo iii - spese per rimborso di prestiti', section_idx),
'simp': ('consuntivo', 'SPESE', section_name, 'Prestiti')},
{'norm': ('consuntivo', '03',
'quadro-3-riepilogo-generale-delle-spese',
'data', 'titolo iv - spese per servirzi per conto di terzi', section_idx),
'simp': ('consuntivo', 'SPESE', section_name, 'Spese per conto terzi')},
])
# quadro 4
totali_consuntivo_spese.extend([
{'norm': ('consuntivo', '04',
'quadro-4-a-impegni',
'data', 'totale', -1),
'simp': ('consuntivo', 'SPESE', 'Impegni', 'Spese correnti', 'TOTALE')},
{'norm': ('consuntivo', '04',
'quadro-4-b-pagamenti-in-conto-competenza',
'data', 'totali', -1),
'simp': ('consuntivo', 'SPESE', 'Pagamenti in conto competenza', 'Spese correnti', 'TOTALE')},
{'norm': ('consuntivo', '04',
'quadro-4-c-pagamenti-in-conto-residui',
'data', 'totali', -1),
'simp': ('consuntivo', 'SPESE', 'Pagamenti in conto residui', 'Spese correnti', 'TOTALE')},
])
# quadro 5
totali_consuntivo_spese.extend([
{'norm': ('consuntivo', '05',
'quadro-5-a-impegni',
'data', 'totale', -1),
'simp': ('consuntivo', 'SPESE', 'Impegni', 'Spese per investimenti', 'TOTALE')},
{'norm': ('consuntivo', '05',
'quadro-5-b-pagamenti-in-conto-competenza',
'data', 'totale', -1),
'simp': ('consuntivo', 'SPESE', 'Pagamenti in conto competenza', 'Spese per investimenti', 'TOTALE')},
{'norm': ('consuntivo', '05',
'quadro-5-c-pagamenti-in-conto-residui',
'data', 'totale', -1),
'simp': ('consuntivo', 'SPESE', 'Pagamenti in conto residui', 'Spese per investimenti', 'TOTALE')},
])
somme_consuntivo_nodes = []
for section_name in entrate_sections.keys():
somme_consuntivo_nodes.extend([
('consuntivo', 'ENTRATE', section_name, 'Imposte e tasse'),
('consuntivo', 'ENTRATE', section_name, 'Imposte e tasse', 'Imposte'),
('consuntivo', 'ENTRATE', section_name, 'Imposte e tasse', 'Tasse'),
('consuntivo', 'ENTRATE', section_name, 'Contributi pubblici'),
('consuntivo', 'ENTRATE', section_name, 'Entrate extratributarie'),
('consuntivo', 'ENTRATE', section_name, 'Entrate extratributarie', 'Servizi pubblici'),
('consuntivo', 'ENTRATE', section_name, 'Entrate extratributarie', 'Proventi di beni dell\'ente'),
('consuntivo', 'ENTRATE', section_name, 'Vendite e trasferimenti di capitali'),
('consuntivo', 'ENTRATE', section_name, 'Vendite e trasferimenti di capitali', 'Trasferimenti di capitali da privati'),
])
somme_preventivo_nodes = [
('preventivo', 'ENTRATE', 'Imposte e tasse'),
('preventivo', 'ENTRATE', 'Imposte e tasse', 'Imposte'),
('preventivo', 'ENTRATE', 'Imposte e tasse', 'Tasse'),
('preventivo', 'ENTRATE', 'Contributi pubblici'),
('preventivo', 'ENTRATE', 'Entrate extratributarie'),
('preventivo', 'ENTRATE', 'Vendite e trasferimenti di capitali'),
]
for city in cities:
for year in years:
self.logger.info("Processing city of {0}, year {1}".format(
city, year
))
code = "{}_{}".format(year, city)
norm_doc_id = "{}_{}".format(year, city)
simple_doc_id = city
# both documents need to exist in the dbs
self.assertTrue(self.test_couch_doc_exists(norm_db, norm_doc_id),
"Could not find {}".format(norm_doc_id))
self.assertTrue(self.test_couch_doc_exists(simple_db, simple_doc_id))
norm_doc = norm_db[norm_doc_id]
simple_doc = simple_db[simple_doc_id]
# preventivo tests
if len(simple_doc[str(year)]['preventivo'].keys()) > 0:
self.logger.debug("::::: Testing first level totals for preventivo entrate")
self.test_totali(totali_preventivo_entrate, simple_doc, norm_doc, year)
self.logger.debug("::::: Testing totale - funzioni - interventi for preventivo/spese")
for tipo_spese in (u'Spese correnti', u'Spese per investimenti'):
node = simple_doc[str(year)]['preventivo']['SPESE'][tipo_spese]
label = u"/Preventivo/{0}".format(tipo_spese)
self.test_totale_funzioni_interventi(label, node, year)
self.logger.debug("::::: Testing inner sums for preventivo entrate")
self.test_somme(somme_preventivo_nodes, simple_doc, year)
# consuntivo tests
if len(simple_doc[str(year)]['consuntivo'].keys()) > 0:
self.logger.debug("::::: Testing first level totals for consuntivo entrate")
self.test_totali(totali_consuntivo_entrate, simple_doc, norm_doc, year)
self.logger.debug("::::: Testing first level totals for consuntivo spese")
self.test_totali(totali_consuntivo_spese, simple_doc, norm_doc, year)
self.logger.debug("::::: Testing totale - funzioni - interventi for consuntivo/spese")
for section_name in spese_sections.keys():
for tipo_spese in ('Spese correnti', 'Spese per investimenti'):
node = simple_doc[str(year)]['consuntivo']['SPESE'][section_name][tipo_spese]
label = u"/Consuntivo/{0}/{1}".format(section_name, tipo_spese)
self.test_totale_funzioni_interventi(label, node, year)
self.logger.debug("::::: Testing inner sums for consuntivo entrate")
self.test_somme(somme_consuntivo_nodes, simple_doc, year)
###
# TESTS
###
def test_couch_doc_exists(self, couch_db, doc_id):
"""
couch db connection is correct and document exists
"""
return doc_id in couch_db
###
# totals for first level sections in normalized and
# simplified trees are compared
###
def test_totali(self, totali, simple_doc, norm_doc, year):
"""
totals for 1st level sections of the preventivo/entrate in the normalized tree (quadro 2)
are compared with the corresponding values in the simplified tree
"""
for tot in totali:
# extract year section from the simple doc (simple docs contain all years)
tot_simp = simple_doc[str(year)]
tot_norm = norm_doc
# drill through the tree to fetch the leaf value in tot['simp']
for t in tot['simp']:
tot_simp = tot_simp[t]
# drill through the tree to fetch the leaf value in tot['simp']
# catch exception om totale/totali, trying both before failing
# in the normalized tree
for t in tot['norm']:
if t == 'totale':
try:
tot_norm = tot_norm['totale']
except KeyError:
try:
tot_norm = tot_norm['totali']
except KeyError:
# log a warning and break away from the inner for loop
# do not execute the else section
self.logger.warning(
"totale/i key not found in bilanci_voce. node: {0}".format(
tot['norm']
)
)
break
else:
tot_norm = tot_norm[t]
else:
# transform the string representation in the normalized doc,
# into an integer (used in the simplified doc)
# so that the comparison is possible
if tot_norm != '':
tot_norm = int(round(float(tot_norm.replace('.', '').replace(',','.'))))
else:
tot_norm = 0
if tot_simp != tot_norm:
self.logger.warning("Totals are different.\n\tnorm val:{0}, node: {1}\n\tsimp val:{2}, node: {3}".format(
tot_norm, tot['norm'],
tot_simp, tot['simp'],
))
###
# sum of funzioni, interventi and the explicit totals in
# the simplified tree are compared
###
def test_totale_funzioni_interventi(self, simple_tree_label, simple_tree_node, year):
totale = simple_tree_node['TOTALE']
somma_funzioni = deep_sum(simple_tree_node['funzioni'])
somma_interventi = deep_sum(simple_tree_node['interventi'])
if self.nearly_equal(totale, somma_interventi) and \
self.nearly_equal(totale, somma_funzioni):
self.logger.debug(u"node: {0}. OK. totale: {1}".format(
simple_tree_label, totale
))
else:
self.logger.warning(u"\nnode: {0}. NOT OK.\n totale:\t\t {1}\n somma_funzioni:\t {2}\n somma_interventi:\t {3}".format(
simple_tree_label, totale, somma_funzioni, somma_interventi
))
# dump non-matching details to logger
if not self.nearly_equal(totale, somma_funzioni):
_ = deep_sum(simple_tree_node['funzioni'], logger=self.logger)
if not self.nearly_equal(totale, somma_interventi):
_ = deep_sum(simple_tree_node['interventi'], logger=self.logger)
###
# first level explicit totals and sums of underlying sections
# in the simplified tree are compared (consistency test)
###
def test_somme(self, nodes, simple_doc, year):
"""
Tests the sum of sections of the tree, against the totals.
This verifies the consistency of the simplified tree,
and, indirectly, the completeness and correctness of the
data fetched from the normalized tree.
"""
test_results = OrderedDict()
for node in nodes:
node_path = u"/{0}/../{1}".format(node[0], node[-1])
simp = simple_doc[str(year)]
for t in node:
simp = simp[t]
somma = deep_sum(simp)
totale = simp['TOTALE']
test_results[node[-1]] = (totale == somma)
if self.nearly_equal(totale, somma):
self.logger.debug(u"node: {0}. OK. totale: {1}".format(
node_path, totale
))
else:
self.logger.warning(u"node: {0}. NOT OK. totale: {1}. somma: {2}".format(
node_path, totale, somma
))
# dump non-matching details to logger
if not self.nearly_equal(totale, somma):
_ = deep_sum(simp, logger=self.logger)
def nearly_equal(self, a, b):
"""
Return true if the numbers are equals or close matches
"""
return nearly_equal(a, b, threshold=settings.NEARLY_EQUAL_THRESHOLD) | {
"content_hash": "564c55a3bf2e0fe47cd53c0bd79db39f",
"timestamp": "",
"source": "github",
"line_count": 447,
"max_line_length": 199,
"avg_line_length": 46.982102908277405,
"alnum_prop": 0.5337364887386314,
"repo_name": "DeppSRL/open_bilanci",
"id": "f211fdadcfdfb098605f027d557a031674bd5f8c",
"size": "21001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bilanci_project/bilanci/management/commands/verify_simple.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "614"
},
{
"name": "CSS",
"bytes": "260422"
},
{
"name": "HTML",
"bytes": "461273"
},
{
"name": "JavaScript",
"bytes": "68685"
},
{
"name": "Makefile",
"bytes": "515"
},
{
"name": "Nginx",
"bytes": "675"
},
{
"name": "PHP",
"bytes": "2274"
},
{
"name": "Python",
"bytes": "638816"
},
{
"name": "Shell",
"bytes": "678328"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/gurtowskij/variation)
# variation
---
This is the basic readme for this module. Include any usage or deployment instructions and links to other documentation here. | {
"content_hash": "d66446d151e3ad50c2e18cd831f40c78",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 125,
"avg_line_length": 44.5,
"alnum_prop": 0.7827715355805244,
"repo_name": "kbaseIncubator/variation",
"id": "a1ce1c64ef124cf8dc3038b4c1bd2303d15e8be0",
"size": "267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "7950"
},
{
"name": "JavaScript",
"bytes": "5284"
},
{
"name": "Makefile",
"bytes": "1684"
},
{
"name": "Perl",
"bytes": "10997"
},
{
"name": "Python",
"bytes": "35366"
},
{
"name": "Shell",
"bytes": "1092"
}
],
"symlink_target": ""
} |
#ifndef CDNS_UART_H
#define CDNS_UART_H
#include <types_ext.h>
void cdns_uart_init(vaddr_t base, uint32_t uart_clk, uint32_t baud_rate);
void cdns_uart_putc(int ch, vaddr_t base);
void cdns_uart_flush(vaddr_t base);
bool cdns_uart_have_rx_data(vaddr_t base);
int cdns_uart_getchar(vaddr_t base);
#endif /* CDNS_UART_H */
| {
"content_hash": "7fce97b545dfdb651da150860819f85c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 73,
"avg_line_length": 19.352941176470587,
"alnum_prop": 0.7082066869300911,
"repo_name": "matt2048/optee_os",
"id": "6688fd34284c8e09b19fc200992587bd32fc4d5e",
"size": "1692",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/include/drivers/cdns_uart.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "263165"
},
{
"name": "Awk",
"bytes": "6672"
},
{
"name": "C",
"bytes": "6833507"
},
{
"name": "C++",
"bytes": "58069"
},
{
"name": "Groff",
"bytes": "276147"
},
{
"name": "HTML",
"bytes": "75678"
},
{
"name": "Makefile",
"bytes": "162955"
},
{
"name": "Python",
"bytes": "14335"
}
],
"symlink_target": ""
} |
package com.facebook.common.internal;
import static com.facebook.common.internal.Preconditions.checkNotNull;
import com.facebook.infer.annotation.Nullsafe;
import java.util.Arrays;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* Helper functions that operate on any {@code Object}, and are not already provided in {@link
* java.util.Objects}.
*
* <p>See the Guava User Guide on <a
* href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object}
* methods with {@code Objects}</a>.
*
* @author Laurence Gonsalves
* @since 18.0 (since 2.0 as {@code Objects})
*/
@Nullsafe(Nullsafe.Mode.STRICT)
public final class Objects {
/**
* Determines whether two possibly-null objects are equal. Returns:
*
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are equal according to
* {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
*
* <p>This assumes that any non-null objects passed to this function conform to the {@code
* equals()} contract.
*/
@CheckReturnValue
public static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by calling {@link
* Arrays#hashCode(Object[])}. Note that array arguments to this method, with the exception of a
* single Object array, do not get any special handling; their hash codes are based on identity
* and not contents.
*
* <p>This is useful for implementing {@link Object#hashCode()}. For example, in an object that
* has three properties, {@code x}, {@code y}, and {@code z}, one could write:
*
* <pre>{@code
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }
* }</pre>
*
* <p><b>Warning</b>: When a single object is supplied, the returned hash code does not equal the
* hash code of that object.
*/
public static int hashCode(@Nullable Object... objects) {
return Arrays.hashCode(objects);
}
/**
* Creates an instance of {@link ToStringHelper}.
*
* <p>This is helpful for implementing {@link Object#toString()}. Specification by example:
*
* <pre>{@code
* // Returns "ClassName{}"
* Objects.toStringHelper(this)
* .toString();
*
* // Returns "ClassName{x=1}"
* Objects.toStringHelper(this)
* .add("x", 1)
* .toString();
*
* // Returns "MyObject{x=1}"
* Objects.toStringHelper("MyObject")
* .add("x", 1)
* .toString();
*
* // Returns "ClassName{x=1, y=foo}"
* Objects.toStringHelper(this)
* .add("x", 1)
* .add("y", "foo")
* .toString();
*
* // Returns "ClassName{x=1}"
* Objects.toStringHelper(this)
* .omitNullValues()
* .add("x", 1)
* .add("y", null)
* .toString();
* }</pre>
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param self the object to generate the string for (typically {@code this}), used only for its
* class name
* @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Object self) {
return new ToStringHelper(self.getClass().getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
* instance's {@link Object#getClass()}.
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param clazz the {@link Class} of the instance
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Class<?> clazz) {
return new ToStringHelper(clazz.getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
* Object#getClass()}.
*
* @param className the name of the instance type
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(String className) {
return new ToStringHelper(className);
}
/**
* Returns the first of two given parameters that is not {@code null}, if either is, or otherwise
* throws a {@link NullPointerException}.
*
* <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be
* accomplished with {@linkplain Optional#or(Object) first.or(second)}. That approach also allows
* for lazy evaluation of the fallback instance, using {@linkplain Optional#or(Supplier)
* first.or(Supplier)}.
*
* @return {@code first} if {@code first} is not {@code null}, or {@code second} if {@code first}
* is {@code null} and {@code second} is not {@code null}
* @throws NullPointerException if both {@code first} and {@code second} were {@code null}
* @since 3.0
*/
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
return first != null ? first : checkNotNull(second);
}
/**
* Support class for {@link Objects#toStringHelper}.
*
* @author Jason Lee
* @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
*/
public static final class ToStringHelper {
private final String className;
private final ValueHolder holderHead = new ValueHolder();
private ValueHolder holderTail = holderHead;
private boolean omitNullValues = false;
/** Use {@link Objects#toStringHelper(Object)} to create an instance. */
private ToStringHelper(String className) {
this.className = checkNotNull(className);
}
/**
* Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null
* value. The order of calling this method, relative to the {@code add()}/{@code addValue()}
* methods, is not significant.
*
* @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
*/
public ToStringHelper omitNullValues() {
omitNullValues = true;
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value}
* is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is
* called, in which case this name/value pair will not be added.
*/
public ToStringHelper add(String name, @Nullable Object value) {
return addHolder(name, value);
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, boolean value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, char value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, double value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, float value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, int value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
public ToStringHelper add(String name, long value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, Object)} instead and give value a
* readable name.
*/
public ToStringHelper addValue(@Nullable Object value) {
return addHolder(value);
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(boolean value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, char)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(char value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, double)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(double value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, float)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(float value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, int)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(int value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, long)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
public ToStringHelper addValue(long value) {
return addHolder(String.valueOf(value));
}
/**
* Returns a string in the format specified by {@link Objects#toStringHelper(Object)}.
*
* <p>After calling this method, you can keep adding more properties to later call toString()
* again and get a more complete representation of the same object; but properties cannot be
* removed, so this only allows limited reuse of the helper instance. The helper allows
* duplication of properties (multiple name/value pairs with the same name can be added).
*/
@Override
public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className).append('{');
for (ValueHolder valueHolder = holderHead.next;
valueHolder != null;
valueHolder = valueHolder.next) {
Object value = valueHolder.value;
if (!omitNullValuesSnapshot || value != null) {
builder.append(nextSeparator);
nextSeparator = ", ";
if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
if (value != null && value.getClass().isArray()) {
Object[] objectArray = {value};
String arrayString = Arrays.deepToString(objectArray);
builder.append(arrayString, 1, arrayString.length() - 1);
} else {
builder.append(value);
}
}
}
return builder.append('}').toString();
}
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
private ToStringHelper addHolder(@Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
private ToStringHelper addHolder(String name, @Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
private static final class ValueHolder {
@Nullable String name;
@Nullable Object value;
@Nullable ValueHolder next;
}
}
private Objects() {}
}
| {
"content_hash": "a062b852fd4d563b334bc63d1d6c61b0",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 100,
"avg_line_length": 34.21938775510204,
"alnum_prop": 0.6370210228119875,
"repo_name": "facebook/fresco",
"id": "ec0788d3a114584c031a2aea556a3379e3c6bf9c",
"size": "14008",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "fbcore/src/main/java/com/facebook/common/internal/Objects.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "53297"
},
{
"name": "C++",
"bytes": "226393"
},
{
"name": "Java",
"bytes": "3181636"
},
{
"name": "Kotlin",
"bytes": "692238"
},
{
"name": "Makefile",
"bytes": "10780"
},
{
"name": "Python",
"bytes": "10096"
},
{
"name": "Shell",
"bytes": "1516"
}
],
"symlink_target": ""
} |
layout: post
published: true
title: Programming Linear Regression in 2 Variables
mathjax: true
categories:
- mathematics
- machine learning
- statistics
- regression
- python
- numpy
- pandas
- matplotlib
---
<script src="https://gist.github.com/shak360/ab3aa9396f20774a1b3d93b2d9263bce.js"></script>
| {
"content_hash": "831295cdddb501669bf3a981a38488ed",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 91,
"avg_line_length": 21.133333333333333,
"alnum_prop": 0.7413249211356467,
"repo_name": "shak360/shak360.github.io",
"id": "cea8621243b44b05ce36109ff5b6cd6a73270bba",
"size": "321",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2017-08-07-Programming-Linear-Regression-in-2-Variables.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "63525"
},
{
"name": "HTML",
"bytes": "6630"
}
],
"symlink_target": ""
} |
Clazz.declarePackage ("J.image");
Clazz.load (["J.image.JpgEncoder"], "J.image.Jpg64Encoder", ["JU.Base64"], function () {
c$ = Clazz.decorateAsClass (function () {
this.outTemp = null;
Clazz.instantialize (this, arguments);
}, J.image, "Jpg64Encoder", J.image.JpgEncoder);
$_M(c$, "setParams",
function (params) {
this.defaultQuality = 75;
this.outTemp = params.remove ("outputChannelTemp");
Clazz.superCall (this, J.image.Jpg64Encoder, "setParams", [params]);
}, "java.util.Map");
$_M(c$, "generate",
function () {
var out0 = this.out;
this.out = this.outTemp;
Clazz.superCall (this, J.image.Jpg64Encoder, "generate", []);
var bytes = JU.Base64.getBytes64 (this.out.toByteArray ());
this.outTemp = null;
this.out = out0;
this.out.write (bytes, 0, bytes.length);
});
});
| {
"content_hash": "b602fe14543a92f3b0dc8c0bb95b6ff7",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 88,
"avg_line_length": 33.65217391304348,
"alnum_prop": 0.6886304909560723,
"repo_name": "khaliiid/visualizer",
"id": "6c2793b325e5bcfc0333cdf6bc3590a50839de0f",
"size": "774",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/lib/jsmol/j2s/J/image/Jpg64Encoder.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ABAP",
"bytes": "1924"
},
{
"name": "ActionScript",
"bytes": "2266"
},
{
"name": "Assembly",
"bytes": "1012"
},
{
"name": "AutoHotkey",
"bytes": "1440"
},
{
"name": "C",
"bytes": "61363"
},
{
"name": "C#",
"bytes": "166"
},
{
"name": "C++",
"bytes": "26528"
},
{
"name": "CSS",
"bytes": "1342147"
},
{
"name": "Clojure",
"bytes": "1588"
},
{
"name": "CoffeeScript",
"bytes": "10192"
},
{
"name": "ColdFusion",
"bytes": "172"
},
{
"name": "Common Lisp",
"bytes": "1264"
},
{
"name": "DOT",
"bytes": "11820"
},
{
"name": "Dart",
"bytes": "1968"
},
{
"name": "Erlang",
"bytes": "974"
},
{
"name": "Go",
"bytes": "1282"
},
{
"name": "Groovy",
"bytes": "10653"
},
{
"name": "Haskell",
"bytes": "1024"
},
{
"name": "Haxe",
"bytes": "894"
},
{
"name": "Java",
"bytes": "10763"
},
{
"name": "JavaScript",
"bytes": "85419041"
},
{
"name": "Julia",
"bytes": "404"
},
{
"name": "LiveScript",
"bytes": "11494"
},
{
"name": "Lua",
"bytes": "1918"
},
{
"name": "OCaml",
"bytes": "1078"
},
{
"name": "Objective-C",
"bytes": "5344"
},
{
"name": "PHP",
"bytes": "4019023"
},
{
"name": "Pascal",
"bytes": "2824"
},
{
"name": "Perl",
"bytes": "36978"
},
{
"name": "PowerShell",
"bytes": "836"
},
{
"name": "Python",
"bytes": "596530"
},
{
"name": "R",
"bytes": "1336"
},
{
"name": "Ruby",
"bytes": "1062"
},
{
"name": "Rust",
"bytes": "990"
},
{
"name": "Scala",
"bytes": "3082"
},
{
"name": "Scheme",
"bytes": "1118"
},
{
"name": "Shell",
"bytes": "19657"
},
{
"name": "Tcl",
"bytes": "1798"
},
{
"name": "TeX",
"bytes": "2690"
},
{
"name": "TypeScript",
"bytes": "3214"
},
{
"name": "Visual Basic",
"bytes": "1832"
},
{
"name": "XQuery",
"bytes": "228"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>backbone.queryRouter.nested.js</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" media="all" href="../doc-style.css" />
<script src="../doc-filelist.js"></script>
<script>
var relativeDir = "../", thisFile = "src/backbone.queryRouter.nested.js", defaultSidebar = true;
</script>
<script src="../doc-script.js"></script>
</head>
<body>
<div id="sidebar_wrapper">
<div id="sidebar_switch">
<span class="tree">Files</span>
<span class="headings">Headings</span>
</div>
<div id="tree"></div>
<div id="headings">
<div class="heading h2">
<a href="#backbone.queryrouter.nested.js">Backbone.queryRouter.nested.js</a>
</div>
</div>
</div>
<div id="sidebar-toggle"></div>
<div id="container"><div class="background highlight"></div>
<table cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="docs">
<div class="pilwrap" id="backbone.queryrouter.nested.js">
<h2>
<a href="#backbone.queryrouter.nested.js" name="backbone.queryrouter.nested.js" class="pilcrow">¶</a>
Backbone.queryRouter.nested.js
</h2>
</div>
<p>Overrides for handling nested querystrings & nested models.</p>
</td>
<td class="code highlight"><div class="highlight"><pre><a class="line-num" href="#line-3" id="line-3">3</a> <span class="s1">'use strict'</span><span class="p">;</span>
<a class="line-num" href="#line-4" id="line-4">4</a>
<a class="line-num" href="#line-5" id="line-5">5</a> </pre></div>
</td>
</tr>
<tr>
<td class="docs">
<div class="pilwrap">
<a class="pilcrow" href="#section-2" id="section-2">¶</a>
</div>
<p>CommonJS includes. This is a browserify module and will run both inside Node and in the browser.</p>
</td>
<td class="code highlight"><div class="highlight"><pre><a class="line-num" href="#line-6" id="line-6">6</a>
<a class="line-num" href="#line-7" id="line-7">7</a> <span class="kd">var</span> <span class="nx">Backbone</span> <span class="o">=</span> <span class="p">(</span><span class="nb">window</span> <span class="o">&&</span> <span class="nb">window</span><span class="p">.</span><span class="nx">Backbone</span><span class="p">)</span> <span class="o">||</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'backbone'</span><span class="p">);</span>
<a class="line-num" href="#line-8" id="line-8">8</a> <span class="kd">var</span> <span class="nx">_</span> <span class="o">=</span> <span class="p">(</span><span class="nb">window</span> <span class="o">&&</span> <span class="nb">window</span><span class="p">.</span><span class="nx">_</span><span class="p">)</span> <span class="o">||</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'underscore'</span><span class="p">);</span>
<a class="line-num" href="#line-9" id="line-9">9</a> <span class="kd">var</span> <span class="nx">diff</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'deep-diff'</span><span class="p">);</span>
<a class="line-num" href="#line-10" id="line-10">10</a>
<a class="line-num" href="#line-11" id="line-11">11</a>
<a class="line-num" href="#line-12" id="line-12">12</a> </pre></div>
</td>
</tr>
<tr>
<td class="docs">
<div class="pilwrap">
<a class="pilcrow" href="#section-3" id="section-3">¶</a>
</div>
<div class="dox">
<div class="summary"><p>Backbone.History nested support.</p>
</div>
<div class="body">
</div>
<div class="details">
<div class="dox_tag_title">Type</div>
<div class="dox_tag_detail">
<span class="dox_type">Backbone.History
</span>
</div>
</div>
</div>
</td>
<td class="code highlight"><div class="highlight"><pre><a class="line-num" href="#line-14" id="line-14">14</a>
<a class="line-num" href="#line-15" id="line-15">15</a>
<a class="line-num" href="#line-16" id="line-16">16</a>
<a class="line-num" href="#line-17" id="line-17">17</a> </pre></div>
</td>
</tr>
<tr>
<td class="docs">
<div class="pilwrap">
<a class="pilcrow" href="#section-4" id="section-4">¶</a>
</div>
<div class="dox">
<div class="summary"><p>Model emcompassing current query state. You can read and set properties
on this Model and <code>Backbone.history.navigate()</code> will automatically be called.
If Backbone.NestedModel is loaded, it will be used to support nested change events.</p>
</div>
<div class="body">
</div>
<div class="details">
<div class="dox_tag_title">Type</div>
<div class="dox_tag_detail">
<span class="dox_type">Backbone.Model
</span>
</div>
</div>
</div>
</td>
<td class="code highlight"><div class="highlight"><pre><a class="line-num" href="#line-21" id="line-21">21</a>
<a class="line-num" href="#line-22" id="line-22">22</a> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">query</span> <span class="o">=</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">NestedModel</span> <span class="o">?</span>
<a class="line-num" href="#line-23" id="line-23">23</a> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">NestedModel</span><span class="p">()</span> <span class="o">:</span> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">();</span>
<a class="line-num" href="#line-24" id="line-24">24</a> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">query</span><span class="p">.</span><span class="nx">nestedSupport</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<a class="line-num" href="#line-25" id="line-25">25</a> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">_bindToQueryObject</span><span class="p">();</span>
<a class="line-num" href="#line-26" id="line-26">26</a>
<a class="line-num" href="#line-27" id="line-27">27</a>
<a class="line-num" href="#line-28" id="line-28">28</a>
<a class="line-num" href="#line-29" id="line-29">29</a> </pre></div>
</td>
</tr>
<tr>
<td class="docs">
<div class="pilwrap">
<a class="pilcrow" href="#section-5" id="section-5">¶</a>
</div>
<div class="dox">
<div class="summary"><p>Given two objects, compute their differences and list them.
When diffing deep objects, return one string for the object and one for each child.
This allows functions to bind to deep properties or its parent.
E.g. a change to a.b.c returns ['a', 'a.b', 'a.b.c']</p>
</div>
<div class="body"><p>This uses DeepDiff (flitbit/diff), which can detect changes deep within objects.
We don't use objects in querystrings quite yet, but we do arrays. And that might change.</p>
</div>
<div class="details">
<div class="dox_tag_title">Params</div>
<div class="dox_tag_detail">
<span class="dox_tag_name"></span>
<span>{Object} lhs Left hand object.</span>
</div>
<div class="dox_tag_detail">
<span class="dox_tag_name"></span>
<span>{Object} rhs Right hand (new) object.</span>
</div>
<div class="dox_tag_title">Returns</div>
<div class="dox_tag_detail">
<span class="dox_tag_name"></span>
<span class="dox_type">Array</span>
<span>Array of string differences.</span>
</div>
</div>
</div>
</td>
<td class="code highlight"><div class="highlight"><pre><a class="line-num" href="#line-44" id="line-44">44</a>
<a class="line-num" href="#line-45" id="line-45">45</a> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">_getDiffs</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">lhs</span><span class="p">,</span> <span class="nx">rhs</span><span class="p">)</span> <span class="p">{</span>
<a class="line-num" href="#line-46" id="line-46">46</a> <span class="kd">var</span> <span class="nx">diffs</span> <span class="o">=</span> <span class="nx">diff</span><span class="p">(</span><span class="nx">lhs</span><span class="p">,</span> <span class="nx">rhs</span><span class="p">);</span>
<a class="line-num" href="#line-47" id="line-47">47</a> <span class="kd">var</span> <span class="nx">diffKeys</span> <span class="o">=</span> <span class="nx">_</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span><span class="nx">diffs</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">result</span><span class="p">,</span> <span class="nx">diff</span><span class="p">)</span> <span class="p">{</span>
<a class="line-num" href="#line-48" id="line-48">48</a> <span class="kd">var</span> <span class="nx">paths</span> <span class="o">=</span> <span class="nx">_</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">diff</span><span class="p">.</span><span class="nx">path</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">path</span><span class="p">,</span> <span class="nx">i</span><span class="p">)</span> <span class="p">{</span>
<a class="line-num" href="#line-49" id="line-49">49</a> <span class="k">return</span> <span class="nx">_</span><span class="p">.</span><span class="nx">first</span><span class="p">(</span><span class="nx">diff</span><span class="p">.</span><span class="nx">path</span><span class="p">,</span> <span class="nx">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">).</span><span class="nx">join</span><span class="p">(</span><span class="s1">'.'</span><span class="p">);</span>
<a class="line-num" href="#line-50" id="line-50">50</a> <span class="p">});</span>
<a class="line-num" href="#line-51" id="line-51">51</a> <span class="k">return</span> <span class="nx">result</span><span class="p">.</span><span class="nx">concat</span><span class="p">(</span><span class="nx">paths</span><span class="p">);</span>
<a class="line-num" href="#line-52" id="line-52">52</a> <span class="p">},</span> <span class="p">[]);</span>
<a class="line-num" href="#line-53" id="line-53">53</a> <span class="k">return</span> <span class="nx">_</span><span class="p">.</span><span class="nx">uniq</span><span class="p">(</span><span class="nx">diffKeys</span><span class="p">);</span>
<a class="line-num" href="#line-54" id="line-54">54</a> <span class="p">};</span>
<a class="line-num" href="#line-55" id="line-55">55</a> </pre></div>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
| {
"content_hash": "c70eb7ca65956db83932510773967c4e",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 532,
"avg_line_length": 64.7953216374269,
"alnum_prop": 0.6104693140794224,
"repo_name": "STRML/backbone.queryRouter",
"id": "b660d590481630e75253ae6d7efd483422348159",
"size": "11080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/src/backbone.queryRouter.nested.js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11040"
},
{
"name": "CoffeeScript",
"bytes": "17402"
},
{
"name": "JavaScript",
"bytes": "84476"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2014 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
<identity>
<version number="$Revision: 13159 $"/>
<language type="ich"/>
</identity>
<layout>
<orientation>
<characterOrder>left-to-right</characterOrder>
<lineOrder>top-to-bottom</lineOrder>
</orientation>
</layout>
<characters>
<exemplarCharacters draft="unconfirmed">[a á à ā b c d e é è ē ɛ {ɛ\u0301} {ɛ\u0300} {ɛ\u0304} f g {gb} h {hw} {hyw} i í ì ī j k {kp} l m n {ng} {ngm} {ny} o ó ò ō ɔ {ɔ\u0301} {ɔ\u0300} {ɔ\u0304} p r s {sh} t {ts} u ú ù ū v w y z]</exemplarCharacters>
<exemplarCharacters type="auxiliary" draft="unconfirmed">[q x]</exemplarCharacters>
</characters>
</ldml>
| {
"content_hash": "6fec000965a424d4badd90789976edbc",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 253,
"avg_line_length": 41.72727272727273,
"alnum_prop": 0.6710239651416122,
"repo_name": "googlei18n/nototools",
"id": "5ced7dfd74d77d77e73e4cbc2d48ee7b89587887",
"size": "942",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "third_party/cldr/exemplars/main/ich.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "665"
},
{
"name": "HTML",
"bytes": "620"
},
{
"name": "Makefile",
"bytes": "3666"
},
{
"name": "Python",
"bytes": "1158880"
},
{
"name": "Shell",
"bytes": "15227"
}
],
"symlink_target": ""
} |
extern crate ratel;
extern crate iron;
#[macro_use]
extern crate json;
use std::env;
use std::str::FromStr;
use std::net::Ipv4Addr;
use std::io::Read;
use iron::prelude::*;
use iron::{headers, status};
use iron::method::Method;
use iron::middleware::AfterMiddleware;
use ratel::error::ParseError;
const PROTOCOL: &'static str = "http";
const DEFAULT_HOST: &'static str = "0.0.0.0";
const DEFAULT_PORT: u16 = 3000;
struct CorsMiddleware;
impl AfterMiddleware for CorsMiddleware {
fn after(&self, _: &mut Request, mut response: Response) -> IronResult<Response> {
let cors_methods: Vec<Method> = vec![Method::Options, Method::Get, Method::Post];
response.headers.set(headers::AccessControlAllowOrigin::Any);
response.headers.set(headers::AccessControlAllowMethods(cors_methods));
Ok(response)
}
}
fn get_json_response(error_code: iron::status::Status, payload: String) -> IronResult<Response> {
let object = object!{
"success" => error_code == status::Ok,
"result" => payload
};
let mut response: Response = Response::with((error_code, object.dump()));
response.headers.set(headers::ContentType::json());
Ok(response)
}
fn compile(source: String, minify: bool, get_ast: bool) -> Result<String, ParseError> {
let mut ast = match ratel::parser::parse(source) {
Ok(ast) => ast,
Err(error) => return Err(error),
};
let settings = ratel::transformer::Settings::target_es5();
ratel::transformer::transform(&mut ast, settings);
if get_ast {
return Ok(format!("{:#?}", ast));
}
Ok(ratel::codegen::generate_code(&ast, minify))
}
fn main() {
fn handler(req: &mut Request) -> IronResult<Response> {
let mut payload = String::new();
match req.body.read_to_string(&mut payload) {
Ok(_) => {},
Err(_) => return get_json_response(status::BadRequest, "Cannot parse request payload".into())
};
let mut payload = match json::parse(&payload.as_str()) {
Ok(value) => value,
Err(_) => return get_json_response(status::BadRequest, "Cannot parse JSON".into())
};
let source = match payload["source"].take_string() {
Some(value) => value,
None => return get_json_response(status::BadRequest, "No source provided".into())
};
let minify = payload["minify"].as_bool().unwrap_or(false);
let get_ast = payload["ast"].as_bool().unwrap_or(false);
let response = match compile(source, minify, get_ast) {
Ok(result) => get_json_response(status::Ok, result),
Err(err) => get_json_response(status::UnprocessableEntity, format!("{:#?}", err))
};
response
}
let mut chain = Chain::new(handler);
if env::var("CORS").is_ok() {
chain.link_after(CorsMiddleware);
}
let host = match env::var("HOST") {
Ok(value) => Ipv4Addr::from_str(&value).expect("Invalid IPv4 address"),
_ => Ipv4Addr::from_str(&DEFAULT_HOST).unwrap()
};
let port = match env::var("PORT") {
Ok(value) => value.parse::<u16>().expect("Invalid port"),
_ => DEFAULT_PORT
};
let address = format!("{}:{}", host, port);
let _server = Iron::new(chain).http(address.as_str()).expect("Cannot start the server");
println!("Listening on {}://{}:{}", PROTOCOL, host, port);
}
| {
"content_hash": "5c56bc426ae0b19aaa8e04d7c1f63773",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 116,
"avg_line_length": 32.30275229357798,
"alnum_prop": 0.5879011644419199,
"repo_name": "ratel-rust/ratel-server",
"id": "d2d5d38a7a24d964251f3c606c28050e1ceba81a",
"size": "3521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "3521"
}
],
"symlink_target": ""
} |
#ifndef WKBundleAPICast_h
#define WKBundleAPICast_h
#include "WKSharedAPICast.h"
#include "WKBundlePage.h"
#include "WKBundlePagePrivate.h"
#include "WKBundlePrivate.h"
#include <WebCore/EditorInsertAction.h>
#include <WebCore/TextAffinity.h>
#include <WebCore/UserContentTypes.h>
#include <WebCore/UserScriptTypes.h>
namespace WebCore {
class CSSStyleDeclaration;
}
namespace WebKit {
class InjectedBundle;
class InjectedBundleBackForwardList;
class InjectedBundleBackForwardListItem;
class InjectedBundleHitTestResult;
class InjectedBundleNavigationAction;
class InjectedBundleNodeHandle;
class InjectedBundleRangeHandle;
class InjectedBundleScriptWorld;
class PageOverlay;
class WebFrame;
class WebInspector;
class WebPage;
class WebPageGroupProxy;
WK_ADD_API_MAPPING(WKBundleBackForwardListItemRef, InjectedBundleBackForwardListItem)
WK_ADD_API_MAPPING(WKBundleBackForwardListRef, InjectedBundleBackForwardList)
WK_ADD_API_MAPPING(WKBundleCSSStyleDeclarationRef, WebCore::CSSStyleDeclaration)
WK_ADD_API_MAPPING(WKBundleFrameRef, WebFrame)
WK_ADD_API_MAPPING(WKBundleHitTestResultRef, InjectedBundleHitTestResult)
WK_ADD_API_MAPPING(WKBundleInspectorRef, WebInspector)
WK_ADD_API_MAPPING(WKBundleNavigationActionRef, InjectedBundleNavigationAction)
WK_ADD_API_MAPPING(WKBundleNodeHandleRef, InjectedBundleNodeHandle)
WK_ADD_API_MAPPING(WKBundlePageGroupRef, WebPageGroupProxy)
WK_ADD_API_MAPPING(WKBundlePageOverlayRef, PageOverlay)
WK_ADD_API_MAPPING(WKBundlePageRef, WebPage)
WK_ADD_API_MAPPING(WKBundleRangeHandleRef, InjectedBundleRangeHandle)
WK_ADD_API_MAPPING(WKBundleRef, InjectedBundle)
WK_ADD_API_MAPPING(WKBundleScriptWorldRef, InjectedBundleScriptWorld)
inline WKInsertActionType toAPI(WebCore::EditorInsertAction action)
{
switch (action) {
case WebCore::EditorInsertActionTyped:
return kWKInsertActionTyped;
break;
case WebCore::EditorInsertActionPasted:
return kWKInsertActionPasted;
break;
case WebCore::EditorInsertActionDropped:
return kWKInsertActionDropped;
break;
}
ASSERT_NOT_REACHED();
return kWKInsertActionTyped;
}
inline WKAffinityType toAPI(WebCore::EAffinity affinity)
{
switch (affinity) {
case WebCore::UPSTREAM:
return kWKAffinityUpstream;
break;
case WebCore::DOWNSTREAM:
return kWKAffinityDownstream;
break;
}
ASSERT_NOT_REACHED();
return kWKAffinityUpstream;
}
inline WebCore::UserScriptInjectionTime toUserScriptInjectionTime(WKUserScriptInjectionTime wkInjectedTime)
{
switch (wkInjectedTime) {
case kWKInjectAtDocumentStart:
return WebCore::InjectAtDocumentStart;
case kWKInjectAtDocumentEnd:
return WebCore::InjectAtDocumentEnd;
}
ASSERT_NOT_REACHED();
return WebCore::InjectAtDocumentStart;
}
inline WebCore::UserContentInjectedFrames toUserContentInjectedFrames(WKUserContentInjectedFrames wkInjectedFrames)
{
switch (wkInjectedFrames) {
case kWKInjectInAllFrames:
return WebCore::InjectInAllFrames;
case kWKInjectInTopFrameOnly:
return WebCore::InjectInTopFrameOnly;
}
ASSERT_NOT_REACHED();
return WebCore::InjectInAllFrames;
}
} // namespace WebKit
#endif // WKBundleAPICast_h
| {
"content_hash": "13a9cff4a5ba7fdb6b2ecf34332d1e80",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 115,
"avg_line_length": 29.853211009174313,
"alnum_prop": 0.7931776275353412,
"repo_name": "kzhong1991/Flight-AR.Drone-2",
"id": "db32716c139b003987e023dd8fc0d2c06db14964",
"size": "4608",
"binary": false,
"copies": "22",
"ref": "refs/heads/master",
"path": "src/3rdparty/Qt4.8.4/src/3rdparty/webkit/Source/WebKit2/WebProcess/InjectedBundle/API/c/WKBundleAPICast.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8366"
},
{
"name": "C++",
"bytes": "172001"
},
{
"name": "Objective-C",
"bytes": "7651"
},
{
"name": "QMake",
"bytes": "1293"
}
],
"symlink_target": ""
} |
require('../../support/spec_helper');
describe("Cucumber.Runtime.StepResult", function() {
var Cucumber = requireLib('cucumber');
var stepResult, step;
beforeEach(function() {
step = createSpy("step");
stepResult = Cucumber.Runtime.StepResult({step: step});
});
it("is not failed", function() {
expect(stepResult.isFailed()).toBeFalsy();
});
it("is not pending", function() {
expect(stepResult.isPending()).toBeFalsy();
});
it("is not skipped", function() {
expect(stepResult.isSkipped()).toBeFalsy();
});
it("is not successful", function () {
expect(stepResult.isSuccessful()).toBeFalsy();
});
it("is not undefined", function() {
expect(stepResult.isUndefined()).toBeFalsy();
});
describe("getStep()", function() {
it("returns the step passed to the constructor", function() {
expect(stepResult.getStep()).toBe(step);
});
});
}); | {
"content_hash": "c483afa633d6632303674db65e6c82ca",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 65,
"avg_line_length": 24.64864864864865,
"alnum_prop": 0.6326754385964912,
"repo_name": "samccone/cucumber-js",
"id": "2e9a82569827977aa191c0641062956b8a168ea0",
"size": "912",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/cucumber/runtime/step_result_spec.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.sakaiproject.user.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.*;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.entity.api.*;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.memory.api.Cache;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.*;
import org.sakaiproject.util.BaseResourceProperties;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.api.FormattedText;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;
/**
* <p>
* BaseUserDirectoryService is a Sakai user directory services implementation.
* </p>
* <p>
* User records can be kept locally, in Sakai, externally, by a UserDirectoryProvider, or a mixture of both.
* </p>
* <p>
* Each User that ever goes through Sakai is allocated a Sakai unique UUID. Even if we don't keep the User record in Sakai, we keep a map of this id to the external eid.
* </p>
*/
public abstract class BaseUserDirectoryService implements UserDirectoryService, UserFactory
{
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(BaseUserDirectoryService.class);
/** Storage manager for this service. */
protected Storage m_storage = null;
/** The initial portion of a relative access point URL. */
protected String m_relativeAccessPoint = null;
/** An anon. user. */
protected User m_anon = null;
/** A user directory provider. */
protected UserDirectoryProvider m_provider = null;
/** Component ID used to find the provider if it's not directly injected. */
protected String m_providerName = null;
/** Key for current service caching of current user */
protected final String M_curUserKey = getClass().getName() + ".currentUser";
/** A cache of users */
protected Cache m_callCache = null;
/** Optional service to provide site-specific aliases for a user's display ID and display name. */
protected ContextualUserDisplayService m_contextualUserDisplayService = null;
/** Collaborator for doing passwords. */
protected PasswordService m_pwdService = null;
/** For validating passwords */
protected PasswordPolicyProvider m_passwordPolicyProvider = null;
/** Component ID used to find the password policy provider */
protected String m_passwordPolicyProviderName = PasswordPolicyProvider.class.getName();
/**********************************************************************************************************************************************************************************************************************************************************
* Abstractions, etc.
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct storage for this service.
*/
protected abstract Storage newStorage();
/* (non-Javadoc)
* @see org.sakaiproject.user.api.UserDirectoryService#validatePassword(java.lang.String, org.sakaiproject.user.api.User)
*/
public PasswordRating validatePassword(String password, User user) {
// NOTE: all passwords are valid by default
PasswordRating rating = PasswordRating.PASSED_DEFAULT;
PasswordPolicyProvider ppp = getPasswordPolicy();
if (ppp != null) {
if (user == null) {
user = getCurrentUser();
if (user == m_anon) {
user = null; // no user available
}
}
rating = ppp.validatePassword(password, user);
}
return rating;
}
/**
* @return the current password policy provider
* OR null if there is not one OR null if the password policy is disabled
*/
public PasswordPolicyProvider getPasswordPolicy() {
// https://jira.sakaiproject.org/browse/KNL-1123
// If the password policy object is not null, return it to the caller
if ( m_passwordPolicyProvider == null ) {
// Otherwise, try to get the (default) password policy object before returning it
// Try getting it by the configured name
if ( m_passwordPolicyProviderName != null ) {
m_passwordPolicyProvider = (PasswordPolicyProvider) ComponentManager.get( m_passwordPolicyProviderName );
}
// Try getting the default impl via ComponentManager
if ( m_passwordPolicyProvider == null ) {
m_passwordPolicyProvider = (PasswordPolicyProvider) ComponentManager.get(PasswordPolicyProvider.class);
}
// If all else failed, manually instantiate default implementation
if ( m_passwordPolicyProvider == null ) {
m_passwordPolicyProvider = new PasswordPolicyProviderDefaultImpl(serverConfigurationService());
}
}
PasswordPolicyProvider ppp = m_passwordPolicyProvider;
if (!serverConfigurationService().getBoolean("user.password.policy", false)) {
ppp = null; // don't send back a policy if disabled
}
return ppp;
}
/**
* Access the partial URL that forms the root of resource URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with /content)
* @return the partial URL that forms the root of resource URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : serverConfigurationService().getAccessUrl()) + m_relativeAccessPoint;
}
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @param id
* The user id string.
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String userReference(String id)
{
// clean up the id
id = cleanId(id);
return getAccessPoint(true) + Entity.SEPARATOR + ((id == null) ? "" : id);
}
/**
* Access the user id extracted from a user reference.
*
* @param ref
* The user reference string.
* @return The the user id extracted from a user reference.
*/
protected String userId(String ref)
{
String start = getAccessPoint(true) + Entity.SEPARATOR;
int i = ref.indexOf(start);
if (i == -1) return ref;
String id = ref.substring(i + start.length());
return id;
}
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @return true if allowd, false if not
*/
protected boolean unlockCheck(String lock, String resource)
{
if (!securityService().unlock(lock, resource))
{
return false;
}
return true;
}
/**
* Check security permission.
*
* @param lock
* A list of lock strings to consider.
* @param resource
* The resource reference string, or null if no resource is involved.
* @return true if any of these locks are allowed, false if not
*/
protected boolean unlockCheck(List<String> locks, String resource)
{
Iterator<String> locksIterator = locks.iterator();
while(locksIterator.hasNext()) {
if(securityService().unlock((String) locksIterator.next(), resource))
return true;
}
return false;
}
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @return true if either allowed, false if not
*/
protected boolean unlockCheck2(String lock1, String lock2, String resource)
{
if (!securityService().unlock(lock1, resource))
{
if (!securityService().unlock(lock2, resource))
{
return false;
}
}
return true;
}
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @exception UserPermissionException
* Thrown if the user does not have access
* @return The lock id string that succeeded
*/
protected String unlock(String lock, String resource) throws UserPermissionException
{
if (!unlockCheck(lock, resource))
{
throw new UserPermissionException(sessionManager().getCurrentSessionUserId(), lock, resource);
}
return lock;
}
/**
* Check security permission.
*
* @param lock1
* The lock id string.
* @param lock2
* The lock id string.
* @param resource
* The resource reference string, or null if no resource is involved.
* @exception UserPermissionException
* Thrown if the user does not have access to either.
*/
protected void unlock2(String lock1, String lock2, String resource) throws UserPermissionException
{
if (!unlockCheck2(lock1, lock2, resource))
{
throw new UserPermissionException(sessionManager().getCurrentSessionUserId(), lock1 + "/" + lock2, resource);
}
}
/**
* Check security permission.
*
*
* @param locks
* The list of lock strings.
* @param resource
* The resource reference string, or null if no resource is involved.
* @exception UserPermissionException
* Thrown if the user does not have access to either.
* @return A list of the lock strings that the user has access to.
*/
protected List<String> unlock(List<String> locks, String resource) throws UserPermissionException
{
List<String> locksSucceeded = new ArrayList<String>();
Iterator<String> locksIterator = locks.iterator();
StringBuilder locksFailedSb = new StringBuilder();
while (locksIterator.hasNext()) {
String lock = (String) locksIterator.next();
if (unlockCheck(lock, resource))
{
locksSucceeded.add(lock);
} else {
locksFailedSb.append(lock + " ");
}
}
if (locksSucceeded.size() < 1) {
throw new UserPermissionException(sessionManager().getCurrentSessionUserId(), locksFailedSb.toString(), resource);
}
return locksSucceeded;
}
/**
* Make sure we have a good uuid for a user record. If id is specified, use that. Otherwise get one from the provider or allocate a uuid.
*
* @param id
* The proposed id.
* @param eid
* The proposed eid.
* @return The id to use as the User's uuid.
*/
protected String assureUuid(String id, String eid)
{
// if we are not using separate id and eid, return the eid
if (!m_separateIdEid) return eid;
if (id != null) return id;
// TODO: let the provider have a chance to set this? -ggolden
// allocate a uuid
id = idManager().createUuid();
return id;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Configuration
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Configuration: set the user directory provider helper service.
*
* @param provider
* the user directory provider helper service.
*/
public void setProvider(UserDirectoryProvider provider)
{
m_provider = provider;
}
public void setProviderName(String userDirectoryProviderName)
{
m_providerName = StringUtils.trimToNull(userDirectoryProviderName);
}
public void setContextualUserDisplayService(ContextualUserDisplayService contextualUserDisplayService) {
m_contextualUserDisplayService = contextualUserDisplayService;
}
public void setPasswordPolicyProvider( PasswordPolicyProvider passwordPolicyProvider ) {
m_passwordPolicyProvider = passwordPolicyProvider;
}
public void setPasswordPolicyProviderName( String passwordPolicyProviderName ) {
m_passwordPolicyProviderName = StringUtils.trimToNull( passwordPolicyProviderName );
}
/** The # seconds to cache gets. 0 disables the cache. */
protected int m_cacheSeconds = 0;
/**
* Set the # minutes to cache a get.
*
* @param time
* The # minutes to cache a get (as an integer string).
*/
public void setCacheMinutes(String time)
{
m_cacheSeconds = Integer.parseInt(time) * 60;
}
/** The # seconds to cache gets. 0 disables the cache. */
protected int m_cacheCleanerSeconds = 0;
/**
* Set the # minutes between cache cleanings.
*
* @param time
* The # minutes between cache cleanings. (as an integer string).
*/
public void setCacheCleanerMinutes(String time)
{
m_cacheCleanerSeconds = Integer.parseInt(time) * 60;
}
/** Configuration: use a different id and eid for each record (otherwise make them the same value). */
protected boolean m_separateIdEid = false;
/**
* Configuration: to use a separate value for id and eid for each user record, or not.
*
* @param value
* The separateIdEid setting.
*/
public void setSeparateIdEid(String value)
{
m_separateIdEid = Boolean.valueOf(value).booleanValue();
}
/**
* Configuration: set the password service to use.
*
*/
public void setPasswordService(PasswordService pwdService)
{
m_pwdService = pwdService;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies
*********************************************************************************************************************************************************************************************************************************************************/
/**
* @return the ServerConfigurationService collaborator.
*/
protected abstract ServerConfigurationService serverConfigurationService();
/**
* @return the EntityManager collaborator.
*/
protected abstract EntityManager entityManager();
/**
* @return the SecurityService collaborator.
*/
protected abstract SecurityService securityService();
/**
* @return the FunctionManager collaborator.
*/
protected abstract FunctionManager functionManager();
/**
* @return the SessionManager collaborator.
*/
protected abstract SessionManager sessionManager();
/**
* @return the MemoryService collaborator.
*/
protected abstract MemoryService memoryService();
/**
* @return the EventTrackingService collaborator.
*/
protected abstract EventTrackingService eventTrackingService();
/**
* @return the AuthzGroupService collaborator.
*/
protected abstract AuthzGroupService authzGroupService();
/**
* @return the TimeService collaborator.
*/
protected abstract TimeService timeService();
/**
* @return the IdManager collaborator.
*/
protected abstract IdManager idManager();
/**
* @return the FormattedTextProcessor collaborator
*/
protected abstract FormattedText formattedText();
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
try
{
m_relativeAccessPoint = REFERENCE_ROOT;
// construct storage and read
m_storage = newStorage();
m_storage.open();
// make an anon. user
m_anon = new BaseUserEdit("");
// <= 0 indicates no caching desired
if (m_cacheSeconds > 0)
{
M_log.warn("cacheSeconds@org.sakaiproject.user.api.UserDirectoryService is no longer supported");
}
if (m_cacheCleanerSeconds > 0) {
M_log.warn("cacheCleanerSeconds@org.sakaiproject.user.api.UserDirectoryService is no longer supported");
}
// caching for users
m_callCache = memoryService().getCache("org.sakaiproject.user.api.UserDirectoryService.callCache");
if (!m_callCache.isDistributed()) {
// KNL_1229 use an Observer for cache cleanup when the cache is not distributed
M_log.info("Creating user callCache observer for event based cache expiration (for local caches)");
m_userCacheObserver = new UserCacheObserver();
eventTrackingService().addObserver(m_userCacheObserver);
}
// register as an entity producer
entityManager().registerEntityProducer(this, REFERENCE_ROOT);
// register functions
functionManager().registerFunction(SECURE_ADD_USER);
functionManager().registerFunction(SECURE_REMOVE_USER);
functionManager().registerFunction(SECURE_UPDATE_USER_OWN);
functionManager().registerFunction(SECURE_UPDATE_USER_OWN_NAME);
functionManager().registerFunction(SECURE_UPDATE_USER_OWN_EMAIL);
functionManager().registerFunction(SECURE_UPDATE_USER_OWN_PASSWORD);
functionManager().registerFunction(SECURE_UPDATE_USER_OWN_TYPE);
functionManager().registerFunction(SECURE_UPDATE_USER_ANY);
// if no provider was set, see if we can find one
if ((m_provider == null) && (m_providerName != null))
{
m_provider = (UserDirectoryProvider) ComponentManager.get(m_providerName);
}
// Check for optional contextual user display service.
if (m_contextualUserDisplayService == null)
{
m_contextualUserDisplayService = (ContextualUserDisplayService) ComponentManager.get(ContextualUserDisplayService.class);
}
// Fallback to the default password service.
if (m_pwdService == null)
{
m_pwdService = new PasswordService();
}
m_passwordPolicyProviderName = serverConfigurationService().getString(PasswordPolicyProvider.SAK_PROP_PROVIDER_NAME, PasswordPolicyProvider.class.getName());
if (StringUtils.isEmpty(m_passwordPolicyProviderName)) {
m_passwordPolicyProviderName = PasswordPolicyProvider.class.getName();
M_log.warn("init(): Empty name for passwordPolicyProvider: Using the default name instead: "+m_passwordPolicyProviderName);
}
if (m_passwordPolicyProvider == null) {
m_passwordPolicyProvider = getPasswordPolicy(); // this will load the PasswordPolicy provider bean or instantiate the default
}
M_log.info("init(): PasswordPolicyProvider ("+m_passwordPolicyProviderName+"): " + ((m_passwordPolicyProvider == null) ? "none" : m_passwordPolicyProvider.getClass().getName()));
M_log.info("init(): provider: " + ((m_provider == null) ? "none" : m_provider.getClass().getName())
+ " separateIdEid: " + m_separateIdEid);
}
catch (Exception t)
{
M_log.error("init(): ", t);
}
}
/**
* KNL-1229 Supports legacy event based cache expiration
*/
UserCacheObserver m_userCacheObserver;
/**
* KNL-1229 Allow for legacy event based cache expiration
* Only used when distributed caches are not in use
*/
class UserCacheObserver implements Observer {
@Override
public void update(Observable observable, Object o) {
if (o instanceof Event) {
Event event = (Event) o;
if (event.getResource() != null && (
SECURE_UPDATE_USER_OWN.equals(event.getEvent())
|| SECURE_UPDATE_USER_ANY.equals(event.getEvent())
|| SECURE_REMOVE_USER.equals(event.getEvent())
)
) {
String userRef = event.getResource();
removeCachedUser(userRef);
}
}
}
}
/**
* Returns to uninitialized state. You can use this method to release resources thet your Service allocated when Turbine shuts down.
*/
public void destroy()
{
m_storage.close();
m_storage = null;
m_provider = null;
m_anon = null;
m_passwordPolicyProvider = null;
m_callCache.close();
m_userCacheObserver = null;
M_log.info("destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* UserDirectoryService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getUserEid(String id) throws UserNotDefinedException
{
id = cleanId(id);
// first, check our map
String eid = m_storage.checkMapForEid(id);
if (eid != null) return eid;
throw new UserNotDefinedException(id);
}
/**
* {@inheritDoc}
*/
public String getUserId(String eid) throws UserNotDefinedException
{
eid = cleanEid(eid);
// first, check our map
String id = m_storage.checkMapForId(eid);
if (id != null) return id;
// Try the provider.
UserEdit user = getProvidedUserByEid(null, eid);
if (user != null)
{
id = user.getId();
putCachedUser(userReference(id), user);
return id;
}
// not found
throw new UserNotDefinedException(eid);
}
protected UserEdit getProvidedUserByEid(String id, String eid)
{
if (m_provider != null)
{
if (eid == null) {
//theres no point in asking a provider if we have no eid
return null;
}
// make a new edit to hold the provider's info, hoping it will be filled in
// Since the provider may actually want to fill in the user ID itself,
// there's no point in us allocating a new user ID until after it returns.
BaseUserEdit user = new BaseUserEdit(id, eid);
// check with the provider
if (m_provider.getUser(user))
{
user.setEid(cleanEid(user.getEid()));
ensureMappedIdForProvidedUser(user);
return user;
}
else
{
return null;
}
}
return null;
}
protected void ensureMappedIdForProvidedUser(UserEdit user)
{
if (user.getId() == null)
{
user.setEid(cleanEid(user.getEid()));
String eid = user.getEid();
String id = assureUuid(null, eid);
m_storage.putMap(id, eid);
user.setId(id);
}
}
protected void checkAndEnsureMappedIdForProvidedUser(UserEdit user)
{
if (user.getId() == null)
{
user.setEid(cleanEid(user.getEid()));
user.setId(m_storage.checkMapForId(user.getEid()));
ensureMappedIdForProvidedUser(user);
}
}
public boolean checkDuplicatedEmail (User user)
{
//Check if another user has the same email
String email = StringUtils.trimToNull (user.getEmail());
M_log.debug("commitEdit(): Check for mail " + email);
if (email!=null)
{
Collection <User> usersByMail = findUsersByEmail(email);
for (User userToCheck : usersByMail)
{
if (!StringUtils.equals(userToCheck.getId(),user.getId()))
{
return true;
}
}
}
return false;
}
/**
* @inheritDoc
*/
public User getUser(String id) throws UserNotDefinedException
{
// clean up the id
id = cleanId(id);
if (id == null) throw new UserNotDefinedException("null");
// see if we've done this already in this thread
String ref = userReference(id);
UserEdit user = getCachedUser(ref);
if (user == null)
{
// find our user record, and use it if we have it
user = m_storage.getById(id);
// let the provider provide if needed
if ((user == null) && (m_provider != null))
{
// we need the eid for the provider - if we can't find an eid, we throw UserNotDefinedException
String eid = m_storage.checkMapForEid(id);
if (eid != null)
{
// TODO Should we distinguish an obsolete user ID from an incorrect user ID?
// An obsolete ID will have an associated EID but that EID won't be known to
// the provider any longer.
// An incorrect ID is not found at all.
user = getProvidedUserByEid(id, eid);
}
}
if (user != null)
{
putCachedUser(ref, user);
}
}
// if not found
if (user == null)
{
throw new UserNotDefinedException(id);
}
return user;
}
/**
* @inheritDoc
*/
public User getUserByEid(String eid) throws UserNotDefinedException
{
UserEdit user = null;
// clean up the eid
eid = cleanEid(eid);
if (eid == null) throw new UserNotDefinedException("null");
String id = m_storage.checkMapForId(eid);
if (id != null)
{
user = getCachedUser(userReference(id));
if (user != null)
{
return user;
}
user = m_storage.getById(id);
}
if (user == null)
{
user = getProvidedUserByEid(id, eid);
if (user == null) throw new UserNotDefinedException(eid);
}
putCachedUser(userReference(user.getId()), user);
return user;
}
/**
* @inheritDoc
*/
public List getUsers(Collection<String> ids)
{
// Clean IDs to match the by-user case.
Set<String> searchIds = new HashSet<String>();
for (Iterator<String> idIter = ids.iterator(); idIter.hasNext(); )
{
String id = (String)idIter.next();
id = cleanEid(id);
if (id != null) searchIds.add(id);
}
if (m_separateIdEid)
{
return m_storage.getUsersByIds(searchIds);
}
// Fall back to the old logic if this is a legacy system where
// "ID == EID", since that setting makes it difficult
// to optimize while maintaining backwards compatibility: the user
// record may be in the Sakai user table or not, and may be in the
// EID-mapping table or not.
// User objects to return
List<UserEdit> rv = new Vector<UserEdit>();
// a list of User (edits) setup to check with the provider
Collection<UserEdit> fromProvider = new Vector<UserEdit>();
// for each requested id
for (String id : searchIds)
{
// see if we've done this already in this thread
String ref = userReference(id);
UserEdit user = getCachedUser(ref);
if (user == null)
{
// find our user record
user = m_storage.getById(id);
if (user != null)
{
putCachedUser(ref, user);
}
else if (m_provider != null)
{
// get the eid for this user so we can ask the provider
String eid = m_storage.checkMapForEid(id);
if (eid != null)
{
// make a new edit to hold the provider's info; the provider will either fill this in, if known, or remove it from the collection
fromProvider.add(new BaseUserEdit(id, eid));
}
else
{
// this user is not internally defined, and we can't find an eid for it, so we skip it
M_log.warn("getUsers: cannot find eid for user id: " + id);
}
}
}
// add to return
if (user != null) rv.add(user);
}
// check the provider, all at once
if (!fromProvider.isEmpty())
{
m_provider.getUsers(fromProvider);
// for each User in the collection that was filled in (and not removed) by the provider, cache and return it
for (Iterator i = fromProvider.iterator(); i.hasNext();)
{
UserEdit user = (UserEdit) i.next();
putCachedUser(user.getReference(), user);
// add to return
rv.add(user);
}
}
return rv;
}
/**
* @see org.sakaiproject.user.api.UserDirectoryService#getUsersByEids(java.util.Collection)
*/
public List<User> getUsersByEids(Collection<String> eids)
{
if (!m_separateIdEid)
{
return getUsers(eids);
}
// Clean EIDs to match the by-user case.
Set<String> searchEids = new HashSet<String>();
for (String eid : eids)
{
eid = cleanEid(eid);
if (eid != null) searchEids.add(eid);
}
return m_storage.getUsersByEids(searchEids);
}
/**
* @inheritDoc
*/
public User getCurrentUser()
{
String id = sessionManager().getCurrentSessionUserId();
User rv = null;
try
{
rv = getUser(id);
}
catch (UserNotDefinedException e)
{
rv = getAnonymousUser();
}
return rv;
}
/**
* @inheritDoc
*/
public boolean allowUpdateUser(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
// is this the user's own?
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
ArrayList<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN_NAME);
locks.add(SECURE_UPDATE_USER_OWN_EMAIL);
locks.add(SECURE_UPDATE_USER_OWN_PASSWORD);
locks.add(SECURE_UPDATE_USER_OWN_TYPE);
// own or any
return unlockCheck(locks, userReference(id));
}
else
{
// just any
return unlockCheck(SECURE_UPDATE_USER_ANY, userReference(id));
}
}
/**
* @inheritDoc
*/
public boolean allowUpdateUserName(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
// is this the user's own?
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
ArrayList<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN_NAME);
// own or any
return unlockCheck(locks, userReference(id));
}
else
{
// just any
return unlockCheck(SECURE_UPDATE_USER_ANY, userReference(id));
}
}
/**
* @inheritDoc
*/
public boolean allowUpdateUserEmail(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
// is this the user's own?
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
ArrayList<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN_EMAIL);
// own or any
return unlockCheck(locks, userReference(id));
}
else
{
// just any
return unlockCheck(SECURE_UPDATE_USER_ANY, userReference(id));
}
}
/**
* @inheritDoc
*/
public boolean allowUpdateUserPassword(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
// is this the user's own?
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
ArrayList<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN_PASSWORD);
// own or any
return unlockCheck(locks, userReference(id));
}
else
{
// just any
return unlockCheck(SECURE_UPDATE_USER_ANY, userReference(id));
}
}
/**
* @inheritDoc
*/
public boolean allowUpdateUserType(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
// is this the user's own?
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
ArrayList<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN_TYPE);
// own or any
return unlockCheck(locks, userReference(id));
}
else
{
// just any
return unlockCheck(SECURE_UPDATE_USER_ANY, userReference(id));
}
}
/**
* @inheritDoc
*/
public UserEdit editUser(String id) throws UserNotDefinedException, UserPermissionException, UserLockedException
{
// clean up the id
id = cleanId(id);
if (id == null) throw new UserNotDefinedException("null");
// is this the user's own?
List<String> locksSucceeded = new ArrayList<String>();
String function = null;
if (id.equals(sessionManager().getCurrentSessionUserId()))
{
// own or any
List<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_OWN_NAME);
locks.add(SECURE_UPDATE_USER_OWN_EMAIL);
locks.add(SECURE_UPDATE_USER_OWN_PASSWORD);
locks.add(SECURE_UPDATE_USER_OWN_TYPE);
locks.add(SECURE_UPDATE_USER_ANY);
locksSucceeded = unlock(locks, userReference(id));
function = SECURE_UPDATE_USER_OWN;
}
else
{
// just any
locksSucceeded.add(unlock(SECURE_UPDATE_USER_ANY, userReference(id)));
function = SECURE_UPDATE_USER_ANY;
}
// ignore the cache - get the user with a lock from the info store
UserEdit user = m_storage.edit(id);
if (user == null)
{
// Figure out which exception to throw.
if (!m_storage.check(id))
{
throw new UserNotDefinedException(id);
}
else
{
throw new UserLockedException(id);
}
}
if(!locksSucceeded.contains(SECURE_UPDATE_USER_ANY) && !locksSucceeded.contains(SECURE_UPDATE_USER_OWN)) {
// current session does not have permission to edit all properties for this user
// lock the properties the user does not have access to edit
if(!locksSucceeded.contains(SECURE_UPDATE_USER_OWN_NAME)) {
user.restrictEditFirstName();
user.restrictEditLastName();
}
if(!locksSucceeded.contains(SECURE_UPDATE_USER_OWN_EMAIL)) {
user.restrictEditEmail();
}
if(!locksSucceeded.contains(SECURE_UPDATE_USER_OWN_PASSWORD)) {
user.restrictEditPassword();
}
if(!locksSucceeded.contains(SECURE_UPDATE_USER_OWN_TYPE)) {
user.restrictEditType();
}
}
//only a super user should ever be able to edit the EID
if (!securityService().isSuperUser()) {
user.restrictEditEid();
}
((BaseUserEdit) user).setEvent(function);
return user;
}
/**
* @inheritDoc
*/
public void commitEdit(UserEdit user) throws UserAlreadyDefinedException
{
// check for closed edit
if (!user.isActiveEdit())
{
M_log.error("commitEdit(): closed UserEdit", new Exception());
return;
}
// update the properties
addLiveUpdateProperties((BaseUserEdit) user);
// complete the edit
if (!m_storage.commit(user))
{
m_storage.cancel(user);
((BaseUserEdit) user).closeEdit();
throw new UserAlreadyDefinedException(user.getEid());
}
String ref = user.getReference();
// track it
eventTrackingService().post(eventTrackingService().newEvent(((BaseUserEdit) user).getEvent(), ref, true));
// close the edit object
((BaseUserEdit) user).closeEdit();
// Update the caches to match any changed data.
putCachedUser(ref, user);
}
/**
* @inheritDoc
*/
public void cancelEdit(UserEdit user)
{
// check for closed edit
if (!user.isActiveEdit())
{
try
{
throw new Exception();
}
catch (Exception e)
{
M_log.error("cancelEdit(): closed UserEdit", e);
}
return;
}
// release the edit lock
m_storage.cancel(user);
// close the edit object
((BaseUserEdit) user).closeEdit();
}
/**
* @inheritDoc
*/
public User getUserByAid(String aid) throws UserNotDefinedException
{
if (m_provider instanceof AuthenticationIdUDP)
{
UserEdit user = new BaseUserEdit();
if (((AuthenticationIdUDP)m_provider).getUserbyAid(aid, user))
{
String id = m_storage.checkMapForId(user.getEid());
user.setId(id);
ensureMappedIdForProvidedUser(user);
putCachedUser(user.getReference(), user);
return user;
}
}
return getUserByEid(aid);
}
/**
* @inheritDoc
*/
public List<User> getUsers()
{
List<User> users = m_storage.getAll();
return users;
}
/**
* @inheritDoc
*/
public List<User> getUsers(int first, int last)
{
List<User> all = m_storage.getAll(first, last);
return all;
}
/**
* @inheritDoc
*/
public int countUsers()
{
return m_storage.count();
}
/**
* @inheritDoc
*/
public List<User> searchUsers(String criteria, int first, int last)
{
//KNL-691 split term on whitespace and perform multiple searches, no duplicates will be returned
Set<User> users = new TreeSet<User>();
List<String> terms = Arrays.asList(StringUtils.split(criteria));
for(String term:terms){
users.addAll(m_storage.search(term, first, last));
}
List<User> userList = new ArrayList<User>(users);
//sort on sortName, default.
Collections.sort(userList);
return userList;
}
/**
* @inheritDoc
*/
public int countSearchUsers(String criteria)
{
//KNL-691 because we need to perform multiple searches and aggregate the results, but without duplicates,
//we just call the above method, which takes care of this, and then count the results
//return m_storage.countSearch(criteria);
return searchUsers(criteria, 1, Integer.MAX_VALUE).size();
}
/**
* @inheritDoc
*/
public List<User> searchExternalUsers(String criteria, int first, int last){
List<User> users = new ArrayList<User>();
List<UserEdit> providedUserRecords = null;
if (m_provider instanceof ExternalUserSearchUDP) {
providedUserRecords = ((ExternalUserSearchUDP) m_provider).searchExternalUsers(criteria, first, last, this);
} else {
M_log.debug("searchExternalUsers capability is not supported by your provider");
}
if (providedUserRecords != null){
for (UserEdit user : providedUserRecords){
// KNL-741 these useredit objects should already have the eid-id mapping
// But just incase the provider hasn't mapped them.
checkAndEnsureMappedIdForProvidedUser(user);
users.add(user);
}
}
return users;
}
/**
* @inheritDoc
*/
@SuppressWarnings("unchecked")
public Collection findUsersByEmail(String email)
{
// check internal users
Collection users = m_storage.findUsersByEmail(email);
// add in provider users
if (m_provider != null)
{
Collection<BaseUserEdit> providedUserRecords = null;
// support UDP that has multiple users per email
if (m_provider instanceof UsersShareEmailUDP)
{
providedUserRecords = ((UsersShareEmailUDP) m_provider).findUsersByEmail(email, this);
}
else
{
// make a new edit to hold the provider's info
BaseUserEdit edit = new BaseUserEdit();
if (m_provider.findUserByEmail(edit, email))
{
providedUserRecords = Arrays.asList(new BaseUserEdit[] {edit});
}
}
if (providedUserRecords != null)
{
for (BaseUserEdit user : providedUserRecords)
{
checkAndEnsureMappedIdForProvidedUser(user);
users.add(user);
}
}
}
return users;
}
/**
* @inheritDoc
*/
public User getAnonymousUser()
{
return m_anon;
}
/**
* @inheritDoc
*/
public boolean allowAddUser()
{
return unlockCheck(SECURE_ADD_USER, userReference(""));
}
/**
* @inheritDoc
*/
public UserEdit addUser(String id, String eid) throws UserIdInvalidException, UserAlreadyDefinedException,
UserPermissionException
{
// clean the ids
id = cleanId(id);
eid = cleanEid(eid);
// make sure we have an id
id = assureUuid(id, eid);
//eid can't be longer than 255 chars
if (eid.length() > 255)
{
throw new UserIdInvalidException("Eid is too long");
}
// check security (throws if not permitted)
unlock(SECURE_ADD_USER, userReference(id));
// reserve a user with this id from the info store - if it's in use, this will return null
UserEdit user = m_storage.put(id, eid);
if (user == null)
{
throw new UserAlreadyDefinedException(id + " -" + eid);
}
((BaseUserEdit) user).setEvent(SECURE_ADD_USER);
return user;
}
/**
* @inheritDoc
*/
public User addUser(String id, String eid, String firstName, String lastName, String email, String pw, String type,
ResourceProperties properties) throws UserIdInvalidException, UserAlreadyDefinedException, UserPermissionException
{
// get it added
UserEdit edit = addUser(id, eid);
// fill in the fields
edit.setLastName(lastName);
edit.setFirstName(firstName);
edit.setEmail(email);
edit.setPassword(pw);
edit.setType(type);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
if (properties != null)
{
props.addAll(properties);
}
// no live props!
// get it committed - no further security check
if (!m_storage.commit(edit))
{
m_storage.cancel(edit);
((BaseUserEdit) edit).closeEdit();
throw new UserAlreadyDefinedException(edit.getEid());
}
// track it
eventTrackingService().post(eventTrackingService().newEvent(((BaseUserEdit) edit).getEvent(), edit.getReference(), true));
// close the edit object
((BaseUserEdit) edit).closeEdit();
return edit;
}
/**
* @inheritDoc
*/
public UserEdit mergeUser(Element el) throws UserIdInvalidException, UserAlreadyDefinedException, UserPermissionException
{
// construct from the XML
User userFromXml = new BaseUserEdit(el);
// check for a valid eid
Validator.checkResourceId(userFromXml.getEid());
// check security (throws if not permitted)
unlock(SECURE_ADD_USER, userFromXml.getReference());
// Check if this user is a provided one:
if (getProvidedUserByEid(userFromXml.getId(), userFromXml.getEid()) != null) {
// This doesn't mean we have a mapping from ID to EID mapping
if (m_storage.checkMapForId(userFromXml.getEid()) == null) {
m_storage.putMap(userFromXml.getId(), userFromXml.getEid());
}
throw new UserAlreadyDefinedException("Provided user: "+ userFromXml.getId() + " - " + userFromXml.getEid());
}
// reserve a user with this id from the info store - if it's in use, this will return null
UserEdit user = m_storage.put(userFromXml.getId(), userFromXml.getEid());
if (user == null)
{
throw new UserAlreadyDefinedException(userFromXml.getId() + " - " + userFromXml.getEid());
}
// transfer from the XML read user object to the UserEdit
((BaseUserEdit) user).set(userFromXml);
((BaseUserEdit) user).setEvent(SECURE_ADD_USER);
return user;
}
/**
* @inheritDoc
*/
public boolean allowRemoveUser(String id)
{
// clean up the id
id = cleanId(id);
if (id == null) return false;
return unlockCheck(SECURE_REMOVE_USER, userReference(id));
}
/**
* @inheritDoc
*/
public void removeUser(UserEdit user) throws UserPermissionException
{
String ref = user.getReference();
// check for closed edit
if (!user.isActiveEdit())
{
M_log.error("removeUser(): closed UserEdit", new Exception());
return;
}
// check security (throws if not permitted)
unlock(SECURE_REMOVE_USER, ref);
// complete the edit
m_storage.remove(user);
// track it
eventTrackingService().post(eventTrackingService().newEvent(SECURE_REMOVE_USER, ref, true));
// close the edit object
((BaseUserEdit) user).closeEdit();
// remove any realm defined for this resource
try
{
authzGroupService().removeAuthzGroup(authzGroupService().getAuthzGroup(ref));
}
catch (AuthzPermissionException e)
{
M_log.warn("removeUser: removing realm for : " + ref + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
}
// Remove from cache.
removeCachedUser(ref);
}
/**
* {@inheritDoc}
*
* <b>WARNING:</b> Do not call this method directly! Use {@link AuthenticationManager#authenticate(org.sakaiproject.user.api.Evidence)}
*/
public User authenticate(String loginId, String password)
{
loginId = cleanEid(loginId);
if (loginId == null) return null;
UserEdit user = null;
boolean authenticateWithProviderFirst = (m_provider != null) && m_provider.authenticateWithProviderFirst(loginId);
if (authenticateWithProviderFirst)
{
user = getProviderAuthenticatedUser(loginId, password);
if (user != null) return user;
}
user = getInternallyAuthenticatedUser(loginId, password);
if (user != null) return user;
if ((m_provider != null) && !authenticateWithProviderFirst)
{
return getProviderAuthenticatedUser(loginId, password);
}
return null;
}
protected UserEdit getInternallyAuthenticatedUser(String eid, String password)
{
try
{
UserEdit user = (UserEdit)getUserByEid(eid);
return user.checkPassword(password) ? user : null;
} catch (UserNotDefinedException e)
{
// Give up and possibly pass along to another authentication service.
return null;
}
}
protected UserEdit getProviderAuthenticatedUser(String loginId, String password)
{
UserEdit user = null;
if (m_provider instanceof AuthenticatedUserProvider)
{
// Since the login ID might differ from the EID, the provider is in charge
// of filling in user data as well as authenticating the user.
user = ((AuthenticatedUserProvider)m_provider).getAuthenticatedUser(loginId, password);
}
else
{
// The pre-2.5 authenticateUser method was ambiguous due to the lack of a
// distinct "AuthenticationProvider" and the inability to indicate "emptiness"
// in a UserEdit record. Here are the revised options:
//
// 1) If the provider is basically authentication-only, then this logic will find
// the locally stored user record and pass it on.
//
// 2) If the provider handles both data provision and authentication, then
// this logic will find the provided user data and pass it on.
//
// 3) If the provider needs to authenticate a user using a login ID
// that does not match the EID of an already locally stored user record or a
// provided user, then the provider should be changed to implement the
// AuthenticatedUserProvider interface.
//
// Note that this legacy interface does not allow EIDs and login IDs to differ,
// and this logic will therefore not attempt to authenticate a user unless
// "getUserByEid(loginId)" returns success. This preserves backwards
// compatibility for legacy providers that perform authentication only for
// locally stored users.
try
{
user = (UserEdit)getUserByAid(loginId);
} catch (UserNotDefinedException e)
{
return null;
}
boolean authenticated = m_provider.authenticateUser(loginId, user, password);
if (!authenticated) user = null;
}
if (user != null)
{
checkAndEnsureMappedIdForProvidedUser(user);
putCachedUser(user.getReference(), user);
return user;
}
return null;
}
/**
* @inheritDoc
*/
public void destroyAuthentication()
{
}
/**
* Create the live properties for the user.
*/
protected void addLiveProperties(BaseUserEdit edit)
{
String current = sessionManager().getCurrentSessionUserId();
edit.m_createdUserId = current;
edit.m_lastModifiedUserId = current;
Time now = timeService().newTime();
edit.m_createdTime = now;
edit.m_lastModifiedTime = (Time) now.clone();
}
/**
* Update the live properties for a user for when modified.
*/
protected void addLiveUpdateProperties(BaseUserEdit edit)
{
String current = sessionManager().getCurrentSessionUserId();
edit.m_lastModifiedUserId = current;
edit.m_lastModifiedTime = timeService().newTime();
}
/**
* Adjust the id - trim it to null. Note: eid case insensitive option does NOT apply to id.
*
* @param id
* The id to clean up.
* @return A cleaned up id.
*/
protected String cleanId(String id)
{
// if we are not doing separate id and eid, use the eid rules
if (!m_separateIdEid) {
id = cleanEid(id);
}
id = StringUtils.trimToNull(id);
// max length for an id is 99 chars
id = StringUtils.abbreviate(id, 99);
return id;
}
/**
* Adjust the eid - trim it to null, and lower case IF we are case insensitive.
*
* @param eid
* The eid to clean up.
* @return A cleaned up eid.
*/
protected String cleanEid(String eid)
{
eid = StringUtils.lowerCase(eid);
eid = StringUtils.trimToNull(eid);
if (eid != null) {
// remove all instances of these chars <>,;:\"
eid = StringUtils.replaceChars(eid, "<>,;:\\/", "");
}
// NOTE: length check is handled later on
return eid;
}
protected UserEdit getCachedUser(String ref)
{
// KNL-1241 removed caching in threadlocal
UserEdit userEdit = null;
if (m_callCache != null)
{
Object cachedRef = m_callCache.get(ref);
if (cachedRef != null)
{
userEdit = (UserEdit) cachedRef;
}
}
return userEdit;
}
protected void putCachedUser(String ref, UserEdit user)
{
// KNL-1241 removed caching in threadlocal
if (m_callCache != null)
{
m_callCache.put(ref, user);
}
}
protected void removeCachedUser(String ref)
{
if (m_callCache != null)
{
m_callCache.remove(ref);
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* EntityProducer implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public String getLabel()
{
return "user";
}
/**
* @inheritDoc
*/
public boolean willArchiveMerge()
{
return false;
}
/**
* @inheritDoc
*/
public HttpAccess getHttpAccess()
{
return null;
}
/**
* @inheritDoc
*/
public boolean parseEntityReference(String reference, Reference ref)
{
// for user access
if (reference.startsWith(REFERENCE_ROOT))
{
String id = null;
// we will get null, service, userId
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
if (parts.length > 2)
{
id = parts[2];
}
ref.set(APPLICATION_ID, null, id, null, null);
return true;
}
return false;
}
/**
* @inheritDoc
*/
public String getEntityDescription(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = "User: " + ref.getReference();
try
{
User user = getUser(ref.getId());
rv = "User: " + user.getDisplayName();
}
catch (UserNotDefinedException e)
{
}
catch (NullPointerException e)
{
}
return rv;
}
/**
* @inheritDoc
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
return null;
}
/**
* @inheritDoc
*/
public Entity getEntity(Reference ref)
{
return null;
}
/**
* @inheritDoc
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Collection rv = new Vector();
// for user access: user and template realms
try
{
rv.add(userReference(ref.getId()));
ref.addUserTemplateAuthzGroup(rv, userId);
}
catch (NullPointerException e)
{
M_log.warn("getEntityRealms(): " + e);
}
return rv;
}
/**
* @inheritDoc
*/
public String getEntityUrl(Reference ref)
{
return null;
}
/**
* @inheritDoc
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
return "";
}
/**
* @inheritDoc
*/
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
return "";
}
/**********************************************************************************************************************************************************************************************************************************************************
* UserFactory implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public UserEdit newUser()
{
return new BaseUserEdit();
}
/**
* @inheritDoc
*/
public UserEdit newUser(String eid)
{
UserEdit u = new BaseUserEdit();
u.setEid(eid);
checkAndEnsureMappedIdForProvidedUser(u);
return u;
}
public boolean updateUserId(String id,String newEmail)
{
try {
List<String> locksSucceeded = new ArrayList<String>();
// own or any
List<String> locks = new ArrayList<String>();
locks.add(SECURE_UPDATE_USER_ANY);
locks.add(SECURE_UPDATE_USER_OWN);
locks.add(SECURE_UPDATE_USER_OWN_EMAIL);
locksSucceeded = unlock(locks, userReference(id));
if(!locksSucceeded.isEmpty()) {
UserEdit user = m_storage.edit(id);
if (user == null) {
M_log.warn("Can't find user " + id + " when trying to update email address");
return false;
}
user.setEid(newEmail);
user.setEmail(newEmail);
commitEdit(user);
return true;
}
else {
M_log.warn("User with id: "+id+" failed permission checks" );
return false;
}
} catch (UserPermissionException e) {
M_log.warn("You do not have sufficient permission to edit the user with Id: "+id, e);
return false;
} catch (UserAlreadyDefinedException e) {
M_log.error("A users already exists with EID of: "+id +"having email :"+ newEmail, e);
return false;
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* UserEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* <p>
* BaseUserEdit is an implementation of the UserEdit object.
* </p>
*/
public class BaseUserEdit implements UserEdit, SessionBindingListener
{
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/** The user id. */
protected String m_id = null;
/** The user eid. */
protected String m_eid = null;
/** The user first name. */
protected String m_firstName = null;
/** The user last name. */
protected String m_lastName = null;
/** The user email address. */
protected String m_email = null;
/** The user password. */
protected String m_pw = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** The user type. */
protected String m_type = null;
/** The created user id. */
protected String m_createdUserId = null;
/** The last modified user id. */
protected String m_lastModifiedUserId = null;
/** The time created. */
protected Time m_createdTime = null;
/** The time last modified. */
protected Time m_lastModifiedTime = null;
/** If editing the first name is restricted **/
protected boolean m_restrictedFirstName = false;
/** If editing the last name is restricted **/
protected boolean m_restrictedLastName = false;
/** If editing the email is restricted **/
protected boolean m_restrictedEmail = false;
/** If editing the password is restricted **/
protected boolean m_restrictedPassword = false;
/** If editing the type is restricted **/
protected boolean m_restrictedType = false;
/** if editing the eid is restricted **/
protected boolean m_restrictedEid = false;
// in object cache of the sort name.
private transient String m_sortName;
/**
* Construct.
*
* @param id
* The user id.
*/
public BaseUserEdit(String id, String eid)
{
m_id = id;
m_eid = eid;
// setup for properties
BaseResourcePropertiesEdit props = new BaseResourcePropertiesEdit();
m_properties = props;
// if the id is not null (a new user, rather than a reconstruction)
// and not the anon (id == "") user,
// add the automatic (live) properties
if ((m_id != null) && (m_id.length() > 0)) addLiveProperties(this);
//KNL-567 lazy set the properties to be lazy so they get loaded
props.setLazy(true);
}
public BaseUserEdit(String id)
{
this(id, null);
}
public BaseUserEdit()
{
this(null, null);
}
/**
* Construct from another User object.
*
* @param user
* The user object to use for values.
*/
public BaseUserEdit(User user)
{
setAll(user);
}
/**
* Construct from information in XML.
*
* @param el
* The XML DOM Element definining the user.
*/
public BaseUserEdit(Element el)
{
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_id = cleanId(el.getAttribute("id"));
m_eid = cleanEid(el.getAttribute("eid"));
m_firstName = StringUtils.trimToNull(el.getAttribute("first-name"));
m_lastName = StringUtils.trimToNull(el.getAttribute("last-name"));
setEmail(StringUtils.trimToNull(el.getAttribute("email")));
m_pw = el.getAttribute("pw");
m_type = StringUtils.trimToNull(el.getAttribute("type"));
m_createdUserId = StringUtils.trimToNull(el.getAttribute("created-id"));
m_lastModifiedUserId = StringUtils.trimToNull(el.getAttribute("modified-id"));
String time = StringUtils.trimToNull(el.getAttribute("created-time"));
if (time != null)
{
m_createdTime = timeService().newTimeGmt(time);
}
time = StringUtils.trimToNull(el.getAttribute("modified-time"));
if (time != null)
{
m_lastModifiedTime = timeService().newTimeGmt(time);
}
// the children (roles, properties)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
// pull out some properties into fields to convert old (pre 1.38) versions
if (m_createdUserId == null)
{
m_createdUserId = m_properties.getProperty("CHEF:creator");
}
if (m_lastModifiedUserId == null)
{
m_lastModifiedUserId = m_properties.getProperty("CHEF:modifiedby");
}
if (m_createdTime == null)
{
try
{
m_createdTime = m_properties.getTimeProperty("DAV:creationdate");
}
catch (Exception ignore)
{
}
}
if (m_lastModifiedTime == null)
{
try
{
m_lastModifiedTime = m_properties.getTimeProperty("DAV:getlastmodified");
}
catch (Exception ignore)
{
}
}
m_properties.removeProperty("CHEF:creator");
m_properties.removeProperty("CHEF:modifiedby");
m_properties.removeProperty("DAV:creationdate");
m_properties.removeProperty("DAV:getlastmodified");
}
}
}
/**
* ReConstruct.
*
* @param id
* The id.
* @param eid
* The eid.
* @param email
* The email.
* @param firstName
* The first name.
* @param lastName
* The last name.
* @param type
* The type.
* @param pw
* The password.
* @param createdBy
* The createdBy property.
* @param createdOn
* The createdOn property.
* @param modifiedBy
* The modified by property.
* @param modifiedOn
* The modified on property.
*/
public BaseUserEdit(String id, String eid, String email, String firstName, String lastName, String type, String pw,
String createdBy, Time createdOn, String modifiedBy, Time modifiedOn)
{
m_id = id;
m_eid = eid;
m_firstName = firstName;
m_lastName = lastName;
m_type = type;
setEmail(email);
m_pw = pw;
m_createdUserId = createdBy;
m_lastModifiedUserId = modifiedBy;
m_createdTime = createdOn;
m_lastModifiedTime = modifiedOn;
// setup for properties, but mark them lazy since we have not yet established them from data
BaseResourcePropertiesEdit props = new BaseResourcePropertiesEdit();
props.setLazy(true);
m_properties = props;
}
/**
* Take all values from this object.
*
* @param user
* The user object to take values from.
*/
protected void setAll(User user)
{
m_id = user.getId();
m_eid = user.getEid();
m_firstName = user.getFirstName();
m_lastName = user.getLastName();
m_type = user.getType();
setEmail(user.getEmail());
m_pw = ((BaseUserEdit) user).m_pw;
m_createdUserId = ((BaseUserEdit) user).m_createdUserId;
m_lastModifiedUserId = ((BaseUserEdit) user).m_lastModifiedUserId;
if (((BaseUserEdit) user).m_createdTime != null) m_createdTime = (Time) ((BaseUserEdit) user).m_createdTime.clone();
if (((BaseUserEdit) user).m_lastModifiedTime != null)
m_lastModifiedTime = (Time) ((BaseUserEdit) user).m_lastModifiedTime.clone();
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(user.getProperties());
((BaseResourcePropertiesEdit) m_properties).setLazy(((BaseResourceProperties) user.getProperties()).isLazy());
}
/**
* @inheritDoc
*/
public Element toXml(Document doc, Stack stack)
{
Element user = doc.createElement("user");
if (stack.isEmpty())
{
doc.appendChild(user);
}
else
{
((Element) stack.peek()).appendChild(user);
}
stack.push(user);
user.setAttribute("id", getId());
user.setAttribute("eid", getEid());
if (m_firstName != null) user.setAttribute("first-name", m_firstName);
if (m_lastName != null) user.setAttribute("last-name", m_lastName);
if (m_type != null) user.setAttribute("type", m_type);
user.setAttribute("email", getEmail());
user.setAttribute("created-id", m_createdUserId);
user.setAttribute("modified-id", m_lastModifiedUserId);
if (m_createdTime != null)
{
user.setAttribute("created-time", m_createdTime.toString());
}
if (m_lastModifiedTime != null)
{
user.setAttribute("modified-time", m_lastModifiedTime.toString());
}
// properties
getProperties().toXml(doc, stack);
stack.pop();
return user;
}
/**
* @inheritDoc
*/
public String getId()
{
return m_id;
}
/**
* @inheritDoc
*/
public String getEid()
{
return m_eid;
}
/**
* @inheritDoc
*/
public String getUrl()
{
return getAccessPoint(false) + m_id;
}
/**
* @inheritDoc
*/
public String getReference()
{
return userReference(m_id);
}
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* @inheritDoc
*/
public ResourceProperties getProperties()
{
// if lazy, resolve
if (((BaseResourceProperties) m_properties).isLazy())
{
((BaseResourcePropertiesEdit) m_properties).setLazy(false);
m_storage.readProperties(this, m_properties);
}
return m_properties;
}
/**
* @inheritDoc
*/
public User getCreatedBy()
{
try
{
return getUser(m_createdUserId);
}
catch (Exception e)
{
return getAnonymousUser();
}
}
/**
* @inheritDoc
*/
public User getModifiedBy()
{
try
{
return getUser(m_lastModifiedUserId);
}
catch (Exception e)
{
return getAnonymousUser();
}
}
/**
* @inheritDoc
*/
public Time getCreatedTime()
{
return m_createdTime;
}
/**
* @inheritDoc
*/
public Date getCreatedDate()
{
return new Date(m_createdTime.getTime());
}
/**
* @inheritDoc
*/
public Time getModifiedTime()
{
return m_lastModifiedTime;
}
/**
* @inheritDoc
*/
public Date getModifiedDate()
{
return new Date(m_lastModifiedTime.getTime());
}
/**
* @inheritDoc
*/
public String getDisplayName()
{
String rv = null;
// If a contextual aliasing service exists, let it have the first try.
if (m_contextualUserDisplayService != null) {
rv = m_contextualUserDisplayService.getUserDisplayName(this);
if (rv != null) {
return rv;
}
}
// let the provider handle it, if we have that sort of provider, and it wants to handle this
if ((m_provider != null) && (m_provider instanceof DisplayAdvisorUDP))
{
rv = ((DisplayAdvisorUDP) m_provider).getDisplayName(this);
}
if (rv == null)
{
// or do it this way
StringBuilder buf = new StringBuilder(128);
if (m_firstName != null) buf.append(m_firstName);
if (m_lastName != null)
{
if (buf.length() > 0) buf.append(" ");
buf.append(m_lastName);
}
if (buf.length() == 0)
{
rv = getEid();
}
else
{
rv = buf.toString();
}
}
return rv;
}
/**
* @inheritDoc
*/
public String getDisplayId()
{
String rv = null;
// If a contextual aliasing service exists, let it have the first try.
if (m_contextualUserDisplayService != null) {
rv = m_contextualUserDisplayService.getUserDisplayId(this);
if (rv != null) {
return rv;
}
}
// let the provider handle it, if we have that sort of provider, and it wants to handle this
if ((m_provider != null) && (m_provider instanceof DisplayAdvisorUDP))
{
rv = ((DisplayAdvisorUDP) m_provider).getDisplayId(this);
}
// use eid if not
if (rv == null)
{
rv = getEid();
}
return rv;
}
/**
* @inheritDoc
*/
public String getFirstName()
{
if (m_firstName == null) return "";
return m_firstName;
}
/**
* @inheritDoc
*/
public String getLastName()
{
if (m_lastName == null) return "";
return m_lastName;
}
/**
* @inheritDoc
*/
public String getSortName()
{
if (m_sortName == null)
{
if (m_provider != null && m_provider instanceof DisplaySortAdvisorUPD)
{
String rv = ((DisplaySortAdvisorUPD) m_provider).getSortName(this);
if (rv != null)
{
m_sortName = rv;
return rv;
}
}
// Cache this locally in the object as otherwise when sorting users we generate lots of objects.
StringBuilder buf = new StringBuilder(128);
if (m_lastName != null) buf.append(m_lastName);
if (m_firstName != null)
{
//KNL-524 no comma if the last name is null
if (m_lastName != null)
{
buf.append(", ");
}
buf.append(m_firstName);
}
m_sortName = (buf.length() == 0)?getEid():buf.toString();
}
return m_sortName;
}
/**
* @inheritDoc
*/
public String getEmail()
{
if (m_email == null) return "";
return m_email;
}
/**
* @inheritDoc
*/
public String getType()
{
return m_type;
}
/**
* @inheritDoc
*/
public boolean checkPassword(String pw)
{
pw = StringUtils.trimToNull(pw);
return m_pwdService.check(pw, m_pw);
}
/**
* @inheritDoc
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseUserEdit that = (BaseUserEdit) o;
if (m_id != null ? !m_id.equals(that.m_id) : that.m_id != null) return false;
if (m_eid != null ? !m_eid.equals(that.m_eid) : that.m_eid != null) return false;
return true;
}
/**
* @inheritDoc
*/
public int hashCode()
{
String id = getId();
if (id == null)
{
// Maintains consistency with Sakai 2.4.x behavior.
id = "";
}
return id.hashCode();
}
/**
* @inheritDoc
*/
public int compareTo(Object obj)
{
if (!(obj instanceof User)) throw new ClassCastException();
// if the object are the same, say so
if (obj == this) return 0;
// start the compare by comparing their sort names
int compare = getSortName().compareTo(((User) obj).getSortName());
// if these are the same
if (compare == 0)
{
// sort based on (unique) eid
compare = getEid().compareTo(((User) obj).getEid());
}
return compare;
}
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
}
/**
* @inheritDoc
*/
public void setId(String id)
{
// set once only!
if (m_id == null)
{
m_id = id;
}
else throw new UnsupportedOperationException("Tried to change user ID from " + m_id + " to " + id);
}
/**
* @inheritDoc
*/
public void setEid(String eid)
{
if (!m_restrictedEid)
{
m_eid = eid;
m_sortName = null;
}
}
/**
* @inheritDoc
*/
public void setFirstName(String name)
{
if(!m_restrictedFirstName) {
// https://jira.sakaiproject.org/browse/SAK-20226 - removed html from name
m_firstName = formattedText().convertFormattedTextToPlaintext(name);
m_sortName = null;
}
}
/**
* @inheritDoc
*/
public void setLastName(String name)
{
if(!m_restrictedLastName) {
// https://jira.sakaiproject.org/browse/SAK-20226 - removed html from name
m_lastName = formattedText().convertFormattedTextToPlaintext(name);
m_sortName = null;
}
}
/**
* @inheritDoc
*/
public void setEmail(String email)
{
if(!m_restrictedEmail) {
m_email = email;
}
}
/**
* @inheritDoc
*/
public void setPassword(String pw)
{
if(!m_restrictedPassword) {
// to clear it
if (pw == null)
{
m_pw = null;
}
// else encode the new one
else
{
// encode this password
String encoded = m_pwdService.encrypt(pw);
m_pw = encoded;
}
}
}
/**
* @inheritDoc
*/
public void setType(String type)
{
if(!m_restrictedType) {
m_type = type;
}
}
public void restrictEditFirstName() {
m_restrictedFirstName = true;
}
public void restrictEditLastName() {
m_restrictedLastName = true;
}
public void restrictEditEmail() {
m_restrictedEmail = true;
}
public void restrictEditPassword() {
m_restrictedPassword = true;
}
public void restrictEditEid() {
m_restrictedEid = true;
}
public void restrictEditType() {
m_restrictedType = true;
}
/**
* Take all values from this object.
*
* @param user
* The user object to take values from.
*/
protected void set(User user)
{
setAll(user);
}
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* @inheritDoc
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
// if lazy, resolve
if (((BaseResourceProperties) m_properties).isLazy())
{
((BaseResourcePropertiesEdit) m_properties).setLazy(false);
m_storage.readProperties(this, m_properties);
}
return m_properties;
}
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
}
/**
* @inheritDoc
*/
public boolean isActiveEdit()
{
return m_active;
}
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
}
/**
* Check this User object to see if it is selected by the criteria.
*
* @param criteria
* The critera.
* @return True if the User object is selected by the criteria, false if not.
*/
protected boolean selectedBy(String criteria)
{
if (StringUtil.containsIgnoreCase(getSortName(), criteria) || StringUtil.containsIgnoreCase(getDisplayName(), criteria)
|| StringUtil.containsIgnoreCase(getEid(), criteria) || StringUtil.containsIgnoreCase(getEmail(), criteria))
{
return true;
}
return false;
}
@Override
public String toString()
{
return "BaseUserEdit{" +
"m_id='" + m_id + '\'' +
", m_eid='" + m_eid + '\'' +
'}';
}
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public void valueBound(SessionBindingEvent event)
{
}
/**
* @inheritDoc
*/
public void valueUnbound(SessionBindingEvent event)
{
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelEdit(this);
}
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* Storage
*********************************************************************************************************************************************************************************************************************************************************/
protected interface Storage
{
/**
* Open.
*/
public void open();
/**
* Close.
*/
public void close();
/**
* Check if a user by this id exists.
*
* @param id
* The user id.
* @return true if a user by this id exists, false if not.
*/
public boolean check(String id);
/**
* Get the user with this id, or null if not found.
*
* @param id
* The user id.
* @return The user with this id, or null if not found.
*/
public UserEdit getById(String id);
/**
* Get the users with this email, or return empty if none found.
*
* @param id
* The user email.
* @return The Collection (User) of users with this email, or an empty collection if none found.
*/
public Collection findUsersByEmail(String email);
/**
* Get all users.
*
* @return The List (UserEdit) of all users.
*/
public List getAll();
/**
* Get all the users in record range.
*
* @param first
* The first record position to return.
* @param last
* The last record position to return.
* @return The List (BaseUserEdit) of all users.
*/
public List getAll(int first, int last);
/**
* Count all the users.
*
* @return The count of all users.
*/
public int count();
/**
* Search for users with id or email, first or last name matching criteria, in range.
*
* @param criteria
* The search criteria.
* @param first
* The first record position to return.
* @param last
* The last record position to return.
* @return The List (BaseUserEdit) of all alias.
*/
public List search(String criteria, int first, int last);
/**
* Count all the users with id or email, first or last name matching criteria.
*
* @param criteria
* The search criteria.
* @return The count of all aliases with id or target matching criteria.
*/
public int countSearch(String criteria);
/**
* Add a new user with this id and eid.
*
* @param id
* The user id.
* @param eid
* The user eid.
* @return The locked User object with this id and eid, or null if the id is in use.
*/
public UserEdit put(String id, String eid);
/**
* Get a lock on the user with this id, or null if a lock cannot be gotten.
*
* @param id
* The user id.
* @return The locked User with this id, or null if this records cannot be locked.
*/
public UserEdit edit(String id);
/**
* Commit the changes and release the lock.
*
* @param user
* The user to commit.
* @return true if successful, false if not (eid may not be unique).
*/
public boolean commit(UserEdit user);
/**
* Cancel the changes and release the lock.
*
* @param user
* The user to commit.
*/
public void cancel(UserEdit user);
/**
* Remove this user.
*
* @param user
* The user to remove.
*/
public void remove(UserEdit user);
/**
* Read properties from storage into the edit's properties.
*
* @param edit
* The user to read properties for.
*/
public void readProperties(UserEdit edit, ResourcePropertiesEdit props);
/**
* Create a mapping between the id and eid.
*
* @param id
* The user id.
* @param eid
* The user eid.
* @return true if successful, false if not (id or eid might be in use).
*/
public boolean putMap(String id, String eid);
/**
* Check the id -> eid mapping: lookup this id and return the eid if found
*
* @param id
* The user id to lookup.
* @return The eid mapped to this id, or null if none.
*/
public String checkMapForEid(String id);
/**
* Check the id -> eid mapping: lookup this eid and return the id if found
*
* @param eid
* The user eid to lookup.
* @return The id mapped to this eid, or null if none.
*/
public String checkMapForId(String eid);
/**
* Since optimizing this call requires access to SQL result sets and
* internally-maintained caches, all the real work is performed by
* the storage class.
*
* @param ids
* @return any user records with matching IDs
*/
public List<User> getUsersByIds(Collection<String> ids);
/**
* Since optimizing this call requires access to SQL result sets and
* internally-maintained caches, all the real work is performed by
* the storage class.
*
* @param eids
* @return any user records with matching EIDs
*/
public List<User> getUsersByEids(Collection<String> eids);
}
}
| {
"content_hash": "a86ca808f8acadd5ec4e4d0f7e82ef05",
"timestamp": "",
"source": "github",
"line_count": 3099,
"max_line_length": 252,
"avg_line_length": 25.31816715069377,
"alnum_prop": 0.6139738213889703,
"repo_name": "conder/sakai",
"id": "99b4f782fb30c9559642c8e867e2d780f701e60b",
"size": "79465",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "kernel/kernel-impl/src/main/java/org/sakaiproject/user/impl/BaseUserDirectoryService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "5172"
},
{
"name": "CSS",
"bytes": "2098402"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "5541072"
},
{
"name": "Java",
"bytes": "47105571"
},
{
"name": "JavaScript",
"bytes": "9733947"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "962699"
},
{
"name": "PLSQL",
"bytes": "2309973"
},
{
"name": "Perl",
"bytes": "61738"
},
{
"name": "Python",
"bytes": "44698"
},
{
"name": "Ruby",
"bytes": "1276"
},
{
"name": "Shell",
"bytes": "19259"
},
{
"name": "SourcePawn",
"bytes": "2242"
},
{
"name": "XSLT",
"bytes": "280557"
}
],
"symlink_target": ""
} |
package com.android.simone.github.marvelapp.presentation.ui.list;
import com.android.simone.github.marvelapp.presentation.viewmodel.ComicModel;
/**
* @author Simone Bellotti
*/
public interface OnComicClickListener {
void onComicClick(ComicModel comic);
}
| {
"content_hash": "3f47e7723eaba84ca7a13abb28f42a47",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 77,
"avg_line_length": 22.166666666666668,
"alnum_prop": 0.7894736842105263,
"repo_name": "SimoneBellotti/MarvelApp",
"id": "98c1860020dd21132a6f423f27482fcbfd1b2e7c",
"size": "266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/android/simone/github/marvelapp/presentation/ui/list/OnComicClickListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "76181"
}
],
"symlink_target": ""
} |
/*
* Subclass of NaClDesc which passes write output data to the
* JavaScript console using the reverse channel.
*/
#ifndef NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_NACL_DESC_JSCONSOLE_H_
#define NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_NACL_DESC_JSCONSOLE_H_
#include "native_client/src/include/nacl_base.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/trusted/desc/nacl_desc_base.h"
EXTERN_C_BEGIN
struct NaClDescEffector;
struct NaClDescXferState;
struct NaClMessageHeader;
struct NaClRuntimeHostInterface;
/*
* A NaClDesc subclass that passes Write data to the runtime host
* via postmessage.
*
* This is a DEBUG interface to make it easier to determine the state
* of a NaCl application. The interface is enabled only when a debug
* environment variable is set.
*/
struct NaClDescPostMessage {
struct NaClDesc base NACL_IS_REFCOUNT_SUBCLASS;
struct NaClRuntimeHostInterface *runtime_host;
};
int NaClDescPostMessageCtor(struct NaClDescPostMessage *self,
struct NaClRuntimeHostInterface *runtime_host);
EXTERN_C_END
#endif
| {
"content_hash": "77226db320aa5700c56a7d08bb35e408",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 75,
"avg_line_length": 26.714285714285715,
"alnum_prop": 0.7638146167557932,
"repo_name": "cvsuser-chromium/native_client",
"id": "2750e9f117162ef5c5e6dce95ba274e6cb9bfd2d",
"size": "1302",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/trusted/service_runtime/nacl_desc_postmessage.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "190904"
},
{
"name": "C",
"bytes": "10474371"
},
{
"name": "C++",
"bytes": "7065153"
},
{
"name": "JavaScript",
"bytes": "5925"
},
{
"name": "Logos",
"bytes": "6875"
},
{
"name": "Objective-C",
"bytes": "51655"
},
{
"name": "Objective-C++",
"bytes": "2658"
},
{
"name": "Python",
"bytes": "1823039"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104506"
},
{
"name": "Shell",
"bytes": "285445"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>UserAsync Class Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Class/UserAsync" class="dashAnchor"></a>
<a title="UserAsync Class Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html">Appudo Docs</a></p>
<p class="header-right"><a href="https://www.github.com/Appudo"><img src="../img/gh.png"/>View on GitHub</a></p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html">Appudo Reference</a>
<img id="carat" src="../img/carat.png" />
UserAsync Class Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/Async.html">Async</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DataBlob.html">DataBlob</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FileItemList.html">FileItemList</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HTTPClient.html">HTTPClient</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HTTPClient/HTTPVersion.html">– HTTPVersion</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SQLQry.html">SQLQry</a>
</li>
<li class="nav-group-task">
<a href="../Classes/UserAsync.html">UserAsync</a>
</li>
<li class="nav-group-task">
<a href="../Classes/UserList.html">UserList</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enums</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/AppudoError.html">AppudoError</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:6Appudo14ErrorEventTypeO">ErrorEventType</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:6Appudo17HTTPRequestStatusO">HTTPRequestStatus</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:6Appudo15HTTPRequestTypeO">HTTPRequestType</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:6Appudo4LangO">Lang</a>
</li>
<li class="nav-group-task">
<a href="../Enums.html#/s:6Appudo8LinkTypeO">LinkType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/SQLQryError.html">SQLQryError</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/Date.html">Date</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Functions/<!(_:).html"><!(_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo2lqopSbyycF"><?(_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions/<?(_:_:).html"><?(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions/<?(_:_:).html"><?(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo12AlphasortASCs5Int32VAA13_UserListItemV1a_AF1btF">AlphasortASC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo12AlphasortASCs5Int32VAA8FileItemV1a_AF1btF">AlphasortASC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo12AlphasortDSCs5Int32VAA13_UserListItemV1a_AF1btF">AlphasortDSC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo12AlphasortDSCs5Int32VAA8FileItemV1a_AF1btF">AlphasortDSC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:6Appudo13appudo_assertySbyXK_SSyXKs12StaticStringVSutF">appudo_assert(_:_:_:_:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/Blob.html">Blob</a>
</li>
<li class="nav-group-task">
<a href="../Protocols.html#/s:6Appudo15DataWriteSourceP">DataWriteSource</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FileLockable.html">FileLockable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FileSeekable.html">FileSeekable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FileSendSource.html">FileSendSource</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structs</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/Account.html">Account</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AccountID.html">AccountID</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AsyncValue.html">AsyncValue</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Dir.html">Dir</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Domain.html">Domain</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ErrorEvent.html">ErrorEvent</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem.html">FileItem</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem/Flag.html">– Flag</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem/RenameFlags.html">– RenameFlags</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem/MKPathFlags.html">– MKPathFlags</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem/Mode.html">– Mode</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileItem/AccessMode.html">– AccessMode</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileSeekFlag.html">FileSeekFlag</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FileStat.html">FileStat</a>
</li>
<li class="nav-group-task">
<a href="../Structs.html#/s:6Appudo8FileViewV">FileView</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Group.html">Group</a>
</li>
<li class="nav-group-task">
<a href="../Structs/GroupID.html">GroupID</a>
</li>
<li class="nav-group-task">
<a href="../Structs.html#/s:6Appudo9GroupInfoV">GroupInfo</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Link.html">Link</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Mail.html">Mail</a>
</li>
<li class="nav-group-task">
<a href="../Structs.html#/s:6Appudo6MemVarV">MemVar</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Memory.html">Memory</a>
</li>
<li class="nav-group-task">
<a href="../Structs/MenuItem.html">MenuItem</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Page.html">Page</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Role.html">Role</a>
</li>
<li class="nav-group-task">
<a href="../Structs/SQLQryValue.html">SQLQryValue</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Setting.html">Setting</a>
</li>
<li class="nav-group-task">
<a href="../Structs/SettingVar.html">SettingVar</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Socket.html">Socket</a>
</li>
<li class="nav-group-task">
<a href="../Structs/StaticDomain.html">StaticDomain</a>
</li>
<li class="nav-group-task">
<a href="../Structs/User.html">User</a>
</li>
<li class="nav-group-task">
<a href="../Structs/UserID.html">UserID</a>
</li>
<li class="nav-group-task">
<a href="../Structs.html#/s:6Appudo8UserInfoV">UserInfo</a>
</li>
<li class="nav-group-task">
<a href="../Structs/UserListItem.html">UserListItem</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Typealiases.html">Typealiases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Typealiases.html#/s:6Appudo10AsyncDelaya">AsyncDelay</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>UserAsync</h1>
<div class="declaration">
<div class="language">
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="kt">UserAsync</span> <span class="p">:</span> <span class="kt"><a href="../Classes/Async.html">Async</a></span></code></pre>
</div>
</div>
<p>UserAsync can be used to create custom async functions.
This is needed to make the async handling of Appudo work with GCD.
We do not recommend the use of GCD.</p>
<div class="aside aside-see-also">
<p class="aside-title">See also</p>
Async
</div>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:6Appudo9UserAsyncC7resolveSbyF"></a>
<a name="//apple_ref/swift/Method/resolve()" class="dashAnchor"></a>
<a class="token" href="#/s:6Appudo9UserAsyncC7resolveSbyF">resolve()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Set the async to ready state.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">resolve</span><span class="p">()</span> <span class="o">-></span> <span class="kt">Bool</span></code></pre>
</div>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2017 <a class="link" href="" target="_blank" rel="external">source@appudo.com</a>. All rights reserved. (Last updated: 2017-08-08)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.8.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {
"content_hash": "7b15d4a9232e2ffb398514a7b34e9d32",
"timestamp": "",
"source": "github",
"line_count": 325,
"max_line_length": 245,
"avg_line_length": 42.50769230769231,
"alnum_prop": 0.4634817227651104,
"repo_name": "Appudo/Appudo.github.io",
"id": "b4de3fb7de2265eebce0dbe5c4eb0b97c0976024",
"size": "13831",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pub/docs_0.1.30/Classes/UserAsync.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "17567"
},
{
"name": "AngelScript",
"bytes": "2387"
},
{
"name": "Batchfile",
"bytes": "963"
},
{
"name": "C",
"bytes": "4472258"
},
{
"name": "C++",
"bytes": "8096232"
},
{
"name": "CSS",
"bytes": "1598579"
},
{
"name": "HTML",
"bytes": "22733727"
},
{
"name": "JavaScript",
"bytes": "26918138"
},
{
"name": "Objective-C",
"bytes": "231"
},
{
"name": "PHP",
"bytes": "38090"
},
{
"name": "PLpgSQL",
"bytes": "48798"
},
{
"name": "Python",
"bytes": "5025"
},
{
"name": "SQLPL",
"bytes": "877"
},
{
"name": "Shell",
"bytes": "3787"
},
{
"name": "Swift",
"bytes": "465672"
},
{
"name": "TSQL",
"bytes": "12185"
},
{
"name": "XSLT",
"bytes": "47380"
}
],
"symlink_target": ""
} |
layout: doc
title: "**HOWTO:** Decode to Texture"
---
# **HOWTO:** Decode to Texture
Starboard declares the interfaces necessary to allow applications to query for
video frames from the media player, and have them returned as texture objects
(e.g. GLES textures). This is useful if the application would like to apply
a geometrical transformation to the rendered video, in order to support 360
spherical video playback for example. Additionally, if a Starboard platform
implementation does not support punch-through video playback, then
applications can choose to use decode-to-texture instead.
## API Overview
Decode-to-texture support involves multiple Starboard API functions spanning
both the [`starboard/player.h`](../player.h) and
[`starboard/decode_target.h`](../decode_target.h) Starboard interface header
files. Support for decode-to-texture began in version 4 of the Starboard
API.
In particular, the following function implementations require consideration
for decode-to-texture support:
From [`starboard/player.h`](../player.h),
* `SbPlayerCreate()`
* `SbPlayerGetPreferredOutputMode()`
* `SbPlayerGetCurrentFrame()`
From [`starboard/decode_target.h`](../decode_target.h),
* `SbDecodeTargetRelease()`
* `SbDecodeTargetGetInfo()`
Note that it is possible that you may not need to use the
`SbDecodeTargetGraphicsContextProvider` parameter of SbPlayerCreate(). More on
this later.
## Example Application Usage Pattern
We now describe an example, and typical, sequence of steps that an
application will take when it wishes to make use of decode-to-texture
support.

1. An application with the desire to make use of decode-to-texture will first
call `SbPlayerGetPreferredOutputMode()`, passing in
`kSbPlayerOutputModeDecodeToTexture` for its `creation_param->output_mode`
parameter. If the function doesn't return
`kSbPlayerOutputModeDecodeToTexture`, the application learns that
decode-to-texture is not supported by the platform and it will not continue
with a decode-to-texture flow.
2. If `SbPlayerGetPreferredOutputMode()` returns
`kSbPlayerOutputModeDecodeToTexture`, the application will call
`SbPlayerCreate()`, passing in `kSbPlayerOutputModeDecodeToTexture` for
the `creation_param->output_mode` parameter, and also providing a valid
`provider` parameter (more on this later). At this point, the Starboard
platform is expected to have created a player with the decode-to-texture
output mode.
3. Once the player is started and playback has begun, the application's
renderer thread (this may be a different thread than the one that called
`SbPlayerCreate()`) will repeatedly and frequently call
`SbPlayerGetCurrentFrame()`. Since this function will be called from the
application's renderer thread, it should be thread-safe. If the platform
uses a GLES renderer, it is guaranteed that this function will be called
with the GLES renderer context set as current. This function is expected
to return the video frame that is to be displayed at the time the function
is called as a `SbDecodeTarget` object. The `SbPlayerGetCurrentFrame()`
will be called at the renderer's frequency, i.e. the application render
loop's frame rate. If the application's frame rate is higher than the
video's frame rate, then the same video frame will sometimes be returned
in consecutive calls to `SbPlayerGetCurrentFrame()`. If the video's frame
rate is higher than the application's (this should be rare), then some
video frames will never be returned by calls to
`SbPlayerGetCurrentFrame()`; in other words, video frames will be
dropped.
4. Once the application has acquired a valid SbDecodeTarget object through a
call to `SbPlayerGetCurrentFrame()`, it will call
`SbDecodeTargetGetInfo()` on it to extract information about the opaque
`SbDecodeTarget` object. The `SbDecodeTargetGetInfo()` function fills
out a `SbDecodeTargetInfo` structure which contains information about the
decoded frame and, most importantly, a reference to a GLES texture ID on
GLES platforms, or a reference to a `SbBlitterSurface` object on
Starboard Blitter API platforms. The application can then use this
texture/surface handle to render the video frame as it wishes.
5. When the application is finished using the `SbDecodeTarget` that it has
acquired through the `SbPlayerGetCurrentFrame()` function, it will call
`SbDecodeTargetRelease()` on it. The Starboard platform implementation
should ensure that the `SbDecodeTarget` object returned by
`SbPlayerGetCurrentFrame()` remains valid until the corresponding call to
`SbDecodeTargetRelease()` is made. A call to `SbDecodeTargetRelease()`
will be made to match each call to `SbPlayerGetCurrentFrame()`.
## The `SbDecodeTargetGraphicsContextProvider` object
It is completely possible that a platform's Starboard implementation can
properly implement decode-to-texture support without dealing with the
`SbDecodeTargetGraphicsContextProvider` object (passed in to
`SbPlayerCreate()`). The `SbDecodeTargetGraphicsContextProvider` reference
gives platforms references to the graphics objects that will later be used to
render the decoded frames. For example, on Blitter API platforms, a reference
to the `SbBlitterDevice` object will be a mamber of
`SbDecodeTargetGraphicsContextProvider`. For EGL platforms, a `EGLDisplay` and
`EGLContext` will be available, but additionally a
`SbDecodeTargetGlesContextRunner` function pointer will be provided that will
allow you to run arbitrary code on the renderer thread with the `EGLContext`
held current. This may be useful if your `SbDecodeTarget` creation code will
required making GLES calls (e.g. `glGenTextures()`) in which a `EGLContext` must
be held current.
## Performance Considerations
The decode-to-texture Starboard API is specifically designed to allow
Starboard implementations to have the player decode directly to a texture,
so that the application can then reference and render with that texture
without at any point performing a pixel copy. The
decode-to-texture path can therefore be highly performant.
It is still recommended however that platforms support the punch-through
player mode if possible. When using the decode-to-texture player output
mode, the video may be rendered within the application's render loop, which
means that non-video-related time complexity in the application's render
loop can affect video playback's apparent frame rate, potentially resulting in
dropped frames. The platform can likely configure punch-through video to
refresh on its own loop, decoupling it from the application render loop.
## Implementation Strategies
### Working with "push" players
If your player implementation is setup with a "push" framework where
frames are pushed out as soon as they are decoded, then you will need
to cache those frames (along with their timestamps) so that they can be
passed on to the application when `SbPlayerGetCurrentFrame()` is called.
This same strategy applies if the player pushes frames only when they are meant
to be rendered.
| {
"content_hash": "872089834c414518100f3ded0c94e12d",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 80,
"avg_line_length": 50.70422535211268,
"alnum_prop": 0.7895833333333333,
"repo_name": "youtube/cobalt_sandbox",
"id": "b15eb5eb04c9cb5fe9bdbab85b0aeae20c6ec93e",
"size": "7204",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "cobalt/site/docs/gen/starboard/doc/howto_decode_to_texture.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\LoginForm;
use Users\Form\LoginFilter;
class LoginController extends AbstractActionController {
public $authservice;
public function indexAction() {
$form = new LoginForm();
$viewModel = new ViewModel(array('form' => $form));
return $viewModel;
}
public function processAction() {
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL, array(
'controller' => 'login',
'action' => 'index'
));
}
$post = $this->request->getPost();
$form = $this->getServiceLocator()->get('LoginForm');
$form->setData($post);
if (!$form->isValid()) {
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model->setTemplate('users/login/index');
return $model;
}
$this->getAuthService()->
getAdapter()->
setIdentity($this->request->getPost('email'))->setCredential($this->request->getPost('password'));
$result = $this->getAuthService()->authenticate();
if ($result->isValid()) {
$this->getAuthService()->getStorage()->write($this->request->getPost('email'));
return $this->redirect()->toRoute(NULL, array(
'controller' => 'login',
'action' => 'confirm'
));
}
}
public function confirmAction() {
$user_email = $this->getAuthService()->getStorage()->read();
$viewModel = new ViewModel(array('user_email' => $user_email));
return $viewModel;
}
public function getAuthService() {
if (!$this->authservice) {
$this->authservice = $this->getServiceLocator()->get('authService');
}
return $this->authservice;
}
}
| {
"content_hash": "e144c9a86dbe955afeb399bac5d56f16",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 114,
"avg_line_length": 32.40625,
"alnum_prop": 0.5231436837029894,
"repo_name": "abdouh/zf2",
"id": "c34b5121b445206557f5cefff9e3467833593605",
"size": "2074",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Users/src/Users/Controller/LoginController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1042"
},
{
"name": "PHP",
"bytes": "76905"
}
],
"symlink_target": ""
} |
/**
*
*/
package org.github.etcd.viewer.html.node;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.ChainingModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.github.etcd.service.EtcdProxyFactory;
import org.github.etcd.service.rest.EtcdNode;
import org.github.etcd.service.rest.EtcdProxy;
import org.github.etcd.viewer.ConvertUtils;
import org.github.etcd.viewer.html.modal.TriggerModalLink;
import org.github.etcd.viewer.html.pages.NavigationPage;
import org.github.etcd.viewer.html.pages.NavigationPageLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EtcdNodePanel extends GenericPanel<EtcdNode> {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(EtcdNodePanel.class);
private static final Comparator<EtcdNode> NODE_SORTER = new Comparator<EtcdNode>() {
@Override
public int compare(EtcdNode o1, EtcdNode o2) {
if (o1.isDir() == o2.isDir()) {
return o1.getKey().compareTo(o2.getKey());
}
if (o1.isDir()) {
return -1;
}
if (o2.isDir()) {
return 1;
}
return 0;
}
};
public static final String ROOT_KEY = "/";
private static final List<String> ROOT_BREADCRUMB = Collections.unmodifiableList(Arrays.asList(ROOT_KEY));
private IModel<EtcdNode> actionModel = Model.of(new EtcdNode());
private IModel<Boolean> updating = Model.of(false);
private EditNodeModalPanel editNodeModal;
private DeleteNodeModalPanel deleteNodeModal;
private WebMarkupContainer breadcrumbAndActions;
private WebMarkupContainer contents;
@Inject
private EtcdProxyFactory proxyFactory;
private IModel<String> registry;
private final IModel<String> key;
private final IModel<String> parentKey;
public EtcdNodePanel(String id, IModel<String> etcdRegistry, IModel<String> keyModel) {
super(id);
this.registry = etcdRegistry;
this.key = keyModel;
setModel(new LoadableDetachableModel<EtcdNode>() {
private static final long serialVersionUID = 1L;
@Override
protected EtcdNode load() {
if (registry.getObject() == null) {
return null;
}
try (EtcdProxy p = proxyFactory.getEtcdProxy(registry.getObject())) {
return p.getNode(key.getObject());
} catch (Exception e) {
log.warn(e.getLocalizedMessage(), e);
// TODO: handle this exception and show some alert on page
error("Could not retrieve key " + key.getObject() + ": " + e.toString());
EtcdNodePanel.this.setEnabled(false);
return null;
}
}
});
parentKey = new ParentKeyModel();
setOutputMarkupId(true);
createModalPanels();
add(breadcrumbAndActions = new WebMarkupContainer("breadcrumbAndActions"));
breadcrumbAndActions.setOutputMarkupId(true);
createBreadcrumb();
createNodeActions();
add(new WebMarkupContainer("icon").add(new AttributeModifier("class", new StringResourceModel("icon.node.dir.${dir}", getModel(), ""))));
add(new Label("key", new PropertyModel<>(getModel(), "key")));
add(contents = new WebMarkupContainer("contents"));
contents.setOutputMarkupId(true);
WebMarkupContainer currentNode;
contents.add(currentNode = new WebMarkupContainer("currentNode"));
currentNode.add(new AttributeAppender("class", new StringResourceModel("nodeClass", getModel(), "") , " "));
currentNode.add(new Label("createdIndex", new PropertyModel<>(getModel(), "createdIndex")));
currentNode.add(new Label("modifiedIndex", new PropertyModel<>(getModel(), "modifiedIndex")));
currentNode.add(new Label("ttl", new PropertyModel<>(getModel(), "ttl")));
currentNode.add(new Label("expiration", new PropertyModel<>(getModel(), "expiration")));
contents.add(new TriggerModalLink<EtcdNode>("editValue", getModel(), editNodeModal) {
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure() {
super.onConfigure();
if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) {
add(AttributeAppender.append("disabled", "disabled"));
} else {
add(AttributeModifier.remove("disabled"));
}
// hide value for directory entries
setVisible(EtcdNodePanel.this.getModelObject() != null && !EtcdNodePanel.this.getModelObject().isDir());
}
@Override
protected void onModalTriggerClick(AjaxRequestTarget target) {
updating.setObject(true);
actionModel.setObject(getModelObject());
}
} .add(new MultiLineLabel("value", new PropertyModel<>(getModel(), "value"))));
AbstractLink goUp;
contents.add(goUp = createNavigationLink("goUp", parentKey));
goUp.add(new Behavior() {
private static final long serialVersionUID = 1L;
@Override
public void onConfigure(Component component) {
super.onConfigure(component);
component.setEnabled(key.getObject() != null && !"".equals(key.getObject()) && !"/".equals(key.getObject()));
}
});
contents.add(createNodesView("nodes"));
}
@Override
protected void onDetach() {
super.onDetach();
registry.detach();
key.detach();
parentKey.detach();
}
protected void onNodeKeyUpdated(AjaxRequestTarget target) {
}
protected void onNodedSaved(AjaxRequestTarget target) {
}
protected void onNodedDeleted(AjaxRequestTarget target) {
}
private void createModalPanels() {
add(editNodeModal = new EditNodeModalPanel("editNodeModal", actionModel, registry, updating) {
private static final long serialVersionUID = 1L;
@Override
protected void onNodeSaved(AjaxRequestTarget target) {
super.onNodeSaved(target);
target.add(contents);
EtcdNodePanel.this.onNodedSaved(target);
}
});
add(deleteNodeModal = new DeleteNodeModalPanel("deleteNodeModal", actionModel, registry) {
private static final long serialVersionUID = 1L;
@Override
protected void onNodeDeleted(AjaxRequestTarget target) {
super.onNodeDeleted(target);
PageParameters params = ConvertUtils.getPageParameters(parentKey.getObject());
params.add("cluster", registry.getObject());
setResponsePage(NavigationPage.class, params);
key.setObject(parentKey.getObject());
// target.add(EtcdNodePanel.this);
onNodeKeyUpdated(target);
target.add(contents, breadcrumbAndActions);
EtcdNodePanel.this.onNodedDeleted(target);
}
});
}
private void createNodeActions() {
breadcrumbAndActions.add(new TriggerModalLink<Void>("addNode", editNodeModal) {
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure() {
super.onConfigure();
if (EtcdNodePanel.this.getModelObject() != null && EtcdNodePanel.this.getModelObject().isDir()) {
add(AttributeModifier.remove("disabled"));
} else {
add(AttributeAppender.append("disabled", "disabled"));
}
}
@Override
protected void onModalTriggerClick(AjaxRequestTarget target) {
updating.setObject(false);
actionModel.setObject(new EtcdNode());
String currentKey = key != null? key.getObject() : "";
StringBuffer newKey = new StringBuffer(currentKey);
if (!currentKey.endsWith("/")) {
newKey.append('/');
}
newKey.append("new_node");
actionModel.getObject().setKey(newKey.toString());
}
});
breadcrumbAndActions.add(new TriggerModalLink<EtcdNode>("editNode", getModel(), editNodeModal) {
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure() {
super.onConfigure();
if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) {
add(AttributeAppender.append("disabled", "disabled"));
} else {
add(AttributeModifier.remove("disabled"));
}
}
@Override
protected void onModalTriggerClick(AjaxRequestTarget target) {
updating.setObject(true);
actionModel.setObject(getModelObject());
}
});
breadcrumbAndActions.add(new TriggerModalLink<EtcdNode>("deleteNode", getModel(), deleteNodeModal) {
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure() {
super.onConfigure();
if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) {
add(AttributeAppender.append("disabled", "disabled"));
} else {
add(AttributeModifier.remove("disabled"));
}
}
@Override
protected void onModalTriggerClick(AjaxRequestTarget target) {
actionModel.setObject(getModelObject());
}
});
}
private void createBreadcrumb() {
IModel<List<String>> breadcrumb = new ChainingModel<List<String>>(new PropertyModel<>(getModel(), "key")) {
private static final long serialVersionUID = 1L;
@Override
public List<String> getObject() {
@SuppressWarnings("unchecked")
String key = ((IModel<String>) super.getChainedModel()).getObject();
if (key == null || key.length() == 0 || "/".equals(key)) {
return ROOT_BREADCRUMB;
}
List<String> crumbs = new ArrayList<>();
int index = -1;
while ((index = key.indexOf('/', index + 1)) != -1) {
if (index == 0) {
crumbs.add("/");
} else {
crumbs.add(key.substring(0, index));
}
}
crumbs.add(key);
return crumbs;
}
};
breadcrumbAndActions.add(new ListView<String>("breadcrumb", breadcrumb) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(ListItem<String> item) {
AbstractLink link;
item.add(link = createNavigationLink("key", item.getModel()));
link.add(new Label("label", new KeyLabelModel(item.getModel())));
// Last breadcrumb part should be active
if (item.getIndex() == getViewSize() - 1) {
item.add(new AttributeAppender("class", Model.of("active"), " "));
item.setEnabled(false);
}
}
});
}
private Component createNodesView(String id) {
IModel<List<EtcdNode>> nodes = new LoadableDetachableModel<List<EtcdNode>>() {
private static final long serialVersionUID = 1L;
@Override
protected List<EtcdNode> load() {
if (getModelObject() == null || getModelObject().getNodes() == null) {
return Collections.emptyList();
}
List<EtcdNode> nodes = getModelObject().getNodes();
Collections.sort(nodes, NODE_SORTER);
return nodes;
}
};
return new ListView<EtcdNode>(id, nodes) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(ListItem<EtcdNode> item) {
item.add(new AttributeModifier("class", new StringResourceModel("nodeClass", item.getModel(), "")));
AbstractLink link;
item.add(link = createNavigationLink("key", new PropertyModel<String>(item.getModel(), "key")));
link.add(new Label("label", new KeyLabelModel(new PropertyModel<String>(item.getModel(), "key"))));
item.add(new MultiLineLabel("value", new PropertyModel<>(item.getModel(), "value")));
item.add(new Label("createdIndex", new PropertyModel<>(item.getModel(), "createdIndex")));
item.add(new Label("modifiedIndex", new PropertyModel<>(item.getModel(), "modifiedIndex")));
item.add(new Label("ttl", new PropertyModel<>(item.getModel(), "ttl")));
item.add(new Label("expiration", new PropertyModel<>(item.getModel(), "expiration")));
}
};
}
private AbstractLink createNavigationLink(final String id, final IModel<String> targetKey) {
return new NavigationPageLink(id, registry, targetKey);
/* return new AjaxLink<String>(id, targetKey) {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
key.setObject(getModelObject());
target.add(EtcdNodePanel.this);
onNodeKeyUpdated(target);
}
@Override
public String getBeforeDisabledLink() {
return "";
}
@Override
public String getAfterDisabledLink() {
return "";
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(selectedCluster != null && selectedCluster.getObject() != null && getModelObject() != null );
}
};*/
}
private class ParentKeyModel extends LoadableDetachableModel<String> {
private static final long serialVersionUID = 1L;
@Override
protected String load() {
String etcdKey = key.getObject();
if (etcdKey == null || etcdKey.indexOf('/') == -1) {
return etcdKey;
}
return etcdKey.substring(0, etcdKey.lastIndexOf('/'));
}
}
private class KeyLabelModel extends ChainingModel<String> {
private static final long serialVersionUID = 1L;
public KeyLabelModel(IModel<String> keyModel) {
super(keyModel);
}
public KeyLabelModel(String key) {
super(key);
}
@Override
public String getObject() {
String etcdKey = super.getObject();
if (etcdKey == null || etcdKey.indexOf('/') == -1) {
return etcdKey;
}
return etcdKey.substring(etcdKey.lastIndexOf('/') + 1);
}
}
}
| {
"content_hash": "ea10c9544ddb5bd23a7d6f5ccfbf656d",
"timestamp": "",
"source": "github",
"line_count": 446,
"max_line_length": 145,
"avg_line_length": 37.23094170403587,
"alnum_prop": 0.5859078590785908,
"repo_name": "raoofm/etcd-viewer",
"id": "611a01ee9fb3c4db6736c9facc8f195eac17ef1e",
"size": "16605",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/github/etcd/viewer/html/node/EtcdNodePanel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "37449"
},
{
"name": "Java",
"bytes": "157480"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.