text stringlengths 2 1.04M | meta dict |
|---|---|
<?php
namespace Rooty\TorrentBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Rooty\TrackerBundle\Entity\Torrent;
class GameFormType extends AbstractType
{
private $mode; //are we creating a new entity or editing existing
public function __construct($mode) {
$this->mode = $mode;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('torrent', new TorrentFormType('new'))
->add('type', 'hidden', array('data' => 'games', 'property_path' => false))
->add('genre', 'text', array('label' => 'Жанр:'))
->add('developer', 'text', array('label' => 'Разработчик:'))
->add('publisher', 'text', array('label' => 'Издатель:'))
->add('system_requirements', 'textarea', array('label' => 'Системные требования:'))
->add('crack', 'text', array('label' => 'Крэк:', 'required' => false))
->add('how_to_run', 'textarea', array('label' => 'Запуск:', 'required' => false));
}
public function getName()
{
return 'rooty_torrentbundle_typeformtype';
}
public function getDefaultOptions(array $options)
{
if($this->mode == 'new') {
return array(
'data_class' => 'Rooty\TorrentBundle\Entity\Game',
'validation_groups' => array('new')
);
} else {
return array(
'data_class' => 'Rooty\TorrentBundle\Entity\Game',
'validation_groups' => array('edit'),
);
}
}
} | {
"content_hash": "f7d848d26354f3ae3a6645b03a2761d9",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 95,
"avg_line_length": 32.666666666666664,
"alnum_prop": 0.5438175270108043,
"repo_name": "highway-accident/tracker",
"id": "28f7cc4b85f6e51e2d9715e4255b903aa4114e39",
"size": "1718",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Rooty/TorrentBundle/Form/Type/GameFormType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "145944"
},
{
"name": "PHP",
"bytes": "284721"
}
],
"symlink_target": ""
} |
package org.osgi.service.condpermadmin;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.Bundle;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
/**
* Condition to test if the location of a bundle matches or does not match a
* pattern. Since the bundle's location cannot be changed, this condition is
* immutable.
*
* <p>
* Pattern matching is done according to the filter string matching rules.
*
* @ThreadSafe
* @author $Id: 262e82a5ba72bf4e142179cf037e09a761743382 $
*/
public class BundleLocationCondition {
private static final String CONDITION_TYPE = "org.osgi.service.condpermadmin.BundleLocationCondition";
/**
* Constructs a condition that tries to match the passed Bundle's location
* to the location pattern.
*
* @param bundle The Bundle being evaluated.
* @param info The ConditionInfo from which to construct the condition. The
* ConditionInfo must specify one or two arguments. The first
* argument of the ConditionInfo specifies the location pattern
* against which to match the bundle location. Matching is done
* according to the filter string matching rules. Any '*' characters
* in the first argument are used as wildcards when matching bundle
* locations unless they are escaped with a '\' character. The
* Condition is satisfied if the bundle location matches the pattern.
* The second argument of the ConditionInfo is optional. If a second
* argument is present and equal to "!", then the satisfaction of the
* Condition is negated. That is, the Condition is satisfied if the
* bundle location does NOT match the pattern. If the second argument
* is present but does not equal "!", then the second argument is
* ignored.
* @return Condition object for the requested condition.
*/
static public Condition getCondition(final Bundle bundle, final ConditionInfo info) {
if (!CONDITION_TYPE.equals(info.getType()))
throw new IllegalArgumentException("ConditionInfo must be of type \"" + CONDITION_TYPE + "\"");
String[] args = info.getArgs();
if (args.length != 1 && args.length != 2)
throw new IllegalArgumentException("Illegal number of args: " + args.length);
String bundleLocation = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return bundle.getLocation();
}
});
Filter filter = null;
try {
filter = FrameworkUtil.createFilter("(location=" + escapeLocation(args[0]) + ")");
} catch (InvalidSyntaxException e) {
// this should never happen, but just in case
throw new RuntimeException("Invalid filter: " + e.getFilter(), e);
}
Dictionary<String, String> matchProps = new Hashtable<String, String>(2);
matchProps.put("location", bundleLocation);
boolean negate = (args.length == 2) ? "!".equals(args[1]) : false;
return (negate ^ filter.match(matchProps)) ? Condition.TRUE : Condition.FALSE;
}
private BundleLocationCondition() {
// private constructor to prevent objects of this type
}
/**
* Escape the value string such that '(', ')' and '\' are escaped. The '\'
* char is only escaped if it is not followed by a '*'.
*
* @param value unescaped value string.
* @return escaped value string.
*/
private static String escapeLocation(final String value) {
boolean escaped = false;
int inlen = value.length();
int outlen = inlen << 1; /* inlen * 2 */
char[] output = new char[outlen];
value.getChars(0, inlen, output, inlen);
int cursor = 0;
for (int i = inlen; i < outlen; i++) {
char c = output[i];
switch (c) {
case '\\' :
if (i + 1 < outlen && output[i + 1] == '*')
break;
case '(' :
case ')' :
output[cursor] = '\\';
cursor++;
escaped = true;
break;
}
output[cursor] = c;
cursor++;
}
return escaped ? new String(output, 0, cursor) : value;
}
}
| {
"content_hash": "15f808e82696d8b2fd2aac3c66d66184",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 103,
"avg_line_length": 36.29203539823009,
"alnum_prop": 0.6861741038771031,
"repo_name": "cnoelle/knopflerfish_framework",
"id": "68a09e7762c9d847e4215e93a978cf7b6e426aec",
"size": "4733",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/osgi/service/condpermadmin/BundleLocationCondition.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "2114635"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Network.Models;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Add, "AzureLoadBalancerProbeConfig"), OutputType(typeof(PSLoadBalancingRule))]
public class AddAzureLoadBalancerProbeConfigCommand : AzureLoadBalancerProbeConfigBase
{
[Parameter(
Mandatory = true,
HelpMessage = "The name of the probe")]
[ValidateNotNullOrEmpty]
public override string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
HelpMessage = "The load balancer")]
public PSLoadBalancer LoadBalancer { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
var existingProbe = this.LoadBalancer.Probes.SingleOrDefault(resource => string.Equals(resource.Name, this.Name, System.StringComparison.CurrentCultureIgnoreCase));
if (existingProbe != null)
{
throw new ArgumentException("Probe with the specified name already exists");
}
var probe = new PSProbe();
probe.Name = this.Name;
probe.Port = this.Port;
probe.Protocol = this.Protocol;
probe.RequestPath = this.RequestPath;
probe.IntervalInSeconds = this.IntervalInSeconds;
probe.NumberOfProbes = this.ProbeCount;
probe.Id =
ChildResourceHelper.GetResourceId(
this.NetworkClient.NetworkResourceProviderClient.Credentials.SubscriptionId,
this.LoadBalancer.ResourceGroupName,
this.LoadBalancer.Name,
Microsoft.Azure.Commands.Network.Properties.Resources.LoadBalancerProbeName,
this.Name);
this.LoadBalancer.Probes.Add(probe);
WriteObject(this.LoadBalancer);
}
}
}
| {
"content_hash": "07878c42b4834e74ea92bc69c6b53b96",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 176,
"avg_line_length": 40.41428571428571,
"alnum_prop": 0.6178861788617886,
"repo_name": "kagamsft/azure-powershell",
"id": "3d91b976620f1e61691ddda3925f832773278420",
"size": "2831",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/ResourceManager/Network/Commands.Network/LoadBalancer/Probe/AddAzureLoadBalancerProbeConfigCommand.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15118"
},
{
"name": "C#",
"bytes": "19360314"
},
{
"name": "HTML",
"bytes": "209"
},
{
"name": "JavaScript",
"bytes": "4979"
},
{
"name": "PHP",
"bytes": "41"
},
{
"name": "PowerShell",
"bytes": "1304704"
},
{
"name": "Shell",
"bytes": "50"
}
],
"symlink_target": ""
} |
namespace ParentLoad.DataAccess.ERLevel
{
public partial interface IA05_SubContinent_ReChildDal
{
}
}
| {
"content_hash": "85c2db0f3b807a9818393a28dadedd62",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 57,
"avg_line_length": 20,
"alnum_prop": 0.7,
"repo_name": "CslaGenFork/CslaGenFork",
"id": "d88c8452b8582d01e09880ae8ba69fd32339cfeb",
"size": "120",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "trunk/Samples/DeepLoad/DAL-DTO/ParentLoad.DataAccess/ERLevel/IA05_SubContinent_ReChildDal.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "4816094"
},
{
"name": "Assembly",
"bytes": "73066"
},
{
"name": "C#",
"bytes": "12314305"
},
{
"name": "C++",
"bytes": "313681"
},
{
"name": "HTML",
"bytes": "30950"
},
{
"name": "PHP",
"bytes": "35716"
},
{
"name": "PLpgSQL",
"bytes": "2164471"
},
{
"name": "Pascal",
"bytes": "1244"
},
{
"name": "PowerShell",
"bytes": "1687"
},
{
"name": "SourcePawn",
"bytes": "500196"
},
{
"name": "Visual Basic",
"bytes": "3027224"
}
],
"symlink_target": ""
} |
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Semantics
{
/// <summary>
/// Represents a reference through a pointer.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IPointerIndirectionReferenceExpression : IOperation
{
/// <summary>
/// Pointer to be dereferenced.
/// </summary>
IOperation Pointer { get; }
}
}
| {
"content_hash": "cd45863ae174869912de651424f6e6e2",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 101,
"avg_line_length": 27.5,
"alnum_prop": 0.6363636363636364,
"repo_name": "akrisiun/roslyn",
"id": "5cd6ef58da15b7b1de15098a25a85f7835c8bca8",
"size": "712",
"binary": false,
"copies": "7",
"ref": "refs/heads/dev16",
"path": "src/Compilers/Core/Portable/Operations/IPointerIndirectionReferenceExpression.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "14082"
},
{
"name": "C#",
"bytes": "95237424"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "F#",
"bytes": "3632"
},
{
"name": "Groovy",
"bytes": "10903"
},
{
"name": "Makefile",
"bytes": "3294"
},
{
"name": "PowerShell",
"bytes": "105924"
},
{
"name": "Shell",
"bytes": "8363"
},
{
"name": "Visual Basic",
"bytes": "72868606"
}
],
"symlink_target": ""
} |
package com.linkedin.databus2.relay.config;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import junit.framework.Assert;
import org.apache.log4j.Level;
import org.testng.annotations.Test;
import com.linkedin.databus2.test.TestUtil;
public class TestDatabusRelaySourcesInFile
{
public static final String tmpDir ="/tmp";
static
{
TestUtil.setupLogging(true, "./TestDatabusRelaySourcesInFile.log", Level.WARN);
}
PhysicalSourceConfig createPhysicalSourceConfig(String pSourceName, int startLogicalId,int numSources)
{
PhysicalSourceConfig pconfig = new PhysicalSourceConfig();
pconfig.setName(pSourceName);
pconfig.setUri("http://"+pSourceName);
ArrayList<LogicalSourceConfig> newSources = new ArrayList<LogicalSourceConfig>();
for (int i=0; i < numSources;++i)
{
short lid = (short) (i+startLogicalId);
LogicalSourceConfig tab = new LogicalSourceConfig();
tab.setName("ls"+lid);
tab.setId(lid);
tab.setUri("tab_"+ lid);
newSources.add(tab);
}
pconfig.setSources(newSources);
return pconfig;
}
void checkIfEqual(PhysicalSourceConfig p1, PhysicalSourceConfig p2)
{
Assert.assertNotNull(p1);
Assert.assertNotNull(p2);
String p1String = p1.toString();
String p2String = p2.toString();
Assert.assertEquals(p1String,p2String);
}
@Test
public void testSourceInfoSaveLoad() throws Exception
{
//create a physcial source config object
int numConfigs = 3;
PhysicalSourceConfig[] pConfigs = new PhysicalSourceConfig[numConfigs];
DatabusRelaySourcesInFiles databusSources = new DatabusRelaySourcesInFiles(tmpDir);
String[] pNames = new String[numConfigs];
for (int i=0; i < numConfigs;++i)
{
String pName = "physical"+i;
pNames[i] = pName;
pConfigs[i] = createPhysicalSourceConfig(pName, 100*(i+1), i+1);
Assert.assertTrue(databusSources.add(pName,pConfigs[i]));
}
Assert.assertTrue(databusSources.save());
DatabusRelaySourcesInFiles readSources = new DatabusRelaySourcesInFiles(tmpDir);
Assert.assertTrue(readSources.load());
PhysicalSourceConfig[] readConfigs = readSources.getAll();
Assert.assertEquals(numConfigs,readConfigs.length);
//now compare configs; what was written is what was read
for (String pSrcName: pNames)
{
PhysicalSourceConfig p1 = databusSources.get(pSrcName);
PhysicalSourceConfig p2 = readSources.get(pSrcName);
checkIfEqual(p1,p2);
}
//remove all entries;
databusSources.removePersistedEntries();
//read empty dir
Assert.assertTrue(readSources.load());
PhysicalSourceConfig[] pNoConfigs=readSources.getAll();
Assert.assertEquals(0,pNoConfigs.length);
Assert.assertEquals(0,readSources.size());
}
@Test
public void testLoadWithBadFiles() throws Exception
{
int numConfigs = 1;
PhysicalSourceConfig[] pConfigs = new PhysicalSourceConfig[numConfigs];
DatabusRelaySourcesInFiles databusSources = new DatabusRelaySourcesInFiles(tmpDir);
String[] pNames = new String[numConfigs];
for (int i=0; i < numConfigs;++i)
{
String pName = "physical"+i;
pNames[i] = pName;
pConfigs[i] = createPhysicalSourceConfig(pName, 100*(i+1), i+1);
Assert.assertTrue(databusSources.add(pName,pConfigs[i]));
}
//save 1 legal json file
Assert.assertTrue(databusSources.save());
//now add bad jsob files
String badJson = tmpDir+"/bad.json";
String emptyJson = tmpDir+"/empty.json";
File fBad = new File(badJson);
fBad.createNewFile();
File fEmpty= new File(emptyJson);
fEmpty.createNewFile();
FileWriter w1 = new FileWriter(fBad);
w1.append("This is bad json");
w1.close();
DatabusRelaySourcesInFiles readSources = new DatabusRelaySourcesInFiles(tmpDir);
boolean t = readSources.load();
//delete old files after reading it
fBad.delete();
readSources.removePersistedEntries();
fEmpty.delete();
Assert.assertTrue(t);
PhysicalSourceConfig[] pNoConfigs=readSources.getAll();
Assert.assertEquals(1,pNoConfigs.length);
Assert.assertEquals(1,readSources.size());
}
}
| {
"content_hash": "77f53c762f2118f690a6e08ed91e4ada",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 104,
"avg_line_length": 31.284671532846716,
"alnum_prop": 0.6945870275314979,
"repo_name": "oeohomos/databus",
"id": "cd16641094143ef1120990a279e6947bacd5fcc7",
"size": "4894",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "databus-core/databus-core-impl/src/test/java/com/linkedin/databus2/relay/config/TestDatabusRelaySourcesInFile.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "1134"
},
{
"name": "Java",
"bytes": "7155058"
},
{
"name": "PHP",
"bytes": "933"
},
{
"name": "Python",
"bytes": "940"
},
{
"name": "Shell",
"bytes": "60423"
},
{
"name": "SourcePawn",
"bytes": "211"
}
],
"symlink_target": ""
} |
#pragma once
#include <SDL.h>
#include "../Core/C_Vec2.h"
#include "../Core/C_Texture.h"
/**
@brief A Particle object for use with the Particle System.
@author Jamie Slowgrove
*/
class PS_Particle
{
public:
/**
@brief Constructs the Particle Object.
@param square A pointer to the Texture.
@param scaleValue The scale of the Particle.
@param direction The direction of the Particle.
@param moveSpeed The move speed of the Particle.
@param pos The position of the Particle.
*/
PS_Particle(C_Texture* texture, float scaleValue, C_Vec2 direction, float moveSpeed, C_Vec2 pos);
/**
@brief Constructs the Particle Object.
@param square A pointer to the Texture.
@param scaleValue The scale of the Particle.
@param direction The direction of the Particle.
@param moveSpeed The move speed of the Particle.
@param pos The position of the Particle.
@param tintColour The tint colour of the Particle.
*/
PS_Particle(C_Texture* texture, float scaleValue, C_Vec2 direction, float moveSpeed,
C_Vec2 pos, SDL_Colour tintColour);
/**
@brief Destructs the Particle Object deleting the Particle Object from memory.
*/
~PS_Particle();
/**
@brief A function that updates the Particle.
@param dt The delta time.
*/
void update(float dt);
/**
@brief Draw the Entity to the screen.
@param renderer A pointer to the renderer.
*/
void draw(SDL_Renderer* renderer);
/**
@brief Move the Particle.
@param movement The amount to move by.
*/
void move(C_Vec2 movement);
/**
@brief Sets the position of the Particle.
@param pos The new position.
*/
void setPosition(C_Vec2 pos);
/**
@brief Sets the scale of the Particle.
@param scaleValue The new scale.
*/
void setScale(float scaleValue);
/**
@brief Sets the moveSpeed of the Particle.
@param moveSpeed The new moveSpeed.
*/
void setMoveSpeed(float moveSpeed);
/**
@brief Sets the direction of the Particle.
@param direction The new direction.
*/
void setDirection(C_Vec2 direction);
/**
@brief Gets the moveSpeed of the Particle.
@returns The moveSpeed.
*/
float getMoveSpeed();
/**
@brief Gets the position of the Particle.
@returns The position of the Particle.
*/
C_Vec2 getPosition();
/**
@brief Gets the direction of the Particle.
@returns The direction of the Particle.
*/
C_Vec2 getDirection();
/**
@brief Gets the scale of the Particle.
@returns The scale of the Particle.
*/
float getScale();
private:
///A pointer to the Texture.
C_Texture* texture;
///The direction of the Particle.
C_Vec2 direction;
///The Position of the Particle.
C_Vec2 pos;
///The scale of the Particle.
float scaleValue;
///The movement speed of the Particle.
float moveSpeed;
///A boolean for if the Particle should be tinted.
bool tint;
///The Tint colour of the Particle.
SDL_Colour tintColour;
};
| {
"content_hash": "4a2148c6736d6bdf1fe938aa63e953c5",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 98,
"avg_line_length": 23.10655737704918,
"alnum_prop": 0.7162114224902447,
"repo_name": "JSlowgrove/Sky-Zone-Omega-PC",
"id": "fb4fcc7c42e162ff392dd1d8d242ab7dba52729a",
"size": "2819",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SkyZoneOmegaPC/ParticleSystem/PS_Particle.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "16"
},
{
"name": "C++",
"bytes": "208634"
}
],
"symlink_target": ""
} |
package com.gunshippenguin.jchat.server;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.gunshippenguin.jchat.shared.AcceptedToChatRoomEvent;
import com.gunshippenguin.jchat.shared.ChatRoomInfo;
import com.gunshippenguin.jchat.shared.Event;
import com.gunshippenguin.jchat.shared.JoinChatRoomEvent;
import com.gunshippenguin.jchat.shared.LeaveChatRoomEvent;
/**
* Class representing a chat room on the server side. Contains methods to obtain
* information about the chat room and interface with its connected clients.
*
* @author GunshipPenguin
*
*/
public class ChatRoom {
protected ChatRoomInfo chatRoomInfo;
protected ArrayList<Client> clients;
private static final Logger logger = Logger.getLogger(ChatRoom.class.getName());
public ChatRoom(String name) {
clients = new ArrayList<Client>();
this.chatRoomInfo = new ChatRoomInfo(name);
}
/**
* Sends the event evnt to all clients in this chat room.
*
* @param evnt
* The event to send
*/
public void sendEventToAllClients(Event evnt) {
logger.log(Level.FINE,
"Event " + evnt.toString() + " being sent to all clients in chat room " + chatRoomInfo.getName());
for (Client c : clients) {
c.sendEvent(evnt);
}
return;
}
/**
* Removes the client with nickname nick from the ChatRoom.
*
* @param nick
* The nickname of the client to remove
*/
public synchronized void removeClient(String nick) {
logger.log(Level.INFO, "Client " + nick + " leaving chat room " + chatRoomInfo.getName());
Iterator<Client> it = clients.iterator();
Client clientToRemove = null;
while (it.hasNext()) {
clientToRemove = it.next();
if (clientToRemove.getClientInfo().getNick().equals(nick)) {
clients.remove(clientToRemove);
break;
}
}
if (clientToRemove != null) {
chatRoomInfo.removeClient(nick);
sendEventToAllClients(
new LeaveChatRoomEvent(clientToRemove.getClientInfo().getNick(), chatRoomInfo.getName()));
} else {
throw new RuntimeException("Trying to remove client " + nick + " from chatRoom " + chatRoomInfo.getName()
+ " but client does not exist");
}
return;
}
/**
* Adds the client client to the ChatRoom.
*
* @param client
* The client to add
*/
public synchronized void addClient(Client client) {
logger.log(Level.INFO,
"Client " + client.getClientInfo().getNick() + " joining chat room" + chatRoomInfo.getName());
sendEventToAllClients(new JoinChatRoomEvent(client.getClientInfo(), chatRoomInfo.getName()));
clients.add(client);
chatRoomInfo.addClient(client.getClientInfo());
client.sendEvent(new AcceptedToChatRoomEvent(chatRoomInfo));
return;
}
/**
* Returns true if a client with nick clientNick is in this ChatRoom, false
* otherwise.
*
* @param nick
* The nickname of the client to search for.
* @return True if a client exists in this chatRoom with the nick
* clientNick, false otherwise.
*/
public boolean hasClient(String nick) {
for (Client c : clients) {
if (c.getClientInfo().getNick().equals(nick)) {
return true;
}
}
return false;
}
/**
* If a client exists in this ChatRoom with the nickname nick, returns its
* Client object. If there is no client with the nick nick in this ChatRoom,
* throws a runtime exception.
*
* @param nick
* The nickname of the client whose Client object should be
* returned
* @return The client object of the client with the nickname nick.
*/
public Client getClientByNick(String nick) {
for (Client c : clients) {
if (c.getClientInfo().getNick().equals(nick)) {
return c;
}
}
throw new RuntimeException("Client with nickname of " + nick + " could not be found");
}
/**
* Returns the ChatRoomInfo for this ChatRoom.
*
* @return The ChatRoomInfo for this ChatRoom
*/
public ChatRoomInfo getChatRoomInfo() {
return chatRoomInfo;
}
}
| {
"content_hash": "ba18234335f0eea7ea84755f2906815e",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 108,
"avg_line_length": 29.725925925925925,
"alnum_prop": 0.6967356092698729,
"repo_name": "GunshipPenguin/jchat",
"id": "12387083a498d78b59eb6671fd375040559f1948",
"size": "4013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/gunshippenguin/jchat/server/ChatRoom.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "77457"
}
],
"symlink_target": ""
} |
package de.nedelosk.modularmachines.common.core;
import de.nedelosk.modularmachines.api.energy.EnergyRegistry;
import de.nedelosk.modularmachines.api.material.EnumMetalMaterials;
import de.nedelosk.modularmachines.api.recipes.OreStack;
import de.nedelosk.modularmachines.api.recipes.RecipeItem;
import de.nedelosk.modularmachines.api.recipes.RecipeRegistry;
import de.nedelosk.modularmachines.api.recipes.RecipeUtil;
import de.nedelosk.modularmachines.common.blocks.BlockMetalBlock.ComponentTypes;
import de.nedelosk.modularmachines.common.items.ItemComponent;
import de.nedelosk.modularmachines.common.items.ItemModule;
import de.nedelosk.modularmachines.common.modules.storaged.tools.ModuleLathe.LatheModes;
import de.nedelosk.modularmachines.common.modules.storaged.tools.recipe.RecipeHandlerDefault;
import de.nedelosk.modularmachines.common.modules.storaged.tools.recipe.RecipeHandlerHeat;
import de.nedelosk.modularmachines.common.modules.storaged.tools.recipe.RecipeHandlerToolMode;
import de.nedelosk.modularmachines.common.recipse.ShapedModuleRecipe;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
public class RecipeManager {
public static void registerRecipes() {
RecipeRegistry.registerRecipeHandler(new RecipeHandlerHeat("Boiler"));
RecipeRegistry.registerRecipeHandler(new RecipeHandlerHeat("AlloySmelter"));
RecipeRegistry.registerRecipeHandler(new RecipeHandlerDefault("Pulverizer"));
RecipeRegistry.registerRecipeHandler(new RecipeHandlerToolMode("Lathe", RecipeUtil.LATHEMODE));
registerSawMillRecipes();
registerPulverizerRecipes();
registerAlloySmelterRecipes();
registerBoilerRecipes();
registerLatheRecipes();
addComponentRecipes();
addMetalRecipes();
addMachineRecipes();
addNormalRecipes();
addModuleRecipes();
}
private static void addModuleRecipes(){
addShapedRecipe(new ItemStack(ItemManager.itemModuleCore),
"PWP",
"WRW",
"PWP", 'P', "plateIron", 'W', "wireIron", 'R', "dustRedstone");
addShapedRecipe(new ItemStack(ItemManager.itemModuleCore, 1, 1),
"BWB",
"PRP",
"BWB", 'P', "plateBronze", 'W', "wireBronze", 'R', "blockRedstone", 'B', new ItemStack(ItemManager.itemModuleCore));
addShapedRecipe(new ItemStack(ItemManager.itemModuleCore, 1, 2),
"BWB",
"PSP",
"BWB", 'P', "plateSteel", 'W', "wireSteel", 'S', "blockSteel", 'B', new ItemStack(ItemManager.itemModuleCore, 1, 1));
//Drawers
addShapedRecipe(new ItemStack(ItemManager.itemDrawer, 1, 0),
"BIB",
"BIB",
"BIB", 'I', "ingotBrick", 'B', new ItemStack(Blocks.BRICK_BLOCK));
//Engines
addShapedModuleRecipe(new ItemStack(ItemManager.itemEngineSteam),
"GHP",
"BII",
"GHP", 'I', "ingotIron", 'H', "blockIron", 'G', "gearIron", 'P', "plateIron", 'B', Blocks.PISTON);
//Turbines
addShapedModuleRecipe(new ItemStack(ItemManager.itemTurbineSteam),
"SPI",
"PBP",
"IPS", 'I', "ingotIron", 'B', "blockIron", 'P', "plateIron", 'S', "screwIron");
//Heaters
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.moduleHeaterBurningIron.getRegistryName(), EnumMetalMaterials.IRON),
"GPR",
"FCF",
"RPG", 'R', "rodIron", 'G', "gearIron", 'P', "plateIron", 'F', Blocks.FURNACE, 'C', new ItemStack(ItemManager.itemModuleCore));
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.moduleHeaterBronzeLarge.getRegistryName(), EnumMetalMaterials.BRONZE),
"GPR",
"COC",
"RPG", 'R', "rodBronze", 'G', "gearBronze", 'P', "plateBronze", 'C', new ItemStack(ItemManager.itemModuleCore, 1, 1), 'O', ItemModule.getItem(ModuleManager.moduleHeaterBurningIron.getRegistryName(), EnumMetalMaterials.IRON));
//Alloy Smleters
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.moduleAlloySmelterIron.getRegistryName(), EnumMetalMaterials.IRON),
"PWP",
"FCF",
"PWP", 'W', "wireIron", 'F', Blocks.FURNACE, 'P', "plateIron", 'C', new ItemStack(ItemManager.itemModuleCore));
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.moduleAlloySmelterBronze.getRegistryName(), EnumMetalMaterials.BRONZE),
"PPP",
"COC",
"PPP", 'O', ItemModule.getItem(ModuleManager.moduleAlloySmelterIron.getRegistryName(), EnumMetalMaterials.IRON), 'F', Blocks.FURNACE, 'P', "plateBronze", 'C', new ItemStack(ItemManager.itemModuleCore, 1, 1));
//Pulverizer
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.modulePulverizerIron.getRegistryName(), EnumMetalMaterials.IRON),
"RWF",
"PCP",
"FWR", 'W', "wireIron", 'R', "rodIron", 'F', Items.FLINT, 'P', "plateIron", 'C', new ItemStack(ItemManager.itemModuleCore));
addShapedModuleRecipe(ItemModule.getItem(ModuleManager.modulePulverizerBronze.getRegistryName(), EnumMetalMaterials.BRONZE),
"PRP",
"COC",
"PRP", 'O', ItemModule.getItem(ModuleManager.modulePulverizerIron.getRegistryName(), EnumMetalMaterials.IRON), 'F', Blocks.FURNACE, 'P', "plateBronze", 'R', "rodBronze", 'C', new ItemStack(ItemManager.itemModuleCore, 1, 1));
}
private static void addNormalRecipes() {
addShapedRecipe(new ItemStack(ItemManager.itemHammer), "+S+", "+S+", " - ", '+', "ingotIron", 'S', "stone", '-', "stickWood");
addShapedRecipe(new ItemStack(ItemManager.itemFileIron), true, " I", "FIF", "S ", 'I', "ingotIron", 'F', Items.FLINT, 'S', "stickWood");
addShapedRecipe(new ItemStack(ItemManager.itemFileDiamond), true, " D", "FDF", "S ", 'D', "gemDiamond", 'F', Items.FLINT, 'S', "stickWood");
addShapedRecipe(new ItemStack(ItemManager.itemCutter), " S", " S ", "FIF", 'I', "ingotIron", 'F', Items.FLINT, 'S', "stickWood");
}
private static void addMachineRecipes() {
//Casings
addShapedRecipe(new ItemStack(BlockManager.blockCasings), "+++", "+ +", "---", '+', "plateIron", '-', Blocks.BRICK_BLOCK);
addShapedRecipe(new ItemStack(BlockManager.blockCasings, 1, 1), "+++", "+ +", "---", '+', "plateBronze", '-', Blocks.BRICK_BLOCK);
}
private static void addMetalRecipes() {
for(int m = 0; m < ItemManager.metals.length; m++) {
Object[][] metal = ItemManager.metals[m];
for(int i = 0; i < metal.length; ++i) {
addShapedRecipe(new ItemStack(ItemManager.itemIngots, 1, m * 10 + i), "+++", "+++", "+++", '+', "nugget" + metal[i][0]);
addShapelessRecipe(new ItemStack(ItemManager.itemNuggets, 9, m * 10 + i), "ingot" + metal[i][0]);
}
}
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 2), new ItemStack(Items.IRON_INGOT), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 3), new ItemStack(Items.GOLD_INGOT), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 10), new ItemStack(ItemManager.itemIngots, 1, 0), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 11), new ItemStack(ItemManager.itemIngots, 1, 1), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 12), new ItemStack(ItemManager.itemIngots, 1, 2), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 13), new ItemStack(ItemManager.itemIngots, 1, 3), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 14), new ItemStack(ItemManager.itemIngots, 1, 4), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 15), new ItemStack(ItemManager.itemIngots, 1, 5), 0.5F);
GameRegistry.addSmelting(new ItemStack(ItemManager.itemDusts, 1, 16), new ItemStack(ItemManager.itemIngots, 1, 6), 0.5F);
}
private static void addComponentRecipes() {
for(int i = 0; i < ItemManager.itemCompPlates.materials.size(); i++) {
ItemStack stack = new ItemStack(ItemManager.itemCompPlates, 1, i);
ItemComponent component = (ItemComponent) stack.getItem();
if (component.materials.get(i).getOreDicts() != null) {
for(String oreDict : component.materials.get(i).getOreDicts()) {
addShapelessRecipe(stack, "ingot" + oreDict, "ingot" + oreDict, "toolHammer");
}
}
}
for(int i = 0; i < ItemManager.itemCompWires.materials.size(); i++) {
ItemStack stack = new ItemStack(ItemManager.itemCompWires, 4, i);
ItemComponent component = (ItemComponent) stack.getItem();
if (component.materials.get(i).getOreDicts() != null) {
for(String oreDict : component.materials.get(i).getOreDicts()) {
if (!oreDict.equals("Bronze") && !oreDict.equals("Steel")) {
addShapelessRecipe(stack, "plate" + oreDict, "toolCutter");
} else {
RecipeUtil.addLathe("plate" + oreDict + "ToWire", new RecipeItem(new OreStack("plate" + oreDict)),
new RecipeItem(new ItemStack(ItemManager.itemCompWires, 8, i)), 3, LatheModes.WIRE);
}
}
}
}
for(int i = 0; i < ItemManager.itemCompScrews.materials.size(); i++) {
ItemStack stack = new ItemStack(ItemManager.itemCompScrews, 1, i);
ItemComponent component = (ItemComponent) stack.getItem();
if (component.materials.get(i).getOreDicts() != null) {
for(String oreDict : component.materials.get(i).getOreDicts()) {
RecipeUtil.addLathe("wire" + oreDict + "ToScrew", new RecipeItem(new OreStack("wire" + oreDict, 2)), new RecipeItem(stack), 3,
LatheModes.SCREW);
}
}
}
for(ComponentTypes type : ComponentTypes.values()) {
ItemStack stack = new ItemStack(BlockManager.blockMetalBlocks, 1, type.ordinal());
for(String oreDict : type.oreDict) {
addShapedRecipe(stack, "+++", "+++", "+++", '+', "ingot" + oreDict);
}
}
for(ComponentTypes type : ComponentTypes.values()) {
ItemStack stack = new ItemStack(BlockManager.blockMetalBlocks, 1, type.ordinal());
for(String oreDict : type.oreDict) {
if (OreDictionary.getOres("ingot" + oreDict) != null && !OreDictionary.getOres("ingot" + oreDict).isEmpty()) {
ItemStack ore = OreDictionary.getOres("ingot" + oreDict).get(0).copy();
ore.stackSize = 9;
addShapelessRecipe(ore, stack);
}
}
}
addShapelessRecipe(new ItemStack(ItemManager.itemCompRods, 1, 0), "ingotIron", "ingotIron", "toolFile");
addShapelessRecipe(new ItemStack(ItemManager.itemCompRods, 1, 1), "ingotTin", "ingotTin", "toolFile");
addShapelessRecipe(new ItemStack(ItemManager.itemCompRods, 1, 2), "ingotCopper", "ingotCopper", "toolFile");
addShapelessRecipe(new ItemStack(ItemManager.itemCompRods, 1, 3), "ingotBronze", "ingotBronze", "toolFile");
addShapelessRecipe(new ItemStack(ItemManager.itemCompRods, 1, 4), "ingotSteel", "ingotSteel", "toolFile");
addShapedRecipe(new ItemStack(ItemManager.itemCompSawBlades), " + ", "+-+", " + ", '+', new ItemStack(ItemManager.itemCompRods), '-', "cobblestone");
addShapedRecipe(new ItemStack(ItemManager.itemCompGears), " + ", "+-+", " + ", '+', "plateStone", '-', "cobblestone");
addShapedRecipe(new ItemStack(BlockManager.blockAssembler), "IPI", "PRP", "III", 'I', "ingotIron", 'P', "plateIron", 'R', "blockRedstone");
}
private static void registerLatheRecipes() {
RecipeUtil.addLathe("IronRod", new RecipeItem(new OreStack("ingotIron")), new RecipeItem(new ItemStack(ItemManager.itemCompRods, 2, 0)), 1, LatheModes.ROD);
RecipeUtil.addLathe("TinRod", new RecipeItem(new OreStack("ingotTin")), new RecipeItem(new ItemStack(ItemManager.itemCompRods, 2, 1)), 2, LatheModes.ROD);
RecipeUtil.addLathe("CopperRod", new RecipeItem(new OreStack("ingotCopper")), new RecipeItem(new ItemStack(ItemManager.itemCompRods, 2, 2)), 1, LatheModes.ROD);
RecipeUtil.addLathe("BronzeRod", new RecipeItem(new OreStack("ingotBronze")), new RecipeItem(new ItemStack(ItemManager.itemCompRods, 2, 3)), 2, LatheModes.ROD);
RecipeUtil.addLathe("SteelRod", new RecipeItem(new OreStack("ingotSteel")), new RecipeItem(new ItemStack(ItemManager.itemCompRods, 2, 4)), 3, LatheModes.ROD);
}
private static void registerSawMillRecipes() {
//RecipeUtil.addSawMill("OakPlanks", new ItemStack(Blocks.LOG, 1, 0), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 0))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10, 300);
//RecipeUtil.addSawMill("SprucePlanks", new ItemStack(Blocks.LOG, 1, 1), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 1))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10,
// 300);
//RecipeUtil.addSawMill("BirchPlanks", new ItemStack(Blocks.LOG, 1, 2), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 2))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10,
// 300);
//RecipeUtil.addSawMill("JunglePlanks", new ItemStack(Blocks.LOG, 1, 3), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 3))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10,
// 300);
//RecipeUtil.addSawMill("AcaciaPlanks", new ItemStack(Blocks.LOG2, 1, 0), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 4))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10,
// 300);
//RecipeUtil.addSawMill("DarkOakPlanks", new ItemStack(Blocks.LOG2, 1, 1), new RecipeItem[] { new RecipeItem(new ItemStack(Blocks.PLANKS, 6, 5))/*, new RecipeItem(new ItemStack(ItemManager.itemNature), 50)*/ }, 10,
// 300);
}
private static void registerPulverizerRecipes() {
/* ORES */
RecipeUtil.addPulverizer("CoalOreToDust", new OreStack("oreCoal"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 0)), new RecipeItem(new ItemStack(Items.COAL), 15) }, 15);
RecipeUtil.addPulverizer("ObsidianBlockToDust", new OreStack("blockObsidian"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 1)) }, 15);
RecipeUtil.addPulverizer("IronOreToDust", new OreStack("oreIron"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 2)) }, 15);
RecipeUtil.addPulverizer("GoldOreToDust", new OreStack("oreGold"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 3)), new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 10), 20) }, 15);
RecipeUtil.addPulverizer("DiamondOreToDust", new OreStack("oreDiamond"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 4)) }, 15);
RecipeUtil.addPulverizer("CopperOreToDust", new OreStack("oreCopper"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 10)), new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 3), 15) }, 12);
RecipeUtil.addPulverizer("TinOreToDust", new OreStack("oreTin"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 11)) }, 15);
RecipeUtil.addPulverizer("SilverOreToDust", new OreStack("oreSilver"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 12)) }, 15);
RecipeUtil.addPulverizer("LeadOreToDust", new OreStack("oreLead"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 13)) }, 15);
RecipeUtil.addPulverizer("NickelOreToDust", new OreStack("oreNickel"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 14)) }, 15);
RecipeUtil.addPulverizer("AluminumOreToDust", new OreStack("oreAluminum"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 15)) }, 15);
RecipeUtil.addPulverizer("AluminiumOreToDust", new OreStack("oreAluminium"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 2, 15)) }, 15);
RecipeUtil.addPulverizer("RedstoneOreToDust", new OreStack("oreRedstone"), new RecipeItem[] { new RecipeItem(new ItemStack(Items.REDSTONE, 8)) }, 15);
RecipeUtil.addPulverizer("CoalToDust", new OreStack("itemCoal"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 0)) }, 7);
/* INGOTS */
RecipeUtil.addPulverizer("IronIngotToDust", new OreStack("ingotIron"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 2)) }, 7);
RecipeUtil.addPulverizer("GoldIngotToDust", new OreStack("ingotGold"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 3)) }, 7);
RecipeUtil.addPulverizer("DiamondGemToDust", new OreStack("gemDiamond"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 4)) }, 7);
RecipeUtil.addPulverizer("CopperIngotToDust", new OreStack("ingotCopper"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 20)) }, 7);
RecipeUtil.addPulverizer("TinIngotToDust", new OreStack("ingotTin"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 11)) }, 7);
RecipeUtil.addPulverizer("SilverIngotToDust", new OreStack("ingotSilver"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 12)) }, 7);
RecipeUtil.addPulverizer("LeadIngotToDust", new OreStack("ingotLead"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 13)) }, 7);
RecipeUtil.addPulverizer("NickelIngotToDust", new OreStack("ingotNickel"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 14)) }, 7);
RecipeUtil.addPulverizer("AluminumIngotToDust", new OreStack("ingotAluminum"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 15)) }, 7);
RecipeUtil.addPulverizer("AluminiumIngotToDust", new OreStack("ingotAluminium"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 15)) }, 7);
RecipeUtil.addPulverizer("BronzeIngotToDust", new OreStack("ingotBronze"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 20)) }, 7);
RecipeUtil.addPulverizer("InvarIngotToDust", new OreStack("ingotInvar"), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemDusts, 1, 21)) }, 7);
}
private static void registerAlloySmelterRecipes() {
/* BRONZE */
RecipeUtil.addAlloySmelter("DustDustToBronze", new RecipeItem(new OreStack("dustTin", 1)), new RecipeItem(new OreStack("dustCopper", 3)), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemIngots, 4, 10)) }, 11, 125, 0.25);
RecipeUtil.addAlloySmelter("DustIngotToBronze", new RecipeItem(new OreStack("ingotTin", 1)), new RecipeItem(new OreStack("ingotCopper", 3)), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemIngots, 4, 10)) }, 11, 125, 0.25);
/* INVAR */
RecipeUtil.addAlloySmelter("DustDustToInvar", new RecipeItem(new OreStack("dustIron", 2)), new RecipeItem(new OreStack("dustNickel", 1)), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemIngots, 3, 11)) }, 9, 175, 0.5);
RecipeUtil.addAlloySmelter("DustIngotToInvar", new RecipeItem(new OreStack("ingotIron", 2)), new RecipeItem(new OreStack("ingotNickel", 1)), new RecipeItem[] { new RecipeItem(new ItemStack(ItemManager.itemIngots, 3, 11)) }, 9, 175, 0.5);
}
private static void registerBoilerRecipes(){
//ONLY FOR JEI
RecipeUtil.addBoilerRecipe("WaterToSteam", new RecipeItem(new FluidStack(FluidRegistry.WATER, 1)), new RecipeItem(new FluidStack(FluidRegistry.getFluid("steam"), EnergyRegistry.STEAM_PER_UNIT_WATER)), 1, 100, 0D);
}
private static void addShapedModuleRecipe(ItemStack stack, Object... obj) {
GameRegistry.addRecipe(new ShapedModuleRecipe(stack, obj));
}
private static void addShapedRecipe(ItemStack stack, Object... obj) {
GameRegistry.addRecipe(new ShapedOreRecipe(stack, obj));
}
private static void addShapelessRecipe(ItemStack stack, Object... obj) {
GameRegistry.addRecipe(new ShapelessOreRecipe(stack, obj));
}
}
| {
"content_hash": "5fc5d3c37297cd5f3683b26fc9e721f6",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 241,
"avg_line_length": 68.98233215547704,
"alnum_prop": 0.7309189632209815,
"repo_name": "Nedelosk/Forest-Mods",
"id": "d2a8e81b5644aee5fbb6caa7aaab15f2d9318079",
"size": "19522",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev-1.9",
"path": "src/main/java/de/nedelosk/modularmachines/common/core/RecipeManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1057246"
}
],
"symlink_target": ""
} |
<?php
/**
* @category Xi_Test
* @package Xi_Acl
* @group Xi_Acl
* @author Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
*/
class Xi_Acl_Builder_PrivilegeTest extends PHPUnit_Framework_TestCase
{
public function getPrivilegeMock(array $methods = array())
{
return $this->getMock('Xi_Acl_Builder_Privilege_Abstract', array_merge($methods, array('setRole', 'addPrivilege', 'getOperation')));
}
public function testThrowsExceptionOnInvalidRole()
{
$this->setExpectedException('Xi_Acl_Builder_Privilege_Exception');
$builder = new Xi_Acl_Builder_Privilege;
$builder->build(new Zend_Config(array('allow' => 'invalid')));
}
public function testHasAllowAndDenyBuildersByDefault()
{
$builder = new Xi_Acl_Builder_Privilege;
$this->assertEquals(array(), array_diff_key(array('allow', 'deny'), array_keys($builder->getBuilders())));
}
public function testCanParseFlatAccessList()
{
$acl = new Zend_Acl;
$acl->addRole(new Zend_Acl_Role('role'));
$privilege = $this->getPrivilegeMock();
$privilege->expects($this->once())->method('setRole')->with($this->equalTo('role'));
$privilege->expects($this->once())->method('addPrivilege')->with($this->equalTo(null), $this->equalTo(null));
$builder = new Xi_Acl_Builder_Privilege($acl);
$builder->setBuilders(array('mock' => $privilege));
$builder->build(new Zend_Config(array('mock' => 'role')));
}
public function testCanParseFlatAccessListWithArray()
{
$acl = new Zend_Acl;
$acl->addRole(new Zend_Acl_Role('role'));
$privilege = $this->getPrivilegeMock();
$privilege->expects($this->once())->method('setRole')->with($this->equalTo('role'));
$privilege->expects($this->once())->method('addPrivilege')->with($this->equalTo(null), $this->equalTo(null));
$builder = new Xi_Acl_Builder_Privilege($acl);
$builder->setBuilders(array('mock' => $privilege));
$builder->build(new Zend_Config(array('mock' => array('role'))));
}
public function testCanParseNestedAccessList()
{
$acl = new Zend_Acl;
$acl->addRole(new Zend_Acl_Role('role'));
$acl->add(new Zend_Acl_Resource('resource'));
$privilege = $this->getPrivilegeMock();
$privilege->expects($this->once())->method('setRole')->with($this->equalTo('role'));
$privilege->expects($this->once())->method('addPrivilege')->with($this->equalTo('resource'), $this->equalTo(null));
$builder = new Xi_Acl_Builder_Privilege($acl);
$builder->setBuilders(array('mock' => $privilege));
$builder->build(new Zend_Config(array('mock' => array('role' => 'resource'))));
}
public function testCanParseListOfResources()
{
$config = new Zend_Config(array('mock' => array('role' => array('resource'))));
$acl = new Zend_Acl;
$acl->addRole(new Zend_Acl_Role('role'));
$acl->add(new Zend_Acl_Resource('resource'));
$privilege = $this->getPrivilegeMock(array('build'));
$privilege->expects($this->once())->method('setRole')->with($this->equalTo('role'));
$privilege->expects($this->once())->method('build')->with($this->equalTo($config->mock->role));
$builder = new Xi_Acl_Builder_Privilege($acl);
$builder->setBuilders(array('mock' => $privilege));
$builder->build($config);
}
}
| {
"content_hash": "3bbe8df1d8d0116c0a9191efcd54f16c",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 140,
"avg_line_length": 41.18888888888889,
"alnum_prop": 0.5816023738872403,
"repo_name": "Ezku/xi-framework",
"id": "aa306ae1dffc216fd864d1eb8fcd4f12aa24d36a",
"size": "3707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/tests/Xi/Acl/Builder/PrivilegeTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "20000"
},
{
"name": "PHP",
"bytes": "17590007"
}
],
"symlink_target": ""
} |
include_recipe "deploy"
include_recipe "opsworks_sidekiq::service"
node[:deploy].each do |application, deploy|
unless node[:sidekiq][application]
next
end
execute "restart Sidekiq app #{application}" do
cwd deploy[:current_path]
command node[:sidekiq][application][:restart_command]
action :nothing
end
node.default[:deploy][application][:database][:adapter] = OpsWorks::RailsConfiguration.determine_database_adapter(application, node[:deploy][application], "#{node[:deploy][application][:deploy_to]}/current", force: node[:force_database_adapter_detection])
deploy = node[:deploy][application]
template "#{deploy[:deploy_to]}/shared/config/database.yml" do
source "database.yml.erb"
cookbook 'rails'
mode "0660"
group deploy[:group]
owner deploy[:user]
variables(
database: deploy[:database],
environment: deploy[:rails_env]
)
notifies :run, "execute[restart Sidekiq app #{application}]"
only_if do
deploy[:database][:host].present? && File.directory?("#{deploy[:deploy_to]}/shared/config/")
end
end
template "#{deploy[:deploy_to]}/shared/config/memcached.yml" do
source "memcached.yml.erb"
cookbook 'rails'
mode "0660"
group deploy[:group]
owner deploy[:user]
variables(
memcached: deploy[:memcached] || {},
environment: deploy[:rails_env]
)
notifies :run, "execute[restart Rails app #{application}]"
only_if do
deploy[:memcached][:host].present? && File.directory?("#{deploy[:deploy_to]}/shared/config/")
end
end
end
| {
"content_hash": "3fdc0e9674ca1a4b1011f2cca7a9d6ad",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 257,
"avg_line_length": 28.78181818181818,
"alnum_prop": 0.6746683512318383,
"repo_name": "fred/opsworks_sidekiq",
"id": "ac7c53c483f65adf2bbcdfa447eda9b1e4183a3b",
"size": "1698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/configure.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1235"
},
{
"name": "Ruby",
"bytes": "7809"
}
],
"symlink_target": ""
} |
#import "AutoManageViewController.h"
#import "UISelectCell.h"
@interface AutoManageViewController ()
@end
@implementation AutoManageViewController
@synthesize cellDataArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (id)initWithList:(NSMutableArray *)list WithType:(ESettingType)type
{
self = [super init];
if (self)
{
self.cellDataArray = list;
settingType = type;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
selectedIndex = -1;
lastSelectedIndex = -1;
UIBarButtonItem *btnBack = [[UIBarButtonItem alloc] initWithCustomView:[CommonTools navigationBackItemBtnInitWithTarget:self action:@selector(goBack)]];
self.navigationItem.leftBarButtonItem = btnBack;
[btnBack release];
if (settingType == EAutoManage)
{
self.title = @"自动增益控制";
}
else if (settingType == EEchoCancelled)
{
self.title = @"回音消除";
}
else if (settingType == ESilenceRestrain)
{
self.title = @"静音抑制";
}
else if (settingType == ECameraFpsControl)
{
self.title = @"摄像头分辨率";
}
self.view.backgroundColor = VIEW_BACKGROUND_COLOR_WHITE;
UIView* headerView = [[UIView alloc] init];
headerView.frame = CGRectMake(0, 0, 320, 29);
UIImageView *imgHeader = [[UIImageView alloc] initWithFrame:headerView.frame];
imgHeader.image = [UIImage imageNamed:@"point_bg.png"];
[headerView addSubview:imgHeader];
[imgHeader release];
UILabel *lbHeader = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 29.0f)] ;
lbHeader.backgroundColor = [UIColor clearColor];
lbHeader.font = [UIFont systemFontOfSize:13.0f];
lbHeader.textColor = [UIColor whiteColor];
lbHeader.textAlignment = UITextAlignmentCenter;
[headerView addSubview:lbHeader];
lbHeader.text = @"请点击选择";
self.headerLabel = lbHeader;
[lbHeader release];
[self.view addSubview:headerView];
[headerView release];
UITableView *tableView = nil;
if (IPHONE5)
{
tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 29, 320, 548-29)
style:UITableViewStylePlain];
}
else
{
tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 29, 320, 460-29)
style:UITableViewStylePlain];
}
tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
self.myTableView = tableView;
[self.view addSubview:tableView];
[tableView release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
self.headerLabel = nil;
self.footerLabel = nil;
self.myTableView = nil;
self.cellDataArray = nil;
[super dealloc];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return cellDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UISelectCell *cell = nil;
static NSString *cellIdentifier = @"Cell";
cell = (UISelectCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if ( cell == nil )
{
cell = [[[UISelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
cell.isSingleCheck = YES;
AccountInfo *content = [cellDataArray objectAtIndex:indexPath.row];
if (content.isChecked) //进来时默认选中的项
{
selectedIndex = indexPath.row;
}
[cell makeCellWithVoipInfo:content];
return cell;
}
-(void)goBack
{
//返回之前保存一下设置
switch (settingType)
{
case EAutoManage: //自动增益控制
{
if (selectedIndex != -1)
{
AccountInfo *info = [cellDataArray objectAtIndex:selectedIndex];
NSString *content = info.voipId;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:selectedIndex forKey:AUTOMANAGE_INDEX_KEY];
[userDefaults setObject:content forKey:AUTOMANAGE_CONTENT_KEY];
[userDefaults synchronize]; // writes modifications to disk
[self.modelEngineVoip setAudioConfigEnabledWithType:eAUDIO_AGC andEnabled:YES andMode:selectedIndex];
}
}
break;
case EEchoCancelled: //回音消除
{
if (selectedIndex != -1)
{
AccountInfo *info = [cellDataArray objectAtIndex:selectedIndex];
NSString *content = info.voipId;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:selectedIndex forKey:ECHOCANCELLED_INDEX_KEY];
[userDefaults setObject:content forKey:ECHOCANCELLED_CONTENT_KEY];
[userDefaults synchronize]; // writes modifications to disk
[self.modelEngineVoip setAudioConfigEnabledWithType:eAUDIO_EC andEnabled:YES andMode:selectedIndex];
}
}
break;
case ESilenceRestrain: //静音抑制
{
if (selectedIndex != -1)
{
AccountInfo *info = [cellDataArray objectAtIndex:selectedIndex];
NSString *content = info.voipId;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:selectedIndex forKey:SILENCERESTRAIN_INDEX_KEY];
[userDefaults setObject:content forKey:SILENCERESTRAIN_CONTENT_KEY];
[userDefaults synchronize]; // writes modifications to disk
[self.modelEngineVoip setAudioConfigEnabledWithType:eAUDIO_NS andEnabled:YES andMode:selectedIndex];
}
}
break;
case ECameraFpsControl: //静音抑制
{
if (selectedIndex != -1)
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:selectedIndex forKey:Camera_Resolution_KEY];
[userDefaults synchronize]; // writes modifications to disk
}
}
break;
default:
break;
}
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
lastSelectedIndex = selectedIndex;
if ( lastSelectedIndex != -1 )
{
AccountInfo* info = [cellDataArray objectAtIndex:lastSelectedIndex];
info.isChecked = !info.isChecked;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastSelectedIndex inSection:0];
UISelectCell *lastCell = (UISelectCell *)[tableView cellForRowAtIndexPath:lastIndexPath];
[lastCell resetCheckImge:info.isChecked];
}
selectedIndex = indexPath.row;
if ( selectedIndex != lastSelectedIndex )
{
AccountInfo* info = [cellDataArray objectAtIndex:indexPath.row];
info.isChecked = !info.isChecked;
UISelectCell* cell = (UISelectCell *)[tableView cellForRowAtIndexPath:indexPath];
[cell resetCheckImge:info.isChecked];
}
else //在当前选中的cell中反选,置为初值
{
lastSelectedIndex = -1;
selectedIndex = -1;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
| {
"content_hash": "d995b00f4229bc32ce2aa277737b672f",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 156,
"avg_line_length": 30.840304182509506,
"alnum_prop": 0.6399950684255948,
"repo_name": "guohaiyang/yuntongxun",
"id": "0193326e2321e756dd8ca2e360d667cfb00a80b4",
"size": "8762",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CCPVoipDemo/Setting/AutoManageViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4954"
},
{
"name": "Objective-C",
"bytes": "2202084"
},
{
"name": "Objective-C++",
"bytes": "454390"
},
{
"name": "Ruby",
"bytes": "4853"
}
],
"symlink_target": ""
} |
//BinarySerialiserUtility.cs
//Created by Evgeniya O'Regan Pevchikh, 8/1/2015
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Project.CustomerFiles
{
/// <summary>
/// helper class to handle binary de/serialisation
/// </summary>
public class BinarySerialiserUtility
{
/// <summary>
/// method to serialise any type of object
/// </summary>
/// <param name="obj"> Object to be serialised</param>
/// <param name="filePath">File path including the name of the file to be serialised.</param>
public static void Serialize<T>(object obj, string filePath)
{
FileStream fileObj = null;
try
{
//Steps in serializing an object
fileObj = new FileStream(filePath, FileMode.Create);
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(fileObj, obj);
}
finally
{
if (fileObj != null)
fileObj.Close();
}
}
/// <summary>
/// Generic method for deserialising any type of object
/// </summary>
/// <typeparam name="T"> Any object</typeparam>
/// <param name="filepath">File path including the name of the file to be deserialised</param>
/// <returns>deserialised object</returns>
public static T Deserialize<T>(string filepath)
{
FileStream fileObj = null;
object obj = null;
try
{
if (!File.Exists(filepath))
{
throw new FileNotFoundException("The file is not found. ", filepath);
}
fileObj = new FileStream(filepath, FileMode.Open);
BinaryFormatter binFormatter = new BinaryFormatter();
obj = binFormatter.Deserialize(fileObj);
}
finally
{
if (fileObj != null)
{
fileObj.Close();
}
}
return (T)obj;
}
}
}
| {
"content_hash": "d6e4353a7b13501222e5752e237dfc91",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 102,
"avg_line_length": 30.493506493506494,
"alnum_prop": 0.5404599659284497,
"repo_name": "vanla/SalesRegistryC-",
"id": "8bd1adf9c1b21aff5ab5b4b3882fda6a66f9911f",
"size": "2350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Project/CustomerFiles/BinarySerialiserUtility.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "94335"
}
],
"symlink_target": ""
} |
package mock_gomock
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockMatcher is a mock of Matcher interface
type MockMatcher struct {
ctrl *gomock.Controller
recorder *MockMatcherMockRecorder
}
// MockMatcherMockRecorder is the mock recorder for MockMatcher
type MockMatcherMockRecorder struct {
mock *MockMatcher
}
// NewMockMatcher creates a new mock instance
func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher {
mock := &MockMatcher{ctrl: ctrl}
mock.recorder = &MockMatcherMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockMatcher) EXPECT() *MockMatcherMockRecorder {
return m.recorder
}
// Matches mocks base method
func (m *MockMatcher) Matches(arg0 interface{}) bool {
ret := m.ctrl.Call(m, "Matches", arg0)
ret0, _ := ret[0].(bool)
return ret0
}
// Matches indicates an expected call of Matches
func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0)
}
// String mocks base method
func (m *MockMatcher) String() string {
ret := m.ctrl.Call(m, "String")
ret0, _ := ret[0].(string)
return ret0
}
// String indicates an expected call of String
func (mr *MockMatcherMockRecorder) String() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockMatcher)(nil).String))
}
| {
"content_hash": "0c1a43c8c1e73ac760876e68dc5c98a6",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 116,
"avg_line_length": 28.07547169811321,
"alnum_prop": 0.7479838709677419,
"repo_name": "ks2software/nodejs-buildpack",
"id": "7e4b4c8a5ef25c486f9cdcde2fb3d01567390296",
"size": "1649",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "src/nodejs/vendor/github.com/golang/mock/gomock/mock_matcher/mock_matcher.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "39147"
},
{
"name": "C++",
"bytes": "23549"
},
{
"name": "Go",
"bytes": "94749"
},
{
"name": "JavaScript",
"bytes": "10260"
},
{
"name": "Makefile",
"bytes": "4194"
},
{
"name": "Perl",
"bytes": "3561"
},
{
"name": "Perl 6",
"bytes": "15557"
},
{
"name": "Roff",
"bytes": "30756"
},
{
"name": "Shell",
"bytes": "10444"
},
{
"name": "Terra",
"bytes": "839"
}
],
"symlink_target": ""
} |
namespace SceneEngine { class MaterialOverride; }
namespace Overlays
{
using namespace RenderOverlays;
using namespace RenderOverlays::DebuggingDisplay;
class TestMaterialSettings : public IWidget ///////////////////////////////////////////////////////////
{
public:
TestMaterialSettings(SceneEngine::MaterialOverride& materialSettings);
~TestMaterialSettings();
void Render(IOverlayContext* context, Layout& layout, Interactables&interactables, InterfaceState& interfaceState);
bool ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input);
private:
ScrollBar _scrollers[11];
SceneEngine::MaterialOverride* _materialSettings;
};
}
| {
"content_hash": "dccd3a6e38b8fdcbcca01299edd3e81c",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 126,
"avg_line_length": 32.08695652173913,
"alnum_prop": 0.6666666666666666,
"repo_name": "xlgames-inc/XLE",
"id": "06babc4dc33b556081f0241c426e7d1c09d67e21",
"size": "964",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "RenderOverlays/Overlays/TestMaterialSettings.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3201604"
},
{
"name": "Awk",
"bytes": "3962"
},
{
"name": "Batchfile",
"bytes": "3360"
},
{
"name": "C",
"bytes": "10674877"
},
{
"name": "C#",
"bytes": "2848942"
},
{
"name": "C++",
"bytes": "19256138"
},
{
"name": "CMake",
"bytes": "61254"
},
{
"name": "CSS",
"bytes": "27391"
},
{
"name": "DIGITAL Command Language",
"bytes": "35816"
},
{
"name": "Fortran",
"bytes": "1454013"
},
{
"name": "GAP",
"bytes": "20112"
},
{
"name": "GLSL",
"bytes": "39352"
},
{
"name": "GSC",
"bytes": "54863"
},
{
"name": "Groovy",
"bytes": "11823"
},
{
"name": "HLSL",
"bytes": "426796"
},
{
"name": "HTML",
"bytes": "530940"
},
{
"name": "JavaScript",
"bytes": "15993"
},
{
"name": "M4",
"bytes": "20151"
},
{
"name": "Makefile",
"bytes": "266194"
},
{
"name": "Perl",
"bytes": "12798"
},
{
"name": "Python",
"bytes": "187255"
},
{
"name": "Rich Text Format",
"bytes": "46532"
},
{
"name": "Roff",
"bytes": "7542"
},
{
"name": "Shell",
"bytes": "848671"
},
{
"name": "sed",
"bytes": "236"
}
],
"symlink_target": ""
} |
#ifndef __tcode_io_ip_udp_operation_write__
#define __tcode_io_ip_udp_operation_write__
#include <tcode/error.hpp>
#include <tcode/io/operation.hpp>
#include <tcode/io/buffer.hpp>
#include <tcode/io/ip/address.hpp>
namespace tcode { namespace io { namespace ip { namespace udp {
/*!
* @class operation_write_base
* @brief
*/
class operation_write_base
: public tcode::io::operation
{
public:
operation_write_base( tcode::operation::execute_handler fn
, const tcode::io::buffer& buf
, const tcode::io::ip::address& addr );
~operation_write_base( void );
bool post_write_impl( io::multiplexer* impl
, io::descriptor desc );
int write_size(void);
tcode::io::ip::address& address( void );
tcode::io::buffer& buffer( void );
static bool post_write( io::operation* op_base
, io::multiplexer* impl
, io::descriptor desc ) ;
private:
tcode::io::ip::address _address;
tcode::io::buffer _buffer;
int _write;
};
template < typename Handler >
class operation_write
: public operation_write_base
{
public:
operation_write( const tcode::io::buffer& buf
, const tcode::io::ip::address& addr
, const Handler& handler )
: operation_write_base( &operation_write::complete
, buf , addr )
, _handler( handler )
{
}
~operation_write( void ){
}
static void complete( tcode::operation* op_base ) {
operation_write* op(
static_cast< operation_write* >(op_base));
Handler h( std::move( op->_handler ));
std::error_code ec = op->error();
int write = op->write_size();
tcode::io::ip::address addr(op->address());
op->~operation_write();
tcode::operation::free( op );
h( ec , write , addr );
}
private:
Handler _handler;
};
}}}}
#endif
| {
"content_hash": "91ebbd4052da3537a7aab3f3116e5636",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 66,
"avg_line_length": 27.675324675324674,
"alnum_prop": 0.5279211637728766,
"repo_name": "aoziczero/tcode",
"id": "55b4e054a6797e4e01778adf820eec7f7e6f8c61",
"size": "2131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/tcode/io/ip/udp/operation_write.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "558095"
},
{
"name": "C++",
"bytes": "803059"
},
{
"name": "Makefile",
"bytes": "10532"
},
{
"name": "Objective-C",
"bytes": "1177"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
La Guerche-sur-l'Aubois est
une commune localisée dans le département de Cher en Centre. Elle totalisait 3 415 habitants en 2008.</p>
<p>La commune propose de multiples équipements, elle propose entre autres un bassin de natation, un centre d'équitation, un terrain de sport et une boucle de randonnée.</p>
<p>À La Guerche-sur-l'Aubois, la valorisation moyenne à l'achat d'un appartement se situe à 1 150 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 163 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.</p>
<p>
La commune est équipée s'agissant de des études de un collège.
S'agissant les très jeunes, la ville est pourvue pour le bien être de sa population de deux maternelles et une école primaire.
La Guerche-sur-l'Aubois dispose des installations permettant une vie locale facilitée.
Si vous avez un projet d'acquisition immobilière à La Guerche-sur-l'Aubois, il est intéressant d' évaluer la valeur des équipements éducatifs</p>
<p>Le nombre d'habitations, à La Guerche-sur-l'Aubois, était réparti en 2011 en 243 appartements et 1 604 maisons soit
un marché plutôt équilibré.</p>
<p>À La Guerche-sur-l'Aubois le salaire moyen mensuel par habitant se situe à environ 1 808 € net. Ceci est inférieur à la moyenne du pays.</p>
<p>À coté de La Guerche-sur-l'Aubois sont localisées les communes de
<a href="{{VLROOT}}/immobilier/torteron_18265/">Torteron</a> à 7 km, 802 habitants,
<a href="{{VLROOT}}/immobilier/cuffy_18082/">Cuffy</a> à 7 km, 1 105 habitants,
<a href="{{VLROOT}}/immobilier/apremont-sur-allier_18007/">Apremont-sur-Allier</a> située à 8 km, 78 habitants,
<a href="{{VLROOT}}/immobilier/germigny-lexempt_18101/">Germigny-l'Exempt</a> à 5 km, 320 habitants,
<a href="{{VLROOT}}/immobilier/tendron_18260/">Tendron</a> localisée à 8 km, 119 habitants,
<a href="{{VLROOT}}/immobilier/grossouvre_18106/">Grossouvre</a> à 8 km, 277 habitants,
entre autres. De plus, La Guerche-sur-l'Aubois est située à seulement 16 km de <a href="{{VLROOT}}/immobilier/nevers_58194/">Nevers</a>.</p>
</div>
| {
"content_hash": "381287505adb29c47960c5baa12c75b9",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 284,
"avg_line_length": 97.21739130434783,
"alnum_prop": 0.751788908765653,
"repo_name": "donaldinou/frontend",
"id": "437857ce8fe7e96f00cc6341f6e6adc95fbe8d0f",
"size": "2289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/18108.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": ""
} |
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace Spect.Net.VsPackage.ToolWindows
{
/// <summary>
/// Interaction logic for CommandPromptControl.xaml
/// </summary>
public partial class CommandPromptControl
{
public static readonly DependencyProperty PromptProperty = DependencyProperty.Register(
"Prompt", typeof(string), typeof(CommandPromptControl), new PropertyMetadata(">"));
public string Prompt
{
get => (string)GetValue(PromptProperty);
set => SetValue(PromptProperty, value);
}
public static readonly DependencyProperty CommandTextProperty = DependencyProperty.Register(
"CommandText", typeof(string), typeof(CommandPromptControl), new PropertyMetadata(default(string)));
public string CommandText
{
get => (string)GetValue(CommandTextProperty);
set => SetValue(CommandTextProperty, value);
}
public static readonly DependencyProperty HelpUrlProperty = DependencyProperty.Register(
"HelpUrl", typeof(string), typeof(CommandPromptControl), new PropertyMetadata(default(string)));
public string HelpUrl
{
get => (string)GetValue(HelpUrlProperty);
set => SetValue(HelpUrlProperty, value);
}
public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.Register(
"MaxLength", typeof(int), typeof(CommandPromptControl), new PropertyMetadata(32));
public int MaxLength
{
get => (int)GetValue(MaxLengthProperty);
set => SetValue(MaxLengthProperty, value);
}
public static readonly DependencyProperty IsValidProperty = DependencyProperty.Register(
"IsValid", typeof(bool), typeof(CommandPromptControl), new PropertyMetadata(true));
public bool IsValid
{
get => (bool)GetValue(IsValidProperty);
set => SetValue(IsValidProperty, value);
}
public static readonly DependencyProperty ValidationMessageProperty = DependencyProperty.Register(
"ValidationMessage", typeof(string), typeof(CommandPromptControl), new PropertyMetadata(default(string)));
public string ValidationMessage
{
get => (string)GetValue(ValidationMessageProperty);
set => SetValue(ValidationMessageProperty, value);
}
/// <summary>
/// This event is raised when the user presses the enter key
/// </summary>
public EventHandler<CommandLineEventArgs> CommandLineEntered;
/// <summary>
/// This event is raised to preview the changes in the command line
/// text input
/// </summary>
public EventHandler<TextCompositionEventArgs> PreviewCommandLineInput;
public CommandPromptControl()
{
InitializeComponent();
ValidationMessage = "";
if (DesignerProperties.GetIsInDesignMode(this))
{
Prompt = ">";
CommandText = "G4567";
}
}
/// <summary>
/// Sets the focus to the command line
/// </summary>
public void SetFocus()
{
CommandLine.Focus();
}
private void OnCommandLineKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter) return;
var args = new CommandLineEventArgs(CommandText);
CommandLineEntered?.Invoke(this, args);
if (args.Handled)
{
CommandText = null;
}
if (args.Invalid)
{
IsValid = false;
}
e.Handled = true;
}
private void OnCommandLinePreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == null || e.Text == "\r") return;
PreviewCommandLineInput?.Invoke(sender, e);
}
private void OnCommandLinePreviewKeyDown(object sender, KeyEventArgs e)
{
IsValid = true;
}
private void PromptClicked(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left) return;
var url = $"{SpectNetPackage.COMMANDS_BASE_URL}/{HelpUrl}";
System.Diagnostics.Process.Start(url);
}
}
}
| {
"content_hash": "db450104cf8f2eacebe4945509f07800",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 118,
"avg_line_length": 33.714285714285715,
"alnum_prop": 0.6052631578947368,
"repo_name": "Dotneteer/spectnetide",
"id": "a7833b14e7091eac98660e5605dd229c2bd56834",
"size": "4486",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "v2/VsIntegration/Spect.Net.VsPackage/ToolWindows/CommandPromptControl.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "76707"
},
{
"name": "Assembly",
"bytes": "3125120"
},
{
"name": "C",
"bytes": "442740"
},
{
"name": "C#",
"bytes": "19216822"
},
{
"name": "HTML",
"bytes": "277068"
}
],
"symlink_target": ""
} |
#include <avian/heap/heap.h>
#include <avian/system/system.h>
#include "avian/common.h"
#include "avian/arch.h"
#include <avian/util/math.h>
using namespace vm;
using namespace avian::util;
namespace {
namespace local {
const unsigned Top = ~static_cast<unsigned>(0);
const unsigned InitialGen2CapacityInBytes = 4 * 1024 * 1024;
const unsigned InitialTenuredFixieCeilingInBytes = 4 * 1024 * 1024;
const bool Verbose = false;
const bool Verbose2 = false;
const bool Debug = false;
const bool DebugFixies = false;
#ifdef NDEBUG
const bool DebugAllocation = false;
#else
const bool DebugAllocation = true;
#endif
#define ACQUIRE(x) MutexLock MAKE_NAME(monitorLock_) (x)
class MutexLock {
public:
MutexLock(System::Mutex* m): m(m) {
m->acquire();
}
~MutexLock() {
m->release();
}
private:
System::Mutex* m;
};
class Context;
Aborter* getAborter(Context* c);
void* tryAllocate(Context* c, unsigned size);
void* allocate(Context* c, unsigned size);
void* allocate(Context* c, unsigned size, bool limit);
void free(Context* c, const void* p, unsigned size);
#ifdef USE_ATOMIC_OPERATIONS
inline void
markBitAtomic(uintptr_t* map, unsigned i)
{
uintptr_t* p = map + wordOf(i);
uintptr_t v = static_cast<uintptr_t>(1) << bitOf(i);
for (uintptr_t old = *p;
not atomicCompareAndSwap(p, old, old | v);
old = *p)
{ }
}
#endif // USE_ATOMIC_OPERATIONS
inline void*
get(void* o, unsigned offsetInWords)
{
return maskAlignedPointer(fieldAtOffset<void*>(o, offsetInWords * BytesPerWord));
}
inline void**
getp(void* o, unsigned offsetInWords)
{
return &fieldAtOffset<void*>(o, offsetInWords * BytesPerWord);
}
inline void
set(void** o, void* value)
{
*o = reinterpret_cast<void*>
(reinterpret_cast<uintptr_t>(value)
| (reinterpret_cast<uintptr_t>(*o) & (~PointerMask)));
}
inline void
set(void* o, unsigned offsetInWords, void* value)
{
set(getp(o, offsetInWords), value);
}
class Segment {
public:
class Map {
public:
class Iterator {
public:
Map* map;
unsigned index;
unsigned limit;
Iterator(Map* map, unsigned start, unsigned end):
map(map)
{
assert(map->segment->context, map->bitsPerRecord == 1);
assert(map->segment->context, map->segment);
assert(map->segment->context, start <= map->segment->position());
if (end > map->segment->position()) end = map->segment->position();
index = map->indexOf(start);
limit = map->indexOf(end);
if ((end - start) % map->scale) ++ limit;
}
bool hasMore() {
unsigned word = wordOf(index);
unsigned bit = bitOf(index);
unsigned wordLimit = wordOf(limit);
unsigned bitLimit = bitOf(limit);
for (; word <= wordLimit and (word < wordLimit or bit < bitLimit);
++word)
{
uintptr_t w = map->data[word];
if (2) {
for (; bit < BitsPerWord and (word < wordLimit or bit < bitLimit);
++bit)
{
if (w & (static_cast<uintptr_t>(1) << bit)) {
index = ::indexOf(word, bit);
// printf("hit at index %d\n", index);
return true;
} else {
// printf("miss at index %d\n", indexOf(word, bit));
}
}
}
bit = 0;
}
index = limit;
return false;
}
unsigned next() {
assert(map->segment->context, hasMore());
assert(map->segment->context, map->segment);
return (index++) * map->scale;
}
};
Segment* segment;
Map* child;
uintptr_t* data;
unsigned bitsPerRecord;
unsigned scale;
bool clearNewData;
Map(Segment* segment, uintptr_t* data, unsigned bitsPerRecord,
unsigned scale, Map* child, bool clearNewData):
segment(segment),
child(child),
data(data),
bitsPerRecord(bitsPerRecord),
scale(scale),
clearNewData(clearNewData)
{ }
Map(Segment* segment, unsigned bitsPerRecord, unsigned scale, Map* child,
bool clearNewData):
segment(segment),
child(child),
data(0),
bitsPerRecord(bitsPerRecord),
scale(scale),
clearNewData(clearNewData)
{ }
void init() {
assert(segment->context, bitsPerRecord);
assert(segment->context, scale);
assert(segment->context, powerOfTwo(scale));
if (data == 0) {
data = segment->data + segment->capacity()
+ calculateOffset(segment->capacity());
}
if (clearNewData) {
memset(data, 0, size() * BytesPerWord);
}
if (child) {
child->init();
}
}
unsigned calculateOffset(unsigned capacity) {
unsigned n = 0;
if (child) n += child->calculateFootprint(capacity);
return n;
}
static unsigned calculateSize(Context* c UNUSED, unsigned capacity,
unsigned scale, unsigned bitsPerRecord)
{
unsigned result
= ceilingDivide(ceilingDivide(capacity, scale) * bitsPerRecord, BitsPerWord);
assert(c, result);
return result;
}
unsigned calculateSize(unsigned capacity) {
return calculateSize(segment->context, capacity, scale, bitsPerRecord);
}
unsigned size() {
return calculateSize(segment->capacity());
}
unsigned calculateFootprint(unsigned capacity) {
unsigned n = calculateSize(capacity);
if (child) n += child->calculateFootprint(capacity);
return n;
}
void replaceWith(Map* m) {
assert(segment->context, bitsPerRecord == m->bitsPerRecord);
assert(segment->context, scale == m->scale);
data = m->data;
m->segment = 0;
m->data = 0;
if (child) child->replaceWith(m->child);
}
unsigned indexOf(unsigned segmentIndex) {
return (segmentIndex / scale) * bitsPerRecord;
}
unsigned indexOf(void* p) {
assert(segment->context, segment->almostContains(p));
assert(segment->context, segment->capacity());
return indexOf(segment->indexOf(p));
}
void clearBit(unsigned i) {
assert(segment->context, wordOf(i) < size());
vm::clearBit(data, i);
}
void setBit(unsigned i) {
assert(segment->context, wordOf(i) < size());
vm::markBit(data, i);
}
void clearOnlyIndex(unsigned index) {
clearBits(data, bitsPerRecord, index);
}
void clearOnly(unsigned segmentIndex) {
clearOnlyIndex(indexOf(segmentIndex));
}
void clearOnly(void* p) {
clearOnlyIndex(indexOf(p));
}
void clear(void* p) {
clearOnly(p);
if (child) child->clear(p);
}
void setOnlyIndex(unsigned index, unsigned v = 1) {
setBits(data, bitsPerRecord, index, v);
}
void setOnly(unsigned segmentIndex, unsigned v = 1) {
setOnlyIndex(indexOf(segmentIndex), v);
}
void setOnly(void* p, unsigned v = 1) {
setOnlyIndex(indexOf(p), v);
}
void set(void* p, unsigned v = 1) {
setOnly(p, v);
assert(segment->context, get(p) == v);
if (child) child->set(p, v);
}
#ifdef USE_ATOMIC_OPERATIONS
void markAtomic(void* p) {
assert(segment->context, bitsPerRecord == 1);
markBitAtomic(data, indexOf(p));
assert(segment->context, getBit(data, indexOf(p)));
if (child) child->markAtomic(p);
}
#endif
unsigned get(void* p) {
return getBits(data, bitsPerRecord, indexOf(p));
}
};
Context* context;
uintptr_t* data;
unsigned position_;
unsigned capacity_;
Map* map;
Segment(Context* context, Map* map, unsigned desired, unsigned minimum,
int64_t available = INT64_MAX):
context(context),
data(0),
position_(0),
capacity_(0),
map(map)
{
if (desired) {
if (minimum == 0) {
minimum = 1;
}
assert(context, desired >= minimum);
capacity_ = desired;
if (static_cast<int64_t>(footprint(capacity_)) > available) {
unsigned top = capacity_;
unsigned bottom = minimum;
unsigned target = available;
while (true) {
if (static_cast<int64_t>(footprint(capacity_)) > target) {
if (bottom == capacity_) {
break;
} else if (static_cast<int64_t>(footprint(capacity_ - 1))
<= target)
{
-- capacity_;
break;
}
top = capacity_;
capacity_ = avg(bottom, capacity_);
} else if (static_cast<int64_t>(footprint(capacity_)) < target) {
if (top == capacity_
or static_cast<int64_t>(footprint(capacity_ + 1)) >= target)
{
break;
}
bottom = capacity_;
capacity_ = avg(top, capacity_);
} else {
break;
}
}
}
while (data == 0) {
data = static_cast<uintptr_t*>
(local::allocate
(context, (footprint(capacity_)) * BytesPerWord, false));
if (data == 0) {
if (capacity_ > minimum) {
capacity_ = avg(minimum, capacity_);
if (capacity_ == 0) {
break;
}
} else {
data = static_cast<uintptr_t*>
(local::allocate
(context, (footprint(capacity_)) * BytesPerWord));
}
}
}
if (map) {
map->init();
}
}
}
Segment(Context* context, Map* map, uintptr_t* data, unsigned position,
unsigned capacity):
context(context),
data(data),
position_(position),
capacity_(capacity),
map(map)
{
if (map) {
map->init();
}
}
unsigned footprint(unsigned capacity) {
return capacity
+ (map and capacity ? map->calculateFootprint(capacity) : 0);
}
unsigned capacity() {
return capacity_;
}
unsigned position() {
return position_;
}
unsigned remaining() {
return capacity() - position();
}
void replaceWith(Segment* s) {
if (data) {
free(context, data, (footprint(capacity())) * BytesPerWord);
}
data = s->data;
s->data = 0;
position_ = s->position_;
s->position_ = 0;
capacity_ = s->capacity_;
s->capacity_ = 0;
if (s->map) {
if (map) {
map->replaceWith(s->map);
s->map = 0;
} else {
abort(context);
}
} else {
assert(context, map == 0);
}
}
bool contains(void* p) {
return position() and p >= data and p < data + position();
}
bool almostContains(void* p) {
return contains(p) or p == data + position();
}
void* get(unsigned offset) {
assert(context, offset <= position());
return data + offset;
}
unsigned indexOf(void* p) {
assert(context, almostContains(p));
return static_cast<uintptr_t*>(p) - data;
}
void* allocate(unsigned size) {
assert(context, size);
assert(context, position() + size <= capacity());
void* p = data + position();
position_ += size;
return p;
}
void dispose() {
if (data) {
free(context, data, (footprint(capacity())) * BytesPerWord);
}
data = 0;
map = 0;
}
};
class Fixie {
public:
static const unsigned HasMask = 1 << 0;
static const unsigned Marked = 1 << 1;
static const unsigned Dirty = 1 << 2;
static const unsigned Dead = 1 << 3;
Fixie(Context* c, unsigned size, bool hasMask, Fixie** handle,
bool immortal):
age(immortal ? FixieTenureThreshold + 1 : 0),
flags(hasMask ? HasMask : 0),
size(size),
next(0),
handle(0)
{
memset(mask(), 0, maskSize(size, hasMask));
add(c, handle);
if (DebugFixies) {
fprintf(stderr, "make fixie %p of size %d\n", this, totalSize());
}
}
bool immortal() {
return age == FixieTenureThreshold + 1;
}
void add(Context* c UNUSED, Fixie** handle) {
assert(c, this->handle == 0);
assert(c, next == 0);
this->handle = handle;
if (handle) {
next = *handle;
if (next) next->handle = &next;
*handle = this;
} else {
next = 0;
}
}
void remove(Context* c UNUSED) {
if (handle) {
assert(c, *handle == this);
*handle = next;
}
if (next) {
next->handle = handle;
}
next = 0;
handle = 0;
}
void move(Context* c, Fixie** handle) {
if (DebugFixies) {
fprintf(stderr, "move fixie %p\n", this);
}
remove(c);
add(c, handle);
}
void** body() {
return static_cast<void**>(static_cast<void*>(body_));
}
uintptr_t* mask() {
return body_ + size;
}
static unsigned maskSize(unsigned size, bool hasMask) {
return hasMask * ceilingDivide(size, BitsPerWord) * BytesPerWord;
}
static unsigned totalSize(unsigned size, bool hasMask) {
return sizeof(Fixie) + (size * BytesPerWord) + maskSize(size, hasMask);
}
unsigned totalSize() {
return totalSize(size, hasMask());
}
bool hasMask() {
return (flags & HasMask) != 0;
}
bool marked() {
return (flags & Marked) != 0;
}
void marked(bool v) {
if (v) {
flags |= Marked;
} else {
flags &= ~Marked;
}
}
bool dirty() {
return (flags & Dirty) != 0;
}
void dirty(bool v) {
if (v) {
flags |= Dirty;
} else {
flags &= ~Dirty;
}
}
bool dead() {
return (flags & Dead) != 0;
}
void dead(bool v) {
if (v) {
flags |= Dead;
} else {
flags &= ~Dead;
}
}
// be sure to update e.g. TargetFixieSizeInBytes in bootimage.cpp if
// you add/remove/change fields in this class:
uint16_t age;
uint16_t flags;
uint32_t size;
Fixie* next;
Fixie** handle;
uintptr_t body_[0];
};
Fixie*
fixie(void* body)
{
return static_cast<Fixie*>(body) - 1;
}
void
free(Context* c, Fixie** fixies, bool resetImmortal = false);
class Context {
public:
Context(System* system, unsigned limit):
system(system),
client(0),
count(0),
limit(limit),
lock(0),
immortalHeapStart(0),
immortalHeapEnd(0),
ageMap(&gen1, max(1, log(TenureThreshold)), 1, 0, false),
gen1(this, &ageMap, 0, 0),
nextAgeMap(&nextGen1, max(1, log(TenureThreshold)), 1, 0, false),
nextGen1(this, &nextAgeMap, 0, 0),
pointerMap(&gen2, 1, 1, 0, true),
pageMap(&gen2, 1, LikelyPageSizeInBytes / BytesPerWord, &pointerMap, true),
heapMap(&gen2, 1, pageMap.scale * 1024, &pageMap, true),
gen2(this, &heapMap, 0, 0),
nextPointerMap(&nextGen2, 1, 1, 0, true),
nextPageMap(&nextGen2, 1, LikelyPageSizeInBytes / BytesPerWord,
&nextPointerMap, true),
nextHeapMap(&nextGen2, 1, nextPageMap.scale * 1024, &nextPageMap, true),
nextGen2(this, &nextHeapMap, 0, 0),
gen2Base(0),
incomingFootprint(0),
pendingAllocation(0),
tenureFootprint(0),
gen1Padding(0),
tenurePadding(0),
gen2Padding(0),
fixieTenureFootprint(0),
untenuredFixieFootprint(0),
tenuredFixieFootprint(0),
tenuredFixieCeiling(InitialTenuredFixieCeilingInBytes),
mode(Heap::MinorCollection),
fixies(0),
tenuredFixies(0),
dirtyTenuredFixies(0),
markedFixies(0),
visitedFixies(0),
lastCollectionTime(system->now()),
totalCollectionTime(0),
totalTime(0),
limitWasExceeded(false)
{
if (not system->success(system->make(&lock))) {
system->abort();
}
}
void dispose() {
gen1.dispose();
nextGen1.dispose();
gen2.dispose();
nextGen2.dispose();
lock->dispose();
}
void disposeFixies() {
free(this, &tenuredFixies, true);
free(this, &dirtyTenuredFixies, true);
free(this, &fixies, true);
}
System* system;
Heap::Client* client;
unsigned count;
unsigned limit;
System::Mutex* lock;
uintptr_t* immortalHeapStart;
uintptr_t* immortalHeapEnd;
Segment::Map ageMap;
Segment gen1;
Segment::Map nextAgeMap;
Segment nextGen1;
Segment::Map pointerMap;
Segment::Map pageMap;
Segment::Map heapMap;
Segment gen2;
Segment::Map nextPointerMap;
Segment::Map nextPageMap;
Segment::Map nextHeapMap;
Segment nextGen2;
unsigned gen2Base;
unsigned incomingFootprint;
int pendingAllocation;
unsigned tenureFootprint;
unsigned gen1Padding;
unsigned tenurePadding;
unsigned gen2Padding;
unsigned fixieTenureFootprint;
unsigned untenuredFixieFootprint;
unsigned tenuredFixieFootprint;
unsigned tenuredFixieCeiling;
Heap::CollectionType mode;
Fixie* fixies;
Fixie* tenuredFixies;
Fixie* dirtyTenuredFixies;
Fixie* markedFixies;
Fixie* visitedFixies;
int64_t lastCollectionTime;
int64_t totalCollectionTime;
int64_t totalTime;
bool limitWasExceeded;
};
const char*
segment(Context* c, void* p)
{
if (c->gen1.contains(p)) {
return "gen1";
} else if (c->nextGen1.contains(p)) {
return "nextGen1";
} else if (c->gen2.contains(p)) {
return "gen2";
} else if (c->nextGen2.contains(p)) {
return "nextGen2";
} else {
return "none";
}
}
inline Aborter* getAborter(Context* c) {
return c->system;
}
inline unsigned
minimumNextGen1Capacity(Context* c)
{
return c->gen1.position() - c->tenureFootprint + c->incomingFootprint
+ c->gen1Padding;
}
inline unsigned
minimumNextGen2Capacity(Context* c)
{
return c->gen2.position() + c->tenureFootprint + c->tenurePadding
+ c->gen2Padding;
}
inline bool
oversizedGen2(Context* c)
{
return c->gen2.capacity() > (InitialGen2CapacityInBytes / BytesPerWord)
and c->gen2.position() < (c->gen2.capacity() / 4);
}
inline void
initNextGen1(Context* c)
{
new (&(c->nextAgeMap)) Segment::Map
(&(c->nextGen1), max(1, log(TenureThreshold)), 1, 0, false);
unsigned minimum = minimumNextGen1Capacity(c);
unsigned desired = minimum;
new (&(c->nextGen1)) Segment(c, &(c->nextAgeMap), desired, minimum);
if (Verbose2) {
fprintf(stderr, "init nextGen1 to %d bytes\n",
c->nextGen1.capacity() * BytesPerWord);
}
}
inline void
initNextGen2(Context* c)
{
new (&(c->nextPointerMap)) Segment::Map
(&(c->nextGen2), 1, 1, 0, true);
new (&(c->nextPageMap)) Segment::Map
(&(c->nextGen2), 1, LikelyPageSizeInBytes / BytesPerWord,
&(c->nextPointerMap), true);
new (&(c->nextHeapMap)) Segment::Map
(&(c->nextGen2), 1, c->pageMap.scale * 1024, &(c->nextPageMap), true);
unsigned minimum = minimumNextGen2Capacity(c);
unsigned desired = minimum;
if (not oversizedGen2(c)) {
desired *= 2;
}
if (desired < InitialGen2CapacityInBytes / BytesPerWord) {
desired = InitialGen2CapacityInBytes / BytesPerWord;
}
new (&(c->nextGen2)) Segment
(c, &(c->nextHeapMap), desired, minimum,
static_cast<int64_t>(c->limit / BytesPerWord)
- (static_cast<int64_t>(c->count / BytesPerWord)
- c->gen2.footprint(c->gen2.capacity())
- c->gen1.footprint(c->gen1.capacity())
+ c->pendingAllocation));
if (Verbose2) {
fprintf(stderr, "init nextGen2 to %d bytes\n",
c->nextGen2.capacity() * BytesPerWord);
}
}
inline bool
fresh(Context* c, void* o)
{
return c->nextGen1.contains(o)
or c->nextGen2.contains(o)
or (c->gen2.contains(o) and c->gen2.indexOf(o) >= c->gen2Base);
}
inline bool
wasCollected(Context* c, void* o)
{
return o and (not fresh(c, o)) and fresh(c, get(o, 0));
}
inline void*
follow(Context* c UNUSED, void* o)
{
assert(c, wasCollected(c, o));
return fieldAtOffset<void*>(o, 0);
}
inline void*&
parent(Context* c UNUSED, void* o)
{
assert(c, wasCollected(c, o));
return fieldAtOffset<void*>(o, BytesPerWord);
}
inline uintptr_t*
bitset(Context* c UNUSED, void* o)
{
assert(c, wasCollected(c, o));
return &fieldAtOffset<uintptr_t>(o, BytesPerWord * 2);
}
void
free(Context* c, Fixie** fixies, bool resetImmortal)
{
for (Fixie** p = fixies; *p;) {
Fixie* f = *p;
if (f->immortal()) {
if (resetImmortal) {
if (DebugFixies) {
fprintf(stderr, "reset immortal fixie %p\n", f);
}
*p = f->next;
memset(f->mask(), 0, Fixie::maskSize(f->size, f->hasMask()));
f->next = 0;
f->handle = 0;
f->marked(false);
f->dirty(false);
} else {
p = &(f->next);
}
} else {
*p = f->next;
if (DebugFixies) {
fprintf(stderr, "free fixie %p\n", f);
}
free(c, f, f->totalSize());
}
}
}
void
kill(Fixie* fixies)
{
for (Fixie* f = fixies; f; f = f->next) {
if (! f->immortal()) {
f->dead(true);
}
}
}
void
killFixies(Context* c)
{
assert(c, c->markedFixies == 0);
if (c->mode == Heap::MajorCollection) {
kill(c->tenuredFixies);
kill(c->dirtyTenuredFixies);
}
kill(c->fixies);
}
void
sweepFixies(Context* c)
{
assert(c, c->markedFixies == 0);
if (c->mode == Heap::MajorCollection) {
free(c, &(c->tenuredFixies));
free(c, &(c->dirtyTenuredFixies));
c->tenuredFixieFootprint = 0;
}
free(c, &(c->fixies));
c->untenuredFixieFootprint = 0;
while (c->visitedFixies) {
Fixie* f = c->visitedFixies;
f->remove(c);
if (not f->immortal()) {
++ f->age;
if (f->age > FixieTenureThreshold) {
f->age = FixieTenureThreshold;
} else if (static_cast<unsigned>(f->age + 1) == FixieTenureThreshold) {
c->fixieTenureFootprint += f->totalSize();
}
}
if (f->age >= FixieTenureThreshold) {
if (DebugFixies) {
fprintf(stderr, "tenure fixie %p (dirty: %d)\n", f, f->dirty());
}
if (not f->immortal()) {
c->tenuredFixieFootprint += f->totalSize();
}
if (f->dirty()) {
f->add(c, &(c->dirtyTenuredFixies));
} else {
f->add(c, &(c->tenuredFixies));
}
} else {
c->untenuredFixieFootprint += f->totalSize();
f->add(c, &(c->fixies));
}
f->marked(false);
}
c->tenuredFixieCeiling = max
(c->tenuredFixieFootprint * 2,
InitialTenuredFixieCeilingInBytes);
}
inline void*
copyTo(Context* c, Segment* s, void* o, unsigned size)
{
assert(c, s->remaining() >= size);
void* dst = s->allocate(size);
c->client->copy(o, dst);
return dst;
}
bool
immortalHeapContains(Context* c, void* p)
{
return p < c->immortalHeapEnd and p >= c->immortalHeapStart;
}
void*
copy2(Context* c, void* o)
{
unsigned size = c->client->copiedSizeInWords(o);
if (c->gen2.contains(o)) {
assert(c, c->mode == Heap::MajorCollection);
return copyTo(c, &(c->nextGen2), o, size);
} else if (c->gen1.contains(o)) {
unsigned age = c->ageMap.get(o);
if (age == TenureThreshold) {
if (c->mode == Heap::MinorCollection) {
assert(c, c->gen2.remaining() >= size);
if (c->gen2Base == Top) {
c->gen2Base = c->gen2.position();
}
return copyTo(c, &(c->gen2), o, size);
} else {
return copyTo(c, &(c->nextGen2), o, size);
}
} else {
o = copyTo(c, &(c->nextGen1), o, size);
c->nextAgeMap.setOnly(o, age + 1);
if (age + 1 == TenureThreshold) {
c->tenureFootprint += size;
}
return o;
}
} else {
assert(c, not c->nextGen1.contains(o));
assert(c, not c->nextGen2.contains(o));
assert(c, not immortalHeapContains(c, o));
o = copyTo(c, &(c->nextGen1), o, size);
c->nextAgeMap.clear(o);
return o;
}
}
void*
copy(Context* c, void* o)
{
void* r = copy2(c, o);
if (Debug) {
fprintf(stderr, "copy %p (%s) to %p (%s)\n",
o, segment(c, o), r, segment(c, r));
}
// leave a pointer to the copy in the original
fieldAtOffset<void*>(o, 0) = r;
return r;
}
void*
update3(Context* c, void* o, bool* needsVisit)
{
if (c->client->isFixed(o)) {
Fixie* f = fixie(o);
if ((not f->marked())
and (c->mode == Heap::MajorCollection
or f->age < FixieTenureThreshold))
{
if (DebugFixies) {
fprintf(stderr, "mark fixie %p\n", f);
}
f->marked(true);
f->dead(false);
f->move(c, &(c->markedFixies));
}
*needsVisit = false;
return o;
} else if (immortalHeapContains(c, o)) {
*needsVisit = false;
return o;
} else if (wasCollected(c, o)) {
*needsVisit = false;
return follow(c, o);
} else {
*needsVisit = true;
return copy(c, o);
}
}
void*
update2(Context* c, void* o, bool* needsVisit)
{
if (c->mode == Heap::MinorCollection and c->gen2.contains(o)) {
*needsVisit = false;
return o;
}
return update3(c, o, needsVisit);
}
void
markDirty(Context* c, Fixie* f)
{
if (not f->dirty()) {
#ifdef USE_ATOMIC_OPERATIONS
ACQUIRE(c->lock);
#endif
if (not f->dirty()) {
f->dirty(true);
f->move(c, &(c->dirtyTenuredFixies));
}
}
}
void
markClean(Context* c, Fixie* f)
{
if (f->dirty()) {
f->dirty(false);
if (f->immortal()) {
f->remove(c);
} else {
f->move(c, &(c->tenuredFixies));
}
}
}
void
updateHeapMap(Context* c, void* p, void* target, unsigned offset, void* result)
{
Segment* seg;
Segment::Map* map;
if (c->mode == Heap::MinorCollection) {
seg = &(c->gen2);
map = &(c->heapMap);
} else {
seg = &(c->nextGen2);
map = &(c->nextHeapMap);
}
if (not (immortalHeapContains(c, result)
or (c->client->isFixed(result)
and fixie(result)->age >= FixieTenureThreshold)
or seg->contains(result)))
{
if (target and c->client->isFixed(target)) {
Fixie* f = fixie(target);
assert(c, offset == 0 or f->hasMask());
if (static_cast<unsigned>(f->age + 1) >= FixieTenureThreshold) {
if (DebugFixies) {
fprintf(stderr, "dirty fixie %p at %d (%p): %p\n",
f, offset, f->body() + offset, result);
}
f->dirty(true);
markBit(f->mask(), offset);
}
} else if (seg->contains(p)) {
if (Debug) {
fprintf(stderr, "mark %p (%s) at %p (%s)\n",
result, segment(c, result), p, segment(c, p));
}
map->set(p);
}
}
}
void*
update(Context* c, void** p, void* target, unsigned offset, bool* needsVisit)
{
if (maskAlignedPointer(*p) == 0) {
*needsVisit = false;
return 0;
}
void* result = update2(c, maskAlignedPointer(*p), needsVisit);
if (result) {
updateHeapMap(c, p, target, offset, result);
}
return result;
}
const uintptr_t BitsetExtensionBit
= (static_cast<uintptr_t>(1) << (BitsPerWord - 1));
void
bitsetInit(uintptr_t* p)
{
memset(p, 0, BytesPerWord);
}
void
bitsetClear(uintptr_t* p, unsigned start, unsigned end)
{
if (end < BitsPerWord - 1) {
// do nothing
} else if (start < BitsPerWord - 1) {
memset(p + 1, 0, (wordOf(end + (BitsPerWord * 2) + 1)) * BytesPerWord);
} else {
unsigned startWord = wordOf(start + (BitsPerWord * 2) + 1);
unsigned endWord = wordOf(end + (BitsPerWord * 2) + 1);
if (endWord > startWord) {
memset(p + startWord + 1, 0, (endWord - startWord) * BytesPerWord);
}
}
}
void
bitsetSet(uintptr_t* p, unsigned i, bool v)
{
if (i >= BitsPerWord - 1) {
i += (BitsPerWord * 2) + 1;
if (v) {
p[0] |= BitsetExtensionBit;
if (p[2] <= wordOf(i) - 3) p[2] = wordOf(i) - 2;
}
}
if (v) {
markBit(p, i);
} else {
clearBit(p, i);
}
}
bool
bitsetHasMore(uintptr_t* p)
{
switch (*p) {
case 0: return false;
case BitsetExtensionBit: {
uintptr_t length = p[2];
uintptr_t word = wordOf(p[1]);
for (; word < length; ++word) {
if (p[word + 3]) {
p[1] = indexOf(word, 0);
return true;
}
}
p[1] = indexOf(word, 0);
return false;
}
default: return true;
}
}
unsigned
bitsetNext(Context* c, uintptr_t* p)
{
bool more UNUSED = bitsetHasMore(p);
assert(c, more);
switch (*p) {
case 0: abort(c);
case BitsetExtensionBit: {
uintptr_t i = p[1];
uintptr_t word = wordOf(i);
assert(c, word < p[2]);
for (uintptr_t bit = bitOf(i); bit < BitsPerWord; ++bit) {
if (p[word + 3] & (static_cast<uintptr_t>(1) << bit)) {
p[1] = indexOf(word, bit) + 1;
bitsetSet(p, p[1] + BitsPerWord - 2, false);
return p[1] + BitsPerWord - 2;
}
}
abort(c);
}
default: {
for (unsigned i = 0; i < BitsPerWord - 1; ++i) {
if (*p & (static_cast<uintptr_t>(1) << i)) {
bitsetSet(p, i, false);
return i;
}
}
abort(c);
}
}
}
void
collect(Context* c, void** p, void* target, unsigned offset)
{
void* original = maskAlignedPointer(*p);
void* parent_ = 0;
if (Debug) {
fprintf(stderr, "update %p (%s) at %p (%s)\n",
maskAlignedPointer(*p), segment(c, *p), p, segment(c, p));
}
bool needsVisit;
local::set(p, update(c, maskAlignedPointer(p), target, offset, &needsVisit));
if (Debug) {
fprintf(stderr, " result: %p (%s) (visit? %d)\n",
maskAlignedPointer(*p), segment(c, *p), needsVisit);
}
if (not needsVisit) return;
visit: {
void* copy = follow(c, original);
class Walker : public Heap::Walker {
public:
Walker(Context* c, void* copy, uintptr_t* bitset):
c(c),
copy(copy),
bitset(bitset),
first(0),
second(0),
last(0),
visits(0),
total(0)
{ }
virtual bool visit(unsigned offset) {
if (Debug) {
fprintf(stderr, " update %p (%s) at %p - offset %d from %p (%s)\n",
get(copy, offset),
segment(c, get(copy, offset)),
getp(copy, offset),
offset,
copy,
segment(c, copy));
}
bool needsVisit;
void* childCopy = update
(c, getp(copy, offset), copy, offset, &needsVisit);
if (Debug) {
fprintf(stderr, " result: %p (%s) (visit? %d)\n",
childCopy, segment(c, childCopy), needsVisit);
}
++ total;
if (total == 3) {
bitsetInit(bitset);
}
if (needsVisit) {
++ visits;
if (visits == 1) {
first = offset;
} else if (visits == 2) {
second = offset;
}
} else {
local::set(copy, offset, childCopy);
}
if (visits > 1 and total > 2 and (second or needsVisit)) {
bitsetClear(bitset, last, offset);
last = offset;
if (second) {
bitsetSet(bitset, second, true);
second = 0;
}
if (needsVisit) {
bitsetSet(bitset, offset, true);
}
}
return true;
}
Context* c;
void* copy;
uintptr_t* bitset;
unsigned first;
unsigned second;
unsigned last;
unsigned visits;
unsigned total;
} walker(c, copy, bitset(c, original));
if (Debug) {
fprintf(stderr, "walk %p (%s)\n", copy, segment(c, copy));
}
c->client->walk(copy, &walker);
if (walker.visits) {
// descend
if (walker.visits > 1) {
parent(c, original) = parent_;
parent_ = original;
}
original = get(copy, walker.first);
local::set(copy, walker.first, follow(c, original));
goto visit;
} else {
// ascend
original = parent_;
}
}
if (original) {
void* copy = follow(c, original);
class Walker : public Heap::Walker {
public:
Walker(Context* c, uintptr_t* bitset):
c(c),
bitset(bitset),
next(0),
total(0)
{ }
virtual bool visit(unsigned offset) {
switch (++ total) {
case 1:
return true;
case 2:
next = offset;
return true;
case 3:
next = bitsetNext(c, bitset);
return false;
default:
abort(c);
}
}
Context* c;
uintptr_t* bitset;
unsigned next;
unsigned total;
} walker(c, bitset(c, original));
if (Debug) {
fprintf(stderr, "scan %p\n", copy);
}
c->client->walk(copy, &walker);
assert(c, walker.total > 1);
if (walker.total == 3 and bitsetHasMore(bitset(c, original))) {
parent_ = original;
} else {
parent_ = parent(c, original);
}
if (Debug) {
fprintf(stderr, " next is %p (%s) at %p - offset %d from %p (%s)\n",
get(copy, walker.next),
segment(c, get(copy, walker.next)),
getp(copy, walker.next),
walker.next,
copy,
segment(c, copy));
}
original = get(copy, walker.next);
local::set(copy, walker.next, follow(c, original));
goto visit;
} else {
return;
}
}
void
collect(Context* c, void** p)
{
collect(c, p, 0, 0);
}
void
collect(Context* c, void* target, unsigned offset)
{
collect(c, getp(target, offset), target, offset);
}
void
visitDirtyFixies(Context* c, Fixie** p)
{
while (*p) {
Fixie* f = *p;
bool wasDirty UNUSED = false;
bool clean = true;
uintptr_t* mask = f->mask();
unsigned word = 0;
unsigned bit = 0;
unsigned wordLimit = wordOf(f->size);
unsigned bitLimit = bitOf(f->size);
if (DebugFixies) {
fprintf(stderr, "clean fixie %p\n", f);
}
for (; word <= wordLimit and (word < wordLimit or bit < bitLimit);
++ word)
{
if (mask[word]) {
for (; bit < BitsPerWord and (word < wordLimit or bit < bitLimit);
++ bit)
{
unsigned index = indexOf(word, bit);
if (getBit(mask, index)) {
wasDirty = true;
clearBit(mask, index);
if (DebugFixies) {
fprintf(stderr, "clean fixie %p at %d (%p)\n",
f, index, f->body() + index);
}
collect(c, f->body(), index);
if (getBit(mask, index)) {
clean = false;
}
}
}
bit = 0;
}
}
if (DebugFixies) {
fprintf(stderr, "done cleaning fixie %p\n", f);
}
assert(c, wasDirty);
if (clean) {
markClean(c, f);
} else {
p = &(f->next);
}
}
}
void
visitMarkedFixies(Context* c)
{
while (c->markedFixies) {
Fixie* f = c->markedFixies;
f->remove(c);
if (DebugFixies) {
fprintf(stderr, "visit fixie %p\n", f);
}
class Walker: public Heap::Walker {
public:
Walker(Context* c, void** p):
c(c), p(p)
{ }
virtual bool visit(unsigned offset) {
local::collect(c, p, offset);
return true;
}
Context* c;
void** p;
} w(c, f->body());
c->client->walk(f->body(), &w);
f->move(c, &(c->visitedFixies));
}
}
void
collect(Context* c, Segment::Map* map, unsigned start, unsigned end,
bool* dirty, bool expectDirty UNUSED)
{
bool wasDirty UNUSED = false;
for (Segment::Map::Iterator it(map, start, end); it.hasMore();) {
wasDirty = true;
if (map->child) {
assert(c, map->scale > 1);
unsigned s = it.next();
unsigned e = s + map->scale;
map->clearOnly(s);
bool childDirty = false;
collect(c, map->child, s, e, &childDirty, true);
if (childDirty) {
map->setOnly(s);
*dirty = true;
}
} else {
assert(c, map->scale == 1);
void** p = reinterpret_cast<void**>(map->segment->get(it.next()));
map->clearOnly(p);
if (c->nextGen1.contains(*p)) {
map->setOnly(p);
*dirty = true;
} else {
collect(c, p);
if (not c->gen2.contains(*p)) {
map->setOnly(p);
*dirty = true;
}
}
}
}
assert(c, wasDirty or not expectDirty);
}
void
collect2(Context* c)
{
c->gen2Base = Top;
c->tenureFootprint = 0;
c->fixieTenureFootprint = 0;
c->gen1Padding = 0;
c->tenurePadding = 0;
if (c->mode == Heap::MajorCollection) {
c->gen2Padding = 0;
}
if (c->mode == Heap::MinorCollection and c->gen2.position()) {
unsigned start = 0;
unsigned end = start + c->gen2.position();
bool dirty;
collect(c, &(c->heapMap), start, end, &dirty, false);
}
if (c->mode == Heap::MinorCollection) {
visitDirtyFixies(c, &(c->dirtyTenuredFixies));
}
class Visitor : public Heap::Visitor {
public:
Visitor(Context* c): c(c) { }
virtual void visit(void* p) {
local::collect(c, static_cast<void**>(p));
visitMarkedFixies(c);
}
Context* c;
} v(c);
c->client->visitRoots(&v);
}
bool
limitExceeded(Context* c, int pendingAllocation)
{
unsigned count = c->count + pendingAllocation
- (c->gen2.remaining() * BytesPerWord);
if (Verbose) {
if (count > c->limit) {
if (not c->limitWasExceeded) {
c->limitWasExceeded = true;
fprintf(stderr, "heap limit %d exceeded: %d\n", c->limit, count);
}
} else if (c->limitWasExceeded) {
c->limitWasExceeded = false;
fprintf(stderr, "heap limit %d no longer exceeded: %d\n",
c->limit, count);
}
}
return count > c->limit;
}
void
collect(Context* c)
{
if (limitExceeded(c, c->pendingAllocation)
or oversizedGen2(c)
or c->tenureFootprint + c->tenurePadding > c->gen2.remaining()
or c->fixieTenureFootprint + c->tenuredFixieFootprint
> c->tenuredFixieCeiling)
{
if (Verbose) {
if (limitExceeded(c, c->pendingAllocation)) {
fprintf(stderr, "low memory causes ");
} else if (oversizedGen2(c)) {
fprintf(stderr, "oversized gen2 causes ");
} else if (c->tenureFootprint + c->tenurePadding > c->gen2.remaining())
{
fprintf(stderr, "undersized gen2 causes ");
} else {
fprintf(stderr, "fixie ceiling causes ");
}
}
c->mode = Heap::MajorCollection;
}
int64_t then;
if (Verbose) {
if (c->mode == Heap::MajorCollection) {
fprintf(stderr, "major collection\n");
} else {
fprintf(stderr, "minor collection\n");
}
then = c->system->now();
}
initNextGen1(c);
if (c->mode == Heap::MajorCollection) {
initNextGen2(c);
}
collect2(c);
c->gen1.replaceWith(&(c->nextGen1));
if (c->mode == Heap::MajorCollection) {
c->gen2.replaceWith(&(c->nextGen2));
}
sweepFixies(c);
if (Verbose) {
int64_t now = c->system->now();
int64_t collection = now - then;
int64_t run = then - c->lastCollectionTime;
c->totalCollectionTime += collection;
c->totalTime += collection + run;
c->lastCollectionTime = now;
fprintf(stderr,
" - collect: %4dms; "
"total: %4dms; "
"run: %4dms; "
"total: %4dms\n",
static_cast<int>(collection),
static_cast<int>(c->totalCollectionTime),
static_cast<int>(run),
static_cast<int>(c->totalTime - c->totalCollectionTime));
fprintf(stderr,
" - gen1: %8d/%8d bytes\n",
c->gen1.position() * BytesPerWord,
c->gen1.capacity() * BytesPerWord);
fprintf(stderr,
" - gen2: %8d/%8d bytes\n",
c->gen2.position() * BytesPerWord,
c->gen2.capacity() * BytesPerWord);
fprintf(stderr,
" - untenured fixies: %8d bytes\n",
c->untenuredFixieFootprint);
fprintf(stderr,
" - tenured fixies: %8d bytes\n",
c->tenuredFixieFootprint);
}
}
void*
allocate(Context* c, unsigned size, bool limit)
{
ACQUIRE(c->lock);
if (DebugAllocation) {
size = pad(size) + 2 * BytesPerWord;
}
if ((not limit) or size + c->count < c->limit) {
void* p = c->system->tryAllocate(size);
if (p) {
c->count += size;
if (DebugAllocation) {
static_cast<uintptr_t*>(p)[0] = 0x22377322;
static_cast<uintptr_t*>(p)[(size / BytesPerWord) - 1] = 0x22377322;
return static_cast<uintptr_t*>(p) + 1;
} else {
return p;
}
}
}
return 0;
}
void*
tryAllocate(Context* c, unsigned size)
{
return allocate(c, size, true);
}
void*
allocate(Context* c, unsigned size)
{
void* p = allocate(c, size, false);
expect(c->system, p);
return p;
}
void
free(Context* c, const void* p, unsigned size)
{
ACQUIRE(c->lock);
if (DebugAllocation) {
size = pad(size) + 2 * BytesPerWord;
memset(const_cast<void*>(p), 0xFE, size - (2 * BytesPerWord));
p = static_cast<const uintptr_t*>(p) - 1;
expect(c->system, static_cast<const uintptr_t*>(p)[0] == 0x22377322);
expect(c->system, static_cast<const uintptr_t*>(p)
[(size / BytesPerWord) - 1] == 0x22377322);
}
expect(c->system, c->count >= size);
c->system->free(p);
c->count -= size;
}
void
free_(Context* c, const void* p, unsigned size)
{
free(c, p, size);
}
class MyHeap: public Heap {
public:
MyHeap(System* system, unsigned limit):
c(system, limit)
{ }
virtual void setClient(Heap::Client* client) {
assert(&c, c.client == 0);
c.client = client;
}
virtual void setImmortalHeap(uintptr_t* start, unsigned sizeInWords) {
c.immortalHeapStart = start;
c.immortalHeapEnd = start + sizeInWords;
}
virtual unsigned remaining() {
return c.limit - c.count;
}
virtual unsigned limit() {
return c.limit;
}
virtual bool limitExceeded(int pendingAllocation = 0) {
return local::limitExceeded(&c, pendingAllocation);
}
virtual void* tryAllocate(unsigned size) {
return local::tryAllocate(&c, size);
}
virtual void* allocate(unsigned size) {
return local::allocate(&c, size);
}
virtual void free(const void* p, unsigned size) {
free_(&c, p, size);
}
virtual void collect(CollectionType type, unsigned incomingFootprint,
int pendingAllocation)
{
c.mode = type;
c.incomingFootprint = incomingFootprint;
c.pendingAllocation = pendingAllocation;
local::collect(&c);
}
virtual unsigned fixedFootprint(unsigned sizeInWords, bool objectMask) {
return Fixie::totalSize(sizeInWords, objectMask);
}
void* allocateFixed(Allocator* allocator, unsigned sizeInWords,
bool objectMask, Fixie** handle, bool immortal)
{
expect(&c, not limitExceeded());
unsigned total = Fixie::totalSize(sizeInWords, objectMask);
void* p = allocator->allocate(total);
expect(&c, not limitExceeded());
return (new (p) Fixie(&c, sizeInWords, objectMask, handle, immortal))
->body();
}
virtual void* allocateFixed(Allocator* allocator, unsigned sizeInWords,
bool objectMask)
{
return allocateFixed
(allocator, sizeInWords, objectMask, &(c.fixies), false);
}
virtual void* allocateImmortalFixed(Allocator* allocator,
unsigned sizeInWords, bool objectMask)
{
return allocateFixed(allocator, sizeInWords, objectMask, 0, true);
}
bool needsMark(void* p) {
assert(&c, c.client->isFixed(p) or (not immortalHeapContains(&c, p)));
if (c.client->isFixed(p)) {
return fixie(p)->age >= FixieTenureThreshold;
} else {
return c.gen2.contains(p) or c.nextGen2.contains(p);
}
}
bool targetNeedsMark(void* target) {
return target
and not c.gen2.contains(target)
and not c.nextGen2.contains(target)
and not immortalHeapContains(&c, target)
and not (c.client->isFixed(target)
and fixie(target)->age >= FixieTenureThreshold);
}
virtual void mark(void* p, unsigned offset, unsigned count) {
if (needsMark(p)) {
#ifndef USE_ATOMIC_OPERATIONS
ACQUIRE(c.lock);
#endif
if (c.client->isFixed(p)) {
Fixie* f = fixie(p);
assert(&c, offset == 0 or f->hasMask());
bool dirty = false;
for (unsigned i = 0; i < count; ++i) {
void** target = static_cast<void**>(p) + offset + i;
if (targetNeedsMark(maskAlignedPointer(*target))) {
if (DebugFixies) {
fprintf(stderr, "dirty fixie %p at %d (%p): %p\n",
f, offset, f->body() + offset, maskAlignedPointer(*target));
}
dirty = true;
#ifdef USE_ATOMIC_OPERATIONS
markBitAtomic(f->mask(), offset + i);
#else
markBit(f->mask(), offset + i);
#endif
assert(&c, getBit(f->mask(), offset + i));
}
}
if (dirty) markDirty(&c, f);
} else {
Segment::Map* map;
if (c.gen2.contains(p)) {
map = &(c.heapMap);
} else {
assert(&c, c.nextGen2.contains(p));
map = &(c.nextHeapMap);
}
for (unsigned i = 0; i < count; ++i) {
void** target = static_cast<void**>(p) + offset + i;
if (targetNeedsMark(maskAlignedPointer(*target))) {
#ifdef USE_ATOMIC_OPERATIONS
map->markAtomic(target);
#else
map->set(target);
#endif
}
}
}
}
}
virtual void pad(void* p) {
if (c.gen1.contains(p)) {
if (c.ageMap.get(p) == TenureThreshold) {
++ c.tenurePadding;
} else {
++ c.gen1Padding;
}
} else if (c.gen2.contains(p)) {
++ c.gen2Padding;
} else {
++ c.gen1Padding;
}
}
virtual void* follow(void* p) {
if (p == 0 or c.client->isFixed(p)) {
return p;
} else if (wasCollected(&c, p)) {
if (Debug) {
fprintf(stderr, "follow %p (%s) to %p (%s)\n",
p, segment(&c, p),
local::follow(&c, p), segment(&c, local::follow(&c, p)));
}
return local::follow(&c, p);
} else {
return p;
}
}
virtual void postVisit() {
killFixies(&c);
}
virtual Status status(void* p) {
p = maskAlignedPointer(p);
if (p == 0) {
return Null;
} else if (c.client->isFixed(p)) {
Fixie* f = fixie(p);
return f->dead()
? Unreachable
: (static_cast<unsigned>(f->age + 1) < FixieTenureThreshold
? Reachable
: Tenured);
} else if (c.nextGen1.contains(p)) {
return Reachable;
} else if (c.nextGen2.contains(p)
or immortalHeapContains(&c, p)
or (c.gen2.contains(p)
and (c.mode == Heap::MinorCollection
or c.gen2.indexOf(p) >= c.gen2Base)))
{
return Tenured;
} else if (wasCollected(&c, p)) {
return Reachable;
} else {
return Unreachable;
}
}
virtual CollectionType collectionType() {
return c.mode;
}
virtual void disposeFixies() {
c.disposeFixies();
}
virtual void dispose() {
c.dispose();
assert(&c, c.count == 0);
c.system->free(this);
}
Context c;
};
} // namespace local
} // namespace
namespace vm {
Heap*
makeHeap(System* system, unsigned limit)
{
return new (system->tryAllocate(sizeof(local::MyHeap)))
local::MyHeap(system, limit);
}
} // namespace vm
| {
"content_hash": "b0f450783a1ad06174f38fe90089e9d2",
"timestamp": "",
"source": "github",
"line_count": 2112,
"max_line_length": 85,
"avg_line_length": 22.362689393939394,
"alnum_prop": 0.5606605970781283,
"repo_name": "nmcl/scratch",
"id": "fa11086b652cb1d5a3c593f91ceea17da58353be",
"size": "47579",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "avian/src/heap/heap.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "37106"
},
{
"name": "Batchfile",
"bytes": "70668"
},
{
"name": "C",
"bytes": "139579"
},
{
"name": "C++",
"bytes": "3001008"
},
{
"name": "CSS",
"bytes": "2238"
},
{
"name": "Clojure",
"bytes": "1535"
},
{
"name": "Dockerfile",
"bytes": "4325"
},
{
"name": "Erlang",
"bytes": "33048"
},
{
"name": "Go",
"bytes": "333"
},
{
"name": "HTML",
"bytes": "1423375"
},
{
"name": "Haskell",
"bytes": "3992"
},
{
"name": "Io",
"bytes": "11232"
},
{
"name": "Java",
"bytes": "22796079"
},
{
"name": "JavaScript",
"bytes": "10464"
},
{
"name": "Makefile",
"bytes": "78159"
},
{
"name": "PHP",
"bytes": "175"
},
{
"name": "PowerShell",
"bytes": "3549"
},
{
"name": "Prolog",
"bytes": "17925"
},
{
"name": "Python",
"bytes": "23464"
},
{
"name": "Roff",
"bytes": "3575"
},
{
"name": "Ruby",
"bytes": "12190"
},
{
"name": "Rust",
"bytes": "880"
},
{
"name": "Scala",
"bytes": "4608"
},
{
"name": "Shell",
"bytes": "165574"
},
{
"name": "Swift",
"bytes": "211"
},
{
"name": "XSLT",
"bytes": "16312"
}
],
"symlink_target": ""
} |
import {FS} from '../lib/fs';
type GroupInfo = import('./config-loader').GroupInfo;
export const PLAYER_SYMBOL: GroupSymbol = '\u2606';
export const HOST_SYMBOL: GroupSymbol = '\u2605';
/**
* Auth table - a Map for which users are in which groups.
*
* Notice that auth.get will return the default group symbol if the
* user isn't in a group.
*/
export abstract class Auth extends Map<ID, GroupSymbol | ''> {
/**
* Will return the default group symbol if the user isn't in a group.
*
* Passing a User will read `user.group`, which is relevant for unregistered
* users with temporary global auth.
*/
get(user: ID | User) {
if (typeof user !== 'string') return (user as User).group;
return super.get(user) || Auth.defaultSymbol();
}
isStaff(userid: ID) {
return this.has(userid) && this.get(userid) !== '+';
}
atLeast(user: User, group: GroupSymbol) {
if (!Config.groups[group]) return false;
if (user.locked || user.semilocked) return false;
if (!this.has(user.id)) return false;
return Auth.getGroup(this.get(user.id)).rank >= Auth.getGroup(group).rank;
}
static defaultSymbol() {
return Config.groupsranking[0];
}
static getGroup(symbol: GroupSymbol): GroupInfo;
static getGroup<T>(symbol: GroupSymbol, fallback: T): GroupInfo | T;
static getGroup(symbol: GroupSymbol, fallback?: AnyObject) {
if (Config.groups[symbol]) return Config.groups[symbol];
if (fallback !== undefined) return fallback;
// unidentified groups are treated as voice
return Object.assign({}, Config.groups['+'] || {}, {
symbol,
id: 'voice',
name: symbol,
});
}
static hasPermission(
symbol: GroupSymbol, permission: string, targetSymbol?: GroupSymbol, targetingSelf?: boolean
): boolean {
const group = Auth.getGroup(symbol);
if (group['root']) {
return true;
}
if (group[permission]) {
const jurisdiction = group[permission];
if (!targetSymbol) {
return !!jurisdiction;
}
if (jurisdiction === true && permission !== 'jurisdiction') {
return Auth.hasPermission(symbol, 'jurisdiction', targetSymbol);
}
if (typeof jurisdiction !== 'string') {
return !!jurisdiction;
}
if (jurisdiction.includes(targetSymbol)) {
return true;
}
if (jurisdiction.includes('s') && targetingSelf) {
return true;
}
if (jurisdiction.includes('u') &&
Config.groupsranking.indexOf(symbol) > Config.groupsranking.indexOf(targetSymbol)) {
return true;
}
}
return false;
}
static listJurisdiction(symbol: GroupSymbol, permission: string) {
const symbols = Object.keys(Config.groups) as GroupSymbol[];
return symbols.filter(targetSymbol => Auth.hasPermission(symbol, permission, targetSymbol));
}
static isValidSymbol(symbol: string): symbol is GroupSymbol {
if (symbol.length !== 1) return false;
return !/[A-Za-z0-9|,]/.test(symbol);
}
}
export class RoomAuth extends Auth {
room: BasicRoom;
constructor(room: BasicRoom) {
super();
this.room = room;
}
get(user: ID | User): GroupSymbol {
const parentAuth: Auth | null = this.room.parent ? this.room.parent.auth :
this.room.settings.isPrivate !== true ? Users.globalAuth : null;
const parentGroup = parentAuth ? parentAuth.get(user) : Auth.defaultSymbol();
const id = typeof user === 'string' ? user : (user as User).id;
if (this.has(id)) {
// authority is whichever is higher between roomauth and global auth
const roomGroup = this.getDirect(id);
let group = Config.greatergroupscache[`${roomGroup}${parentGroup}`];
if (!group) {
// unrecognized groups always trump higher global rank
const roomRank = Auth.getGroup(roomGroup, {rank: Infinity}).rank;
const globalRank = Auth.getGroup(parentGroup).rank;
if (roomGroup === Users.PLAYER_SYMBOL || roomGroup === Users.HOST_SYMBOL || roomGroup === '#') {
// Player, Host, and Room Owner always trump higher global rank
group = roomGroup;
} else {
group = (roomRank > globalRank ? roomGroup : parentGroup);
}
Config.greatergroupscache[`${roomGroup}${parentGroup}`] = group;
}
return group;
}
return parentGroup;
}
/** gets the room group without inheriting */
getDirect(id: ID): GroupSymbol {
return super.get(id);
}
save() {
// construct auth object
const auth = Object.create(null);
for (const [userid, groupSymbol] of this) {
auth[userid] = groupSymbol;
}
(this.room.settings as any).auth = auth;
this.room.saveSettings();
}
load() {
for (const userid in this.room.settings.auth) {
super.set(userid as ID, this.room.settings.auth[userid]);
}
}
set(id: ID, symbol: GroupSymbol) {
const user = Users.get(id);
if (user) {
this.room.onUpdateIdentity(user);
}
if (symbol === 'whitelist' as GroupSymbol) {
symbol = Auth.defaultSymbol();
}
super.set(id, symbol);
this.room.settings.auth[id] = symbol;
this.room.saveSettings();
return this;
}
delete(id: ID) {
if (!this.has(id)) return false;
super.delete(id);
delete this.room.settings.auth[id];
this.room.saveSettings();
return true;
}
}
export class GlobalAuth extends Auth {
usernames = new Map<ID, string>();
constructor() {
super();
this.load();
}
save() {
FS('config/usergroups.csv').writeUpdate(() => {
let buffer = '';
for (const [userid, groupSymbol] of this) {
buffer += `${this.usernames.get(userid) || userid},${groupSymbol}\n`;
}
return buffer;
});
}
load() {
const data = FS('config/usergroups.csv').readIfExistsSync();
for (const row of data.split("\n")) {
if (!row) continue;
const [name, symbol] = row.split(",");
const id = toID(name);
this.usernames.set(id, name);
super.set(id, symbol.charAt(0) as GroupSymbol);
}
}
set(id: ID, group: GroupSymbol, username?: string) {
if (!username) username = id;
const user = Users.get(id);
if (user) {
user.group = group;
user.updateIdentity();
username = user.name;
}
this.usernames.set(id, username);
super.set(id, group);
void this.save();
return this;
}
delete(id: ID) {
if (!super.has(id)) return false;
super.delete(id);
const user = Users.get(id);
if (user) {
user.group = ' ';
}
this.usernames.delete(id);
this.save();
return true;
}
}
| {
"content_hash": "44ccd341e04d005225d5b89e90bbf359",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 100,
"avg_line_length": 28.88372093023256,
"alnum_prop": 0.6619967793880838,
"repo_name": "AustinXII/Pokemon-Showdown",
"id": "a6a9662ca2efb589f8785b1c6389dfc68d75fde2",
"size": "6210",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server/user-groups.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "351"
},
{
"name": "HTML",
"bytes": "655"
},
{
"name": "JavaScript",
"bytes": "10612959"
},
{
"name": "TypeScript",
"bytes": "481827"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//
package org.mule.modules.hybris.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for orderReturnRecordDTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="orderReturnRecordDTO">
* <complexContent>
* <extension base="{}orderModificationRecordDTO">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "orderReturnRecordDTO")
public class OrderReturnRecordDTO
extends OrderModificationRecordDTO
{
}
| {
"content_hash": "67b1b449c7c4d12ba58a40e9ed46ec63",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 111,
"avg_line_length": 27.29268292682927,
"alnum_prop": 0.7167113494191242,
"repo_name": "ryandcarter/hybris-connector",
"id": "c33c16db8bbffbd986030309ef68fd1cd29750b4",
"size": "1119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/mule/modules/hybris/model/OrderReturnRecordDTO.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7702461"
}
],
"symlink_target": ""
} |
""" Cisco_IOS_XR_aaa_protocol_radius_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR aaa\-protocol\-radius package operational data.
This module contains definitions
for the following management objects\:
radius\: RADIUS operational data
This YANG module augments the
Cisco\-IOS\-XR\-aaa\-locald\-oper
module with state data.
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk.errors import YPYError, YPYModelError
class Radius(object):
"""
RADIUS operational data
.. attribute:: nodes
Contains all the nodes
**type**\: :py:class:`Nodes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.nodes = Radius.Nodes()
self.nodes.parent = self
class Nodes(object):
"""
Contains all the nodes
.. attribute:: node
RADIUS operational data for a particular node
**type**\: list of :py:class:`Node <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node = YList()
self.node.parent = self
self.node.name = 'node'
class Node(object):
"""
RADIUS operational data for a particular node
.. attribute:: node_name <key>
Node name
**type**\: str
**pattern:** ([a\-zA\-Z0\-9\_]\*\\d+/){1,2}([a\-zA\-Z0\-9\_]\*\\d+)
.. attribute:: accounting
RADIUS accounting data
**type**\: :py:class:`Accounting <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Accounting>`
.. attribute:: authentication
RADIUS authentication data
**type**\: :py:class:`Authentication <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Authentication>`
.. attribute:: client
RADIUS client data
**type**\: :py:class:`Client <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Client>`
.. attribute:: dead_criteria
RADIUS dead criteria information
**type**\: :py:class:`DeadCriteria <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DeadCriteria>`
.. attribute:: dynamic_authorization
Dynamic authorization data
**type**\: :py:class:`DynamicAuthorization <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DynamicAuthorization>`
.. attribute:: server_groups
RADIUS server group table
**type**\: :py:class:`ServerGroups <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node_name = None
self.accounting = Radius.Nodes.Node.Accounting()
self.accounting.parent = self
self.authentication = Radius.Nodes.Node.Authentication()
self.authentication.parent = self
self.client = Radius.Nodes.Node.Client()
self.client.parent = self
self.dead_criteria = Radius.Nodes.Node.DeadCriteria()
self.dead_criteria.parent = self
self.dynamic_authorization = Radius.Nodes.Node.DynamicAuthorization()
self.dynamic_authorization.parent = self
self.server_groups = Radius.Nodes.Node.ServerGroups()
self.server_groups.parent = self
class Client(object):
"""
RADIUS client data
.. attribute:: authentication_nas_id
NAS\-Identifier of the RADIUS authentication client
**type**\: str
.. attribute:: unknown_accounting_responses
Number of RADIUS accounting responses packets received from unknown addresses
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_authentication_responses
Number of RADIUS access responses packets received from unknown addresses
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.authentication_nas_id = None
self.unknown_accounting_responses = None
self.unknown_authentication_responses = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:client'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.authentication_nas_id is not None:
return True
if self.unknown_accounting_responses is not None:
return True
if self.unknown_authentication_responses is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Client']['meta_info']
class DeadCriteria(object):
"""
RADIUS dead criteria information
.. attribute:: hosts
RADIUS server dead criteria host table
**type**\: :py:class:`Hosts <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DeadCriteria.Hosts>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.hosts = Radius.Nodes.Node.DeadCriteria.Hosts()
self.hosts.parent = self
class Hosts(object):
"""
RADIUS server dead criteria host table
.. attribute:: host
RADIUS Server
**type**\: list of :py:class:`Host <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DeadCriteria.Hosts.Host>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.host = YList()
self.host.parent = self
self.host.name = 'host'
class Host(object):
"""
RADIUS Server
.. attribute:: acct_port_number
Accounting Port number (standard port 1646)
**type**\: int
**range:** 1..65535
.. attribute:: auth_port_number
Authentication Port number (standard port 1645)
**type**\: int
**range:** 1..65535
.. attribute:: ip_address
IP address of RADIUS server
**type**\: one of the below types:
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
----
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
----
.. attribute:: time
Time in seconds
**type**\: :py:class:`Time <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DeadCriteria.Hosts.Host.Time>`
.. attribute:: tries
Number of tries
**type**\: :py:class:`Tries <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.DeadCriteria.Hosts.Host.Tries>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.acct_port_number = None
self.auth_port_number = None
self.ip_address = None
self.time = Radius.Nodes.Node.DeadCriteria.Hosts.Host.Time()
self.time.parent = self
self.tries = Radius.Nodes.Node.DeadCriteria.Hosts.Host.Tries()
self.tries.parent = self
class Time(object):
"""
Time in seconds
.. attribute:: is_computed
True if computed; false if not
**type**\: bool
.. attribute:: value
Value for time or tries
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.is_computed = None
self.value = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:time'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.is_computed is not None:
return True
if self.value is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DeadCriteria.Hosts.Host.Time']['meta_info']
class Tries(object):
"""
Number of tries
.. attribute:: is_computed
True if computed; false if not
**type**\: bool
.. attribute:: value
Value for time or tries
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.is_computed = None
self.value = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:tries'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.is_computed is not None:
return True
if self.value is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DeadCriteria.Hosts.Host.Tries']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:host'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.acct_port_number is not None:
return True
if self.auth_port_number is not None:
return True
if self.ip_address is not None:
return True
if self.time is not None and self.time._has_data():
return True
if self.tries is not None and self.tries._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DeadCriteria.Hosts.Host']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:hosts'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.host is not None:
for child_ref in self.host:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DeadCriteria.Hosts']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:dead-criteria'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.hosts is not None and self.hosts._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DeadCriteria']['meta_info']
class Authentication(object):
"""
RADIUS authentication data
.. attribute:: authentication_group
List of authentication groups
**type**\: list of :py:class:`AuthenticationGroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Authentication.AuthenticationGroup>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.authentication_group = YList()
self.authentication_group.parent = self
self.authentication_group.name = 'authentication_group'
class AuthenticationGroup(object):
"""
List of authentication groups
.. attribute:: authentication
Authentication data
**type**\: :py:class:`Authentication_ <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Authentication.AuthenticationGroup.Authentication_>`
.. attribute:: family
IP address Family
**type**\: str
.. attribute:: ip_address
IP address buffer
**type**\: str
.. attribute:: port
Authentication port number
**type**\: int
**range:** 0..4294967295
.. attribute:: server_address
IP address of RADIUS server
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.authentication = Radius.Nodes.Node.Authentication.AuthenticationGroup.Authentication_()
self.authentication.parent = self
self.family = None
self.ip_address = None
self.port = None
self.server_address = None
class Authentication_(object):
"""
Authentication data
.. attribute:: access_accepts
Number of access accepts
**type**\: int
**range:** 0..4294967295
.. attribute:: access_challenges
Number of access challenges
**type**\: int
**range:** 0..4294967295
.. attribute:: access_rejects
Number of access rejects
**type**\: int
**range:** 0..4294967295
.. attribute:: access_request_retransmits
Number of retransmitted access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_requests
Number of access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_timeouts
Number of access packets timed out
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_incorrect_responses
Number of incorrect authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_server_error_responses
Number of server error authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_unexpected_responses
Number of unexpected authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_authenticators
Number of bad access authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_responses
Number of bad access responses
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_access_responses
Number of access responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_access_requests
Number of pending access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: rtt
Round trip time for authentication in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: unknown_access_types
Number of packets received with unknown type from authentication server
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.access_accepts = None
self.access_challenges = None
self.access_rejects = None
self.access_request_retransmits = None
self.access_requests = None
self.access_timeouts = None
self.authen_incorrect_responses = None
self.authen_response_time = None
self.authen_server_error_responses = None
self.authen_transaction_failure = None
self.authen_transaction_successess = None
self.authen_unexpected_responses = None
self.bad_access_authenticators = None
self.bad_access_responses = None
self.dropped_access_responses = None
self.pending_access_requests = None
self.rtt = None
self.unknown_access_types = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:authentication'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.access_accepts is not None:
return True
if self.access_challenges is not None:
return True
if self.access_rejects is not None:
return True
if self.access_request_retransmits is not None:
return True
if self.access_requests is not None:
return True
if self.access_timeouts is not None:
return True
if self.authen_incorrect_responses is not None:
return True
if self.authen_response_time is not None:
return True
if self.authen_server_error_responses is not None:
return True
if self.authen_transaction_failure is not None:
return True
if self.authen_transaction_successess is not None:
return True
if self.authen_unexpected_responses is not None:
return True
if self.bad_access_authenticators is not None:
return True
if self.bad_access_responses is not None:
return True
if self.dropped_access_responses is not None:
return True
if self.pending_access_requests is not None:
return True
if self.rtt is not None:
return True
if self.unknown_access_types is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Authentication.AuthenticationGroup.Authentication_']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:authentication-group'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.authentication is not None and self.authentication._has_data():
return True
if self.family is not None:
return True
if self.ip_address is not None:
return True
if self.port is not None:
return True
if self.server_address is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Authentication.AuthenticationGroup']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:authentication'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.authentication_group is not None:
for child_ref in self.authentication_group:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Authentication']['meta_info']
class Accounting(object):
"""
RADIUS accounting data
.. attribute:: accounting_group
List of accounting groups
**type**\: list of :py:class:`AccountingGroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Accounting.AccountingGroup>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.accounting_group = YList()
self.accounting_group.parent = self
self.accounting_group.name = 'accounting_group'
class AccountingGroup(object):
"""
List of accounting groups
.. attribute:: accounting
Accounting data
**type**\: :py:class:`Accounting_ <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.Accounting.AccountingGroup.Accounting_>`
.. attribute:: family
IP address Family
**type**\: str
.. attribute:: ip_address
IP address buffer
**type**\: str
.. attribute:: port
Accounting port number
**type**\: int
**range:** 0..4294967295
.. attribute:: server_address
IP address of RADIUS server
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.accounting = Radius.Nodes.Node.Accounting.AccountingGroup.Accounting_()
self.accounting.parent = self
self.family = None
self.ip_address = None
self.port = None
self.server_address = None
class Accounting_(object):
"""
Accounting data
.. attribute:: acct_incorrect_responses
Number of incorrect accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_server_error_responses
Number of server error accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_unexpected_responses
Number of unexpected accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_authenticators
Number of bad accounting authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_responses
Number of bad accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_responses
Number of accounting responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_requests
Number of pending accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: requests
Number of accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: responses
Number of accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: retransmits
Number of retransmitted accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: rtt
Round trip time for accounting in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: timeouts
Number of accounting packets timed\-out
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_packet_types
Number of packets received with unknown type from accounting server
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.acct_incorrect_responses = None
self.acct_response_time = None
self.acct_server_error_responses = None
self.acct_transaction_failure = None
self.acct_transaction_successess = None
self.acct_unexpected_responses = None
self.bad_authenticators = None
self.bad_responses = None
self.dropped_responses = None
self.pending_requests = None
self.requests = None
self.responses = None
self.retransmits = None
self.rtt = None
self.timeouts = None
self.unknown_packet_types = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:accounting'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.acct_incorrect_responses is not None:
return True
if self.acct_response_time is not None:
return True
if self.acct_server_error_responses is not None:
return True
if self.acct_transaction_failure is not None:
return True
if self.acct_transaction_successess is not None:
return True
if self.acct_unexpected_responses is not None:
return True
if self.bad_authenticators is not None:
return True
if self.bad_responses is not None:
return True
if self.dropped_responses is not None:
return True
if self.pending_requests is not None:
return True
if self.requests is not None:
return True
if self.responses is not None:
return True
if self.retransmits is not None:
return True
if self.rtt is not None:
return True
if self.timeouts is not None:
return True
if self.unknown_packet_types is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Accounting.AccountingGroup.Accounting_']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:accounting-group'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.accounting is not None and self.accounting._has_data():
return True
if self.family is not None:
return True
if self.ip_address is not None:
return True
if self.port is not None:
return True
if self.server_address is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Accounting.AccountingGroup']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:accounting'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.accounting_group is not None:
for child_ref in self.accounting_group:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.Accounting']['meta_info']
class ServerGroups(object):
"""
RADIUS server group table
.. attribute:: server_group
RADIUS server group data
**type**\: list of :py:class:`ServerGroup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups.ServerGroup>`
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.server_group = YList()
self.server_group.parent = self
self.server_group.name = 'server_group'
class ServerGroup(object):
"""
RADIUS server group data
.. attribute:: server_group_name <key>
Group name
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: dead_time
Dead time in minutes
**type**\: int
**range:** 0..4294967295
**units**\: minute
.. attribute:: groups
Number of groups
**type**\: int
**range:** 0..4294967295
.. attribute:: server_group
Server groups
**type**\: list of :py:class:`ServerGroup_ <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_>`
.. attribute:: servers
Number of servers
**type**\: int
**range:** 0..4294967295
.. attribute:: vrf_name
VRF name
**type**\: str
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.server_group_name = None
self.dead_time = None
self.groups = None
self.server_group = YList()
self.server_group.parent = self
self.server_group.name = 'server_group'
self.servers = None
self.vrf_name = None
class ServerGroup_(object):
"""
Server groups
.. attribute:: accounting
Accounting data
**type**\: :py:class:`Accounting <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Accounting>`
.. attribute:: accounting_port
Accounting port
**type**\: int
**range:** 0..4294967295
.. attribute:: authentication
Authentication data
**type**\: :py:class:`Authentication <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authentication>`
.. attribute:: authentication_port
Authentication port
**type**\: int
**range:** 0..4294967295
.. attribute:: authorization
Authorization data
**type**\: :py:class:`Authorization <ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_protocol_radius_oper.Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authorization>`
.. attribute:: family
IP address Family
**type**\: str
.. attribute:: ip_address
IP address buffer
**type**\: str
.. attribute:: is_private
True if private
**type**\: bool
.. attribute:: server_address
Server address
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.accounting = Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Accounting()
self.accounting.parent = self
self.accounting_port = None
self.authentication = Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authentication()
self.authentication.parent = self
self.authentication_port = None
self.authorization = Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authorization()
self.authorization.parent = self
self.family = None
self.ip_address = None
self.is_private = None
self.server_address = None
class Accounting(object):
"""
Accounting data
.. attribute:: acct_incorrect_responses
Number of incorrect accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_server_error_responses
Number of server error accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: acct_unexpected_responses
Number of unexpected accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_authenticators
Number of bad accounting authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_responses
Number of bad accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_responses
Number of accounting responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_requests
Number of pending accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: requests
Number of accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: responses
Number of accounting responses
**type**\: int
**range:** 0..4294967295
.. attribute:: retransmits
Number of retransmitted accounting requests
**type**\: int
**range:** 0..4294967295
.. attribute:: rtt
Round trip time for accounting in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: timeouts
Number of accounting packets timed\-out
**type**\: int
**range:** 0..4294967295
.. attribute:: unknown_packet_types
Number of packets received with unknown type from accounting server
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.acct_incorrect_responses = None
self.acct_response_time = None
self.acct_server_error_responses = None
self.acct_transaction_failure = None
self.acct_transaction_successess = None
self.acct_unexpected_responses = None
self.bad_authenticators = None
self.bad_responses = None
self.dropped_responses = None
self.pending_requests = None
self.requests = None
self.responses = None
self.retransmits = None
self.rtt = None
self.timeouts = None
self.unknown_packet_types = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:accounting'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.acct_incorrect_responses is not None:
return True
if self.acct_response_time is not None:
return True
if self.acct_server_error_responses is not None:
return True
if self.acct_transaction_failure is not None:
return True
if self.acct_transaction_successess is not None:
return True
if self.acct_unexpected_responses is not None:
return True
if self.bad_authenticators is not None:
return True
if self.bad_responses is not None:
return True
if self.dropped_responses is not None:
return True
if self.pending_requests is not None:
return True
if self.requests is not None:
return True
if self.responses is not None:
return True
if self.retransmits is not None:
return True
if self.rtt is not None:
return True
if self.timeouts is not None:
return True
if self.unknown_packet_types is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Accounting']['meta_info']
class Authentication(object):
"""
Authentication data
.. attribute:: access_accepts
Number of access accepts
**type**\: int
**range:** 0..4294967295
.. attribute:: access_challenges
Number of access challenges
**type**\: int
**range:** 0..4294967295
.. attribute:: access_rejects
Number of access rejects
**type**\: int
**range:** 0..4294967295
.. attribute:: access_request_retransmits
Number of retransmitted access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_requests
Number of access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: access_timeouts
Number of access packets timed out
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_incorrect_responses
Number of incorrect authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_response_time
Average response time for authentication requests
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_server_error_responses
Number of server error authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_failure
Number of failed authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_transaction_successess
Number of succeeded authentication transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: authen_unexpected_responses
Number of unexpected authentication responses
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_authenticators
Number of bad access authenticators
**type**\: int
**range:** 0..4294967295
.. attribute:: bad_access_responses
Number of bad access responses
**type**\: int
**range:** 0..4294967295
.. attribute:: dropped_access_responses
Number of access responses dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: pending_access_requests
Number of pending access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: rtt
Round trip time for authentication in milliseconds
**type**\: int
**range:** 0..4294967295
**units**\: millisecond
.. attribute:: unknown_access_types
Number of packets received with unknown type from authentication server
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.access_accepts = None
self.access_challenges = None
self.access_rejects = None
self.access_request_retransmits = None
self.access_requests = None
self.access_timeouts = None
self.authen_incorrect_responses = None
self.authen_response_time = None
self.authen_server_error_responses = None
self.authen_transaction_failure = None
self.authen_transaction_successess = None
self.authen_unexpected_responses = None
self.bad_access_authenticators = None
self.bad_access_responses = None
self.dropped_access_responses = None
self.pending_access_requests = None
self.rtt = None
self.unknown_access_types = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:authentication'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.access_accepts is not None:
return True
if self.access_challenges is not None:
return True
if self.access_rejects is not None:
return True
if self.access_request_retransmits is not None:
return True
if self.access_requests is not None:
return True
if self.access_timeouts is not None:
return True
if self.authen_incorrect_responses is not None:
return True
if self.authen_response_time is not None:
return True
if self.authen_server_error_responses is not None:
return True
if self.authen_transaction_failure is not None:
return True
if self.authen_transaction_successess is not None:
return True
if self.authen_unexpected_responses is not None:
return True
if self.bad_access_authenticators is not None:
return True
if self.bad_access_responses is not None:
return True
if self.dropped_access_responses is not None:
return True
if self.pending_access_requests is not None:
return True
if self.rtt is not None:
return True
if self.unknown_access_types is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authentication']['meta_info']
class Authorization(object):
"""
Authorization data
.. attribute:: author_incorrect_responses
Number of incorrect authorization responses
**type**\: int
**range:** 0..4294967295
.. attribute:: author_request_timeouts
Number of access packets timed out
**type**\: int
**range:** 0..4294967295
.. attribute:: author_requests
Number of access requests
**type**\: int
**range:** 0..4294967295
.. attribute:: author_response_time
Average response time for authorization requests
**type**\: int
**range:** 0..4294967295
.. attribute:: author_server_error_responses
Number of server error authorization responses
**type**\: int
**range:** 0..4294967295
.. attribute:: author_transaction_failure
Number of failed authorization transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: author_transaction_successess
Number of succeeded authorization transactions
**type**\: int
**range:** 0..4294967295
.. attribute:: author_unexpected_responses
Number of unexpected authorization responses
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.author_incorrect_responses = None
self.author_request_timeouts = None
self.author_requests = None
self.author_response_time = None
self.author_server_error_responses = None
self.author_transaction_failure = None
self.author_transaction_successess = None
self.author_unexpected_responses = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:authorization'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.author_incorrect_responses is not None:
return True
if self.author_request_timeouts is not None:
return True
if self.author_requests is not None:
return True
if self.author_response_time is not None:
return True
if self.author_server_error_responses is not None:
return True
if self.author_transaction_failure is not None:
return True
if self.author_transaction_successess is not None:
return True
if self.author_unexpected_responses is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_.Authorization']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:server-group'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.accounting is not None and self.accounting._has_data():
return True
if self.accounting_port is not None:
return True
if self.authentication is not None and self.authentication._has_data():
return True
if self.authentication_port is not None:
return True
if self.authorization is not None and self.authorization._has_data():
return True
if self.family is not None:
return True
if self.ip_address is not None:
return True
if self.is_private is not None:
return True
if self.server_address is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups.ServerGroup.ServerGroup_']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.server_group_name is None:
raise YPYModelError('Key property server_group_name is None')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:server-group[Cisco-IOS-XR-aaa-protocol-radius-oper:server-group-name = ' + str(self.server_group_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.server_group_name is not None:
return True
if self.dead_time is not None:
return True
if self.groups is not None:
return True
if self.server_group is not None:
for child_ref in self.server_group:
if child_ref._has_data():
return True
if self.servers is not None:
return True
if self.vrf_name is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups.ServerGroup']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:server-groups'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.server_group is not None:
for child_ref in self.server_group:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.ServerGroups']['meta_info']
class DynamicAuthorization(object):
"""
Dynamic authorization data
.. attribute:: disconnected_invalid_requests
Invalid disconnected requests
**type**\: int
**range:** 0..4294967295
.. attribute:: invalid_coa_requests
Invalid change of authorization requests
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'aaa-protocol-radius-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.disconnected_invalid_requests = None
self.invalid_coa_requests = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-aaa-protocol-radius-oper:dynamic-authorization'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.disconnected_invalid_requests is not None:
return True
if self.invalid_coa_requests is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node.DynamicAuthorization']['meta_info']
@property
def _common_path(self):
if self.node_name is None:
raise YPYModelError('Key property node_name is None')
return '/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/Cisco-IOS-XR-aaa-protocol-radius-oper:nodes/Cisco-IOS-XR-aaa-protocol-radius-oper:node[Cisco-IOS-XR-aaa-protocol-radius-oper:node-name = ' + str(self.node_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node_name is not None:
return True
if self.accounting is not None and self.accounting._has_data():
return True
if self.authentication is not None and self.authentication._has_data():
return True
if self.client is not None and self.client._has_data():
return True
if self.dead_criteria is not None and self.dead_criteria._has_data():
return True
if self.dynamic_authorization is not None and self.dynamic_authorization._has_data():
return True
if self.server_groups is not None and self.server_groups._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes.Node']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-aaa-protocol-radius-oper:radius/Cisco-IOS-XR-aaa-protocol-radius-oper:nodes'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node is not None:
for child_ref in self.node:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius.Nodes']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-aaa-protocol-radius-oper:radius'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.nodes is not None and self.nodes._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_aaa_protocol_radius_oper as meta
return meta._meta_table['Radius']['meta_info']
| {
"content_hash": "807e093ce49248a8e468b7eaff86dfd1",
"timestamp": "",
"source": "github",
"line_count": 2190,
"max_line_length": 269,
"avg_line_length": 41.546118721461184,
"alnum_prop": 0.3778493394588178,
"repo_name": "111pontes/ydk-py",
"id": "2975497caad225bb3f147381a6321ddfebbe4ea2",
"size": "90986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_aaa_protocol_radius_oper.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "7226"
},
{
"name": "Python",
"bytes": "446117948"
}
],
"symlink_target": ""
} |
/* eslint-env mocha */
'use strict'
const expect = require('chai').expect
const loadFixture = require('aegir/fixtures')
const UnixFS = require('../src')
const raw = loadFixture(__dirname, 'fixtures/raw.unixfs')
const directory = loadFixture(__dirname, 'fixtures/directory.unixfs')
const file = loadFixture(__dirname, 'fixtures/file.txt.unixfs')
const symlink = loadFixture(__dirname, 'fixtures/symlink.txt.unixfs')
describe('unixfs-format', () => {
it('raw', (done) => {
const data = new UnixFS('raw', new Buffer('bananas'))
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
done()
})
it('directory', (done) => {
const data = new UnixFS('directory')
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
done()
})
it('file', (done) => {
const data = new UnixFS('file', new Buffer('batata'))
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
done()
})
it('file add blocksize', (done) => {
const data = new UnixFS('file')
data.addBlockSize(256)
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
done()
})
it('file add and remove blocksize', (done) => {
const data = new UnixFS('file')
data.addBlockSize(256)
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
unmarsheled.removeBlockSize(0)
expect(data.blockSizes).to.not.deep.equal(unmarsheled.blockSizes)
done()
})
// figuring out what is this metadata for https://github.com/ipfs/js-ipfs-data-importing/issues/3#issuecomment-182336526
it.skip('metadata', (done) => {})
it('symlink', (done) => {
const data = new UnixFS('symlink')
const marsheled = data.marshal()
const unmarsheled = UnixFS.unmarshal(marsheled)
expect(data.type).to.equal(unmarsheled.type)
expect(data.data).to.deep.equal(unmarsheled.data)
expect(data.blockSizes).to.deep.equal(unmarsheled.blockSizes)
expect(data.fileSize()).to.deep.equal(unmarsheled.fileSize())
done()
})
it('wrong type', (done) => {
let data
try {
data = new UnixFS('bananas')
} catch (err) {
expect(err).to.exist
expect(data).to.not.exist
done()
}
})
describe('interop', () => {
it('raw', (done) => {
const unmarsheled = UnixFS.unmarshal(raw)
expect(unmarsheled.data).to.deep.equal(new Buffer('Hello UnixFS\n'))
expect(unmarsheled.type).to.equal('file')
expect(unmarsheled.marshal()).to.deep.equal(raw)
done()
})
it('directory', (done) => {
const unmarsheled = UnixFS.unmarshal(directory)
expect(unmarsheled.data).to.deep.equal(undefined)
expect(unmarsheled.type).to.equal('directory')
expect(unmarsheled.marshal()).to.deep.equal(directory)
done()
})
it('file', (done) => {
const unmarsheled = UnixFS.unmarshal(file)
expect(unmarsheled.data).to.deep.equal(new Buffer('Hello UnixFS\n'))
expect(unmarsheled.type).to.equal('file')
expect(unmarsheled.marshal()).to.deep.equal(file)
done()
})
it.skip('metadata', (done) => {
})
it('symlink', (done) => {
const unmarsheled = UnixFS.unmarshal(symlink)
expect(unmarsheled.data).to.deep.equal(new Buffer('file.txt'))
expect(unmarsheled.type).to.equal('symlink')
// TODO: waiting on https://github.com/ipfs/js-ipfs-data-importing/issues/3#issuecomment-182440079
// expect(unmarsheled.marshal()).to.deep.equal(symlink)
done()
})
})
})
| {
"content_hash": "7551c7e00953f36d2e3f794fa201c9de",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 122,
"avg_line_length": 35.34074074074074,
"alnum_prop": 0.6730245231607629,
"repo_name": "Project-Oaken/water-meter-acorn",
"id": "8d748cbbbc859f5407a110cfa3095d0891ebfff8",
"size": "4771",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo-for-video/water-meter-1-liter-demo/node/node_modules/ipfs-unixfs/test/unixfs-format.spec.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "32638"
},
{
"name": "HTML",
"bytes": "20240"
},
{
"name": "JavaScript",
"bytes": "1104017"
}
],
"symlink_target": ""
} |
<?php
namespace yiingine\modules\users\controllers;
use \Yii;
use \yiingine\modules\users\models\User;
/**
* Controller for user self registration and activation.
* */
class RegisterController extends \yiingine\modules\media\web\Controller
{
/**
* @inheritdoc
*/
public function actions()
{
return array_merge(parent::actions(), \yiingine\widgets\Captcha::actions());
}
/**
* Presents the user with a registration form.
*/
public function actionIndex()
{
if(!$this->module->allowRegistration) // If self registration is not enabled.
{
throw new \yii\web\NotFoundHttpException();
}
if(!Yii::$app->user->isGuest) //If a user is already logged in.
{
//Redirect instead of throwing a 403, because logged user end up on this page quite often.
$this->redirect($this->module->returnLogoutUrl, 302); // Temporary redirect.
}
//If user registration or user accounts has been temporarily disabled or if the site is read-only.
if(Yii::$app->getParameter('yiingine.uers.disable_user_registration') ||
Yii::$app->getParameter('app.read_only') ||
Yii::$app->getParameter('yiingine.users.disable_user_accounts')
)
{
throw new \yii\HttpException(503); // Service unavailable.
}
// If the system_email configuration entry is not set.
if(!isset(Yii::$app->params['app.system_email']))
{
throw new \yii\base\Exception('app.system_email configuration entry not set');
}
$model = new \yiingine\modules\users\models\RegistrationForm(); // User registration form.
$model->scenario = 'registration';
if($model->load(Yii::$app->request->post())) // If a registration form has been posted.
{
if($model->validate())
{
// Keep the password for logging in the user once he has registered.
$sourcePassword = $model->password;
// Activate the user if that option is set in the module.
$model->status = $this->module->activeAfterRegister ?
User::STATUS_ACTIVE:
User::STATUS_NOACTIVE;
if($model->save()) // If the user saved sucessfully.
{
// If the user needs to activate his account.
if(!$this->module->activeAfterRegister)
{
// If the user must contact an admin to get his account activated.
if(!$this->module->sendActivationMail)
{
// Notify the user.
return $this->render('message', [
'model' => $model,
'message' => Yii::t(__CLASS__, 'Thank you for your registration. Please contact an administrator to activate your account.'),
'type' => 'success'
]);
}
else // An email is to be sent to the user detailing the procedure for account activation.
{
try
{
Yii::$app->mailer->view = Yii::$app->view;
$message = Yii::$app->mailer->compose('@yiingine/modules/users/views/register/activation.php', [
'model' => $model,
'activationUrl' => ['activate', 'email' => $model->email, 'activationKey' => $model->activation_key]
]);
$message->setTo($model->email);
$message->setFrom(Yii::$app->getParameter('app.system_email', 'system@notset.com'));
$message->setSubject(Yii::t(__CLASS__, '{siteName} - account activation', ['siteName' => Yii::$app->name]));
if(!$message->send()) //If the message did not send.
{
throw new \yii\web\ServerErrorHttpException(Yii::t(__CLASS__, 'Sending the message failed, please try again later.'));
}
}
catch(\Exception $e)
{
$model->delete(); // Activation failed so delete the user.
throw $e;
}
/* The user account has been registered sucessfully,
inform the user of the next step. */
// Notify the user.
return $this->render('message', [
'model' => $model,
'message' => Yii::t(__CLASS__, 'Thank you for your registration. An activation e-mail was sent to the address provided.'),
'type' => 'success'
]);
}
}
else // Else the user is logged in after registration.
{
// Log the user in.
$login = new \yiingine\modules\users\models\UserLogin();
$login->password = $sourcePassword;
$login->username = $model->username;
$login->login();
// Notify the user his registration was successful..
return $this->render('message', [
'model' => $model,
'message' => Yii::t(__CLASS__, 'Thank you for registering. You are now logged in.'),
'type' => 'success'
]);
}
}
}
}
return $this->render('index', ['model' => $model]);
}
/**
* Activate a user account.
* @param string $email the email of the account that needs activation.
* @param string $activationKey the key for activating the account.
*/
public function actionActivate($email, $activationKey)
{
if($this->module->activeAfterRegister) // If accounts do not need to be activated.
{
throw new \yii\web\NotFoundHttpException(); // Hide this action.
}
if(!Yii::$app->user->isGuest) // Only guest can activate accounts.
{
// Redirect instead of throwing a 403, because logged user end up on this page quite often.
$this->redirect($this->module->returnLogoutUrl, 302); // Temporary redirect.
}
$model= User::find()->where(['email' => $email])->one();
if($model && (int)$model->status === User::STATUS_ACTIVE) // If the account is already active.
{
throw new \yii\web\ForbiddenHttpException(Yii::t(__CLASS__, 'This account is already active.'));
}
else if($model->activation_key && $model->activation_key == $activationKey) // The activation data checked out.
{
$model->scenario = 'activation';
$model->status = User::STATUS_ACTIVE;
$model->save();
// Notify the user that activation was sucessful.
return $this->render('message', [
'model' => $model,
'message' => Yii::t(__CLASS__, 'Your account is now active. Please log in to start using the service.'),
'type' => 'success'
]);
}
else if($model && (int)$model->status !== User::STATUS_ACTIVE && ($model->activation_key == $activationKey)) // The account has been disabled.
{
throw new \yii\web\ForbiddenHttpException(Yii::t(__CLASS__, 'This account is not active.'));
}
// The activation url was wrong.
throw new \yii\web\ForbiddenHttpException(Yii::t(__CLASS__, 'Incorrect activation URL.'));
}
/**
* This action is used to test the message view and is only available in debug mode.
* @param string $message the message to display.
* @param string $type the type of message to display
* */
public function actionMessage($message, $type = 'success')
{
if(!YII_DEBUG) // This action is only available in debug mode.
{
throw new \yii\web\NotFoundHttpException();
}
return $this->render('message', [
'message' => $message,
'type' => $type
]);
}
}
| {
"content_hash": "992e8391fc747c06d60abcd6c90c42fe",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 157,
"avg_line_length": 45.707317073170735,
"alnum_prop": 0.4610458911419424,
"repo_name": "Arza-Studio/yiingine",
"id": "08d46ae09693c74e5c94c479df01adaebc439351",
"size": "9550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/users/controllers/RegisterController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "48090"
},
{
"name": "JavaScript",
"bytes": "51133"
},
{
"name": "PHP",
"bytes": "1678948"
}
],
"symlink_target": ""
} |
<field synchronizeInterval="1000">
<connections>
<connection id="DUMMY" class="ch.hevs.jscada.io.field.dummy.DummyConnection"/>
</connections>
<inputs>
<input connectionRef="DUMMY" pointRef="aBooleanInput" type="BOOLEAN" id="aBoolean">
<wuff/>
</input>
<input connectionRef="DUMMY" pointRef="anIntegerInput" type="INTEGER" id="anInteger"/>
<input connectionRef="DUMMY" pointRef="aFloatInput" type="FLOATING_POINT" id="aFloat"/>
</inputs>
<outputs>
<output connectionRef="DUMMY" pointRef="aBooleanOutput" type="BOOLEAN" id="aBoolean"/>
<output connectionRef="DUMMY" pointRef="anIntegerOutput" type="INTEGER" id="anInteger"/>
<output connectionRef="DUMMY" pointRef="aFloatOutput" type="FLOATING_POINT" id="aFloat"/>
</outputs>
</field>
| {
"content_hash": "fd05fe559efb96cebb823a4ff69771a9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 97,
"avg_line_length": 41.85,
"alnum_prop": 0.6630824372759857,
"repo_name": "jSCADA/jscada-core",
"id": "5c9dfda20c9828190982d8a8b1b3ea36f48f4227",
"size": "837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/resources/configurations/xml/invalid-tag-in-input.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "194963"
}
],
"symlink_target": ""
} |
"""Context manager for Cloud Spanner batched writes."""
from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation
from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionOptions
# pylint: disable=ungrouped-imports
from google.cloud._helpers import _pb_timestamp_to_datetime
from google.cloud.spanner_v1._helpers import _SessionWrapper
from google.cloud.spanner_v1._helpers import _make_list_value_pbs
from google.cloud.spanner_v1._helpers import _metadata_with_prefix
# pylint: enable=ungrouped-imports
class _BatchBase(_SessionWrapper):
"""Accumulate mutations for transmission during :meth:`commit`.
:type session: :class:`~google.cloud.spanner_v1.session.Session`
:param session: the session used to perform the commit
"""
def __init__(self, session):
super(_BatchBase, self).__init__(session)
self._mutations = []
def _check_state(self):
"""Helper for :meth:`commit` et al.
Subclasses must override
:raises: :exc:`ValueError` if the object's state is invalid for making
API requests.
"""
raise NotImplementedError
def insert(self, table, columns, values):
"""Insert one or more new table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified.
"""
self._mutations.append(Mutation(insert=_make_write_pb(table, columns, values)))
def update(self, table, columns, values):
"""Update one or more existing table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified.
"""
self._mutations.append(Mutation(update=_make_write_pb(table, columns, values)))
def insert_or_update(self, table, columns, values):
"""Insert/update one or more table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified.
"""
self._mutations.append(
Mutation(insert_or_update=_make_write_pb(table, columns, values))
)
def replace(self, table, columns, values):
"""Replace one or more table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified.
"""
self._mutations.append(Mutation(replace=_make_write_pb(table, columns, values)))
def delete(self, table, keyset):
"""Delete one or more table rows.
:type table: str
:param table: Name of the table to be modified.
:type keyset: :class:`~google.cloud.spanner_v1.keyset.Keyset`
:param keyset: Keys/ranges identifying rows to delete.
"""
delete = Mutation.Delete(table=table, key_set=keyset._to_pb())
self._mutations.append(Mutation(delete=delete))
class Batch(_BatchBase):
"""Accumulate mutations for transmission during :meth:`commit`.
"""
committed = None
"""Timestamp at which the batch was successfully committed."""
def _check_state(self):
"""Helper for :meth:`commit` et al.
Subclasses must override
:raises: :exc:`ValueError` if the object's state is invalid for making
API requests.
"""
if self.committed is not None:
raise ValueError("Batch already committed")
def commit(self):
"""Commit mutations to the database.
:rtype: datetime
:returns: timestamp of the committed changes.
"""
self._check_state()
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
txn_options = TransactionOptions(read_write=TransactionOptions.ReadWrite())
response = api.commit(
self._session.name,
mutations=self._mutations,
single_use_transaction=txn_options,
metadata=metadata,
)
self.committed = _pb_timestamp_to_datetime(response.commit_timestamp)
return self.committed
def __enter__(self):
"""Begin ``with`` block."""
self._check_state()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""End ``with`` block."""
if exc_type is None:
self.commit()
def _make_write_pb(table, columns, values):
"""Helper for :meth:`Batch.insert` et aliae.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified.
:rtype: :class:`google.cloud.spanner_v1.proto.mutation_pb2.Mutation.Write`
:returns: Write protobuf
"""
return Mutation.Write(
table=table, columns=columns, values=_make_list_value_pbs(values)
)
| {
"content_hash": "1408c02824a74669655d236dee986f0b",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 88,
"avg_line_length": 31.632183908045977,
"alnum_prop": 0.6320857558139535,
"repo_name": "tswast/google-cloud-python",
"id": "e62763d7fd7c965fabe531ddbe60ed4f5a5bd0e4",
"size": "6100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spanner/google/cloud/spanner_v1/batch.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1094"
},
{
"name": "Python",
"bytes": "33785371"
},
{
"name": "Shell",
"bytes": "9148"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@color/primary_text_disabled_material_light"/>
<item android:color="@color/primary_text_default_material_light"/>
</selector>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-dev/frameworks/support/v7/appcompat/res/color/abc_primary_text_material_light.xml --><!-- From: file:/Users/wyao/demoSrc/SyncedListView/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.0.0/res/color/abc_primary_text_material_light.xml --> | {
"content_hash": "73a958f76419425e22f952a747213f4d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 394,
"avg_line_length": 63.04761904761905,
"alnum_prop": 0.7439577039274925,
"repo_name": "wenhuiyao/SyncedListView",
"id": "f455804cfb7ed6f13c6ca654801bc46a398d46f9",
"size": "1324",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/build/intermediates/res/debug/color/abc_primary_text_material_light.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "438507"
}
],
"symlink_target": ""
} |
package org.codehaus.httpcache4j.payload;
import org.codehaus.httpcache4j.uri.QueryParam;
import org.junit.Test;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:hamnis@codehaus.org">Erlend Hamnaberg</a>
* @version $Revision: $
*/
public class FormDataPayloadTest {
static final String newline = "%0D%0A";
@Test
public void testSimpleFormPayload() {
List<QueryParam> parameters = new ArrayList<>();
parameters.add(new QueryParam("foo", "bar"));
parameters.add(new QueryParam("bar", "foo"));
FormDataPayload payload = new FormDataPayload(parameters);
Assert.assertEquals("foo=bar&bar=foo",payload.getValue());
}
@Test
public void testEscapedList() {
List<QueryParam> parameters = new ArrayList<>();
parameters.add(new QueryParam("selected song", "hey jude"));
parameters.add(new QueryParam("bar", "foo"));
FormDataPayload payload = new FormDataPayload(parameters);
Assert.assertEquals("selected+song=hey+jude&bar=foo",payload.getValue());
}
@Test
public void testEscapedWithNewLines() {
List<QueryParam> parameters = new ArrayList<>();
parameters.add(new QueryParam("lyrics", "Hello!\r\nIs there anybody out there?\r\nIs there anyone at home"));
parameters.add(new QueryParam("bar", "foo"));
FormDataPayload payload = new FormDataPayload(parameters);
Assert.assertEquals("lyrics=Hello%21"+ newline + "Is+there+anybody+out+there%3F"+ newline +"Is+there+anyone+at+home&bar=foo", payload.getValue());
}
}
| {
"content_hash": "ac424cd90206b2c96e201ae03905f163",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 154,
"avg_line_length": 36.2,
"alnum_prop": 0.6783302639656231,
"repo_name": "httpcache4j/httpcache4j",
"id": "c7668d912b468bb82d215f0463b67440795e70ec",
"size": "2262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "httpcache4j-api/src/test/java/org/codehaus/httpcache4j/payload/FormDataPayloadTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "16659"
},
{
"name": "Java",
"bytes": "382078"
}
],
"symlink_target": ""
} |
export * from './build';
export * from './deployer';
export * from './modelVisitor';
export * from './coreBuildPlugin';
export * from './coreRuntime';
export * from './typescriptTranslate';
| {
"content_hash": "7d90212ef891e558a241be9cd90f3275",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 38,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.6842105263157895,
"repo_name": "christyharagan/markscript",
"id": "ac9e90c7b29d6cd900d60d68ec6dd6f71126c3ed",
"size": "190",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "57427"
},
{
"name": "TypeScript",
"bytes": "56500"
}
],
"symlink_target": ""
} |
<?php
namespace
{
// note: this will crash if loaded in PHP, as the Traversable interface is already in core
interface Traversable {}
}
namespace BetterReflectionTest\ClassesImplementingIterators
{
class TraversableImplementation implements \Traversable
{
}
class NonTraversableImplementation
{
}
abstract class AbstractTraversableImplementation implements \Traversable
{
}
interface TraversableExtension extends \Traversable
{
}
}
| {
"content_hash": "6f7c0e69a56d30579979deb00fdd061c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 94,
"avg_line_length": 18.96153846153846,
"alnum_prop": 0.7241379310344828,
"repo_name": "digitalkaoz/BetterReflection",
"id": "a0d85c5f638e55b6c859ef27ab4bda2a9fc7db19",
"size": "493",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/unit/Fixture/ClassesImplementingIterators.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "726822"
},
{
"name": "Shell",
"bytes": "66"
}
],
"symlink_target": ""
} |
package eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
/**
* A manager class for the highlighting of occurrences and brackets.
*/
public class HyvalidityformulaHighlighting implements ISelectionProvider, ISelectionChangedListener {
private final static eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPositionHelper positionHelper = new eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPositionHelper();
private List<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
private ISelection selection = null;
private boolean isHighlightBrackets = true;
private eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaColorManager colorManager;
private Color bracketColor;
private Color black;
private StyledText textWidget;
private IPreferenceStore preferenceStore;
private eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaEditor editor;
private ProjectionViewer projectionViewer;
private eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaOccurrence occurrence;
private eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaBracketSet bracketSet;
private Display display;
/**
* A key and mouse listener for the highlighting. It removes the highlighting
* before documents change. No highlighting is set after document changes to
* increase the performance. Occurrences are not searched if the caret is still in
* the same token to increase the performance.
*/
private final class UpdateHighlightingListener implements KeyListener, VerifyListener, MouseListener, eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaBackgroundParsingListener {
private boolean changed = false;
private int caret = -1;
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (changed) {
changed = false;
return;
}
refreshHighlighting();
}
private void refreshHighlighting() {
if (textWidget.isDisposed()) {
return;
}
int textCaret = textWidget.getCaretOffset();
if (textCaret < 0 || textCaret > textWidget.getCharCount()) {
return;
}
if (textCaret != caret) {
caret = textCaret;
removeHighlighting();
setHighlighting();
updateEObjectSelection();
}
}
public void verifyText(VerifyEvent e) {
occurrence.resetTokenRegion();
removeHighlighting();
changed = true;
}
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
}
// 1-left click, 2-middle click,
public void mouseUp(MouseEvent e) {
// 3-right click
if (e.button != 1) {
return;
}
refreshHighlighting();
}
public void parsingCompleted(Resource resource) {
display.asyncExec(new Runnable() {
public void run() {
refreshHighlighting();
}
});
}
}
/**
* <p>
* Creates the highlighting manager class.
* </p>
*
* @param textResource the text resource to be provided to other classes
* @param sourceviewer the source viewer converts offset between master and slave
* documents
* @param colorManager the color manager provides highlighting colors
* @param editor the editor that uses this highlighting object
*/
public HyvalidityformulaHighlighting(eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaTextResource textResource, ProjectionViewer projectionViewer, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaColorManager colorManager, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaEditor editor) {
this.display = Display.getCurrent();
projectionViewer.getSelectionProvider();
this.preferenceStore = eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaUIPlugin.getDefault().getPreferenceStore();
this.editor = editor;
this.textWidget = projectionViewer.getTextWidget();
this.projectionViewer = projectionViewer;
this.occurrence = new eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaOccurrence(textResource, projectionViewer);
this.bracketSet = new eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaBracketSet();
this.colorManager = colorManager;
this.isHighlightBrackets = preferenceStore.getBoolean(eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPreferenceConstants.EDITOR_MATCHING_BRACKETS_CHECKBOX);
this.bracketColor = colorManager.getColor(PreferenceConverter.getColor(preferenceStore, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR));
this.black = colorManager.getColor(new RGB(0, 0, 0));
addListeners(editor);
}
private void addListeners(eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaEditor editor) {
UpdateHighlightingListener hl = new UpdateHighlightingListener();
textWidget.addKeyListener(hl);
textWidget.addVerifyListener(hl);
textWidget.addMouseListener(hl);
editor.addBackgroundParsingListener(hl);
}
private void setHighlighting() {
IDocument document = projectionViewer.getDocument();
if (isHighlightBrackets) {
int offset = bracketSet.getCaretOffset((ISourceViewer) editor.getViewer(), textWidget);
bracketSet.findAndHighlightMatchingBrackets(document, offset);
}
occurrence.updateOccurrenceAnnotations();
setBracketHighlighting(document);
}
private void setBracketHighlighting(IDocument document) {
StyleRange styleRange = null;
Position[] positions = positionHelper.getPositions(document, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPositionCategory.BRACKET.toString());
for (Position position : positions) {
Position tmpPosition = convertToWidgetPosition(position);
if (tmpPosition != null) {
styleRange = getStyleRangeAtPosition(tmpPosition);
styleRange.borderStyle = SWT.BORDER_SOLID;
styleRange.borderColor = bracketColor;
if (styleRange.foreground == null) {
styleRange.foreground = black;
}
textWidget.setStyleRange(styleRange);
}
}
}
private void removeHighlighting() {
IDocument document = projectionViewer.getDocument();
// remove highlighted matching brackets
removeHighlightingCategory(document, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPositionCategory.BRACKET.toString());
}
private void removeHighlightingCategory(IDocument document, String category) {
Position[] positions = positionHelper.getPositions(document, category);
if (category.equals(eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPositionCategory.BRACKET.toString())) {
StyleRange styleRange;
for (Position position : positions) {
Position tmpPosition = convertToWidgetPosition(position);
if (tmpPosition != null) {
styleRange = getStyleRangeAtPosition(tmpPosition);
styleRange.borderStyle = SWT.NONE;
styleRange.borderColor = null;
styleRange.background = null;
textWidget.setStyleRange(styleRange);
}
}
}
positionHelper.removePositions(document, category);
}
/**
* Updates the currently selected EObject and notifies registered selection
* listeners (e.g., the outline page) about this asynchronously.
*/
public void updateEObjectSelection() {
display.asyncExec(new Runnable() {
public void run() {
EObject selectedEObject = occurrence.getEObjectAtCurrentPosition();
if (selectedEObject != null) {
setSelection(new eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaEObjectSelection(selectedEObject));
}
}
});
}
/**
* Resets the changed values after setting the preference pages.
*/
public void resetValues() {
isHighlightBrackets = preferenceStore.getBoolean(eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPreferenceConstants.EDITOR_MATCHING_BRACKETS_CHECKBOX);
bracketColor = colorManager.getColor(PreferenceConverter.getColor(preferenceStore, eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui.HyvalidityformulaPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR));
bracketSet.resetBrackets(preferenceStore);
}
private Position convertToWidgetPosition(Position position) {
if (position == null) {
return null;
}
int startOffset = projectionViewer.modelOffset2WidgetOffset(position.offset);
int endOffset = projectionViewer.modelOffset2WidgetOffset(position.offset + position.length);
if (endOffset - startOffset != position.length || startOffset == -1 || textWidget.getCharCount() < endOffset) {
return null;
}
return new Position(startOffset, endOffset - startOffset);
}
private StyleRange getStyleRangeAtPosition(Position position) {
StyleRange styleRange = null;
try {
styleRange = textWidget.getStyleRangeAtOffset(position.offset);
} catch (IllegalArgumentException iae) {
}
if (styleRange == null) {
styleRange = new StyleRange(position.offset, position.length, black, null);
} else {
styleRange.length = position.length;
}
return styleRange;
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* Updates the current selection and notifies registered selection listeners
* (e.g., the outline page) about this.
*/
public void setSelection(ISelection selection) {
this.selection = selection;
SelectionChangedEvent event = new SelectionChangedEvent(this, selection);
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(event);
}
}
public ISelection getSelection() {
return selection;
}
/**
* This method is called by the outline page if its selection was changed. This is
* accomplished by adding this class as selection change listener to the outline
* page, which is performed by the editor.
*/
public void selectionChanged(SelectionChangedEvent event) {
if (event.getSelection() instanceof TreeSelection) {
handleContentOutlineSelection(event.getSelection());
}
}
/**
* Notifies the editor that the selection in the outline page has changed. This
* method assumes that the origin of the selection is the outline page or its tree
* viewer.
*/
private void handleContentOutlineSelection(ISelection selection) {
if (selection.isEmpty()) {
// Ignore empty selections
return;
}
editor.setSelection(selection);
}
}
| {
"content_hash": "12e035e9d05d9e9f87635b8645ff2a9d",
"timestamp": "",
"source": "github",
"line_count": 308,
"max_line_length": 381,
"avg_line_length": 39.061688311688314,
"alnum_prop": 0.7832266644501704,
"repo_name": "DarwinSPL/DarwinSPL",
"id": "99a6aa0e07ecefea2c2f822905c45ab348cca021",
"size": "12076",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/eu.hyvar.context.contextValidity.resource.hyvalidityformula.ui/src-gen/eu/hyvar/context/contextValidity/resource/hyvalidityformula/ui/HyvalidityformulaHighlighting.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "18119"
},
{
"name": "CSS",
"bytes": "367911"
},
{
"name": "FreeMarker",
"bytes": "13035"
},
{
"name": "GAP",
"bytes": "1672492"
},
{
"name": "Gherkin",
"bytes": "987"
},
{
"name": "Java",
"bytes": "78282002"
},
{
"name": "JavaScript",
"bytes": "145859"
},
{
"name": "Smalltalk",
"bytes": "1783"
}
],
"symlink_target": ""
} |
import Mirage from 'ember-cli-mirage';
export default Mirage.Factory.extend({
startYear: (i) => 2012 + i,
program: (i) => (i+1),
published: true,
publishedAsTbd: false,
cohort: (i) => (i+1),
archived: false,
});
| {
"content_hash": "64ec92a206c3199a6e2282c99e3c63c7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 38,
"avg_line_length": 22.5,
"alnum_prop": 0.6266666666666667,
"repo_name": "gboushey/frontend",
"id": "0f1c5424c57eedb5b069838589658d17701f5fa9",
"size": "225",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/mirage/factories/programYear.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "124203"
},
{
"name": "HTML",
"bytes": "400486"
},
{
"name": "JavaScript",
"bytes": "1855666"
}
],
"symlink_target": ""
} |
package liquibase.util;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
public class SqlUtil {
public static boolean isNumeric(int dataType) {
List<Integer> numericTypes = Arrays.asList(
Types.BIGINT,
Types.BIT,
Types.INTEGER,
Types.SMALLINT,
Types.TINYINT,
Types.DECIMAL,
Types.DOUBLE,
Types.FLOAT,
Types.NUMERIC,
Types.REAL
);
return numericTypes.contains(dataType);
}
public static boolean isBoolean(int dataType) {
return dataType == Types.BOOLEAN;
}
public static boolean isDate(int dataType) {
List<Integer> validTypes = Arrays.asList(
Types.DATE,
Types.TIME,
Types.TIMESTAMP
);
return validTypes.contains(dataType);
}
}
| {
"content_hash": "16fa0b889d8988905eb6d437767d6e71",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 51,
"avg_line_length": 25.23076923076923,
"alnum_prop": 0.5182926829268293,
"repo_name": "liquibase/BACKUP_FROM_SVN",
"id": "9afb52126be77a68d0332057e7bf964b617aef1f",
"size": "984",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "liquibase-core/src/main/java/liquibase/util/SqlUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "20589"
},
{
"name": "Java",
"bytes": "2519208"
},
{
"name": "Shell",
"bytes": "1720"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="corner_radius">8dp</dimen>
<dimen name="tab_space_top">4dp</dimen>
<dimen name="tab_space">0dp</dimen>
<dimen name="tab_space_plus1">3dp</dimen>
<dimen name="tab_space_bottom_line">36sp</dimen>
<dimen name="tab_space_unselected_top">6sp</dimen>
</resources> | {
"content_hash": "da16e2a300c02fe7c2b8a66ee1377a1f",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 55,
"avg_line_length": 38.77777777777778,
"alnum_prop": 0.6532951289398281,
"repo_name": "cpcs499/Presentation-2",
"id": "bc15100a41c1c46edaad8563c00141095d1a88a3",
"size": "349",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "res/values/dimensions.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7506"
},
{
"name": "HTML",
"bytes": "2417458"
},
{
"name": "Java",
"bytes": "550914"
}
],
"symlink_target": ""
} |
import paddle.static as static
from .meta_optimizer_base import MetaOptimizerBase
from .common import (
CollectiveHelper,
OP_ROLE_KEY,
OP_ROLE_VAR_KEY,
OpRole,
is_backward_op,
is_loss_grad_op,
is_optimizer_op,
)
__all__ = []
class TensorParallelOptimizer(MetaOptimizerBase):
def __init__(self, optimizer):
super().__init__(optimizer)
self.inner_opt = optimizer
self.meta_optimizers_white_list = [
"RecomputeOptimizer",
"AMPOptimizer",
"LarsOptimizer",
"LambOptimizer",
]
self.meta_optimizers_black_list = [
"GraphExecutionOptimizer",
]
self.mp_ring_id = 0
self.global_ring_id = 1
self.dp_ring_id = 2
def _set_basic_info(
self, loss, role_maker, user_defined_optimizer, user_defined_strategy
):
super()._set_basic_info(
loss, role_maker, user_defined_optimizer, user_defined_strategy
)
self.mp_degree = user_defined_strategy.tensor_parallel_configs[
'tensor_parallel_degree'
]
def _can_apply(self):
if not self.role_maker._is_collective:
return False
if self.user_defined_strategy.tensor_parallel:
return True
return False
def _disable_strategy(self, dist_strategy):
dist_strategy.tensor_parallel = False
dist_strategy.tensor_parallel_configs = {}
def _enable_strategy(self, dist_strategy, context):
dist_strategy.tensor_parallel = True
dist_strategy.tensor_parallel_configs = {
"tensor_parallel_degree": 1,
}
def _broadcast_params(self, ring_id, mp_mode):
block = self.startup_program.global_block()
param = None
for param in block.iter_parameters():
if param.is_distributed and mp_mode:
continue
block.append_op(
type='c_broadcast',
inputs={'X': param},
outputs={'Out': param},
attrs={
'ring_id': ring_id,
'root': 0,
OP_ROLE_KEY: OpRole.Forward,
},
)
if not param:
return # no parameter on this device
block.append_op(
type='c_sync_comm_stream',
inputs={'X': param},
outputs={'Out': param},
attrs={'ring_id': ring_id, OP_ROLE_KEY: OpRole.Forward},
)
def _get_process_group_info(self):
# global ring info
self.global_endpoints = self.endpoints
self.global_rank = self.rank
self.global_nranks = self.nranks
# model parallel ring info
self.mp_rank = self.rank % self.mp_degree
self.mp_nranks = self.mp_degree
mp_group = self.rank // self.mp_degree
self.mp_endpoints = [
self.endpoints[i]
for i in range(self.global_nranks)
if i // self.mp_degree == mp_group
]
# data parallel ring info
if self.nranks > self.mp_degree:
self.dp_rank = self.rank // self.mp_degree
self.dp_nranks = self.nranks // self.mp_degree
start_index = self.rank % self.mp_degree
self.dp_endpoints = [
self.endpoints[start_index + i * self.mp_degree]
for i in range(self.dp_nranks)
]
def _init_process_group(self):
self._get_process_group_info()
collective_helper = CollectiveHelper(self.role_maker, wait_port=False)
# Create global ring for all gpus
collective_helper._init_communicator(
self.startup_program,
self.current_endpoint,
self.global_endpoints,
self.global_rank,
self.global_ring_id,
True,
self.global_ring_id,
True,
)
# Create model parallel ring for all gpus
collective_helper._init_communicator(
self.startup_program,
self.current_endpoint,
self.mp_endpoints,
self.mp_rank,
self.mp_ring_id,
True,
self.global_ring_id,
True,
)
self._broadcast_params(self.mp_ring_id, mp_mode=True)
# Create dp rings
if self.nranks > self.mp_degree:
collective_helper._init_communicator(
self.startup_program,
self.current_endpoint,
self.dp_endpoints,
self.dp_rank,
self.dp_ring_id,
True,
self.global_ring_id,
True,
)
self._broadcast_params(self.dp_ring_id, mp_mode=False)
def minimize_impl(
self, loss, startup_program=None, parameter_list=None, no_grad_set=None
):
self.endpoints = self.role_maker._get_trainer_endpoints()
self.current_endpoint = self.endpoints[self.role_maker._worker_index()]
self.startup_program = startup_program
if startup_program is None:
self.startup_program = static.default_startup_program()
optimize_ops, params_grads = self.inner_opt.minimize(
loss, self.startup_program, parameter_list, no_grad_set
)
self.main_program = loss.block.program
self.nranks = len(self.endpoints)
self.rank = self.role_maker._worker_index()
self._init_process_group()
assert self.nranks % self.mp_degree == 0
if self.nranks > self.mp_degree:
# data parallelism
dp_degree = self.nranks // self.mp_degree
self._transpile_main_program(loss, dp_degree)
return optimize_ops, params_grads
def _transpile_main_program(self, loss, dp_degree):
self._insert_loss_grad_ops(loss, dp_degree)
self._insert_allreduce_ops(loss, self.dp_ring_id)
def _insert_loss_grad_ops(self, loss, dp_degree):
"""
In order to keep the learning rate consistent in different numbers of
training workers, we scale the loss grad by the number of workers
"""
block = loss.block
for idx, op in reversed(list(enumerate(block.ops))):
if is_loss_grad_op(op):
loss_grad_var = block.vars[op.output_arg_names[0]]
block._insert_op(
idx + 1,
type='scale',
inputs={'X': loss_grad_var},
outputs={'Out': loss_grad_var},
attrs={
'scale': 1.0 / dp_degree,
OP_ROLE_KEY: OpRole.Backward,
},
)
break
def _insert_allreduce_ops(self, loss, ring_id):
block = loss.block
grad = None
for idx, op in reversed(list(enumerate(block.ops))):
if is_backward_op(op) and OP_ROLE_VAR_KEY in op.attr_names:
op_role_var = op.attr(OP_ROLE_VAR_KEY)
if len(op_role_var) == 0:
continue
assert len(op_role_var) % 2 == 0
offset = idx
for i in range(0, len(op_role_var), 2):
param = block.vars[op_role_var[i]]
grad = block.vars[op_role_var[i + 1]]
if offset == idx:
offset += 1
block._insert_op(
offset,
type='c_sync_calc_stream',
inputs={'X': grad},
outputs={'Out': grad},
attrs={OP_ROLE_KEY: OpRole.Backward},
)
offset += 1
block._insert_op(
offset,
type='c_allreduce_sum',
inputs={'X': grad},
outputs={'Out': grad},
attrs={
'ring_id': ring_id,
OP_ROLE_KEY: OpRole.Backward,
},
)
if grad is None:
return
for idx, op in list(enumerate(block.ops)):
if is_optimizer_op(op):
block._insert_op(
idx,
type='c_sync_comm_stream',
inputs={'X': grad},
outputs={'Out': grad},
attrs={'ring_id': ring_id, OP_ROLE_KEY: OpRole.Backward},
)
break
| {
"content_hash": "03666e5c211379fd48152ef3e12bf752",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 79,
"avg_line_length": 33.77734375,
"alnum_prop": 0.5039898230600208,
"repo_name": "PaddlePaddle/Paddle",
"id": "41ef5f6190ebf9d36616e55132110355137c046b",
"size": "9227",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "python/paddle/distributed/fleet/meta_optimizers/tensor_parallel_optimizer.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "58544"
},
{
"name": "C",
"bytes": "210300"
},
{
"name": "C++",
"bytes": "36848680"
},
{
"name": "CMake",
"bytes": "902619"
},
{
"name": "Cuda",
"bytes": "5227207"
},
{
"name": "Dockerfile",
"bytes": "4361"
},
{
"name": "Go",
"bytes": "49796"
},
{
"name": "Java",
"bytes": "16630"
},
{
"name": "Jinja",
"bytes": "23852"
},
{
"name": "MLIR",
"bytes": "39982"
},
{
"name": "Python",
"bytes": "36203874"
},
{
"name": "R",
"bytes": "1332"
},
{
"name": "Shell",
"bytes": "553177"
}
],
"symlink_target": ""
} |
package org.springframework.boot.autoconfigure.flyway;
import java.sql.Connection;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.callback.FlywayCallback;
import org.flywaydb.core.internal.callback.SqlScriptFlywayCallback;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.InOrder;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.MapPropertySource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link FlywayAutoConfiguration}.
*
* @author Dave Syer
* @author Phillip Webb
* @author Andy Wilkinson
* @author Vedran Pavic
* @author Eddú Meléndez
*/
public class FlywayAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@Before
public void init() {
TestPropertyValues.of(
"spring.datasource.name:flywaytest").applyTo(this.context);
}
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void noDataSource() throws Exception {
registerAndRefresh(FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
assertThat(this.context.getBeanNamesForType(Flyway.class).length).isEqualTo(0);
}
@Test
public void createDataSource() throws Exception {
TestPropertyValues.of(
"flyway.url:jdbc:hsqldb:mem:flywaytest", "flyway.user:sa").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getDataSource()).isNotNull();
}
@Test
public void flywayDataSource() throws Exception {
registerAndRefresh(FlywayDataSourceConfiguration.class,
EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getDataSource())
.isEqualTo(this.context.getBean("flywayDataSource"));
}
@Test
public void defaultFlyway() throws Exception {
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactly("classpath:db/migration");
}
@Test
public void overrideLocations() throws Exception {
TestPropertyValues.of(
"flyway.locations:classpath:db/changelog,classpath:db/migration").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog",
"classpath:db/migration");
}
@Test
public void overrideLocationsList() throws Exception {
TestPropertyValues.of(
"flyway.locations[0]:classpath:db/changelog",
"flyway.locations[1]:classpath:db/migration").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog",
"classpath:db/migration");
}
@Test
public void overrideSchemas() throws Exception {
TestPropertyValues.of("flyway.schemas:public").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(Arrays.asList(flyway.getSchemas()).toString()).isEqualTo("[public]");
}
@Test
public void changeLogDoesNotExist() throws Exception {
TestPropertyValues.of(
"flyway.locations:file:no-such-dir").applyTo(this.context);
this.thrown.expect(BeanCreationException.class);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
}
@Test
public void checkLocationsAllMissing() throws Exception {
TestPropertyValues.of(
"flyway.locations:classpath:db/missing1,classpath:db/migration2",
"flyway.check-location:true").applyTo(this.context);
this.thrown.expect(BeanCreationException.class);
this.thrown.expectMessage("Cannot find migrations location in");
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
}
@Test
public void checkLocationsAllExist() throws Exception {
TestPropertyValues.of(
"flyway.locations:classpath:db/changelog,classpath:db/migration",
"flyway.check-location:true").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
}
@Test
public void customFlywayMigrationStrategy() throws Exception {
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
MockFlywayMigrationStrategy.class);
assertThat(this.context.getBean(Flyway.class)).isNotNull();
this.context.getBean(MockFlywayMigrationStrategy.class).assertCalled();
}
@Test
public void customFlywayMigrationInitializer() throws Exception {
registerAndRefresh(CustomFlywayMigrationInitializer.class,
EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
assertThat(this.context.getBean(Flyway.class)).isNotNull();
FlywayMigrationInitializer initializer = this.context
.getBean(FlywayMigrationInitializer.class);
assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE);
}
@Test
public void customFlywayWithJpa() throws Exception {
registerAndRefresh(CustomFlywayWithJpaConfiguration.class,
EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
}
@Test
public void overrideBaselineVersionString() throws Exception {
TestPropertyValues.of("flyway.baseline-version=0").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getBaselineVersion())
.isEqualTo(MigrationVersion.fromVersion("0"));
}
@Test
public void overrideBaselineVersionNumber() throws Exception {
Map<String, Object> source = Collections
.<String, Object>singletonMap("flyway.baseline-version", 1);
this.context.getEnvironment().getPropertySources()
.addLast(new MapPropertySource("flyway", source));
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getBaselineVersion())
.isEqualTo(MigrationVersion.fromVersion("1"));
}
@Test
public void useVendorDirectory() throws Exception {
TestPropertyValues.of(
"flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog").applyTo(this.context);
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
Flyway flyway = this.context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactlyInAnyOrder(
"classpath:db/vendors/h2", "classpath:db/changelog");
}
@Test
public void callbacksAreConfiguredAndOrdered() throws Exception {
registerAndRefresh(EmbeddedDataSourceConfiguration.class,
FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
CallbackConfiguration.class);
assertThat(this.context.getBeansOfType(Flyway.class)).hasSize(1);
Flyway flyway = this.context.getBean(Flyway.class);
FlywayCallback callbackOne = this.context.getBean("callbackOne",
FlywayCallback.class);
FlywayCallback callbackTwo = this.context.getBean("callbackTwo",
FlywayCallback.class);
assertThat(flyway.getCallbacks()).hasSize(3);
assertThat(flyway.getCallbacks()).startsWith(callbackTwo, callbackOne);
assertThat(flyway.getCallbacks()[2]).isInstanceOf(SqlScriptFlywayCallback.class);
InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo);
orderedCallbacks.verify(callbackTwo).beforeMigrate(any(Connection.class));
orderedCallbacks.verify(callbackOne).beforeMigrate(any(Connection.class));
}
private void registerAndRefresh(Class<?>... annotatedClasses) {
this.context.register(annotatedClasses);
this.context.refresh();
}
@Configuration
protected static class FlywayDataSourceConfiguration {
@Bean
@Primary
public DataSource normalDataSource() {
return DataSourceBuilder.create().url("jdbc:hsqldb:mem:normal").username("sa")
.build();
}
@FlywayDataSource
@Bean
public DataSource flywayDataSource() {
return DataSourceBuilder.create().url("jdbc:hsqldb:mem:flywaytest")
.username("sa").build();
}
}
@Configuration
protected static class CustomFlywayMigrationInitializer {
@Bean
public FlywayMigrationInitializer flywayMigrationInitializer(Flyway flyway) {
FlywayMigrationInitializer initializer = new FlywayMigrationInitializer(
flyway);
initializer.setOrder(Ordered.HIGHEST_PRECEDENCE);
return initializer;
}
}
@Configuration
protected static class CustomFlywayWithJpaConfiguration {
private final DataSource dataSource;
protected CustomFlywayWithJpaConfiguration(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public Flyway flyway() {
return new Flyway();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
Map<String, Object> properties = new HashMap<>();
properties.put("configured", "manually");
properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE);
return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(),
properties, null).dataSource(this.dataSource).build();
}
}
@Component
protected static class MockFlywayMigrationStrategy
implements FlywayMigrationStrategy {
private boolean called = false;
@Override
public void migrate(Flyway flyway) {
this.called = true;
}
public void assertCalled() {
assertThat(this.called).isTrue();
}
}
@Configuration
static class CallbackConfiguration {
@Bean
@Order(1)
public FlywayCallback callbackOne() {
return mock(FlywayCallback.class);
}
@Bean
@Order(0)
public FlywayCallback callbackTwo() {
return mock(FlywayCallback.class);
}
}
}
| {
"content_hash": "0708ae48f8ef6047c863ae10e37c6fc0",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 99,
"avg_line_length": 34.30362116991643,
"alnum_prop": 0.7952902963865205,
"repo_name": "shangyi0102/spring-boot",
"id": "6ab718e627c4cd91514e9237a84a3cd253caa12b",
"size": "12937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6954"
},
{
"name": "CSS",
"bytes": "5769"
},
{
"name": "FreeMarker",
"bytes": "2134"
},
{
"name": "Groovy",
"bytes": "49495"
},
{
"name": "HTML",
"bytes": "69695"
},
{
"name": "Java",
"bytes": "11388701"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1307"
},
{
"name": "Shell",
"bytes": "27916"
},
{
"name": "Smarty",
"bytes": "3276"
},
{
"name": "XSLT",
"bytes": "34105"
}
],
"symlink_target": ""
} |
package features
import (
"github.com/eriq-augustine/goml/base"
)
// A ManualReducer is initialized with the columns to choose.
// This should mainly be used for testing.
type ManualReducer struct{
features []int
}
func NewManualReducer(selectedFeatures []int) ManualReducer {
if (selectedFeatures == nil) {
selectedFeatures = make([]int, 0);
}
return ManualReducer{selectedFeatures};
}
func (this ManualReducer) Init(tuples []base.Tuple) {}
func (this ManualReducer) Reduce(tuples []base.Tuple) []base.Tuple {
return SelectFeatures(tuples, this.features);
}
func (this ManualReducer) GetFeatures() []int {
return append([]int(nil), this.features...);
}
| {
"content_hash": "f4b488ea71e45cb9e37b239f1fe5e65b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 68,
"avg_line_length": 23.724137931034484,
"alnum_prop": 0.7151162790697675,
"repo_name": "eriq-augustine/goml",
"id": "9cd49eccf3bc3ac5635d25e5ab44ed5ff2a513dc",
"size": "688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "features/manualReducer.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "109937"
}
],
"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_102) on Thu Sep 29 16:37:39 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class energy.usef.agr.model.UdiEventType (usef-root-pom 1.3.6 API)</title>
<meta name="date" content="2016-09-29">
<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="Uses of Class energy.usef.agr.model.UdiEventType (usef-root-pom 1.3.6 API)";
}
}
catch(err) {
}
//-->
</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><a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?energy/usef/agr/model/class-use/UdiEventType.html" target="_top">Frames</a></li>
<li><a href="UdiEventType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class energy.usef.agr.model.UdiEventType" class="title">Uses of Class<br>energy.usef.agr.model.UdiEventType</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#energy.usef.agr.model">energy.usef.agr.model</a></td>
<td class="colLast">
<div class="block">Model classes of the Aggregator.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#energy.usef.agr.transformer">energy.usef.agr.transformer</a></td>
<td class="colLast">
<div class="block">Package contains helper classes to transform between our Model and the DTO's</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="energy.usef.agr.model">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a> in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a> that return <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></code></td>
<td class="colLast"><span class="typeNameLabel">UdiEvent.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/UdiEvent.html#getUdiEventType--">getUdiEventType</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></code></td>
<td class="colLast"><span class="typeNameLabel">UdiEventType.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/UdiEventType.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">UdiEventType.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/UdiEventType.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../energy/usef/agr/model/package-summary.html">energy.usef.agr.model</a> with parameters of type <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">UdiEvent.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/model/UdiEvent.html#setUdiEventType-energy.usef.agr.model.UdiEventType-">setUdiEventType</a></span>(<a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a> udiEventType)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="energy.usef.agr.transformer">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a> in <a href="../../../../../energy/usef/agr/transformer/package-summary.html">energy.usef.agr.transformer</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../energy/usef/agr/transformer/package-summary.html">energy.usef.agr.transformer</a> that return <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></code></td>
<td class="colLast"><span class="typeNameLabel">UdiEventTransformer.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/transformer/UdiEventTransformer.html#transformToModel-energy.usef.agr.dto.device.capability.UdiEventTypeDto-">transformToModel</a></span>(<a href="../../../../../energy/usef/agr/dto/device/capability/UdiEventTypeDto.html" title="enum in energy.usef.agr.dto.device.capability">UdiEventTypeDto</a> udiEventTypeDto)</code>
<div class="block">Transforms a UdiEventTypeDto to its related model format.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../energy/usef/agr/transformer/package-summary.html">energy.usef.agr.transformer</a> with parameters of type <a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../energy/usef/agr/dto/device/capability/UdiEventTypeDto.html" title="enum in energy.usef.agr.dto.device.capability">UdiEventTypeDto</a></code></td>
<td class="colLast"><span class="typeNameLabel">UdiEventTransformer.</span><code><span class="memberNameLink"><a href="../../../../../energy/usef/agr/transformer/UdiEventTransformer.html#transformToDto-energy.usef.agr.model.UdiEventType-">transformToDto</a></span>(<a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">UdiEventType</a> udiEventType)</code>
<div class="block">Transforms a UdiEventType to its related DTO format.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= 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><a href="../../../../../energy/usef/agr/model/UdiEventType.html" title="enum in energy.usef.agr.model">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?energy/usef/agr/model/class-use/UdiEventType.html" target="_top">Frames</a></li>
<li><a href="UdiEventType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "8ed25c6f06f1b5f92aac5e740bb941fa",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 474,
"avg_line_length": 52.46808510638298,
"alnum_prop": 0.6516626115166261,
"repo_name": "FHPproject/FHPUsef",
"id": "ffaea9f5f4bf6e349db7af4942e8d507cc93423a",
"size": "12330",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "usef-javadoc/energy/usef/agr/model/class-use/UdiEventType.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25252"
},
{
"name": "CSS",
"bytes": "13416"
},
{
"name": "HTML",
"bytes": "33111187"
},
{
"name": "Java",
"bytes": "6924158"
},
{
"name": "JavaScript",
"bytes": "857"
},
{
"name": "PowerShell",
"bytes": "6025"
},
{
"name": "Shell",
"bytes": "18804"
},
{
"name": "TSQL",
"bytes": "407953"
}
],
"symlink_target": ""
} |
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.2</a>, using an XML
* Schema.
* $Id: ConfigurationOpDescriptor.java,v 1.2 2009/05/20 05:29:14 cvsuser3 Exp $
*/
package org.morozko.java.mod.dbsrc.config.xml.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.morozko.java.mod.dbsrc.config.xml.ConfigurationOp;
/**
* Class ConfigurationOpDescriptor.
*
* @version $Revision: 1.2 $ $Date: 2009/05/20 05:29:14 $
*/
public class ConfigurationOpDescriptor extends org.morozko.java.mod.dbsrc.config.xml.descriptors.ConfigurationTypeDescriptor {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ConfigurationOpDescriptor() {
super();
setExtendsWithoutFlatten(new org.morozko.java.mod.dbsrc.config.xml.descriptors.ConfigurationTypeDescriptor());
_nsURI = "http://www.morozko.org/data/java/mod/dbsrc/xsd/dbsrc-config.xsd";
_xmlName = "configuration-op";
_elementDefinition = true;
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
if (_identity == null) {
return super.getIdentity();
}
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
public java.lang.Class getJavaClass(
) {
return org.morozko.java.mod.dbsrc.config.xml.ConfigurationOp.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| {
"content_hash": "6693aa915201af93453132e6602aa65e",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 126,
"avg_line_length": 23.88050314465409,
"alnum_prop": 0.5438504082170135,
"repo_name": "fugeritaetas/morozko-lib",
"id": "b84e148d58a59746f07d4c74f3c2f97c8b864114",
"size": "3797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java14-morozko/org.morozko.java.mod.dbsrc/src/org/morozko/java/mod/dbsrc/config/xml/descriptors/ConfigurationOpDescriptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "100"
},
{
"name": "CSS",
"bytes": "3435"
},
{
"name": "HTML",
"bytes": "674165"
},
{
"name": "Java",
"bytes": "5309090"
},
{
"name": "PLSQL",
"bytes": "2172"
},
{
"name": "Shell",
"bytes": "239"
}
],
"symlink_target": ""
} |
var VASTTimer = function(config){
if(!config.player)
return alert("No player object passed for registration")
this.player = config.player
this.container = "#" + this.player.id + "_wrapper"
this.box = "#" + this.player.id + "_vast_timer"
this.register()
}
/**
* Properties for configuration
*/
VASTTimer.prototype.player = {}
VASTTimer.prototype.container = null
VASTTimer.prototype.box = null
VASTTimer.prototype.bar_height = 30
VASTTimer.prototype.time_remaining = 30
VASTTimer.prototype.time_counted = 0
/**
* Show the block frame
*/
VASTTimer.prototype.show = function(){
var div = $(document.createElement("div"))
div.prop("id",this.box.replace("#",""))
div.css(
{position: "absolute"
,"line-height": this.bar_height + "px"
,background: "#222"
,top: $(window).height() - this.bar_height
,left: 0
,width: $(window).width()
,opacity: "0.8"
,color: "#fff"
,"z-index": "100"
,"text-align": "center"
}
)
div.html(
"Ad will complete in " +
"<span class=\"time\">" +
this.time_remaining +
"</span> seconds " +
", thanks for your patience "
)
$(this.container).append(div)
setTimeout(this.update.bind(this),1000)
}
/**
* Resize / position with the player
*/
VASTTimer.prototype.resize = function(){
$(this.box).css(
{width: $(window).width()
,top: $(window).height() - this.bar_height
}
)
}
/**
* Update time remaining
*/
VASTTimer.prototype.update = function(){
this.time_remaining--
this.time_counted++
if(this.time_remaining <= 0)
return this.hide()
$(this.box).find(".time").first().text(this.time_remaining)
setTimeout(this.update.bind(this),1000)
}
/**
* Destroy the block frame
*/
VASTTimer.prototype.hide = function(){
$(this.box).remove()
}
/**
* Register callbacks to jwplayer
*/
VASTTimer.prototype.register = function(){
this.player.onResize(function(){
this.resize()
}.bind(this))
this.player.onAdImpression(function(){
this.show()
}.bind(this))
this.player.onPlay(function(){
this.hide()
}.bind(this))
this.player.onAdComplete(function(){
this.hide()
}.bind(this))
}
| {
"content_hash": "22bbdc91b8a2c292386935265a36b399",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 61,
"avg_line_length": 22.427083333333332,
"alnum_prop": 0.6372503483511379,
"repo_name": "nullivex/node-portal-skeleton",
"id": "3f42f723933c77365ec552fac1f50a8c3b4e13d7",
"size": "2153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main/themes/saleleap/public/jwplayer/VASTTimer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3367"
},
{
"name": "HTML",
"bytes": "72334"
},
{
"name": "JavaScript",
"bytes": "100141"
}
],
"symlink_target": ""
} |
package org.springframework.cloud.netflix.hystrix.dashboard;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;
/**
* @author Dave Syer
*/
@Controller
public class HystrixDashboardController {
@RequestMapping("/hystrix")
public String home(Model model, WebRequest request) {
model.addAttribute("basePath", extractPath(request));
return "hystrix/index";
}
@RequestMapping("/hystrix/{path}")
public String monitor(@PathVariable String path, Model model, WebRequest request) {
model.addAttribute("basePath", extractPath(request));
model.addAttribute("contextPath", request.getContextPath());
return "hystrix/" + path;
}
private String extractPath(WebRequest request) {
String path = request.getContextPath() + request.getAttribute(
"org.springframework."
+ "web.servlet.HandlerMapping.pathWithinHandlerMapping",
RequestAttributes.SCOPE_REQUEST);
return path;
}
}
| {
"content_hash": "18246e4206eea150a8cfe96cc48d24e9",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 84,
"avg_line_length": 30.53846153846154,
"alnum_prop": 0.780016792611251,
"repo_name": "sfat/spring-cloud-netflix",
"id": "3d372e9b6fcf50cec858e96a9bace984f5b5aab0",
"size": "1812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-cloud-netflix-hystrix-dashboard/src/main/java/org/springframework/cloud/netflix/hystrix/dashboard/HystrixDashboardController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "52461"
},
{
"name": "Groovy",
"bytes": "964"
},
{
"name": "HTML",
"bytes": "10579"
},
{
"name": "Java",
"bytes": "1931316"
},
{
"name": "JavaScript",
"bytes": "33194"
},
{
"name": "Ruby",
"bytes": "481"
},
{
"name": "Shell",
"bytes": "952"
},
{
"name": "TSQL",
"bytes": "349"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example109-jquery</title>
<script src="../../components/jquery-1.10.2/jquery.js"></script>
<script src="../../../angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="eventExample">
<div ng-controller="EventController">
Root scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-repeat="i in [1]" ng-controller="EventController">
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
<br>
Middle scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-repeat="item in [1, 2]" ng-controller="EventController">
Leaf scope <tt>MyEvent</tt> count: {{count}}
</li>
</ul>
</li>
</ul>
</div>
</body>
</html> | {
"content_hash": "75c53576bb2e0de345457a3e7f1ee817",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 79,
"avg_line_length": 27.78787878787879,
"alnum_prop": 0.5670665212649946,
"repo_name": "JSoon/EzineMetroUI",
"id": "be2fceb3492b569787072e7259155ebaeafde8c0",
"size": "917",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "frontend/lib/angularjs/1.3.0-beta.17/docs/examples/example-example109/index-jquery.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "223"
},
{
"name": "ActionScript",
"bytes": "146499"
},
{
"name": "C#",
"bytes": "94651"
},
{
"name": "CSS",
"bytes": "1380368"
},
{
"name": "JavaScript",
"bytes": "4275234"
},
{
"name": "PowerShell",
"bytes": "193761"
},
{
"name": "Shell",
"bytes": "274"
}
],
"symlink_target": ""
} |
cask 'font-noto-sans-syloti-nagri' do
version :latest
sha256 :no_check
# noto-website.storage.googleapis.com was verified as official when first introduced to the cask
url 'https://noto-website.storage.googleapis.com/pkgs/NotoSansSylotiNagri-unhinted.zip'
name 'Noto Sans Syloti Nagri'
homepage 'https://www.google.com/get/noto/#sans-sylo'
font 'NotoSansSylotiNagri-Regular.ttf'
end
| {
"content_hash": "10fa3c4a61e498fc608a86cf449bedf1",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 98,
"avg_line_length": 36.27272727272727,
"alnum_prop": 0.7694235588972431,
"repo_name": "guerrero/homebrew-fonts",
"id": "f063aaa1bbbee19fee6486617ea59ad3f9258749",
"size": "399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Casks/font-noto-sans-syloti-nagri.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "536809"
},
{
"name": "Shell",
"bytes": "2394"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!-- $Rev$ $Date$ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.geronimo.testsuite</groupId>
<artifactId>jaxr-tests</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<artifactId>jaxr-client</artifactId>
<name>Geronimo TestSuite :: WebServices TestSuite :: JAXR Client</name>
<packaging>jar</packaging>
<description>This project executes testcases for your testsuite</description>
<properties>
<clientLogFile>${basedir}/target/client.log</clientLogFile>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jaxr_1.0_spec</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>org.apache.geronimo.test.JAXRClient</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>it</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties>
<property>
<name>clientLogFile</name>
<value>${clientLogFile}</value>
</property>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.geronimo.buildsupport</groupId>
<artifactId>geronimo-maven-plugin</artifactId>
<executions>
<execution>
<id>deploy-client</id>
<phase>pre-integration-test</phase>
<goals>
<goal>deploy-module</goal>
</goals>
<configuration>
<moduleArchive>${project.build.directory}/${project.artifactId}-${project.version}.jar</moduleArchive>
</configuration>
</execution>
<execution>
<phase>pre-integration-test</phase>
<id>run-client</id>
<goals>
<goal>run-client</goal>
</goals>
<configuration>
<moduleId>JEE5/JAXRClient/1.1/car</moduleId>
<logOutput>true</logOutput>
<logFile>${clientLogFile}</logFile>
</configuration>
</execution>
<execution>
<id>undeploy-client-as-moduleId</id>
<phase>post-integration-test</phase>
<goals>
<goal>undeploy-module</goal>
</goals>
<configuration>
<moduleId>JEE5/JAXRClientServer/1.1/car</moduleId>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "3abdc6ad7c456958b10812136a99a73f",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 201,
"avg_line_length": 39.79545454545455,
"alnum_prop": 0.46811345897582335,
"repo_name": "apache/geronimo",
"id": "8fe9a242636c3879ad6b70c08a491d06f84425f2",
"size": "5253",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "testsuite/webservices-testsuite/jaxr-tests/jaxr-client/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29627"
},
{
"name": "CSS",
"bytes": "47972"
},
{
"name": "HTML",
"bytes": "838469"
},
{
"name": "Java",
"bytes": "8975734"
},
{
"name": "JavaScript",
"bytes": "906"
},
{
"name": "Shell",
"bytes": "32814"
},
{
"name": "XSLT",
"bytes": "4468"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace LiteDbExplorer.Converters
{
public class DoubleToGridLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var val = (double)value;
return new GridLength(val);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var val = (GridLength)value;
return val.Value;
}
}
}
| {
"content_hash": "9f5458b35ecc58b01c21ec5ef4893e32",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 103,
"avg_line_length": 28.03846153846154,
"alnum_prop": 0.654320987654321,
"repo_name": "JosefNemec/LiteDbExplorer",
"id": "2953bb1453217fbe3af56ff06d761d545001a310",
"size": "731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/LiteDbExplorer/Converters/DoubleToGridLengthConverter .cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "107093"
},
{
"name": "NSIS",
"bytes": "9253"
},
{
"name": "PowerShell",
"bytes": "3831"
}
],
"symlink_target": ""
} |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
use Concrete\Core\Entity\Attribute\Key\Key;
use Concrete\Core\Form\Service\Form;
use Concrete\Core\Form\Service\Widget\ExpressEntrySelector;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\Entity\Express\Entity;
use Concrete\Core\Entity\Express\Entry;
/** @var array $entities */
/** @var Key[] $expressAttributes */
/** @var Entry|null $entry */
/** @var Entity|null $entity */
/** @var string $exEntityID */
/** @var int $exSpecificEntryID */
/** @var string $exEntryAttributeKeyHandle */
/** @var string $exFormID */
/** @var string $entryMode */
$app = Application::getFacadeApplication();
/** @var Form $form */
$form = $app->make(Form::class);
/** @var ExpressEntrySelector $expressEntrySelector */
$expressEntrySelector = $app->make(ExpressEntrySelector::class);
$exForms = [];
if (is_object($entity)) {
foreach ($entity->getForms() as $form) {
$exForms[$form->getID()] = $form->getName();
}
}
?>
<div id="ccm-block-express-entry-detail-edit">
<div class="form-group">
<?php echo $form->label('entryMode', t('Entry')) ?>
<?php echo $form->select('entryMode', [
'E' => t('Get entry from list block on another page'),
'S' => t('Display specific entry'),
'A' => t('Get entry from custom attribute on this page'),
], $entryMode);
?>
</div>
<div class="form-group" data-container="express-entity">
<?php echo $form->label('exEntityID', t('Entity')) ?>
<?php echo $form->select('exEntityID', $entities, $exEntityID, [
'data-action' => $view->action('load_entity_data')
]); ?>
</div>
<div class="form-group" data-container="express-entry-specific-entry">
<?php if (is_object($entity)) { ?>
<?php print $expressEntrySelector->selectEntry($entity, 'exSpecificEntryID', $entry); ?>
<?php } else { ?>
<p>
<?php echo t('You must select an entity before you can choose a specific entry from it.') ?>
</p>
<?php } ?>
</div>
<div class="form-group" data-container="express-entry-custom-attribute">
<?php echo $form->label('akID', t('Express Entry Attribute')) ?>
<?php if (count($expressAttributes)) { ?>
<!--suppress HtmlFormInputWithoutLabel -->
<select name="exEntryAttributeKeyHandle" class="form-control">
<option value="">
<?php echo t('** Select Attribute') ?>
</option>
<?php foreach ($expressAttributes as $ak) { ?>
<?php $settings = $ak->getAttributeKeySettings(); ?>
<option data-entity-id="<?php echo $settings->getEntity()->getID() ?>"
<?php if ($ak->getAttributeKeyHandle() == $exEntryAttributeKeyHandle) { ?>selected="selected" <?php } ?>
value="<?php echo h($ak->getAttributeKeyHandle()) ?>">
<?php echo $ak->getAttributeKeyDisplayName() ?>
</option>
<?php } ?>
</select>
<?php } else { ?>
<p><?php echo t('There are no express entity page attributes defined.') ?></p>
<?php } ?>
</div>
<div class="form-group">
<?php echo $form->label('exFormID', t('Display Data in Entity Form')) ?>
<div data-container="express-entry-detail-form">
<?php if (is_object($entity)) { ?>
<?php echo $form->select('exFormID', $exForms, $exFormID); ?>
<?php } else { ?>
<?php echo t('You must select an entity before you can choose its display form.') ?>
<?php } ?>
</div>
</div>
</div>
<script type="text/template" data-template="express-attribute-form-list">
<!--suppress HtmlFormInputWithoutLabel -->
<select name="exFormID" class="form-control">
<% _.each(forms, function(form) { %>
<option value="<%=form.exFormID%>"
<% if (exFormID == form.exFormID) { %>selected<% } %>><%=form.exFormName%></option>
<% }); %>
</select>
</script>
<script type="application/javascript">
$(function(){
Concrete.event.publish('block.express_entry_detail.open', {
exFormID: '<?php echo $exFormID?>'
});
});
</script> | {
"content_hash": "ab483e5a6aa9c3150480a35b75cdcccb",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 132,
"avg_line_length": 36.865546218487395,
"alnum_prop": 0.5605197173467061,
"repo_name": "olsgreen/concrete5",
"id": "958d0a66dbed6d1b799796b3c96795ccb0935e4a",
"size": "4387",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "concrete/blocks/express_entry_detail/edit.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "37"
},
{
"name": "CSS",
"bytes": "512312"
},
{
"name": "Hack",
"bytes": "45"
},
{
"name": "JavaScript",
"bytes": "1446693"
},
{
"name": "PHP",
"bytes": "12532521"
},
{
"name": "PowerShell",
"bytes": "4277"
},
{
"name": "Shell",
"bytes": "5873"
},
{
"name": "Vue",
"bytes": "2254"
}
],
"symlink_target": ""
} |
using System;
[AttributeUsage(
AttributeTargets.Struct |
AttributeTargets.Class |
AttributeTargets.Method |
AttributeTargets.Enum
)]
class VersionAttribute : System.Attribute
{
public string Version { get; private set; }
public VersionAttribute(string version)
{
this.Version = version;
}
public override string ToString()
{
return this.Version;
}
} | {
"content_hash": "1cbeebee84c93d741d093ed3ef2d9ea5",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 47,
"avg_line_length": 18.09090909090909,
"alnum_prop": 0.6934673366834171,
"repo_name": "TsvetanKT/TelerikHomeworks",
"id": "8c81cc397f83036465c1123ee641ece147214198",
"size": "400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharpOOP/02.DefiningClassesStaticMembersGenerics/VersionAttribute/TheAttribute.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "8070"
},
{
"name": "C#",
"bytes": "1071835"
},
{
"name": "CSS",
"bytes": "83000"
},
{
"name": "CoffeeScript",
"bytes": "943"
},
{
"name": "JavaScript",
"bytes": "326048"
},
{
"name": "PHP",
"bytes": "5957"
},
{
"name": "XSLT",
"bytes": "4692"
}
],
"symlink_target": ""
} |
#ifndef _MRVL_QOS_H_
#define _MRVL_QOS_H_
#include <rte_common.h>
#include "mrvl_ethdev.h"
/** Code Points per Traffic Class. Equals max(DSCP, PCP). */
#define MRVL_CP_PER_TC (64)
/** Value used as "unknown". */
#define MRVL_UNKNOWN_TC (0xFF)
/* config. */
struct mrvl_cfg {
struct {
struct pp2_parse_udfs prs_udfs;
} pp2_cfg;
struct port_cfg {
enum pp2_ppio_eth_start_hdr eth_start_hdr;
int rate_limit_enable;
struct pp2_ppio_rate_limit_params rate_limit_params;
struct {
uint8_t inq[MRVL_PP2_RXQ_MAX];
uint8_t dscp[MRVL_CP_PER_TC];
uint8_t pcp[MRVL_CP_PER_TC];
uint8_t inqs;
uint8_t dscps;
uint8_t pcps;
enum pp2_ppio_color color;
} tc[MRVL_PP2_TC_MAX];
struct {
enum pp2_ppio_outq_sched_mode sched_mode;
uint8_t weight;
int rate_limit_enable;
struct pp2_ppio_rate_limit_params rate_limit_params;
} outq[MRVL_PP2_RXQ_MAX];
enum pp2_cls_qos_tbl_type mapping_priority;
uint16_t inqs;
uint16_t outqs;
uint8_t default_tc;
uint8_t use_qos_global_defaults;
struct pp2_cls_plcr_params policer_params;
uint8_t setup_policer;
uint8_t forward_bad_frames;
uint32_t fill_bpool_buffs;
} port[RTE_MAX_ETHPORTS];
};
/** Global configuration. */
extern struct mrvl_cfg *mrvl_cfg;
/**
* Parse configuration - rte_kvargs_process handler.
*
* Opens configuration file and parses its content.
*
* @param key Unused.
* @param path Path to config file.
* @param extra_args Pointer to configuration structure.
* @returns 0 in case of success, exits otherwise.
*/
int
mrvl_get_cfg(const char *key __rte_unused, const char *path, void *extra_args);
/**
* Configure RX Queues in a given port.
*
* Sets up RX queues, their Traffic Classes and DPDK rxq->(TC,inq) mapping.
*
* @param priv Port's private data
* @param portid DPDK port ID
* @param max_queues Maximum number of queues to configure.
* @returns 0 in case of success, negative value otherwise.
*/
int
mrvl_configure_rxqs(struct mrvl_priv *priv, uint16_t portid,
uint16_t max_queues);
/**
* Configure TX Queues in a given port.
*
* Sets up TX queues egress scheduler and limiter.
*
* @param priv Port's private data
* @param portid DPDK port ID
* @param max_queues Maximum number of queues to configure.
* @returns 0 in case of success, negative value otherwise.
*/
int
mrvl_configure_txqs(struct mrvl_priv *priv, uint16_t portid,
uint16_t max_queues);
/**
* Start QoS mapping.
*
* Finalize QoS table configuration and initialize it in SDK. It can be done
* only after port is started, so we have a valid ppio reference.
*
* @param priv Port's private (configuration) data.
* @returns 0 in case of success, exits otherwise.
*/
int
mrvl_start_qos_mapping(struct mrvl_priv *priv);
#endif /* _MRVL_QOS_H_ */
| {
"content_hash": "0429d531341db0c4ec7fa231f8cecd8a",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 79,
"avg_line_length": 25.65740740740741,
"alnum_prop": 0.6943341753879466,
"repo_name": "john-mcnamara-intel/dpdk",
"id": "38ea309caa6bfb9a205a8b5a3a198d40930f43e1",
"size": "2918",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "drivers/net/mvpp2/mrvl_qos.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1623"
},
{
"name": "C",
"bytes": "39269990"
},
{
"name": "C++",
"bytes": "860345"
},
{
"name": "Makefile",
"bytes": "342834"
},
{
"name": "Meson",
"bytes": "144875"
},
{
"name": "Objective-C",
"bytes": "224248"
},
{
"name": "Python",
"bytes": "115929"
},
{
"name": "Shell",
"bytes": "77250"
},
{
"name": "SmPL",
"bytes": "2074"
}
],
"symlink_target": ""
} |
package byoid
import (
"context"
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"golang.org/x/oauth2/google"
"google.golang.org/api/dns/v1"
"google.golang.org/api/idtoken"
"google.golang.org/api/option"
)
const (
envCredentials = "GOOGLE_APPLICATION_CREDENTIALS"
envAudienceOIDC = "GCLOUD_TESTS_GOLANG_AUDIENCE_OIDC"
envAudienceAWS = "GCLOUD_TESTS_GOLANG_AUDIENCE_AWS"
envProject = "GOOGLE_CLOUD_PROJECT"
)
var (
oidcAudience string
awsAudience string
oidcToken string
clientID string
projectID string
)
// TestMain contains all of the setup code that needs to be run once before any of the tests are run
func TestMain(m *testing.M) {
flag.Parse()
if testing.Short() {
// This line runs all of our individual tests
os.Exit(m.Run())
}
keyFileName := os.Getenv(envCredentials)
if keyFileName == "" {
log.Fatalf("Please set %s to your keyfile", envCredentials)
}
projectID = os.Getenv(envProject)
if projectID == "" {
log.Fatalf("Please set %s to the ID of the project", envProject)
}
oidcAudience = os.Getenv(envAudienceOIDC)
if oidcAudience == "" {
log.Fatalf("Please set %s to the OIDC Audience", envAudienceOIDC)
}
awsAudience = os.Getenv(envAudienceAWS)
if awsAudience == "" {
log.Fatalf("Please set %s to the AWS Audience", envAudienceAWS)
}
var err error
clientID, err = getClientID(keyFileName)
if err != nil {
log.Fatalf("Error getting Client ID: %v", err)
}
oidcToken, err = generateGoogleToken(keyFileName)
if err != nil {
log.Fatalf("Error generating Google token: %v", err)
}
// This line runs all of our individual tests
os.Exit(m.Run())
}
// keyFile is a struct to extract the relevant json fields for our ServiceAccount KeyFile
type keyFile struct {
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
}
func getClientID(keyFileName string) (string, error) {
kf, err := os.Open(keyFileName)
if err != nil {
return "", err
}
defer kf.Close()
decoder := json.NewDecoder(kf)
var keyFileSettings keyFile
if err = decoder.Decode(&keyFileSettings); err != nil {
return "", err
}
return fmt.Sprintf("projects/-/serviceAccounts/%s", keyFileSettings.ClientEmail), nil
}
func generateGoogleToken(keyFileName string) (string, error) {
ts, err := idtoken.NewTokenSource(context.Background(), oidcAudience, option.WithCredentialsFile(keyFileName))
if err != nil {
return "", nil
}
token, err := ts.Token()
if err != nil {
return "", nil
}
return token.AccessToken, nil
}
// writeConfig writes a temporary config file to memory, and cleans it up after
// testing code is run.
func writeConfig(t *testing.T, c config, f func(name string)) {
t.Helper()
// Set up config file.
configFile, err := ioutil.TempFile("", "config.json")
if err != nil {
t.Fatalf("Error creating config file: %v", err)
}
defer os.Remove(configFile.Name())
err = json.NewEncoder(configFile).Encode(c)
if err != nil {
t.Errorf("Error writing to config file: %v", err)
}
configFile.Close()
f(configFile.Name())
}
// testBYOID makes sure that the default credentials works for
// whatever preconditions have been set beforehand
// by using those credentials to run our client libraries.
//
// In each test we will set up whatever preconditions we need,
// and then use this function.
func testBYOID(t *testing.T, c config) {
t.Helper()
writeConfig(t, c, func(name string) {
// Once the default credentials are obtained,
// we should be able to access Google Cloud resources.
dnsService, err := dns.NewService(context.Background(), option.WithCredentialsFile(name))
if err != nil {
t.Fatalf("Could not establish DNS Service: %v", err)
}
_, err = dnsService.Projects.Get(projectID).Do()
if err != nil {
t.Fatalf("DNS Service failed: %v", err)
}
})
}
// These structs makes writing our config as json to a file much easier.
type config struct {
Type string `json:"type"`
Audience string `json:"audience"`
SubjectTokenType string `json:"subject_token_type"`
TokenURL string `json:"token_url"`
ServiceAccountImpersonationURL string `json:"service_account_impersonation_url"`
ServiceAccountImpersonation serviceAccountImpersonationInfo `json:"service_account_impersonation,omitempty"`
CredentialSource credentialSource `json:"credential_source"`
}
type serviceAccountImpersonationInfo struct {
TokenLifetimeSeconds int `json:"token_lifetime_seconds,omitempty"`
}
type credentialSource struct {
File string `json:"file,omitempty"`
URL string `json:"url,omitempty"`
Executable executableConfig `json:"executable,omitempty"`
EnvironmentID string `json:"environment_id,omitempty"`
RegionURL string `json:"region_url,omitempty"`
RegionalCredVerificationURL string `json:"regional_cred_verification_url,omitempty"`
}
type executableConfig struct {
Command string `json:"command,omitempty"`
TimeoutMillis int `json:"timeout_millis,omitempty"`
OutputFile string `json:"output_file,omitempty"`
}
// Tests to make sure File based external credentials continues to work.
func TestFileBasedCredentials(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
// Set up Token as a file
tokenFile, err := ioutil.TempFile("", "token.txt")
if err != nil {
t.Fatalf("Error creating token file:")
}
defer os.Remove(tokenFile.Name())
tokenFile.WriteString(oidcToken)
tokenFile.Close()
// Run our test!
testBYOID(t, config{
Type: "external_account",
Audience: oidcAudience,
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
TokenURL: "https://sts.googleapis.com/v1beta/token",
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", clientID),
CredentialSource: credentialSource{
File: tokenFile.Name(),
},
})
}
// Tests to make sure URL based external credentials work properly.
func TestURLBasedCredentials(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
//Set up a server to return a token
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Unexpected request method, %v is found", r.Method)
}
w.Write([]byte(oidcToken))
}))
testBYOID(t, config{
Type: "external_account",
Audience: oidcAudience,
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
TokenURL: "https://sts.googleapis.com/v1/token",
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", clientID),
CredentialSource: credentialSource{
URL: ts.URL,
},
})
}
// Tests to make sure AWS based external credentials work properly.
func TestAWSBasedCredentials(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
data := url.Values{}
data.Set("audience", clientID)
data.Set("includeEmail", "true")
client, err := google.DefaultClient(context.Background(), "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
t.Fatalf("Failed to create default client: %v", err)
}
resp, err := client.PostForm(fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateIdToken", clientID), data)
if err != nil {
t.Fatalf("Failed to generate an ID token: %v", err)
}
if resp.StatusCode != 200 {
t.Fatalf("Failed to get Google ID token for AWS test: %v", err)
}
var res map[string]interface{}
if err = json.NewDecoder(resp.Body).Decode(&res); err != nil {
t.Fatalf("Could not successfully parse response from generateIDToken: %v", err)
}
token, ok := res["token"]
if !ok {
t.Fatalf("Didn't receieve an ID token back from generateIDToken")
}
data = url.Values{}
data.Set("Action", "AssumeRoleWithWebIdentity")
data.Set("Version", "2011-06-15")
data.Set("DurationSeconds", "3600")
data.Set("RoleSessionName", os.Getenv("GCLOUD_TESTS_GOLANG_AWS_ROLE_NAME"))
data.Set("RoleArn", os.Getenv("GCLOUD_TESTS_GOLANG_AWS_ROLE_ID"))
data.Set("WebIdentityToken", token.(string))
resp, err = http.PostForm("https://sts.amazonaws.com/", data)
if err != nil {
t.Fatalf("Failed to post data to AWS: %v", err)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to parse response body from AWS: %v", err)
}
var respVars struct {
SessionToken string `xml:"AssumeRoleWithWebIdentityResult>Credentials>SessionToken"`
SecretAccessKey string `xml:"AssumeRoleWithWebIdentityResult>Credentials>SecretAccessKey"`
AccessKeyID string `xml:"AssumeRoleWithWebIdentityResult>Credentials>AccessKeyId"`
}
if err = xml.Unmarshal(bodyBytes, &respVars); err != nil {
t.Fatalf("Failed to unmarshal XML response from AWS.")
}
if respVars.SessionToken == "" || respVars.SecretAccessKey == "" || respVars.AccessKeyID == "" {
t.Fatalf("Couldn't find the required variables in the response from the AWS server.")
}
currSessTokEnv := os.Getenv("AWS_SESSION_TOKEN")
defer os.Setenv("AWS_SESSION_TOKEN", currSessTokEnv)
os.Setenv("AWS_SESSION_TOKEN", respVars.SessionToken)
currSecAccKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
defer os.Setenv("AWS_SECRET_ACCESS_KEY", currSecAccKey)
os.Setenv("AWS_SECRET_ACCESS_KEY", respVars.SecretAccessKey)
currAccKeyID := os.Getenv("AWS_ACCESS_KEY_ID")
defer os.Setenv("AWS_ACCESS_KEY_ID", currAccKeyID)
os.Setenv("AWS_ACCESS_KEY_ID", respVars.AccessKeyID)
currRegion := os.Getenv("AWS_REGION")
defer os.Setenv("AWS_REGION", currRegion)
os.Setenv("AWS_REGION", "us-east-1")
testBYOID(t, config{
Type: "external_account",
Audience: awsAudience,
SubjectTokenType: "urn:ietf:params:aws:token-type:aws4_request",
TokenURL: "https://sts.googleapis.com/v1/token",
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", clientID),
CredentialSource: credentialSource{
EnvironmentID: "aws1",
RegionalCredVerificationURL: "https://sts.us-east-1.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15",
},
})
}
// Tests to make sure executable based external credentials continues to work.
// We're using the same setup as file based external account credentials, and using `cat` as the command
func TestExecutableBasedCredentials(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
// Set up Script as a executable file
scriptFile, err := ioutil.TempFile("", "script.sh")
if err != nil {
t.Fatalf("Error creating token file:")
}
defer os.Remove(scriptFile.Name())
fmt.Fprintf(scriptFile, `#!/bin/bash
echo "{\"success\":true,\"version\":1,\"expiration_time\":%v,\"token_type\":\"urn:ietf:params:oauth:token-type:jwt\",\"id_token\":\"%v\"}"`,
time.Now().Add(time.Hour).Unix(), oidcToken)
scriptFile.Close()
os.Chmod(scriptFile.Name(), 0700)
// Run our test!
testBYOID(t, config{
Type: "external_account",
Audience: oidcAudience,
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
TokenURL: "https://sts.googleapis.com/v1/token",
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", clientID),
CredentialSource: credentialSource{
Executable: executableConfig{
Command: scriptFile.Name(),
},
},
})
}
func TestConfigurableTokenLifetime(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
// Set up Token as a file
tokenFile, err := ioutil.TempFile("", "token.txt")
if err != nil {
t.Fatalf("Error creating token file:")
}
defer os.Remove(tokenFile.Name())
tokenFile.WriteString(oidcToken)
tokenFile.Close()
const tokenLifetimeSeconds = 2800
const safetyBuffer = 5
writeConfig(t, config{
Type: "external_account",
Audience: oidcAudience,
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
TokenURL: "https://sts.googleapis.com/v1/token",
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/%s:generateAccessToken", clientID),
ServiceAccountImpersonation: serviceAccountImpersonationInfo{
TokenLifetimeSeconds: tokenLifetimeSeconds,
},
CredentialSource: credentialSource{
File: tokenFile.Name(),
},
}, func(filename string) {
b, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("Coudn't read temp config file")
}
creds, err := google.CredentialsFromJSON(context.Background(), b, "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
t.Fatalf("Error retrieving credentials")
}
token, err := creds.TokenSource.Token()
if err != nil {
t.Fatalf("Error getting token")
}
now := time.Now()
expiryMax := now.Add(tokenLifetimeSeconds * time.Second)
expiryMin := expiryMax.Add(-safetyBuffer * time.Second)
if token.Expiry.Before(expiryMin) || token.Expiry.After(expiryMax) {
t.Fatalf("Expiry time not set correctly. Got %v, want %v", token.Expiry, expiryMax)
}
})
}
| {
"content_hash": "2897a72732fa023ec3124b50bc3c914f",
"timestamp": "",
"source": "github",
"line_count": 425,
"max_line_length": 140,
"avg_line_length": 32.287058823529414,
"alnum_prop": 0.6760676286255648,
"repo_name": "google/google-api-go-client",
"id": "da3074c4233ffb92fa38549bdc775b010f2d6beb",
"size": "15165",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "integration-tests/byoid/integration_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "611768"
},
{
"name": "Makefile",
"bytes": "1232"
},
{
"name": "Shell",
"bytes": "13231"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="PortaPlanter" />
<meta name="description" content="PortaPlanter™ makes products that help you have healthier, more manageable, and more environmentally beneficial plants and planters.">
<link rel="favicon" href="/image/firehorse_icon_v2_w68.png">
<title>Blog</title>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"
integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
crossorigin="anonymous">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Custom styles for this template -->
<link href="/static/css/main.css" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,200bold,400old" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="/static/css/bootstrap.icon-large.min.css" rel="stylesheet">
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-69391421-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<!-- Main Body-->
<body>
<!-- Wrap all page content here -->
<div id="wrap">
<!-- Navbar header -->
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><i class="fa fa-home"></i></a>
</div>
<div id="navbar">
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</nav>
<div class="container">
<h3>Archive</h3>
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
June 5, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post1.html">A Full and Comprehensive Style Test</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
May 27, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post2.html">Another markdown full cheatsheet demo</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
April 2, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post3.html">Now some lorem ipsum</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
March 15, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post4.html">Continued...</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
February 10, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post5.html">Now seriously something real</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
January 24, 2013</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post6.html">I have a dream <3</a></strong></h5></div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4"><h5 style="text-align: right">
November 4, 2012</h5></div>
<div class="col-sm-8 col-md-8 col-lg-8"><h5 style="text-align: left">
<strong><a href="//post7.html">Nice sticky footer down there ↓ ↓</a></strong></h5></div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer>
<div id="footer">
<div class="container">
<p class="text-muted">PortaPlanter © 2015, All rights reserved.</p>
</div>
</div>
</footer>
<div class="footer"></div>
<!-- Bootstrap core JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"
integrity="sha256-Sk3nkD6mLTMOF0EOpNtsIry+s1CsaqQC1rVLTAy+0yc= sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ=="
crossorigin="anonymous"></script>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/static/js/docs.min.js"></script>
<script src="/static/js/main.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html> | {
"content_hash": "159535cffe887fd3d76f4a90da896ece",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 172,
"avg_line_length": 40.6875,
"alnum_prop": 0.6272401433691757,
"repo_name": "portaplanter/portaplanter.github.io",
"id": "b4dcafda480de74fd7abaa997331c6640454eb8a",
"size": "5862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blog.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4180"
},
{
"name": "HTML",
"bytes": "104706"
},
{
"name": "JavaScript",
"bytes": "980"
}
],
"symlink_target": ""
} |
import pandas as pd
from itertools import islice
import pickle
import re
from time import time
t0 = time()
df = pd.read_csv('metadata.csv')
print('columns',list(df))
selected = df[['cord_uid','sha','publish_time','journal','url','title']].where(df['sha'].notna())
meta_by_sha = {}
rows = selected.iterrows()
for _,r in rows:
if type(r['cord_uid']) is float: continue # NaN
for sha in r['sha'].split(';'):
sha = sha.strip()
if not re.match('^[a-f0-9]+$',sha):
print(r)
exit()
meta = {k:r[k] for k in ['cord_uid','publish_time','journal','title']}
meta_by_sha[sha] = meta
pickle.dump(meta_by_sha,open('paper_meta_by_sha.pkl','wb'))
print(f"done in {time()-t0:.01f} seconds")
| {
"content_hash": "0e8bf0168b06c88db1b3cf1d7cdacf69",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 97,
"avg_line_length": 26.692307692307693,
"alnum_prop": 0.638328530259366,
"repo_name": "mobarski/sandbox",
"id": "ef9fdddd93593ac9d4aae92fcc03acdebf268a50",
"size": "694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "covid19/data/test_meta.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "862"
},
{
"name": "CSS",
"bytes": "6757"
},
{
"name": "Go",
"bytes": "2645"
},
{
"name": "HTML",
"bytes": "637936"
},
{
"name": "JavaScript",
"bytes": "23025"
},
{
"name": "Jupyter Notebook",
"bytes": "57502"
},
{
"name": "Lua",
"bytes": "549110"
},
{
"name": "Makefile",
"bytes": "580"
},
{
"name": "Python",
"bytes": "1329224"
},
{
"name": "Roff",
"bytes": "561"
}
],
"symlink_target": ""
} |
//-----------------------------------------------------------------------
// <copyright file="EndpointRegistrySpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.TestKit;
using Akka.Util.Internal;
using Xunit;
namespace Akka.Remote.Tests
{
public class EndpointRegistrySpec : AkkaSpec
{
private IActorRef actorA;
private IActorRef actorB;
Address address1 = new Address("test", "testsys1", "testhost1", 1234);
Address address2 = new Address("test", "testsy2", "testhost2", 1234);
public EndpointRegistrySpec()
{
actorA = Sys.ActorOf(Props.Empty, "actorA");
actorB = Sys.ActorOf(Props.Empty, "actorB");
}
[Fact]
public void EndpointRegistry_must_be_able_to_register_a_writeable_endpoint_and_policy()
{
var reg = new EndpointRegistry();
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
Assert.Equal(actorA, reg.RegisterWritableEndpoint(address1, actorA,null,null));
Assert.IsType<EndpointManager.Pass>(reg.WritableEndpointWithPolicyFor(address1));
Assert.Equal(actorA, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Pass>().Endpoint);
Assert.Null(reg.ReadOnlyEndpointFor(address1));
Assert.True(reg.IsWritable(actorA));
Assert.False(reg.IsReadOnly(actorA));
Assert.False(reg.IsQuarantined(address1, 42));
}
[Fact]
public void EndpointRegistry_must_be_able_to_register_a_readonly_endpoint()
{
var reg = new EndpointRegistry();
Assert.Null(reg.ReadOnlyEndpointFor(address1));
Assert.Equal(actorA, reg.RegisterReadOnlyEndpoint(address1, actorA, 0));
Assert.Equal(Tuple.Create(actorA, 0), reg.ReadOnlyEndpointFor(address1));
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
Assert.False(reg.IsWritable(actorA));
Assert.True(reg.IsReadOnly(actorA));
Assert.False(reg.IsQuarantined(address1, 42));
}
[Fact]
public void EndpointRegistry_must_be_able_to_register_writable_and_readonly_endpoint_correctly()
{
var reg = new EndpointRegistry();
Assert.Null(reg.ReadOnlyEndpointFor(address1));
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
Assert.Equal(actorA, reg.RegisterReadOnlyEndpoint(address1, actorA, 1));
Assert.Equal(actorB, reg.RegisterWritableEndpoint(address1, actorB, null,null));
Assert.Equal(Tuple.Create(actorA,1), reg.ReadOnlyEndpointFor(address1));
Assert.Equal(actorB, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Pass>().Endpoint);
Assert.False(reg.IsWritable(actorA));
Assert.True(reg.IsWritable(actorB));
Assert.True(reg.IsReadOnly(actorA));
Assert.False(reg.IsReadOnly(actorB));
}
[Fact]
public void EndpointRegistry_must_be_able_to_register_Gated_policy_for_an_address()
{
var reg = new EndpointRegistry();
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
reg.RegisterWritableEndpoint(address1, actorA, null, null);
var deadline = Deadline.Now;
reg.MarkAsFailed(actorA, deadline);
Assert.Equal(deadline, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Gated>().TimeOfRelease);
Assert.False(reg.IsReadOnly(actorA));
Assert.False(reg.IsWritable(actorA));
}
[Fact]
public void EndpointRegistry_must_remove_readonly_endpoints_if_marked_as_failed()
{
var reg = new EndpointRegistry();
reg.RegisterReadOnlyEndpoint(address1, actorA, 2);
reg.MarkAsFailed(actorA, Deadline.Now);
Assert.Null(reg.ReadOnlyEndpointFor(address1));
}
[Fact]
public void EndpointRegistry_must_keep_tombstones_when_removing_an_endpoint()
{
var reg = new EndpointRegistry();
reg.RegisterWritableEndpoint(address1, actorA, null, null);
reg.RegisterWritableEndpoint(address2, actorB, null, null);
var deadline = Deadline.Now;
reg.MarkAsFailed(actorA, deadline);
reg.MarkAsQuarantined(address2, 42, deadline);
reg.UnregisterEndpoint(actorA);
reg.UnregisterEndpoint(actorB);
Assert.Equal(deadline, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Gated>().TimeOfRelease);
Assert.Equal(deadline, reg.WritableEndpointWithPolicyFor(address2).AsInstanceOf<EndpointManager.Quarantined>().Deadline);
Assert.Equal(42, reg.WritableEndpointWithPolicyFor(address2).AsInstanceOf<EndpointManager.Quarantined>().Uid);
}
[Fact]
public void EndpointRegistry_should_prune_outdated_Gated_directives_properly()
{
var reg = new EndpointRegistry();
reg.RegisterWritableEndpoint(address1, actorA, null, null);
reg.RegisterWritableEndpoint(address2, actorB, null, null);
reg.MarkAsFailed(actorA, Deadline.Now);
var farIntheFuture = Deadline.Now + TimeSpan.FromSeconds(60);
reg.MarkAsFailed(actorB, farIntheFuture);
reg.Prune();
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
Assert.Equal(farIntheFuture, reg.WritableEndpointWithPolicyFor(address2).AsInstanceOf<EndpointManager.Gated>().TimeOfRelease);
}
[Fact]
public void EndpointRegistry_should_be_able_to_register_Quarantined_policy_for_an_address()
{
var reg = new EndpointRegistry();
var deadline = Deadline.Now + TimeSpan.FromMinutes(30);
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
reg.MarkAsQuarantined(address1, 42, deadline);
Assert.True(reg.IsQuarantined(address1, 42));
Assert.False(reg.IsQuarantined(address1, 33));
Assert.Equal(42, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Quarantined>().Uid);
Assert.Equal(deadline, reg.WritableEndpointWithPolicyFor(address1).AsInstanceOf<EndpointManager.Quarantined>().Deadline);
}
[Fact]
public void Fix_1845_EndpointRegistry_should_override_ReadOnly_endpoint()
{
var reg = new EndpointRegistry();
var endpoint = TestActor;
reg.RegisterReadOnlyEndpoint(address1, endpoint, 1);
reg.RegisterReadOnlyEndpoint(address1, endpoint, 2);
var ep = reg.ReadOnlyEndpointFor(address1);
ep.Item1.ShouldBe(endpoint);
ep.Item2.ShouldBe(2);
}
[Fact]
public void EndpointRegistry_should_overwrite_Quarantine_policy_with_Pass_on_RegisterWritableEndpoint()
{
var reg = new EndpointRegistry();
var deadline = Deadline.Now + TimeSpan.FromMinutes(30);
var quarantinedUid = 42;
Assert.Null(reg.WritableEndpointWithPolicyFor(address1));
reg.MarkAsQuarantined(address1, quarantinedUid, deadline);
Assert.True(reg.IsQuarantined(address1, quarantinedUid));
var writableUid = 43;
reg.RegisterWritableEndpoint(address1, TestActor, writableUid, quarantinedUid);
Assert.True(reg.IsWritable(TestActor));
}
[Fact]
public void EndpointRegistry_should_overwrite_Gated_policy_with_Pass_on_RegisterWritableEndpoint()
{
var reg = new EndpointRegistry();
var deadline = Deadline.Now + TimeSpan.FromMinutes(30);
var willBeGated = 42;
reg.RegisterWritableEndpoint(address1, TestActor, willBeGated, null);
Assert.NotNull(reg.WritableEndpointWithPolicyFor(address1));
Assert.True(reg.IsWritable(TestActor));
reg.MarkAsFailed(TestActor, deadline);
Assert.False(reg.IsWritable(TestActor));
var writableUid = 43;
reg.RegisterWritableEndpoint(address1, TestActor, writableUid, willBeGated);
Assert.True(reg.IsWritable(TestActor));
}
[Fact]
public void EndpointRegister_should_not_report_endpoint_as_writeable_if_no_Pass_policy()
{
var reg = new EndpointRegistry();
var deadline = Deadline.Now + TimeSpan.FromMinutes(30);
Assert.False(reg.IsWritable(TestActor)); // no policy
reg.RegisterWritableEndpoint(address1, TestActor, 42, null);
Assert.True(reg.IsWritable(TestActor)); // pass
reg.MarkAsFailed(TestActor, deadline);
Assert.False(reg.IsWritable(TestActor)); // Gated
reg.RegisterWritableEndpoint(address1, TestActor, 43, 42); // restarted
Assert.True(reg.IsWritable(TestActor)); // pass
reg.MarkAsQuarantined(address1, 43, deadline);
Assert.False(reg.HasWriteableEndpointFor(address1)); // Quarantined
}
}
}
| {
"content_hash": "152ed3da6a2f5c80a3ef5d6119dc7278",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 138,
"avg_line_length": 43.61926605504587,
"alnum_prop": 0.6370806604269639,
"repo_name": "eloraiby/akka.net",
"id": "8e48d52421693577d63c41b40e68b36dd244085e",
"size": "9511",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/core/Akka.Remote.Tests/EndpointRegistrySpec.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1387"
},
{
"name": "C#",
"bytes": "7405797"
},
{
"name": "F#",
"bytes": "120261"
},
{
"name": "Protocol Buffer",
"bytes": "37516"
},
{
"name": "Shell",
"bytes": "1740"
}
],
"symlink_target": ""
} |
import ntpath
import sys
from unittest import TestCase
from exifread import IfdTag
from mock import mock
from pictures.rename import rename
from tests import helpers
def ifd_tag_from(date_time_original):
return IfdTag(None, None, None, date_time_original, None, None)
class MockFile(object):
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
return self
def __exit__(self, *args):
pass
def create_mock_process_file(files):
return lambda f_mock: files[f_mock.filename]
def create_mock_isfile(files):
return lambda f: f in files
class TestRename(TestCase):
FILES = {
r'C:\dir\no_exif_tags.jpeg': {},
r'C:\dir\timestamp_does_not_exist.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2016:10:29 15:43:56')}, # 1 check
r'C:\dir\timestamp_does_exist.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2016:02:04 12:03:35')}, # 2 checks
r'C:\dir\20160204_120335.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2016:02:04 12:03:35')},
r'C:\dir\timestamp_does_exist_multiple.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2017:01:03 14:23:45')}, # 4 checks
r'C:\dir\20170103_142345.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2017:01:03 14:23:45')},
r'C:\dir\20170103_142345_1.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2017:01:03 14:23:45')},
r'C:\dir\20170103_142345_2.jpeg': {'EXIF DateTimeOriginal': ifd_tag_from('2017:01:03 14:23:45')}
}
@mock.patch('os.rename')
@mock.patch('exifread.process_file', side_effect=create_mock_process_file(FILES))
@mock.patch('builtins.open' if sys.version_info[0] >= 3 else '__builtin__.open', side_effect=MockFile)
@mock.patch('os.path.isfile', create_mock_isfile(FILES))
@mock.patch('os.path', ntpath)
def test_rename(self, mock_open, mock_process_file, mock_rename):
rename(self.FILES)
self.assertEquals(mock_open.mock_calls, helpers.calls_from(zip(self.FILES.keys(), ['rb'] * len(self.FILES))))
self.assertEquals(mock_process_file.call_count, len(self.FILES))
self.assertEquals(sorted(mock_rename.mock_calls), sorted(helpers.calls_from([
(r'C:\dir\timestamp_does_not_exist.jpeg', r'C:\dir\20161029_154356.jpeg'),
(r'C:\dir\timestamp_does_exist.jpeg', r'C:\dir\20160204_120335_1.jpeg'),
(r'C:\dir\timestamp_does_exist_multiple.jpeg', r'C:\dir\20170103_142345_3.jpeg')
])))
| {
"content_hash": "efa2fc4b9447b9b175f0111a5f7b7cd6",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 129,
"avg_line_length": 38.52307692307692,
"alnum_prop": 0.6553514376996805,
"repo_name": "mina-asham/pictures-dedupe-and-rename",
"id": "fe6295126fdb425934c20d5aaf75706fdea94858",
"size": "2504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_rename.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "9416"
}
],
"symlink_target": ""
} |
var ServerStacks = require('../../muon/api/server-stacks.js');
var handler = require('../../muon/infrastructure/handler.js');
var assert = require('assert');
describe("serverStacks test:", function () {
it("does the server stack thing", function (done) {
var serverStacks = new ServerStacks('test-server');
var message = 'this is a test message';
var stubProtocol = {
name: function () {
return 'stub'
},
protocolHandler: function () {
return {
server: function () {
var protocolHandler = handler.create('server', {});
protocolHandler.outgoing(function (data, accept, reject, route) {
console.log('server outgoing data: ' + data);
});
protocolHandler.incoming(function (data, accept, reject, route) {
console.log('server incoming data: ' + data);
reject(data);
});
return protocolHandler;
},
client: function () {
var protocolHandler = handler.create('client', {});
protocolHandler.outgoing(function (data, accept, reject, route) {
console.log('client outgoing data: ' + data);
});
protocolHandler.incoming(function (data, accept, reject, route) {
console.log('client incoming data: ' + data);
});
return protocolHandler;
}
}
}
}
serverStacks.addProtocol(stubProtocol);
var channel = serverStacks.openChannel('stub');
channel.send(message);
channel.listen(function (data) {
if (data.protocol != 'muon' && data.step != 'ChannelShutdown') {
assert.equal(message, data, 'expected simple test message ""' + message + '" but instead received ' + JSON.stringify(data));
done();
}
});
});
it("responds success to shared-channel", function (done) {
var serverStacks = new ServerStacks('test-server');
var channel = serverStacks.openChannel('shared-channel');
assert(channel);
done();
});
it("handles missing protocol gracefully", function (done) {
var serverStacks = new ServerStacks('test-server');
var channel = serverStacks.openChannel('non-existant-protocol');
assert.equal(null, channel);
done();
});
});
| {
"content_hash": "48cf3ad5cfe62f65a5017d83a2ae9ab5",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 140,
"avg_line_length": 34.69620253164557,
"alnum_prop": 0.4968989419919737,
"repo_name": "microserviceux/muon-node",
"id": "e1edb9f992b910670cdbe1e334848a67d8a4709a",
"size": "2741",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/api/serverstacks-test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "221557"
},
{
"name": "Makefile",
"bytes": "329"
},
{
"name": "Shell",
"bytes": "742"
}
],
"symlink_target": ""
} |
% frate = ASDFGetfrate(asdf)
%
% asdf - {nNeu+2, 1} ASDF format spike data file
%
% Returns:
% frate - (nNeu, 1) Probability of firing at one bin for each neuron.
%==============================================================================
% Copyright (c) 2011, The Trustees of Indiana University
% All rights reserved.
%
% Authors: Michael Hansen (mihansen@indiana.edu), Shinya Ito (itos@indiana.edu)
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% 3. Neither the name of Indiana University nor the names of its contributors
% may be used to endorse or promote products derived from this software
% without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%==============================================================================
function frate = ASDFGetfrate(asdf)
nNeu = asdf{end}(1);
duration = asdf{end}(2);
frate = zeros(nNeu, 1);
for i = 1:nNeu
nFire = length(asdf{i});
frate(i) = nFire/duration;
end
| {
"content_hash": "8e71e5fb766ffdf45965d8d572b62c2a",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 80,
"avg_line_length": 44.7,
"alnum_prop": 0.6805369127516778,
"repo_name": "Neuroglycerin/hail-seizure",
"id": "a4fa5e5c7ea7678daa02cc34b9bbe13d595ee4c6",
"size": "2235",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "matlab/dependencies/TransferEntropyToolbox/ASDFGetfrate.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "145807"
},
{
"name": "C++",
"bytes": "44415"
},
{
"name": "HTML",
"bytes": "58482"
},
{
"name": "Jupyter Notebook",
"bytes": "2848412"
},
{
"name": "M",
"bytes": "11958"
},
{
"name": "Makefile",
"bytes": "4720"
},
{
"name": "Matlab",
"bytes": "1357334"
},
{
"name": "Python",
"bytes": "165166"
},
{
"name": "Shell",
"bytes": "1043"
}
],
"symlink_target": ""
} |
#import <MapKit/MKMapSnapshotter.h>
#import <PromiseKit/AnyPromise.h>
/**
To import the `MKMapSnapshotter` category:
use_frameworks!
pod "PromiseKit/MapKit"
And then in your sources:
@import PromiseKit;
*/
@interface MKMapSnapshotter (PromiseKit)
/**
Starts generating the snapshot using the options set in this object.
@return A promise that fulfills with the generated `MKMapSnapshot` object.
*/
- (AnyPromise *)start NS_REFINED_FOR_SWIFT;
@end
| {
"content_hash": "c67d429d4eb619761e912a68f32f721f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 75,
"avg_line_length": 20.434782608695652,
"alnum_prop": 0.7382978723404255,
"repo_name": "OneBusAway/onebusaway-iphone",
"id": "13f33e9b5246fdf39985715ba6fba33757fefab4",
"size": "470",
"binary": false,
"copies": "8",
"ref": "refs/heads/develop",
"path": "OneBusAway/externals/PromiseKit/Extensions/MapKit/Sources/MKMapSnapshotter+AnyPromise.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "67761"
},
{
"name": "HTML",
"bytes": "1774"
},
{
"name": "Objective-C",
"bytes": "1512210"
},
{
"name": "Ruby",
"bytes": "10497"
},
{
"name": "Shell",
"bytes": "306"
},
{
"name": "Swift",
"bytes": "551929"
}
],
"symlink_target": ""
} |
LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image)
: RenderingHelpers::StackBasedLowLevelGraphicsContext<RenderingHelpers::SoftwareRendererSavedState>
(new RenderingHelpers::SoftwareRendererSavedState (image, image.getBounds()))
{
}
LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image, Point<int> origin,
const RectangleList<int>& initialClip)
: RenderingHelpers::StackBasedLowLevelGraphicsContext<RenderingHelpers::SoftwareRendererSavedState>
(new RenderingHelpers::SoftwareRendererSavedState (image, initialClip, origin))
{
}
LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer() {}
| {
"content_hash": "987bd1b1d8ab82d21b2b7439fd16094d",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 106,
"avg_line_length": 49.0625,
"alnum_prop": 0.7401273885350318,
"repo_name": "timedata-org/timedata_visualizer",
"id": "535f74e785ee69fccc237c31e011a203783980e3",
"size": "1712",
"binary": false,
"copies": "30",
"ref": "refs/heads/master",
"path": "JuceLibraryCode/modules/juce_graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2577713"
},
{
"name": "C++",
"bytes": "7170680"
},
{
"name": "Java",
"bytes": "73692"
},
{
"name": "Makefile",
"bytes": "4441"
},
{
"name": "Objective-C",
"bytes": "6635"
},
{
"name": "Objective-C++",
"bytes": "401985"
},
{
"name": "Python",
"bytes": "21811"
}
],
"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.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Evolutionary Diversification in Anolis Lizards: src/simulation.cpp File Reference</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>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js"></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 id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Evolutionary Diversification in Anolis Lizards
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',false,false,'search.php','Search');
});
/* @license-end */</script>
<div id="main-nav"></div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> |
<a href="#var-members">Variables</a> </div>
<div class="headertitle">
<div class="title">simulation.cpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Implementation of Simulation class.
<a href="#details">More...</a></p>
<div class="textblock"><code>#include "<a class="el" href="simulation_8hpp_source.html">simulation.hpp</a>"</code><br />
<code>#include "<a class="el" href="patch_8hpp_source.html">patch.hpp</a>"</code><br />
<code>#include "<a class="el" href="individual_8hpp_source.html">individual.hpp</a>"</code><br />
<code>#include <wtl/exception.hpp></code><br />
<code>#include <wtl/debug.hpp></code><br />
<code>#include <wtl/iostr.hpp></code><br />
<code>#include <wtl/chrono.hpp></code><br />
<code>#include <wtl/concurrent.hpp></code><br />
<code>#include <wtl/filesystem.hpp></code><br />
<code>#include <wtl/zlib.hpp></code><br />
<code>#include <clippson/clippson.hpp></code><br />
<code>#include <sfmt.hpp></code><br />
</div><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:ga4e04878fd7307723a764d239b0b661a5"><td class="memItemLeft" align="right" valign="top">clipp::group </td><td class="memItemRight" valign="bottom"><a class="el" href="group__biol__param.html#ga4e04878fd7307723a764d239b0b661a5">edal::general_options</a> (nlohmann::json *vm)</td></tr>
<tr class="separator:ga4e04878fd7307723a764d239b0b661a5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af0d8e94b893afe44771a69af3d95c31e"><td class="memItemLeft" align="right" valign="top"><a id="af0d8e94b893afe44771a69af3d95c31e"></a>
clipp::group </td><td class="memItemRight" valign="bottom"><b>edal::simulation_options</b> (nlohmann::json *vm)</td></tr>
<tr class="separator:af0d8e94b893afe44771a69af3d95c31e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga079b9868cd651ad76cfd2119dd3784ec"><td class="memItemLeft" align="right" valign="top">clipp::group </td><td class="memItemRight" valign="bottom"><a class="el" href="group__biol__param.html#ga079b9868cd651ad76cfd2119dd3784ec">edal::individual_options</a> (nlohmann::json *vm, IndividualParams *p)</td></tr>
<tr class="memdesc:ga079b9868cd651ad76cfd2119dd3784ec"><td class="mdescLeft"> </td><td class="mdescRight">Symbols for the program options can be different from those in equations. <a href="group__biol__param.html#ga079b9868cd651ad76cfd2119dd3784ec">More...</a><br /></td></tr>
<tr class="separator:ga079b9868cd651ad76cfd2119dd3784ec"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="var-members"></a>
Variables</h2></td></tr>
<tr class="memitem:a24be96b8c5f9c9b38aca5aa64cee2780"><td class="memItemLeft" align="right" valign="top"><a id="a24be96b8c5f9c9b38aca5aa64cee2780"></a>
nlohmann::json </td><td class="memItemRight" valign="bottom"><a class="el" href="simulation_8cpp.html#a24be96b8c5f9c9b38aca5aa64cee2780">edal::VM</a></td></tr>
<tr class="memdesc:a24be96b8c5f9c9b38aca5aa64cee2780"><td class="mdescLeft"> </td><td class="mdescRight">Global variables mapper of commane-line arguments. <br /></td></tr>
<tr class="separator:a24be96b8c5f9c9b38aca5aa64cee2780"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Implementation of Simulation class. </p>
</div></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.14
</small></address>
</body>
</html>
| {
"content_hash": "dde4601247a61e1f15136fa1660c7cba",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 330,
"avg_line_length": 58.794117647058826,
"alnum_prop": 0.7045189261297315,
"repo_name": "heavywatal/edal",
"id": "a17495fb98468146e33a07c8757515e75c5000da",
"size": "5997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/simulation_8cpp.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "58468"
},
{
"name": "CMake",
"bytes": "1786"
},
{
"name": "Python",
"bytes": "6024"
},
{
"name": "R",
"bytes": "20707"
},
{
"name": "TeX",
"bytes": "10177"
}
],
"symlink_target": ""
} |
1. Select the **General** tab on the right.
| {
"content_hash": "5a45b89b66ec7e387c8ec29bded6ec5a",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 43,
"avg_line_length": 44,
"alnum_prop": 0.6818181818181818,
"repo_name": "rht/zulip",
"id": "0b0e325ec6aa2f484df84b902a61f001bbf44977",
"size": "44",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "templates/zerver/help/include/select-stream-view-general.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "489438"
},
{
"name": "Dockerfile",
"bytes": "4025"
},
{
"name": "Emacs Lisp",
"bytes": "157"
},
{
"name": "HTML",
"bytes": "743287"
},
{
"name": "Handlebars",
"bytes": "374049"
},
{
"name": "JavaScript",
"bytes": "4000260"
},
{
"name": "Perl",
"bytes": "10163"
},
{
"name": "Puppet",
"bytes": "112128"
},
{
"name": "Python",
"bytes": "10160680"
},
{
"name": "Ruby",
"bytes": "3459"
},
{
"name": "Shell",
"bytes": "146797"
},
{
"name": "TypeScript",
"bytes": "284836"
}
],
"symlink_target": ""
} |
<?php
namespace PhpOffice\PhpWord\Writer\HTML\Element;
/**
* TextRun element HTML writer
*
* @since 0.10.0
*/
class TextRun extends Text
{
/**
* Write text run
*
* @return string
*/
public function write()
{
$content = '';
$content .= $this->writeOpening();
$writer = new Container($this->parentWriter, $this->element);
$content .= $writer->write();
$content .= $this->writeClosing();
return $content;
}
}
| {
"content_hash": "e3571fe0cf7c8581c5ea3f876f5d0666",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 69,
"avg_line_length": 17.20689655172414,
"alnum_prop": 0.5470941883767535,
"repo_name": "romariick/sf3certif",
"id": "492f7597e3a7d34d52629c41783ba30f837fd932",
"size": "1168",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "Excercies/vendor/phpoffice/phpword/src/PhpWord/Writer/HTML/Element/TextRun.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "395"
},
{
"name": "HTML",
"bytes": "13759"
},
{
"name": "PHP",
"bytes": "124663"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator" >
<translate
android:duration="@integer/config_activity_animation_time"
android:fromXDelta="-100.0%"
android:toXDelta="0.0" />
</set> | {
"content_hash": "bc5a2932ab25ed062290396ff08a8eac",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 66,
"avg_line_length": 34,
"alnum_prop": 0.6588235294117647,
"repo_name": "kiwigo/Private-custom",
"id": "96737a9ab46a107a626480a504de572d8d595036",
"size": "340",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "res/anim/activity_slide_back_in.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "168"
},
{
"name": "Java",
"bytes": "2003613"
}
],
"symlink_target": ""
} |
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module SurveysV2
#
class FieldMask
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `fields`
# @return [Array<Google::Apis::SurveysV2::FieldMask>]
attr_accessor :fields
#
# Corresponds to the JSON property `id`
# @return [Fixnum]
attr_accessor :id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@id = args[:id] if args.key?(:id)
end
end
# Representation of an individual pre-defined panel object defining a targeted
# audience of opinion rewards mobile app users.
class MobileAppPanel
include Google::Apis::Core::Hashable
# Country code for the country of the users that the panel contains. Uses
# standard ISO 3166-1 2-character language codes. For instance, 'US' for the
# United States, and 'GB' for the United Kingdom. Any survey created targeting
# this panel must also target the corresponding country.
# Corresponds to the JSON property `country`
# @return [String]
attr_accessor :country
# Whether or not the panel is accessible to all API users.
# Corresponds to the JSON property `isPublicPanel`
# @return [Boolean]
attr_accessor :is_public_panel
alias_method :is_public_panel?, :is_public_panel
# Language code that the panel can target. For instance, 'en-US'. Uses standard
# BCP47 language codes. See specification. Any survey created targeting this
# panel must also target the corresponding language.
# Corresponds to the JSON property `language`
# @return [String]
attr_accessor :language
# Unique panel ID string. This corresponds to the mobile_app_panel_id used in
# Survey Insert requests.
# Corresponds to the JSON property `mobileAppPanelId`
# @return [String]
attr_accessor :mobile_app_panel_id
# Human readable name of the audience panel.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# List of email addresses for users who can target members of this panel. Must
# contain at least the address of the user making the API call for panels that
# are not public. This field will be empty for public panels.
# Corresponds to the JSON property `owners`
# @return [Array<String>]
attr_accessor :owners
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@country = args[:country] if args.key?(:country)
@is_public_panel = args[:is_public_panel] if args.key?(:is_public_panel)
@language = args[:language] if args.key?(:language)
@mobile_app_panel_id = args[:mobile_app_panel_id] if args.key?(:mobile_app_panel_id)
@name = args[:name] if args.key?(:name)
@owners = args[:owners] if args.key?(:owners)
end
end
#
class MobileAppPanelsListResponse
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `pageInfo`
# @return [Google::Apis::SurveysV2::PageInfo]
attr_accessor :page_info
# Unique request ID used for logging and debugging. Please include in any error
# reporting or troubleshooting requests.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
# An individual predefined panel of Opinion Rewards mobile users.
# Corresponds to the JSON property `resources`
# @return [Array<Google::Apis::SurveysV2::MobileAppPanel>]
attr_accessor :resources
#
# Corresponds to the JSON property `tokenPagination`
# @return [Google::Apis::SurveysV2::TokenPagination]
attr_accessor :token_pagination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_info = args[:page_info] if args.key?(:page_info)
@request_id = args[:request_id] if args.key?(:request_id)
@resources = args[:resources] if args.key?(:resources)
@token_pagination = args[:token_pagination] if args.key?(:token_pagination)
end
end
#
class PageInfo
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `resultPerPage`
# @return [Fixnum]
attr_accessor :result_per_page
#
# Corresponds to the JSON property `startIndex`
# @return [Fixnum]
attr_accessor :start_index
#
# Corresponds to the JSON property `totalResults`
# @return [Fixnum]
attr_accessor :total_results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@result_per_page = args[:result_per_page] if args.key?(:result_per_page)
@start_index = args[:start_index] if args.key?(:start_index)
@total_results = args[:total_results] if args.key?(:total_results)
end
end
#
class ResultsGetRequest
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `resultMask`
# @return [Google::Apis::SurveysV2::ResultsMask]
attr_accessor :result_mask
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@result_mask = args[:result_mask] if args.key?(:result_mask)
end
end
#
class ResultsMask
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `fields`
# @return [Array<Google::Apis::SurveysV2::FieldMask>]
attr_accessor :fields
#
# Corresponds to the JSON property `projection`
# @return [String]
attr_accessor :projection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@projection = args[:projection] if args.key?(:projection)
end
end
# Representation of an individual survey object.
class Survey
include Google::Apis::Core::Hashable
# Specifications for the target audience of a survey run through the API.
# Corresponds to the JSON property `audience`
# @return [Google::Apis::SurveysV2::SurveyAudience]
attr_accessor :audience
# Message defining the cost to run a given survey through API.
# Corresponds to the JSON property `cost`
# @return [Google::Apis::SurveysV2::SurveyCost]
attr_accessor :cost
# Additional information to store on behalf of the API consumer and associate
# with this question. This binary blob is treated as opaque. This field is
# limited to 64K bytes.
# Corresponds to the JSON property `customerData`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :customer_data
# Text description of the survey.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# List of email addresses for survey owners. Must contain at least the address
# of the user making the API call.
# Corresponds to the JSON property `owners`
# @return [Array<String>]
attr_accessor :owners
# List of questions defining the survey.
# Corresponds to the JSON property `questions`
# @return [Array<Google::Apis::SurveysV2::SurveyQuestion>]
attr_accessor :questions
# Message representing why the survey was rejected from review, if it was.
# Corresponds to the JSON property `rejectionReason`
# @return [Google::Apis::SurveysV2::SurveyRejection]
attr_accessor :rejection_reason
# State that the survey is in.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# Unique survey ID, that is viewable in the URL of the Survey Creator UI
# Corresponds to the JSON property `surveyUrlId`
# @return [String]
attr_accessor :survey_url_id
# Optional name that will be given to the survey.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
# Number of responses desired for the survey.
# Corresponds to the JSON property `wantedResponseCount`
# @return [Fixnum]
attr_accessor :wanted_response_count
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@audience = args[:audience] if args.key?(:audience)
@cost = args[:cost] if args.key?(:cost)
@customer_data = args[:customer_data] if args.key?(:customer_data)
@description = args[:description] if args.key?(:description)
@owners = args[:owners] if args.key?(:owners)
@questions = args[:questions] if args.key?(:questions)
@rejection_reason = args[:rejection_reason] if args.key?(:rejection_reason)
@state = args[:state] if args.key?(:state)
@survey_url_id = args[:survey_url_id] if args.key?(:survey_url_id)
@title = args[:title] if args.key?(:title)
@wanted_response_count = args[:wanted_response_count] if args.key?(:wanted_response_count)
end
end
# Specifications for the target audience of a survey run through the API.
class SurveyAudience
include Google::Apis::Core::Hashable
# Optional list of age buckets to target. Supported age buckets are: ['18-24', '
# 25-34', '35-44', '45-54', '55-64', '65+']
# Corresponds to the JSON property `ages`
# @return [Array<String>]
attr_accessor :ages
# Required country code that surveys should be targeted to. Accepts standard ISO
# 3166-1 2 character language codes. For instance, 'US' for the United States,
# and 'GB' for the United Kingdom.
# Corresponds to the JSON property `country`
# @return [String]
attr_accessor :country
# Country subdivision (states/provinces/etc) that surveys should be targeted to.
# For all countries except GB, ISO-3166-2 subdivision code is required (eg. 'US-
# OH' for Ohio, United States). For GB, NUTS 1 statistical region codes for the
# United Kingdom is required (eg. 'UK-UKC' for North East England).
# Corresponds to the JSON property `countrySubdivision`
# @return [String]
attr_accessor :country_subdivision
# Optional gender to target.
# Corresponds to the JSON property `gender`
# @return [String]
attr_accessor :gender
# Language code that surveys should be targeted to. For instance, 'en-US'.
# Surveys may target bilingual users by specifying a list of language codes (for
# example, 'de' and 'en-US'). In that case, all languages will be used for
# targeting users but the survey content (which is displayed) must match the
# first language listed. Accepts standard BCP47 language codes. See
# specification.
# Corresponds to the JSON property `languages`
# @return [Array<String>]
attr_accessor :languages
# Key for predefined panel that causes survey to be sent to a predefined set of
# Opinion Rewards App users. You must set PopulationSource to ANDROID_APP_PANEL
# to use this field.
# Corresponds to the JSON property `mobileAppPanelId`
# @return [String]
attr_accessor :mobile_app_panel_id
# Online population source where the respondents are sampled from.
# Corresponds to the JSON property `populationSource`
# @return [String]
attr_accessor :population_source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@ages = args[:ages] if args.key?(:ages)
@country = args[:country] if args.key?(:country)
@country_subdivision = args[:country_subdivision] if args.key?(:country_subdivision)
@gender = args[:gender] if args.key?(:gender)
@languages = args[:languages] if args.key?(:languages)
@mobile_app_panel_id = args[:mobile_app_panel_id] if args.key?(:mobile_app_panel_id)
@population_source = args[:population_source] if args.key?(:population_source)
end
end
# Message defining the cost to run a given survey through API.
class SurveyCost
include Google::Apis::Core::Hashable
# Cost per survey response in nano units of the given currency. To get the total
# cost for a survey, multiply this value by wanted_response_count.
# Corresponds to the JSON property `costPerResponseNanos`
# @return [Fixnum]
attr_accessor :cost_per_response_nanos
# Currency code that the cost is given in.
# Corresponds to the JSON property `currencyCode`
# @return [String]
attr_accessor :currency_code
# Threshold to start a survey automatically if the quoted price is at most this
# value. When a survey has a Screener (threshold) question, it must go through
# an incidence pricing test to determine the final cost per response. Typically
# you will have to make a followup call to start the survey giving the final
# computed cost per response. If the survey has no threshold_answers, setting
# this property will return an error. By specifying this property, you indicate
# the max price per response you are willing to pay in advance of the incidence
# test. If the price turns out to be lower than the specified value, the survey
# will begin immediately and you will be charged at the rate determined by the
# incidence pricing test. If the price turns out to be greater than the
# specified value the survey will not be started and you will instead be
# notified what price was determined by the incidence test. At that point, you
# must raise the value of this property to be greater than or equal to that cost
# before attempting to start the survey again. This will immediately start the
# survey as long the incidence test was run within the last 21 days.
# Corresponds to the JSON property `maxCostPerResponseNanos`
# @return [Fixnum]
attr_accessor :max_cost_per_response_nanos
# Cost of survey in nano units of the given currency. DEPRECATED in favor of
# cost_per_response_nanos
# Corresponds to the JSON property `nanos`
# @return [Fixnum]
attr_accessor :nanos
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@cost_per_response_nanos = args[:cost_per_response_nanos] if args.key?(:cost_per_response_nanos)
@currency_code = args[:currency_code] if args.key?(:currency_code)
@max_cost_per_response_nanos = args[:max_cost_per_response_nanos] if args.key?(:max_cost_per_response_nanos)
@nanos = args[:nanos] if args.key?(:nanos)
end
end
# Message defining the question specifications.
class SurveyQuestion
include Google::Apis::Core::Hashable
# The randomization option for multiple choice and multi-select questions. If
# not specified, this option defaults to randomize.
# Corresponds to the JSON property `answerOrder`
# @return [String]
attr_accessor :answer_order
# Required list of answer options for a question.
# Corresponds to the JSON property `answers`
# @return [Array<String>]
attr_accessor :answers
# Option to allow open-ended text box for Single Answer and Multiple Answer
# question types. This can be used with SINGLE_ANSWER, SINGLE_ANSWER_WITH_IMAGE,
# MULTIPLE_ANSWERS, and MULTIPLE_ANSWERS_WITH_IMAGE question types.
# Corresponds to the JSON property `hasOther`
# @return [Boolean]
attr_accessor :has_other
alias_method :has_other?, :has_other
# For rating questions, the text for the higher end of the scale, such as 'Best'.
# For numeric questions, a string representing a floating-point that is the
# maximum allowed number for a response.
# Corresponds to the JSON property `highValueLabel`
# @return [String]
attr_accessor :high_value_label
#
# Corresponds to the JSON property `images`
# @return [Array<Google::Apis::SurveysV2::SurveyQuestionImage>]
attr_accessor :images
# Currently only support pinning an answer option to the last position.
# Corresponds to the JSON property `lastAnswerPositionPinned`
# @return [Boolean]
attr_accessor :last_answer_position_pinned
alias_method :last_answer_position_pinned?, :last_answer_position_pinned
# For rating questions, the text for the lower end of the scale, such as 'Worst'.
# For numeric questions, a string representing a floating-point that is the
# minimum allowed number for a response.
# Corresponds to the JSON property `lowValueLabel`
# @return [String]
attr_accessor :low_value_label
# Option to force the user to pick one of the open text suggestions. This
# requires that suggestions are provided for this question.
# Corresponds to the JSON property `mustPickSuggestion`
# @return [Boolean]
attr_accessor :must_pick_suggestion
alias_method :must_pick_suggestion?, :must_pick_suggestion
# Number of stars to use for ratings questions.
# Corresponds to the JSON property `numStars`
# @return [String]
attr_accessor :num_stars
# Placeholder text for an open text question.
# Corresponds to the JSON property `openTextPlaceholder`
# @return [String]
attr_accessor :open_text_placeholder
# A list of suggested answers for open text question auto-complete. This is only
# valid if single_line_response is true.
# Corresponds to the JSON property `openTextSuggestions`
# @return [Array<String>]
attr_accessor :open_text_suggestions
# Required question text shown to the respondent.
# Corresponds to the JSON property `question`
# @return [String]
attr_accessor :question
# Used by the Rating Scale with Text question type. This text goes along with
# the question field that is presented to the respondent, and is the actual text
# that the respondent is asked to rate.
# Corresponds to the JSON property `sentimentText`
# @return [String]
attr_accessor :sentiment_text
# Option to allow multiple line open text responses instead of a single line
# response. Note that we don't show auto-complete suggestions with multiple line
# responses.
# Corresponds to the JSON property `singleLineResponse`
# @return [Boolean]
attr_accessor :single_line_response
alias_method :single_line_response?, :single_line_response
# The threshold/screener answer options, which will screen a user into the rest
# of the survey. These will be a subset of the answer option strings.
# Corresponds to the JSON property `thresholdAnswers`
# @return [Array<String>]
attr_accessor :threshold_answers
# Required field defining the question type. For details about configuring
# different type of questions, consult the question configuration guide.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# Optional unit of measurement for display (for example: hours, people, miles).
# Corresponds to the JSON property `unitOfMeasurementLabel`
# @return [String]
attr_accessor :unit_of_measurement_label
# The YouTube video ID to be show in video questions.
# Corresponds to the JSON property `videoId`
# @return [String]
attr_accessor :video_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@answer_order = args[:answer_order] if args.key?(:answer_order)
@answers = args[:answers] if args.key?(:answers)
@has_other = args[:has_other] if args.key?(:has_other)
@high_value_label = args[:high_value_label] if args.key?(:high_value_label)
@images = args[:images] if args.key?(:images)
@last_answer_position_pinned = args[:last_answer_position_pinned] if args.key?(:last_answer_position_pinned)
@low_value_label = args[:low_value_label] if args.key?(:low_value_label)
@must_pick_suggestion = args[:must_pick_suggestion] if args.key?(:must_pick_suggestion)
@num_stars = args[:num_stars] if args.key?(:num_stars)
@open_text_placeholder = args[:open_text_placeholder] if args.key?(:open_text_placeholder)
@open_text_suggestions = args[:open_text_suggestions] if args.key?(:open_text_suggestions)
@question = args[:question] if args.key?(:question)
@sentiment_text = args[:sentiment_text] if args.key?(:sentiment_text)
@single_line_response = args[:single_line_response] if args.key?(:single_line_response)
@threshold_answers = args[:threshold_answers] if args.key?(:threshold_answers)
@type = args[:type] if args.key?(:type)
@unit_of_measurement_label = args[:unit_of_measurement_label] if args.key?(:unit_of_measurement_label)
@video_id = args[:video_id] if args.key?(:video_id)
end
end
# Container object for image data and alt_text.
class SurveyQuestionImage
include Google::Apis::Core::Hashable
# The alt text property used in image tags is required for all images.
# Corresponds to the JSON property `altText`
# @return [String]
attr_accessor :alt_text
# Inline jpeg, gif, tiff, bmp, or png image raw bytes for an image question
# types.
# Corresponds to the JSON property `data`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :data
# The read-only URL for the hosted images.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alt_text = args[:alt_text] if args.key?(:alt_text)
@data = args[:data] if args.key?(:data)
@url = args[:url] if args.key?(:url)
end
end
# Message representing why the survey was rejected from review, if it was.
class SurveyRejection
include Google::Apis::Core::Hashable
# A human-readable explanation of what was wrong with the survey.
# Corresponds to the JSON property `explanation`
# @return [String]
attr_accessor :explanation
# Which category of rejection this was. See the Google Surveys Help Center for
# additional details on each category.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@explanation = args[:explanation] if args.key?(:explanation)
@type = args[:type] if args.key?(:type)
end
end
# Reference to the current results for a given survey.
class SurveyResults
include Google::Apis::Core::Hashable
# Human readable string describing the status of the request.
# Corresponds to the JSON property `status`
# @return [String]
attr_accessor :status
# External survey ID as viewable by survey owners in the editor view.
# Corresponds to the JSON property `surveyUrlId`
# @return [String]
attr_accessor :survey_url_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@status = args[:status] if args.key?(:status)
@survey_url_id = args[:survey_url_id] if args.key?(:survey_url_id)
end
end
#
class SurveysDeleteResponse
include Google::Apis::Core::Hashable
# Unique request ID used for logging and debugging. Please include in any error
# reporting or troubleshooting requests.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@request_id = args[:request_id] if args.key?(:request_id)
end
end
#
class SurveysListResponse
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `pageInfo`
# @return [Google::Apis::SurveysV2::PageInfo]
attr_accessor :page_info
# Unique request ID used for logging and debugging. Please include in any error
# reporting or troubleshooting requests.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
# An individual survey resource.
# Corresponds to the JSON property `resources`
# @return [Array<Google::Apis::SurveysV2::Survey>]
attr_accessor :resources
#
# Corresponds to the JSON property `tokenPagination`
# @return [Google::Apis::SurveysV2::TokenPagination]
attr_accessor :token_pagination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_info = args[:page_info] if args.key?(:page_info)
@request_id = args[:request_id] if args.key?(:request_id)
@resources = args[:resources] if args.key?(:resources)
@token_pagination = args[:token_pagination] if args.key?(:token_pagination)
end
end
#
class SurveysStartRequest
include Google::Apis::Core::Hashable
# Threshold to start a survey automically if the quoted prices is less than or
# equal to this value. See Survey.Cost for more details.
# Corresponds to the JSON property `maxCostPerResponseNanos`
# @return [Fixnum]
attr_accessor :max_cost_per_response_nanos
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@max_cost_per_response_nanos = args[:max_cost_per_response_nanos] if args.key?(:max_cost_per_response_nanos)
end
end
#
class SurveysStartResponse
include Google::Apis::Core::Hashable
# Unique request ID used for logging and debugging. Please include in any error
# reporting or troubleshooting requests.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@request_id = args[:request_id] if args.key?(:request_id)
end
end
#
class SurveysStopResponse
include Google::Apis::Core::Hashable
# Unique request ID used for logging and debugging. Please include in any error
# reporting or troubleshooting requests.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@request_id = args[:request_id] if args.key?(:request_id)
end
end
#
class TokenPagination
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
#
# Corresponds to the JSON property `previousPageToken`
# @return [String]
attr_accessor :previous_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@previous_page_token = args[:previous_page_token] if args.key?(:previous_page_token)
end
end
end
end
end
| {
"content_hash": "d77034c06f7fa6a371df1ac55cc04b71",
"timestamp": "",
"source": "github",
"line_count": 780,
"max_line_length": 118,
"avg_line_length": 39.56025641025641,
"alnum_prop": 0.6105583822147325,
"repo_name": "saicheems/google-api-ruby-client",
"id": "dc854a9f900a50b2a352e32844ad9ed8f9f5ff6d",
"size": "31434",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "generated/google/apis/surveys_v2/classes.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "32608551"
},
{
"name": "Shell",
"bytes": "1186"
}
],
"symlink_target": ""
} |
package org.codehaus.plexus.archiver.bzip2;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.util.Compressor;
import org.codehaus.plexus.util.IOUtil;
import java.io.IOException;
import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream;
import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream;
/**
* @version $Revision$ $Date$
*/
public class BZip2Compressor
extends Compressor
{
private BZip2CompressorOutputStream zOut;
/**
* perform the BZip2 compression operation.
*/
public void compress()
throws ArchiverException
{
try
{
zOut = new BZip2CompressorOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) );
compress( getSource(), zOut );
}
catch ( IOException ioe )
{
String msg = "Problem creating bzip2 " + ioe.getMessage();
throw new ArchiverException( msg, ioe );
}
}
public void close()
{
IOUtil.close( zOut );
zOut = null;
}
}
| {
"content_hash": "44e5f04fe12399b3013653b896013e3f",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 112,
"avg_line_length": 25.97826086956522,
"alnum_prop": 0.6711297071129707,
"repo_name": "sonatype/plexus-archiver",
"id": "628f0e17cb9253022f6aaf126fabc55f29ca6ef0",
"size": "1820",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Compressor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "490394"
},
{
"name": "Shell",
"bytes": "138"
}
],
"symlink_target": ""
} |
package io.cattle.platform.servicediscovery.api.service.impl;
import static io.cattle.platform.core.model.tables.CertificateTable.*;
import static io.cattle.platform.core.model.tables.InstanceTable.*;
import static io.cattle.platform.core.model.tables.ServiceTable.*;
import static io.cattle.platform.core.model.tables.StackTable.*;
import static io.cattle.platform.core.model.tables.VolumeTemplateTable.*;
import io.cattle.platform.core.addon.LbConfig;
import io.cattle.platform.core.addon.ServiceLink;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.LoadBalancerConstants;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.constants.ServiceConstants;
import io.cattle.platform.core.dao.DataDao;
import io.cattle.platform.core.model.Certificate;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.ServiceConsumeMap;
import io.cattle.platform.core.model.Stack;
import io.cattle.platform.core.model.VolumeTemplate;
import io.cattle.platform.core.util.LBMetadataUtil.LBConfigMetadataStyle;
import io.cattle.platform.docker.constants.DockerInstanceConstants;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.servicediscovery.api.dao.ServiceConsumeMapDao;
import io.cattle.platform.servicediscovery.api.resource.ServiceDiscoveryConfigItem;
import io.cattle.platform.servicediscovery.api.service.RancherConfigToComposeFormatter;
import io.cattle.platform.servicediscovery.api.service.ServiceDiscoveryApiService;
import io.cattle.platform.servicediscovery.api.util.ServiceDiscoveryUtil;
import io.cattle.platform.token.CertSet;
import io.cattle.platform.token.impl.RSAKeyProvider;
import java.io.ByteArrayOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.TransformerUtils;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
@Named
public class ServiceDiscoveryApiServiceImpl implements ServiceDiscoveryApiService {
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager objectProcessManager;
@Inject
ServiceConsumeMapDao consumeMapDao;
@Inject
List<RancherConfigToComposeFormatter> formatters;
@Inject
JsonMapper jsonMapper;
@Inject
RSAKeyProvider keyProvider;
@Inject
DataDao dataDao;
private final static String COMPOSE_PREFIX = "version: '2'\r\n";
@Override
public void addServiceLink(Service service, ServiceLink serviceLink) {
consumeMapDao.createServiceLink(service, serviceLink);
}
@Override
public void removeServiceLink(Service service, ServiceLink serviceLink) {
ServiceConsumeMap map = consumeMapDao.findMapToRemove(service.getId(), serviceLink.getServiceId());
if (map != null) {
objectProcessManager.scheduleProcessInstance(ServiceConstants.PROCESS_SERVICE_CONSUME_MAP_REMOVE,
map, null);
}
}
@Override
public List<? extends Service> listStackServices(long stackId) {
return objectManager.find(Service.class, SERVICE.STACK_ID, stackId, SERVICE.REMOVED,
null);
}
@Override
public Map.Entry<String, String> buildComposeConfig(List<? extends Service> services, Stack stack) {
return new SimpleEntry<>(buildDockerComposeConfig(services, stack), buildRancherComposeConfig(services));
}
@Override
public String buildDockerComposeConfig(List<? extends Service> services, Stack stack) {
List<? extends VolumeTemplate> volumes = objectManager.find(VolumeTemplate.class, VOLUME_TEMPLATE.STACK_ID,
stack.getId(),
VOLUME_TEMPLATE.REMOVED, null);
Map<String, Object> dockerComposeData = createComposeData(services, true, volumes);
if (dockerComposeData.isEmpty()) {
return COMPOSE_PREFIX;
} else {
return COMPOSE_PREFIX + convertToYml(dockerComposeData);
}
}
@Override
public String buildRancherComposeConfig(List<? extends Service> services) {
Map<String, Object> dockerComposeData = createComposeData(services, false, new ArrayList<VolumeTemplate>());
if (dockerComposeData.isEmpty()) {
return COMPOSE_PREFIX;
} else {
return COMPOSE_PREFIX + convertToYml(dockerComposeData);
}
}
private String convertToYml(Map<String, Object> dockerComposeData) {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setLineBreak(LineBreak.WIN);
Representer representer = new SkipNullRepresenter();
representer.addClassTag(LBConfigMetadataStyle.class, Tag.MAP);
Yaml yaml = new Yaml(representer, options);
String yamlStr = yaml.dump(dockerComposeData);
return yamlStr.replaceAll("[$]", "\\$\\$");
}
private class SkipNullRepresenter extends Representer {
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
Object propertyValue, Tag customTag) {
if (propertyValue == null) {
return null;
} else {
return super
.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> createComposeData(List<? extends Service> servicesToExport, boolean forDockerCompose, List<? extends VolumeTemplate> volumes) {
Map<String, Object> servicesData = new HashMap<String, Object>();
Collection<Long> servicesToExportIds = CollectionUtils.collect(servicesToExport,
TransformerUtils.invokerTransformer("getId"));
Map<String, Object> volumesData = new HashMap<String, Object>();
for (Service service : servicesToExport) {
List<String> launchConfigNames = ServiceDiscoveryUtil.getServiceLaunchConfigNames(service);
for (String launchConfigName : launchConfigNames) {
boolean isPrimaryConfig = launchConfigName
.equals(ServiceConstants.PRIMARY_LAUNCH_CONFIG_NAME);
Map<String, Object> cattleServiceData = ServiceDiscoveryUtil.getLaunchConfigWithServiceDataAsMap(
service, launchConfigName);
Map<String, Object> composeServiceData = new HashMap<>();
excludeRancherHash(cattleServiceData);
formatScale(service, cattleServiceData);
formatLBConfig(service, cattleServiceData);
setupServiceType(service, cattleServiceData);
for (String cattleService : cattleServiceData.keySet()) {
translateRancherToCompose(forDockerCompose, cattleServiceData, composeServiceData, cattleService, service, false);
}
if (forDockerCompose) {
populateLinksForService(service, servicesToExportIds, composeServiceData);
populateNetworkForService(service, launchConfigName, composeServiceData);
populateVolumesForService(service, launchConfigName, composeServiceData);
addExtraComposeParameters(service, launchConfigName, composeServiceData);
populateSidekickLabels(service, composeServiceData, isPrimaryConfig);
populateLoadBalancerServiceLabels(service, launchConfigName, composeServiceData);
populateSelectorServiceLabels(service, launchConfigName, composeServiceData);
populateLogConfig(cattleServiceData, composeServiceData);
populateTmpfs(cattleServiceData, composeServiceData);
populateUlimit(cattleServiceData, composeServiceData);
populateBlkioOptions(cattleServiceData, composeServiceData);
translateV1VolumesToV2(cattleServiceData, composeServiceData, volumesData);
}
if (!composeServiceData.isEmpty()) {
servicesData.put(isPrimaryConfig ? service.getName() : launchConfigName, composeServiceData);
}
}
}
for (VolumeTemplate volume : volumes) {
Map<String, Object> cattleVolumeData = new HashMap<>();
cattleVolumeData.putAll(DataUtils.getFields(volume));
cattleVolumeData.put(ServiceConstants.FIELD_VOLUME_EXTERNAL, volume.getExternal());
cattleVolumeData.put(ServiceConstants.FIELD_VOLUME_DRIVER, volume.getDriver());
cattleVolumeData.put(ServiceConstants.FIELD_VOLUME_PER_CONTAINER, volume.getPerContainer());
Map<String, Object> composeVolumeData = new HashMap<>();
for (String cattleVolume : cattleVolumeData.keySet()) {
translateRancherToCompose(forDockerCompose, cattleVolumeData, composeVolumeData, cattleVolume,
null, true);
}
if (!composeVolumeData.isEmpty()) {
volumesData.put(volume.getName(), composeVolumeData);
}
}
Map<String, Object> data = new HashMap<String, Object>();
if (!servicesData.isEmpty()) {
data.put("services", servicesData);
}
if (!volumesData.isEmpty()) {
data.put("volumes", volumesData);
}
return data;
}
@SuppressWarnings("unchecked")
private void excludeRancherHash(Map<String, Object> composeServiceData) {
if (composeServiceData.get(InstanceConstants.FIELD_LABELS) != null) {
Map<String, String> labels = new HashMap<>();
labels.putAll((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_LABELS));
String serviceHash = labels.get(ServiceConstants.LABEL_SERVICE_HASH);
if (serviceHash != null) {
labels.remove(ServiceConstants.LABEL_SERVICE_HASH);
composeServiceData.put(InstanceConstants.FIELD_LABELS, labels);
}
}
if (composeServiceData.get(InstanceConstants.FIELD_METADATA) != null) {
Map<String, String> metadata = new HashMap<>();
metadata.putAll((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_METADATA));
String serviceHash = metadata.get(ServiceConstants.LABEL_SERVICE_HASH);
if (serviceHash != null) {
metadata.remove(ServiceConstants.LABEL_SERVICE_HASH);
composeServiceData.put(InstanceConstants.FIELD_METADATA, metadata);
}
}
}
@SuppressWarnings("unchecked")
protected void formatScale(Service service, Map<String, Object> composeServiceData) {
if (composeServiceData.get(InstanceConstants.FIELD_LABELS) != null) {
Map<String, String> labels = ((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_LABELS));
String globalService = labels.get(ServiceConstants.LABEL_SERVICE_GLOBAL);
if (Boolean.valueOf(globalService) == true) {
composeServiceData.remove(ServiceConstants.FIELD_SCALE);
}
}
}
protected void formatLBConfig(Service service, Map<String, Object> composeServiceData) {
if (composeServiceData.get(ServiceConstants.FIELD_LB_CONFIG) != null) {
LbConfig lbConfig = DataAccessor.field(service, ServiceConstants.FIELD_LB_CONFIG, jsonMapper,
LbConfig.class);
Map<Long, Service> serviceIdsToService = new HashMap<>();
Map<Long, Stack> stackIdsToStack = new HashMap<>();
Map<Long, Certificate> certIdsToCert = new HashMap<>();
for (Service svc : objectManager.find(Service.class, SERVICE.ACCOUNT_ID,
service.getAccountId(), SERVICE.REMOVED, null)) {
serviceIdsToService.put(svc.getId(), svc);
}
for (Stack stack : objectManager.find(Stack.class,
STACK.ACCOUNT_ID,
service.getAccountId(), STACK.REMOVED, null)) {
stackIdsToStack.put(stack.getId(), stack);
}
for (Certificate cert : objectManager.find(Certificate.class,
CERTIFICATE.ACCOUNT_ID, service.getAccountId(), CERTIFICATE.REMOVED, null)) {
certIdsToCert.put(cert.getId(), cert);
}
composeServiceData.put(ServiceConstants.FIELD_LB_CONFIG,
new LBConfigMetadataStyle(lbConfig.getPortRules(), lbConfig.getCertificateIds(),
lbConfig.getDefaultCertificateId(),
lbConfig.getConfig(), lbConfig.getStickinessPolicy(), serviceIdsToService,
stackIdsToStack, certIdsToCert, service.getStackId(), true));
}
}
protected void setupServiceType(Service service, Map<String, Object> composeServiceData) {
Object type = composeServiceData.get(ServiceDiscoveryConfigItem.SERVICE_TYPE.getCattleName());
if (type == null) {
return;
}
if (!InstanceConstants.KIND_VIRTUAL_MACHINE.equals(type.toString())) {
composeServiceData.remove(ServiceDiscoveryConfigItem.SERVICE_TYPE.getCattleName());
}
}
@SuppressWarnings("unchecked")
private void translateV1VolumesToV2(Map<String, Object> cattleServiceData,
Map<String, Object> composeServiceData, Map<String, Object> volumesData) {
// volume driver presence defines the v1 format for the volumes
String volumeDriver = String.valueOf(cattleServiceData.get(ServiceDiscoveryConfigItem.VOLUME_DRIVER
.getCattleName()));
if (StringUtils.isEmpty(volumeDriver)) {
return;
}
composeServiceData.remove(ServiceDiscoveryConfigItem.VOLUME_DRIVER
.getDockerName());
Object dataVolumes = cattleServiceData.get(InstanceConstants.FIELD_DATA_VOLUMES);
if (dataVolumes == null) {
return;
}
for (String dataVolume : (List<String>) dataVolumes) {
String[] splitted = dataVolume.split(":");
if (splitted.length < 2) {
// only process named volumes
continue;
}
String dataVolumeName = splitted[0];
// skip bind mounts
Path p = Paths.get(dataVolumeName);
if (p.isAbsolute()) {
continue;
}
if (volumesData.containsKey(dataVolumeName)) {
// either defined by volumeTemplate, or external volume is already created for it
continue;
}
Map<String, Object> cattleVolumeData = new HashMap<>();
cattleVolumeData.put(ServiceConstants.FIELD_VOLUME_EXTERNAL, true);
cattleVolumeData.put(ServiceConstants.FIELD_VOLUME_DRIVER, volumeDriver);
Map<String, Object> composeVolumeData = new HashMap<>();
for (String cattleVolume : cattleVolumeData.keySet()) {
translateRancherToCompose(true, cattleVolumeData, composeVolumeData, cattleVolume,
null, true);
}
if (!composeVolumeData.isEmpty()) {
volumesData.put(dataVolumeName, composeVolumeData);
}
}
}
@SuppressWarnings("unchecked")
private void populateLogConfig(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) {
Object value = cattleServiceData.get(ServiceConstants.FIELD_LOG_CONFIG);
if (value instanceof Map) {
if (!((Map<?, ?>) value).isEmpty()) {
Map<String, Object> logConfig = new HashMap<>();
Map<String, Object> map = (Map<String, Object>) value;
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if (key.equalsIgnoreCase("config") && map.get(key) != null) {
if (map.get(key) instanceof java.util.Map && !((Map<?, ?>) map.get(key)).isEmpty()) {
logConfig.put("options", map.get(key));
}
} else if (key.equalsIgnoreCase("driver") && map.get(key) != null && map.get(key) != "") {
logConfig.put("driver", map.get(key));
}
}
if (!logConfig.isEmpty() && logConfig.get("driver") != null) {
composeServiceData.put("logging", logConfig);
}
}
}
}
@SuppressWarnings("unchecked")
private void populateTmpfs(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) {
Object value = cattleServiceData.get(ServiceConstants.FIELD_TMPFS);
if (value instanceof Map) {
if (!((Map<?, ?>) value).isEmpty()) {
Map<String, Object> map = (Map<String, Object>)value;
Iterator<String> it = map.keySet().iterator();
ArrayList<String> list = new ArrayList<>();
while (it.hasNext()) {
String key = it.next();
String option = "";
if (map.get(key) != null) {
option = map.get(key).toString();
}
if (option.isEmpty()) {
list.add(key);
} else {
list.add(key + ":" + option);
}
}
composeServiceData.put("tmpfs", list);
}
}
}
@SuppressWarnings("unchecked")
private void populateUlimit(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) {
Object value = cattleServiceData.get(ServiceConstants.FIELD_ULIMITS);
if (value instanceof List<?>) {
if (!((List<?>) value).isEmpty()) {
List<Object> list = (List<Object>) value;
Map<String, Object> ulimits = new HashMap<>();
for (Object ulimit: list) {
// if there is one limit set(must be soft), parse it as map[string]string. If not, parse it as nested map
if (ulimit instanceof Map) {
Map<String, Object> ulimitMap = (Map<String, Object>) ulimit;
// name can not be null
if (ulimitMap.get("name").toString() != null) {
if (ulimitMap.get("soft") != null && ulimitMap.get("hard") == null) {
ulimits.put(ulimitMap.get("name").toString(), ulimitMap.get("soft"));
}
else if (ulimitMap.get("soft") != null && ulimitMap.get("hard") != null) {
Map<String, Object> nestedMap = new HashMap<>();
nestedMap.put("hard", ulimitMap.get("hard"));
nestedMap.put("soft", ulimitMap.get("soft"));
ulimits.put(ulimitMap.get("name").toString(), nestedMap);
}
}
}
}
composeServiceData.put("ulimits", ulimits);
}
}
}
@SuppressWarnings("unchecked")
private void populateBlkioOptions(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) {
Object value = cattleServiceData.get(ServiceConstants.FIELD_BLKIOOPTIONS);
if (value instanceof Map) {
if (!((Map<?, ?>) value).isEmpty()) {
Map<String, Object> options = (Map<String, Object>) value;
Map<String, Object> deviceWeight = new HashMap<>();
Map<String, Object> deviceReadBps = new HashMap<>();
Map<String, Object> deviceReadIops = new HashMap<>();
Map<String, Object> deviceWriteBps = new HashMap<>();
Map<String, Object> deviceWriteIops = new HashMap<>();
for (String key: options.keySet()) {
Object option = options.get(key);
if (option instanceof Map) {
Map<String, Object> optionMap = (Map<String, Object>) option;
if (optionMap.get("readIops") != null) {
deviceReadIops.put(key, optionMap.get("readIops"));
}
if (optionMap.get("writeIops") != null) {
deviceWriteIops.put(key, optionMap.get("writeIops"));
}
if (optionMap.get("readBps") != null) {
deviceReadBps.put(key, optionMap.get("readBps"));
}
if (optionMap.get("writeBps") != null) {
deviceWriteBps.put(key, optionMap.get("writeBps"));
}
if (optionMap.get("weight") != null) {
deviceWeight.put(key, optionMap.get("weight"));
}
}
}
if (!deviceWeight.isEmpty()) {
composeServiceData.put("blkio_weight_device", deviceWeight);
}
if (!deviceReadBps.isEmpty()) {
composeServiceData.put("device_read_bps", deviceReadBps);
}
if (!deviceReadIops.isEmpty()) {
composeServiceData.put("device_read_iops", deviceReadIops);
}
if (!deviceWriteBps.isEmpty()) {
composeServiceData.put("device_write_bps", deviceWriteBps);
}
if (!deviceWriteIops.isEmpty()) {
composeServiceData.put("device_write_iops", deviceWriteIops);
}
}
}
}
@SuppressWarnings("unchecked")
protected void populateLoadBalancerServiceLabels(Service service,
String launchConfigName, Map<String, Object> composeServiceData) {
// to support lb V1 export format
if (!isV1LB(service)) {
return;
}
Map<String, String> labels = new HashMap<>();
if (composeServiceData.get(InstanceConstants.FIELD_LABELS) != null) {
labels.putAll((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_LABELS));
}
// get all consumed services maps
List<? extends ServiceConsumeMap> consumedServiceMaps = consumeMapDao.findConsumedServices(service.getId());
// for each port, populate the label
for (ServiceConsumeMap map : consumedServiceMaps) {
Service consumedService = objectManager.loadResource(Service.class, map.getConsumedServiceId());
List<String> ports = DataAccessor.fieldStringList(map, LoadBalancerConstants.FIELD_LB_TARGET_PORTS);
String consumedServiceName = consumedService.getName();
if (!service.getStackId().equals(consumedService.getStackId())) {
Stack env = objectManager.loadResource(Stack.class,
consumedService.getStackId());
consumedServiceName = env.getName() + "/" + consumedServiceName;
}
String labelName = ServiceConstants.LABEL_LB_TARGET + consumedServiceName;
StringBuilder bldr = new StringBuilder();
for (String port : ports) {
bldr.append(port).append(",");
}
if (bldr.length() > 0) {
labels.put(labelName, bldr.toString().substring(0, bldr.length() - 1));
}
}
if (!labels.isEmpty()) {
composeServiceData.put(InstanceConstants.FIELD_LABELS, labels);
}
}
@SuppressWarnings("unchecked")
protected void populateSelectorServiceLabels(Service service,
String launchConfigName, Map<String, Object> composeServiceData) {
String selectorContainer = service.getSelectorContainer();
String selectorLink = service.getSelectorLink();
if (selectorContainer == null && selectorLink == null) {
return;
}
Map<String, String> labels = new HashMap<>();
if (composeServiceData.get(InstanceConstants.FIELD_LABELS) != null) {
labels.putAll((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_LABELS));
}
if (selectorLink != null) {
labels.put(ServiceConstants.LABEL_SELECTOR_LINK, selectorLink);
}
if (selectorContainer != null) {
labels.put(ServiceConstants.LABEL_SELECTOR_CONTAINER, selectorContainer);
}
if (!labels.isEmpty()) {
composeServiceData.put(InstanceConstants.FIELD_LABELS, labels);
}
}
@SuppressWarnings("unchecked")
protected void populateSidekickLabels(Service service, Map<String, Object> composeServiceData, boolean isPrimary) {
List<? extends String> configs = ServiceDiscoveryUtil
.getServiceLaunchConfigNames(service);
configs.remove(ServiceConstants.PRIMARY_LAUNCH_CONFIG_NAME);
StringBuilder sidekicks = new StringBuilder();
for (String config : configs) {
sidekicks.append(config).append(",");
}
Map<String, String> labels = new HashMap<>();
if (composeServiceData.get(InstanceConstants.FIELD_LABELS) != null) {
labels.putAll((HashMap<String, String>) composeServiceData.get(InstanceConstants.FIELD_LABELS));
labels.remove(ServiceConstants.LABEL_SIDEKICK);
}
if (!sidekicks.toString().isEmpty() && isPrimary) {
String sidekicksFinal = sidekicks.toString().substring(0, sidekicks.length() - 1);
labels.put(ServiceConstants.LABEL_SIDEKICK, sidekicksFinal);
}
if (!labels.isEmpty()) {
composeServiceData.put(InstanceConstants.FIELD_LABELS, labels);
} else {
composeServiceData.remove(InstanceConstants.FIELD_LABELS);
}
}
private void populateLinksForService(Service service, Collection<Long> servicesToExportIds,
Map<String, Object> composeServiceData) {
List<String> serviceLinksWithNames = new ArrayList<>();
List<String> externalLinksServices = new ArrayList<>();
List<? extends ServiceConsumeMap> consumedServiceMaps = consumeMapDao.findConsumedServices(service.getId());
for (ServiceConsumeMap consumedServiceMap : consumedServiceMaps) {
Service consumedService = objectManager.findOne(Service.class, SERVICE.ID,
consumedServiceMap.getConsumedServiceId());
String linkName = consumedService.getName()
+ ":"
+ (!StringUtils.isEmpty(consumedServiceMap.getName()) ? consumedServiceMap.getName()
: consumedService
.getName());
if (servicesToExportIds.contains(consumedServiceMap.getConsumedServiceId())) {
serviceLinksWithNames.add(linkName);
} else if (!consumedService.getStackId().equals(service.getStackId())) {
Stack externalStack = objectManager.loadResource(Stack.class,
consumedService.getStackId());
externalLinksServices.add(externalStack.getName() + "/" + linkName);
}
}
if (!serviceLinksWithNames.isEmpty()) {
composeServiceData.put(ServiceDiscoveryConfigItem.LINKS.getDockerName(), serviceLinksWithNames);
}
if (!externalLinksServices.isEmpty()) {
composeServiceData.put(ServiceDiscoveryConfigItem.EXTERNALLINKS.getDockerName(), externalLinksServices);
}
}
private void addExtraComposeParameters(Service service,
String launchConfigName, Map<String, Object> composeServiceData) {
if (service.getKind().equalsIgnoreCase(ServiceConstants.KIND_DNS_SERVICE)) {
composeServiceData.put(ServiceDiscoveryConfigItem.IMAGE.getDockerName(), "rancher/dns-service");
} else if (isV1LB(service)) {
composeServiceData.put(ServiceDiscoveryConfigItem.IMAGE.getDockerName(),
"rancher/load-balancer-service");
} else if (service.getKind().equalsIgnoreCase(ServiceConstants.KIND_EXTERNAL_SERVICE)) {
composeServiceData.put(ServiceDiscoveryConfigItem.IMAGE.getDockerName(), "rancher/external-service");
}
}
private void populateNetworkForService(Service service,
String launchConfigName, Map<String, Object> composeServiceData) {
Object networkMode = composeServiceData.get(ServiceDiscoveryConfigItem.NETWORKMODE.getDockerName());
if (networkMode != null) {
if (networkMode.equals(NetworkConstants.NETWORK_MODE_CONTAINER)) {
Map<String, Object> serviceData = ServiceDiscoveryUtil.getLaunchConfigDataAsMap(service,
launchConfigName);
// network mode can be passed by container, or by service name, so check both
// networkFromContainerId wins
Integer targetContainerId = DataAccessor
.fieldInteger(service, DockerInstanceConstants.DOCKER_CONTAINER);
if (targetContainerId != null) {
Instance instance = objectManager.loadResource(Instance.class, targetContainerId.longValue());
String instanceName = ServiceDiscoveryUtil.getInstanceName(instance);
composeServiceData.put(ServiceDiscoveryConfigItem.NETWORKMODE.getDockerName(),
NetworkConstants.NETWORK_MODE_CONTAINER + ":" + instanceName);
} else {
Object networkLaunchConfig = serviceData
.get(ServiceConstants.FIELD_NETWORK_LAUNCH_CONFIG);
if (networkLaunchConfig != null) {
composeServiceData.put(ServiceDiscoveryConfigItem.NETWORKMODE.getDockerName(),
NetworkConstants.NETWORK_MODE_CONTAINER + ":" + networkLaunchConfig);
}
}
} else if (networkMode.equals(NetworkConstants.NETWORK_MODE_MANAGED)) {
composeServiceData.remove(ServiceDiscoveryConfigItem.NETWORKMODE.getDockerName());
}
}
}
protected void translateRancherToCompose(boolean forDockerCompose, Map<String, Object> rancherServiceData,
Map<String, Object> composeServiceData, String cattleName, Service service, boolean isVolume) {
ServiceDiscoveryConfigItem item = ServiceDiscoveryConfigItem.getServiceConfigItemByCattleName(cattleName,
service, isVolume);
if (item != null && item.isDockerComposeProperty() == forDockerCompose) {
Object value = rancherServiceData.get(cattleName);
boolean export = false;
if (value instanceof List) {
if (!((List<?>) value).isEmpty()) {
export = true;
}
} else if (value instanceof Map) {
if (!((Map<?, ?>) value).isEmpty()) {
export = true;
}
} else if (value instanceof Boolean) {
if (((Boolean) value).booleanValue()) {
export = true;
}
} else if (value != null) {
export = true;
}
if (export) {
// for every lookup, do transform
Object formattedValue = null;
for (RancherConfigToComposeFormatter formatter : formatters) {
formattedValue = formatter.format(item, value);
if (formattedValue != null) {
break;
}
}
if (formattedValue != null) {
if (formattedValue != RancherConfigToComposeFormatter.Option.REMOVE) {
composeServiceData.put(item.getDockerName().toLowerCase(), formattedValue);
}
} else {
composeServiceData.put(item.getDockerName().toLowerCase(), value);
}
}
}
}
@SuppressWarnings("unchecked")
private void populateVolumesForService(Service service, String launchConfigName,
Map<String, Object> composeServiceData) {
List<String> namesCombined = new ArrayList<>();
List<String> launchConfigNames = new ArrayList<>();
Map<String, Object> launchConfigData = ServiceDiscoveryUtil.getLaunchConfigDataAsMap(service, launchConfigName);
Object dataVolumesLaunchConfigs = launchConfigData.get(
ServiceConstants.FIELD_DATA_VOLUMES_LAUNCH_CONFIG);
if (dataVolumesLaunchConfigs != null) {
launchConfigNames.addAll((List<String>) dataVolumesLaunchConfigs);
}
// 1. add launch config names
namesCombined.addAll(launchConfigNames);
// 2. add instance names if specified
List<? extends Integer> instanceIds = (List<? extends Integer>) launchConfigData
.get(DockerInstanceConstants.FIELD_VOLUMES_FROM);
if (instanceIds != null) {
for (Integer instanceId : instanceIds) {
Instance instance = objectManager.findOne(Instance.class, INSTANCE.ID, instanceId, INSTANCE.REMOVED,
null);
String instanceName = ServiceDiscoveryUtil.getInstanceName(instance);
if (instanceName != null) {
namesCombined.add(instanceName);
}
}
}
if (!namesCombined.isEmpty()) {
composeServiceData.put(ServiceDiscoveryConfigItem.VOLUMESFROM.getDockerName(), namesCombined);
}
}
@Override
public String getServiceCertificate(final Service service) {
if (service == null) {
return null;
}
final Stack stack = objectManager.loadResource(Stack.class, service.getStackId());
if (stack == null) {
return null;
}
String key = String.format("service.v2.%d.cert", service.getId());
return dataDao.getOrCreate(key, false, new Callable<String>() {
@Override
public String call() throws Exception {
return generateService(service, stack);
}
});
}
protected String generateService(Service service, Stack stack) throws Exception {
@SuppressWarnings("unchecked")
Map<String, Object> metadata = DataAccessor.fields(service).withKey(ServiceConstants.FIELD_METADATA)
.withDefault(Collections.EMPTY_MAP).as(Map.class);
String serviceName = service.getName();
List<? extends String> configuredSans = DataAccessor.fromMap(metadata).withKey("sans")
.withDefault(Collections.emptyList()).asList(jsonMapper, String.class);
List<String> sans = new ArrayList<>(configuredSans);
sans.add(serviceName.toLowerCase());
sans.add(String.format("%s.%s", serviceName, stack.getName()).toLowerCase());
sans.add(String.format("%s.%s.%s", serviceName, stack.getName(), NetworkConstants.INTERNAL_DNS_SEARCH_DOMAIN)
.toLowerCase());
CertSet certSet = keyProvider.generateCertificate(serviceName, sans.toArray(new String[sans.size()]));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
certSet.writeZip(baos);
return Base64.encodeBase64String(baos.toByteArray());
}
@Override
public boolean isV1LB(Service service) {
if (!service.getKind().equalsIgnoreCase(ServiceConstants.KIND_LOAD_BALANCER_SERVICE)) {
return false;
}
LbConfig lbConfig = DataAccessor.field(service, ServiceConstants.FIELD_LB_CONFIG, jsonMapper,
LbConfig.class);
return lbConfig == null;
}
} | {
"content_hash": "f27cc83ab83bedf8d6b8c08a0efb2d7c",
"timestamp": "",
"source": "github",
"line_count": 781,
"max_line_length": 159,
"avg_line_length": 47.9270166453265,
"alnum_prop": 0.6165744970746173,
"repo_name": "wlan0/cattle",
"id": "b6e08e3ff486fe1b796217fae359b500903be1fa",
"size": "37431",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "code/iaas/service-discovery/api/src/main/java/io/cattle/platform/servicediscovery/api/service/impl/ServiceDiscoveryApiServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "71"
},
{
"name": "Java",
"bytes": "6216905"
},
{
"name": "Makefile",
"bytes": "308"
},
{
"name": "Python",
"bytes": "1535973"
},
{
"name": "Shell",
"bytes": "33788"
}
],
"symlink_target": ""
} |
package org.joyrest.examples.di.jokeapp.spring;
import org.joyrest.examples.di.jokeapp.JokeController;
import org.joyrest.examples.di.jokeapp.JokeService;
import org.joyrest.examples.di.jokeapp.JokeServiceImpl;
import org.joyrest.gson.GsonReaderWriter;
import org.joyrest.routing.ControllerConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfiguration {
@Bean
GsonReaderWriter jsonReaderWriter() {
return new GsonReaderWriter();
}
@Bean
ControllerConfiguration jokeControllerConfiguration() {
return new JokeController();
}
@Bean
JokeService jokeService() {
return new JokeServiceImpl();
}
}
| {
"content_hash": "67560877bb881ce167602a9da256489c",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 60,
"avg_line_length": 25.933333333333334,
"alnum_prop": 0.7660668380462725,
"repo_name": "petrbouda/joyrest",
"id": "adef4a2ff50e61a5d0d132a3df47e7fa992f0a61",
"size": "1371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "joyrest-examples/di-examples/src/main/java/org/joyrest/examples/di/jokeapp/spring/ApplicationConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "620430"
}
],
"symlink_target": ""
} |
package blended.streams.testsupport
import akka.util.ByteString
import blended.streams.message.{FlowEnvelope, FlowMessage}
import blended.testsupport.scalatest.LoggingFreeSpec
import org.scalatest.Matchers
class FlowMessageAssertionSpec extends LoggingFreeSpec
with Matchers {
"The FlowMessageAssertions should" - {
"support to check expected string bodies" in {
val env = FlowEnvelope(FlowMessage("Hello Blended!")(FlowMessage.noProps))
FlowMessageAssertion.checkAssertions(env)(
ExpectedBodies(Some("Hello Blended!"))
) should be (empty)
FlowMessageAssertion.checkAssertions(env)(
ExpectedBodies(Some("foo"))
) should have size 1
FlowMessageAssertion.checkAssertions(env)(
ExpectedBodies(Some(100))
) should have size 1
}
"support to check expected byte string bodies" in {
val env = FlowEnvelope(FlowMessage(ByteString("Hello Blended!"))(FlowMessage.noProps))
FlowMessageAssertion.checkAssertions(env)(
ExpectedBodies(Some(ByteString("Hello Blended!")))
) should be (empty)
FlowMessageAssertion.checkAssertions(env)(
ExpectedBodies(Some("foo"))
) should have size 1
}
}
}
| {
"content_hash": "7f1620e275169b87dbbdd8624d9c8ed6",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 92,
"avg_line_length": 27.772727272727273,
"alnum_prop": 0.7127659574468085,
"repo_name": "lefou/blended",
"id": "cbcc0fe2b6061c20abeb0f755ca4eb10d7d6174e",
"size": "1222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blended.streams.testsupport/src/test/scala/blended/streams/testsupport/FlowMessageAssertionSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2690"
},
{
"name": "DIGITAL Command Language",
"bytes": "975"
},
{
"name": "Java",
"bytes": "24549"
},
{
"name": "Scala",
"bytes": "1411284"
},
{
"name": "Shell",
"bytes": "62880"
}
],
"symlink_target": ""
} |
module PromotionSupport
class << self
def line_item_promotion(order)
promo = FactoryGirl.create(:promotion_with_item_adjustment, code: 'line_item_promotion')
promo.rules << Spree::Promotion::Rules::Product.create!(preferred_match_policy: 'any', product_ids_string: order.line_items.first.product.id.to_s)
promo
end
def set_line_item_promotion(order)
order.coupon_code = line_item_promotion(order).code
Spree::PromotionHandler::Coupon.new(order).apply_without_avatax
order.reload
end
def order_promotion(order)
promo = FactoryGirl.create(:promotion, code: "order_promotion")
calculator = Spree::Calculator::FlatRate.new
calculator.preferred_amount = 10
Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator, promotion: promo)
promo
end
def set_order_promotion(order)
order.coupon_code = order_promotion(order).code
Spree::PromotionHandler::Coupon.new(order).apply_without_avatax
order.reload
end
end
end
| {
"content_hash": "78e81b20a221a525eb9c47444c87e467",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 152,
"avg_line_length": 36.10344827586207,
"alnum_prop": 0.7039159503342884,
"repo_name": "CandleScience/new_spree_avatax",
"id": "b9ca8c4abb70c6101e1cb05642a71b43353ea16c",
"size": "1047",
"binary": false,
"copies": "1",
"ref": "refs/heads/3-0-stable",
"path": "spec/support/promotion_support.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "109756"
}
],
"symlink_target": ""
} |
<?php
class Google_Service_CloudHealthcare_DeidentifySummary extends Google_Model
{
}
| {
"content_hash": "891b9537809d91d859d67435c209bf24",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 75,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.8068181818181818,
"repo_name": "phil-davis/core",
"id": "118a0e6c873571e872a58098ef74e637f3d07cef",
"size": "678",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "apps/files_external/3rdparty/google/apiclient-services/src/Google/Service/CloudHealthcare/DeidentifySummary.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "262"
},
{
"name": "Makefile",
"bytes": "473"
},
{
"name": "Shell",
"bytes": "8644"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Cache_Core
*/
require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Class extends Zend_Cache_Core
{
/**
* Available options
*
* ====> (mixed) cached_entity :
* - if set to a class name, we will cache an abstract class and will use only static calls
* - if set to an object, we will cache this object methods
*
* ====> (boolean) cache_by_default :
* - if true, method calls will be cached by default
*
* ====> (array) cached_methods :
* - an array of method names which will be cached (even if cache_by_default = false)
*
* ====> (array) non_cached_methods :
* - an array of method names which won't be cached (even if cache_by_default = true)
*
* @var array available options
*/
protected $_specificOptions = array(
'cached_entity' => null,
'cache_by_default' => true,
'cached_methods' => array(),
'non_cached_methods' => array()
);
/**
* Tags array
*
* @var array
*/
private $_tags = array();
/**
* SpecificLifetime value
*
* false => no specific life time
*
* @var int
*/
private $_specificLifetime = false;
/**
* The cached object or the name of the cached abstract class
*
* @var mixed
*/
private $_cachedEntity = null;
/**
* The class name of the cached object or cached abstract class
*
* Used to differentiate between different classes with the same method calls.
*
* @var string
*/
private $_cachedEntityLabel = '';
/**
* Priority (used by some particular backends)
*
* @var int
*/
private $_priority = 8;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
if (is_null($this->_specificOptions['cached_entity'])) {
Zend_Cache::throwException('cached_entity must be set !');
}
$this->setCachedEntity($this->_specificOptions['cached_entity']);
$this->setOption('automatic_serialization', true);
}
/**
* Set a specific life time
*
* @param int $specificLifetime
* @return void
*/
public function setSpecificLifetime($specificLifetime = false)
{
$this->_specificLifetime = $specificLifetime;
}
/**
* Set the priority (used by some particular backends)
*
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority)
*/
public function setPriority($priority)
{
$this->_priority = $priority;
}
/**
* Public frontend to set an option
*
* Just a wrapper to get a specific behaviour for cached_entity
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if ($name == 'cached_entity') {
$this->setCachedEntity($value);
} else {
parent::setOption($name, $value);
}
}
/**
* Specific method to set the cachedEntity
*
* if set to a class name, we will cache an abstract class and will use only static calls
* if set to an object, we will cache this object methods
*
* @param mixed $cachedEntity
*/
public function setCachedEntity($cachedEntity)
{
if (!is_string($cachedEntity) && !is_object($cachedEntity)) {
Zend_Cache::throwException('cached_entity must be an object or a class name');
}
$this->_cachedEntity = $cachedEntity;
$this->_specificOptions['cached_entity'] = $cachedEntity;
if (is_string($this->_cachedEntity)){
$this->_cachedEntityLabel = $this->_cachedEntity;
} else {
$ro = new ReflectionObject($this->_cachedEntity);
$this->_cachedEntityLabel = $ro->getName();
}
}
/**
* Set the cache array
*
* @param array $tags
* @return void
*/
public function setTagsArray($tags = array())
{
$this->_tags = $tags;
}
/**
* Main method : call the specified method or get the result from cache
*
* @param string $name Method name
* @param array $parameters Method parameters
* @return mixed Result
*/
public function __call($name, $parameters)
{
$cacheBool1 = $this->_specificOptions['cache_by_default'];
$cacheBool2 = in_array($name, $this->_specificOptions['cached_methods']);
$cacheBool3 = in_array($name, $this->_specificOptions['non_cached_methods']);
$cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
if (!$cache) {
// We do not have not cache
return call_user_func_array(array($this->_cachedEntity, $name), $parameters);
}
$id = $this->_makeId($name, $parameters);
if ($this->test($id)) {
// A cache is available
$result = $this->load($id);
$output = $result[0];
$return = $result[1];
} else {
// A cache is not available
ob_start();
ob_implicit_flush(false);
$return = call_user_func_array(array($this->_cachedEntity, $name), $parameters);
$output = ob_get_contents();
ob_end_clean();
$data = array($output, $return);
$this->save($data, $id, $this->_tags, $this->_specificLifetime, $this->_priority);
}
echo $output;
return $return;
}
/**
* Make a cache id from the method name and parameters
*
* @param string $name Method name
* @param array $parameters Method parameters
* @return string Cache id
*/
private function _makeId($name, $parameters)
{
return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($parameters));
}
}
| {
"content_hash": "c903ea866d46624abe817d4a2ea65b40",
"timestamp": "",
"source": "github",
"line_count": 224,
"max_line_length": 95,
"avg_line_length": 29.125,
"alnum_prop": 0.5591661557326794,
"repo_name": "sitengine/sitengine",
"id": "77dcaa4c1ea5c7aa2bfb0f613611a19f786a1c85",
"size": "7230",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "_Contrib/Zend-1.7.6/Cache/Frontend/Class.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "636344"
},
{
"name": "PHP",
"bytes": "25952146"
}
],
"symlink_target": ""
} |
title: "{{ replace .Name "-" " " | title }}"
linktitle: "{{ replace .Name "-" " " | title }}"
summary:
date: {{ .Date }}
lastmod: {{ .Date }}
draft: false # Is this a draft? true/false
toc: true # Show table of contents? true/false
type: docs # Do not modify.
# Add menu entry to sidebar.
# - Substitute `example` with the name of your course/documentation folder.
# - name: Declare this menu item as a parent with ID `name`.
# - parent: Reference a parent ID if this page is a child.
# - weight: Position of link in menu.
menu:
example:
name: YourParentID
# parent: YourParentID
weight: 1
---
| {
"content_hash": "651de8e6d4009e9fce548fd55e6542e2",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 75,
"avg_line_length": 30.6,
"alnum_prop": 0.6519607843137255,
"repo_name": "chengjun/mywebsite-hugo",
"id": "fce204c384a25825a544e639020a06f00b279e76",
"size": "691",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "themes/academic/archetypes/docs.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "73306"
},
{
"name": "HTML",
"bytes": "13348533"
},
{
"name": "JavaScript",
"bytes": "43691"
},
{
"name": "Jupyter Notebook",
"bytes": "20048"
},
{
"name": "Python",
"bytes": "2512"
},
{
"name": "Shell",
"bytes": "1785"
},
{
"name": "TeX",
"bytes": "1371"
}
],
"symlink_target": ""
} |
package com.twitter.finagle
import com.twitter.concurrent.Once
import com.twitter.finagle.exp.FinagleScheduler
import com.twitter.finagle.util.DefaultLogger
import com.twitter.util.NonFatal
import java.util.Properties
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import java.util.logging.Level
/**
* Global initialization of Finagle.
*/
private[twitter] object Init {
private val log = DefaultLogger
// Used to record Finagle versioning in trace info.
private val unknownVersion = "?"
private val _finagleVersion = new AtomicReference[String](unknownVersion)
def finagleVersion = _finagleVersion.get
private[this] val once = Once {
FinagleScheduler.init()
val p = new Properties
try {
val resource = getClass.getResource("/com/twitter/finagle-core/build.properties")
if (resource == null)
log.log(Level.WARNING, "Finagle's build.properties not found")
else
p.load(resource.openStream())
} catch {
case NonFatal(exc) =>
log.log(Level.WARNING, "Exception while loading finagle's build.properties", exc)
}
_finagleVersion.set(p.getProperty("version", unknownVersion))
log.info("Finagle version %s (rev=%s) built at %s".format(
finagleVersion,
p.getProperty("build_revision", "?"),
p.getProperty("build_name", "?")
))
}
def apply(): Unit = once()
}
| {
"content_hash": "216baf578dcbe37a645a19ebe3b9da58",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 89,
"avg_line_length": 29.617021276595743,
"alnum_prop": 0.7040229885057471,
"repo_name": "Krasnyanskiy/finagle",
"id": "d983a90be8f3d6033ea8e3874d5d2df53c6c6b1d",
"size": "1392",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "finagle-core/src/main/scala/com/twitter/finagle/Init.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "4771"
},
{
"name": "Java",
"bytes": "964871"
},
{
"name": "Python",
"bytes": "44335"
},
{
"name": "Ruby",
"bytes": "23987"
},
{
"name": "Scala",
"bytes": "4217720"
},
{
"name": "Shell",
"bytes": "10011"
},
{
"name": "Thrift",
"bytes": "18518"
}
],
"symlink_target": ""
} |
/* $Id: tif_print.c,v 1.37 2011/04/10 17:14:09 drolon Exp $ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Directory Printing Support
*/
#include "tiffiop.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static const char *photoNames[] = {
"min-is-white", /* PHOTOMETRIC_MINISWHITE */
"min-is-black", /* PHOTOMETRIC_MINISBLACK */
"RGB color", /* PHOTOMETRIC_RGB */
"palette color (RGB from colormap)", /* PHOTOMETRIC_PALETTE */
"transparency mask", /* PHOTOMETRIC_MASK */
"separated", /* PHOTOMETRIC_SEPARATED */
"YCbCr", /* PHOTOMETRIC_YCBCR */
"7 (0x7)",
"CIE L*a*b*", /* PHOTOMETRIC_CIELAB */
};
#define NPHOTONAMES (sizeof (photoNames) / sizeof (photoNames[0]))
static const char *orientNames[] = {
"0 (0x0)",
"row 0 top, col 0 lhs", /* ORIENTATION_TOPLEFT */
"row 0 top, col 0 rhs", /* ORIENTATION_TOPRIGHT */
"row 0 bottom, col 0 rhs", /* ORIENTATION_BOTRIGHT */
"row 0 bottom, col 0 lhs", /* ORIENTATION_BOTLEFT */
"row 0 lhs, col 0 top", /* ORIENTATION_LEFTTOP */
"row 0 rhs, col 0 top", /* ORIENTATION_RIGHTTOP */
"row 0 rhs, col 0 bottom", /* ORIENTATION_RIGHTBOT */
"row 0 lhs, col 0 bottom", /* ORIENTATION_LEFTBOT */
};
#define NORIENTNAMES (sizeof (orientNames) / sizeof (orientNames[0]))
static void
_TIFFPrintField(FILE* fd, const TIFFFieldInfo *fip,
uint32 value_count, void *raw_data)
{
uint32 j;
fprintf(fd, " %s: ", fip->field_name);
for(j = 0; j < value_count; j++) {
if(fip->field_type == TIFF_BYTE)
fprintf(fd, "%u", ((uint8 *) raw_data)[j]);
else if(fip->field_type == TIFF_UNDEFINED)
fprintf(fd, "0x%x",
(unsigned int) ((unsigned char *) raw_data)[j]);
else if(fip->field_type == TIFF_SBYTE)
fprintf(fd, "%d", ((int8 *) raw_data)[j]);
else if(fip->field_type == TIFF_SHORT)
fprintf(fd, "%u", ((uint16 *) raw_data)[j]);
else if(fip->field_type == TIFF_SSHORT)
fprintf(fd, "%d", ((int16 *) raw_data)[j]);
else if(fip->field_type == TIFF_LONG)
fprintf(fd, "%lu",
(unsigned long)((uint32 *) raw_data)[j]);
else if(fip->field_type == TIFF_SLONG)
fprintf(fd, "%ld", (long)((int32 *) raw_data)[j]);
else if(fip->field_type == TIFF_RATIONAL
|| fip->field_type == TIFF_SRATIONAL
|| fip->field_type == TIFF_FLOAT)
fprintf(fd, "%f", ((float *) raw_data)[j]);
else if(fip->field_type == TIFF_IFD)
fprintf(fd, "0x%ulx", ((uint32 *) raw_data)[j]);
else if(fip->field_type == TIFF_ASCII) {
fprintf(fd, "%s", (char *) raw_data);
break;
}
else if(fip->field_type == TIFF_DOUBLE)
fprintf(fd, "%f", ((double *) raw_data)[j]);
else if(fip->field_type == TIFF_FLOAT)
fprintf(fd, "%f", ((float *)raw_data)[j]);
else {
fprintf(fd, "<unsupported data type in TIFFPrint>");
break;
}
if(j < value_count - 1)
fprintf(fd, ",");
}
fprintf(fd, "\n");
}
static int
_TIFFPrettyPrintField(TIFF* tif, FILE* fd, ttag_t tag,
uint32 value_count, void *raw_data)
{
TIFFDirectory *td = &tif->tif_dir;
switch (tag)
{
case TIFFTAG_INKSET:
fprintf(fd, " Ink Set: ");
switch (*((uint16*)raw_data)) {
case INKSET_CMYK:
fprintf(fd, "CMYK\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
*((uint16*)raw_data),
*((uint16*)raw_data));
break;
}
return 1;
case TIFFTAG_WHITEPOINT:
fprintf(fd, " White Point: %g-%g\n",
((float *)raw_data)[0], ((float *)raw_data)[1]); return 1;
case TIFFTAG_REFERENCEBLACKWHITE:
{
uint16 i;
fprintf(fd, " Reference Black/White:\n");
for (i = 0; i < 3; i++)
fprintf(fd, " %2d: %5g %5g\n", i,
((float *)raw_data)[2*i+0],
((float *)raw_data)[2*i+1]);
return 1;
}
case TIFFTAG_XMLPACKET:
{
uint32 i;
fprintf(fd, " XMLPacket (XMP Metadata):\n" );
for(i = 0; i < value_count; i++)
fputc(((char *)raw_data)[i], fd);
fprintf( fd, "\n" );
return 1;
}
case TIFFTAG_RICHTIFFIPTC:
/*
* XXX: for some weird reason RichTIFFIPTC tag
* defined as array of LONG values.
*/
fprintf(fd,
" RichTIFFIPTC Data: <present>, %lu bytes\n",
(unsigned long) value_count * 4);
return 1;
case TIFFTAG_PHOTOSHOP:
fprintf(fd, " Photoshop Data: <present>, %lu bytes\n",
(unsigned long) value_count);
return 1;
case TIFFTAG_ICCPROFILE:
fprintf(fd, " ICC Profile: <present>, %lu bytes\n",
(unsigned long) value_count);
return 1;
case TIFFTAG_STONITS:
fprintf(fd,
" Sample to Nits conversion factor: %.4e\n",
*((double*)raw_data));
return 1;
}
return 0;
}
/*
* Print the contents of the current directory
* to the specified stdio file stream.
*/
void
TIFFPrintDirectory(TIFF* tif, FILE* fd, long flags)
{
TIFFDirectory *td = &tif->tif_dir;
char *sep;
uint16 i;
long l, n;
fprintf(fd, "TIFF Directory at offset 0x%lx (%lu)\n",
(unsigned long)tif->tif_diroff, (unsigned long)tif->tif_diroff);
if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) {
fprintf(fd, " Subfile Type:");
sep = " ";
if (td->td_subfiletype & FILETYPE_REDUCEDIMAGE) {
fprintf(fd, "%sreduced-resolution image", sep);
sep = "/";
}
if (td->td_subfiletype & FILETYPE_PAGE) {
fprintf(fd, "%smulti-page document", sep);
sep = "/";
}
if (td->td_subfiletype & FILETYPE_MASK)
fprintf(fd, "%stransparency mask", sep);
fprintf(fd, " (%lu = 0x%lx)\n",
(long) td->td_subfiletype, (long) td->td_subfiletype);
}
if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) {
fprintf(fd, " Image Width: %lu Image Length: %lu",
(unsigned long) td->td_imagewidth, (unsigned long) td->td_imagelength);
if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH))
fprintf(fd, " Image Depth: %lu",
(unsigned long) td->td_imagedepth);
fprintf(fd, "\n");
}
if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) {
fprintf(fd, " Tile Width: %lu Tile Length: %lu",
(unsigned long) td->td_tilewidth, (unsigned long) td->td_tilelength);
if (TIFFFieldSet(tif,FIELD_TILEDEPTH))
fprintf(fd, " Tile Depth: %lu",
(unsigned long) td->td_tiledepth);
fprintf(fd, "\n");
}
if (TIFFFieldSet(tif,FIELD_RESOLUTION)) {
fprintf(fd, " Resolution: %g, %g",
td->td_xresolution, td->td_yresolution);
if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) {
switch (td->td_resolutionunit) {
case RESUNIT_NONE:
fprintf(fd, " (unitless)");
break;
case RESUNIT_INCH:
fprintf(fd, " pixels/inch");
break;
case RESUNIT_CENTIMETER:
fprintf(fd, " pixels/cm");
break;
default:
fprintf(fd, " (unit %u = 0x%x)",
td->td_resolutionunit,
td->td_resolutionunit);
break;
}
}
fprintf(fd, "\n");
}
if (TIFFFieldSet(tif,FIELD_POSITION))
fprintf(fd, " Position: %g, %g\n",
td->td_xposition, td->td_yposition);
if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE))
fprintf(fd, " Bits/Sample: %u\n", td->td_bitspersample);
if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) {
fprintf(fd, " Sample Format: ");
switch (td->td_sampleformat) {
case SAMPLEFORMAT_VOID:
fprintf(fd, "void\n");
break;
case SAMPLEFORMAT_INT:
fprintf(fd, "signed integer\n");
break;
case SAMPLEFORMAT_UINT:
fprintf(fd, "unsigned integer\n");
break;
case SAMPLEFORMAT_IEEEFP:
fprintf(fd, "IEEE floating point\n");
break;
case SAMPLEFORMAT_COMPLEXINT:
fprintf(fd, "complex signed integer\n");
break;
case SAMPLEFORMAT_COMPLEXIEEEFP:
fprintf(fd, "complex IEEE floating point\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_sampleformat, td->td_sampleformat);
break;
}
}
if (TIFFFieldSet(tif,FIELD_COMPRESSION)) {
const TIFFCodec* c = TIFFFindCODEC(td->td_compression);
fprintf(fd, " Compression Scheme: ");
if (c)
fprintf(fd, "%s\n", c->name);
else
fprintf(fd, "%u (0x%x)\n",
td->td_compression, td->td_compression);
}
if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) {
fprintf(fd, " Photometric Interpretation: ");
if (td->td_photometric < NPHOTONAMES)
fprintf(fd, "%s\n", photoNames[td->td_photometric]);
else {
switch (td->td_photometric) {
case PHOTOMETRIC_LOGL:
fprintf(fd, "CIE Log2(L)\n");
break;
case PHOTOMETRIC_LOGLUV:
fprintf(fd, "CIE Log2(L) (u',v')\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_photometric, td->td_photometric);
break;
}
}
}
if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES) && td->td_extrasamples) {
fprintf(fd, " Extra Samples: %u<", td->td_extrasamples);
sep = "";
for (i = 0; i < td->td_extrasamples; i++) {
switch (td->td_sampleinfo[i]) {
case EXTRASAMPLE_UNSPECIFIED:
fprintf(fd, "%sunspecified", sep);
break;
case EXTRASAMPLE_ASSOCALPHA:
fprintf(fd, "%sassoc-alpha", sep);
break;
case EXTRASAMPLE_UNASSALPHA:
fprintf(fd, "%sunassoc-alpha", sep);
break;
default:
fprintf(fd, "%s%u (0x%x)", sep,
td->td_sampleinfo[i], td->td_sampleinfo[i]);
break;
}
sep = ", ";
}
fprintf(fd, ">\n");
}
if (TIFFFieldSet(tif,FIELD_INKNAMES)) {
char* cp;
fprintf(fd, " Ink Names: ");
i = td->td_samplesperpixel;
sep = "";
for (cp = td->td_inknames; i > 0; cp = strchr(cp,'\0')+1, i--) {
fputs(sep, fd);
_TIFFprintAscii(fd, cp);
sep = ", ";
}
fputs("\n", fd);
}
if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) {
fprintf(fd, " Thresholding: ");
switch (td->td_threshholding) {
case THRESHHOLD_BILEVEL:
fprintf(fd, "bilevel art scan\n");
break;
case THRESHHOLD_HALFTONE:
fprintf(fd, "halftone or dithered scan\n");
break;
case THRESHHOLD_ERRORDIFFUSE:
fprintf(fd, "error diffused\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_threshholding, td->td_threshholding);
break;
}
}
if (TIFFFieldSet(tif,FIELD_FILLORDER)) {
fprintf(fd, " FillOrder: ");
switch (td->td_fillorder) {
case FILLORDER_MSB2LSB:
fprintf(fd, "msb-to-lsb\n");
break;
case FILLORDER_LSB2MSB:
fprintf(fd, "lsb-to-msb\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_fillorder, td->td_fillorder);
break;
}
}
if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING))
{
/*
* For hacky reasons (see tif_jpeg.c - JPEGFixupTestSubsampling),
* we need to fetch this rather than trust what is in our
* structures.
*/
uint16 subsampling[2];
TIFFGetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
subsampling + 0, subsampling + 1 );
fprintf(fd, " YCbCr Subsampling: %u, %u\n",
subsampling[0], subsampling[1] );
}
if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) {
fprintf(fd, " YCbCr Positioning: ");
switch (td->td_ycbcrpositioning) {
case YCBCRPOSITION_CENTERED:
fprintf(fd, "centered\n");
break;
case YCBCRPOSITION_COSITED:
fprintf(fd, "cosited\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_ycbcrpositioning, td->td_ycbcrpositioning);
break;
}
}
if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS))
fprintf(fd, " Halftone Hints: light %u dark %u\n",
td->td_halftonehints[0], td->td_halftonehints[1]);
if (TIFFFieldSet(tif,FIELD_ORIENTATION)) {
fprintf(fd, " Orientation: ");
if (td->td_orientation < NORIENTNAMES)
fprintf(fd, "%s\n", orientNames[td->td_orientation]);
else
fprintf(fd, "%u (0x%x)\n",
td->td_orientation, td->td_orientation);
}
if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL))
fprintf(fd, " Samples/Pixel: %u\n", td->td_samplesperpixel);
if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) {
fprintf(fd, " Rows/Strip: ");
if (td->td_rowsperstrip == (uint32) -1)
fprintf(fd, "(infinite)\n");
else
fprintf(fd, "%lu\n", (unsigned long) td->td_rowsperstrip);
}
if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE))
fprintf(fd, " Min Sample Value: %u\n", td->td_minsamplevalue);
if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE))
fprintf(fd, " Max Sample Value: %u\n", td->td_maxsamplevalue);
if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE))
fprintf(fd, " SMin Sample Value: %g\n",
td->td_sminsamplevalue);
if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE))
fprintf(fd, " SMax Sample Value: %g\n",
td->td_smaxsamplevalue);
if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) {
fprintf(fd, " Planar Configuration: ");
switch (td->td_planarconfig) {
case PLANARCONFIG_CONTIG:
fprintf(fd, "single image plane\n");
break;
case PLANARCONFIG_SEPARATE:
fprintf(fd, "separate image planes\n");
break;
default:
fprintf(fd, "%u (0x%x)\n",
td->td_planarconfig, td->td_planarconfig);
break;
}
}
if (TIFFFieldSet(tif,FIELD_PAGENUMBER))
fprintf(fd, " Page Number: %u-%u\n",
td->td_pagenumber[0], td->td_pagenumber[1]);
if (TIFFFieldSet(tif,FIELD_COLORMAP)) {
fprintf(fd, " Color Map: ");
if (flags & TIFFPRINT_COLORMAP) {
fprintf(fd, "\n");
n = 1L<<td->td_bitspersample;
for (l = 0; l < n; l++)
fprintf(fd, " %5lu: %5u %5u %5u\n",
l,
td->td_colormap[0][l],
td->td_colormap[1][l],
td->td_colormap[2][l]);
} else
fprintf(fd, "(present)\n");
}
if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) {
fprintf(fd, " Transfer Function: ");
if (flags & TIFFPRINT_CURVES) {
fprintf(fd, "\n");
n = 1L<<td->td_bitspersample;
for (l = 0; l < n; l++) {
fprintf(fd, " %2lu: %5u",
l, td->td_transferfunction[0][l]);
for (i = 1; i < td->td_samplesperpixel; i++)
fprintf(fd, " %5u",
td->td_transferfunction[i][l]);
fputc('\n', fd);
}
} else
fprintf(fd, "(present)\n");
}
if (TIFFFieldSet(tif, FIELD_SUBIFD) && (td->td_subifd)) {
fprintf(fd, " SubIFD Offsets:");
for (i = 0; i < td->td_nsubifd; i++)
fprintf(fd, " %5lu", (long) td->td_subifd[i]);
fputc('\n', fd);
}
/*
** Custom tag support.
*/
{
int i;
short count;
count = (short) TIFFGetTagListCount(tif);
for(i = 0; i < count; i++) {
ttag_t tag = TIFFGetTagListEntry(tif, i);
const TIFFFieldInfo *fip;
uint32 value_count;
int mem_alloc = 0;
void *raw_data;
fip = TIFFFieldWithTag(tif, tag);
if(fip == NULL)
continue;
if(fip->field_passcount) {
if(TIFFGetField(tif, tag, &value_count, &raw_data) != 1)
continue;
} else {
if (fip->field_readcount == TIFF_VARIABLE
|| fip->field_readcount == TIFF_VARIABLE2)
value_count = 1;
else if (fip->field_readcount == TIFF_SPP)
value_count = td->td_samplesperpixel;
else
value_count = fip->field_readcount;
if ((fip->field_type == TIFF_ASCII
|| fip->field_readcount == TIFF_VARIABLE
|| fip->field_readcount == TIFF_VARIABLE2
|| fip->field_readcount == TIFF_SPP
|| value_count > 1)
&& fip->field_tag != TIFFTAG_PAGENUMBER
&& fip->field_tag != TIFFTAG_HALFTONEHINTS
&& fip->field_tag != TIFFTAG_YCBCRSUBSAMPLING
&& fip->field_tag != TIFFTAG_DOTRANGE) {
if(TIFFGetField(tif, tag, &raw_data) != 1)
continue;
} else if (fip->field_tag != TIFFTAG_PAGENUMBER
&& fip->field_tag != TIFFTAG_HALFTONEHINTS
&& fip->field_tag != TIFFTAG_YCBCRSUBSAMPLING
&& fip->field_tag != TIFFTAG_DOTRANGE) {
raw_data = _TIFFmalloc(
_TIFFDataSize(fip->field_type)
* value_count);
mem_alloc = 1;
if(TIFFGetField(tif, tag, raw_data) != 1) {
_TIFFfree(raw_data);
continue;
}
} else {
/*
* XXX: Should be fixed and removed, see the
* notes related to TIFFTAG_PAGENUMBER,
* TIFFTAG_HALFTONEHINTS,
* TIFFTAG_YCBCRSUBSAMPLING and
* TIFFTAG_DOTRANGE tags in tif_dir.c. */
char *tmp;
raw_data = _TIFFmalloc(
_TIFFDataSize(fip->field_type)
* value_count);
tmp = raw_data;
mem_alloc = 1;
if(TIFFGetField(tif, tag, tmp,
tmp + _TIFFDataSize(fip->field_type)) != 1) {
_TIFFfree(raw_data);
continue;
}
}
}
/*
* Catch the tags which needs to be specially handled and
* pretty print them. If tag not handled in
* _TIFFPrettyPrintField() fall down and print it as any other
* tag.
*/
if (_TIFFPrettyPrintField(tif, fd, tag, value_count, raw_data)) {
if(mem_alloc)
_TIFFfree(raw_data);
continue;
}
else
_TIFFPrintField(fd, fip, value_count, raw_data);
if(mem_alloc)
_TIFFfree(raw_data);
}
}
if (tif->tif_tagmethods.printdir)
(*tif->tif_tagmethods.printdir)(tif, fd, flags);
if ((flags & TIFFPRINT_STRIPS) &&
TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) {
tstrip_t s;
fprintf(fd, " %lu %s:\n",
(long) td->td_nstrips,
isTiled(tif) ? "Tiles" : "Strips");
for (s = 0; s < td->td_nstrips; s++)
fprintf(fd, " %3lu: [%8lu, %8lu]\n",
(unsigned long) s,
(unsigned long) td->td_stripoffset[s],
(unsigned long) td->td_stripbytecount[s]);
}
}
void
_TIFFprintAscii(FILE* fd, const char* cp)
{
for (; *cp != '\0'; cp++) {
const char* tp;
if (isprint((int)*cp)) {
fputc(*cp, fd);
continue;
}
for (tp = "\tt\bb\rr\nn\vv"; *tp; tp++)
if (*tp++ == *cp)
break;
if (*tp)
fprintf(fd, "\\%c", *tp);
else
fprintf(fd, "\\%03o", *cp & 0xff);
}
}
void
_TIFFprintAsciiTag(FILE* fd, const char* name, const char* value)
{
fprintf(fd, " %s: \"", name);
_TIFFprintAscii(fd, value);
fprintf(fd, "\"\n");
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| {
"content_hash": "36513a040e97d7c0211f80c728187f00",
"timestamp": "",
"source": "github",
"line_count": 642,
"max_line_length": 78,
"avg_line_length": 29.235202492211837,
"alnum_prop": 0.6032820075656667,
"repo_name": "sekys/Carlos",
"id": "016649d558c9f680968926e0d3880ea38dfd3b5a",
"size": "18769",
"binary": false,
"copies": "16",
"ref": "refs/heads/develop",
"path": "libs/include/FreeImage/LibTIFF/tif_print.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8314"
},
{
"name": "C",
"bytes": "20838139"
},
{
"name": "C++",
"bytes": "6295358"
},
{
"name": "Cuda",
"bytes": "58218"
},
{
"name": "Objective-C",
"bytes": "164165"
},
{
"name": "Python",
"bytes": "2198"
}
],
"symlink_target": ""
} |
export class AgreementDiscount {
discount: number;
} | {
"content_hash": "6766a5bcefd741a5243c698af6f92956",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 32,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.75,
"repo_name": "dotnetprofessional/ABusJS",
"id": "3fa18e8990f62f5b28ad6fb4f8c1634a700814f1",
"size": "56",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/abus-bubbles/features/Agreements/model/AgreementDiscount.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1684"
},
{
"name": "HTML",
"bytes": "117"
},
{
"name": "JavaScript",
"bytes": "32262"
},
{
"name": "TypeScript",
"bytes": "342029"
}
],
"symlink_target": ""
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#ifndef EIGEN_SELFADJOINT_PRODUCT_H
#define EIGEN_SELFADJOINT_PRODUCT_H
/**********************************************************************
* This file implements a self adjoint product: C += A A^T updating only
* half of the selfadjoint matrix C.
* It corresponds to the level 3 SYRK Blas routine.
**********************************************************************/
// forward declarations (defined at the end of this file)
template<typename Scalar, typename Index, int mr, int nr, bool ConjLhs, bool ConjRhs, int UpLo>
struct ei_sybb_kernel;
/* Optimized selfadjoint product (_SYRK) */
template <typename Scalar, typename Index,
int RhsStorageOrder,
int ResStorageOrder, bool AAT, int UpLo>
struct ei_selfadjoint_product;
// as usual if the result is row major => we transpose the product
template <typename Scalar, typename Index, int MatStorageOrder, bool AAT, int UpLo>
struct ei_selfadjoint_product<Scalar, Index, MatStorageOrder, RowMajor, AAT, UpLo>
{
static EIGEN_STRONG_INLINE void run(Index size, Index depth, const Scalar* mat, Index matStride, Scalar* res, Index resStride, Scalar alpha)
{
ei_selfadjoint_product<Scalar, Index, MatStorageOrder, ColMajor, !AAT, UpLo==Lower?Upper:Lower>
::run(size, depth, mat, matStride, res, resStride, alpha);
}
};
template <typename Scalar, typename Index,
int MatStorageOrder, bool AAT, int UpLo>
struct ei_selfadjoint_product<Scalar, Index, MatStorageOrder, ColMajor, AAT, UpLo>
{
static EIGEN_DONT_INLINE void run(
Index size, Index depth,
const Scalar* _mat, Index matStride,
Scalar* res, Index resStride,
Scalar alpha)
{
ei_const_blas_data_mapper<Scalar, Index, MatStorageOrder> mat(_mat,matStride);
// if(AAT)
// alpha = ei_conj(alpha);
typedef ei_gebp_traits<Scalar,Scalar> Traits;
Index kc = depth; // cache block size along the K direction
Index mc = size; // cache block size along the M direction
Index nc = size; // cache block size along the N direction
computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc);
// !!! mc must be a multiple of nr:
if(mc>Traits::nr)
mc = (mc/Traits::nr)*Traits::nr;
Scalar* blockA = ei_aligned_stack_new(Scalar, kc*mc);
std::size_t sizeW = kc*Traits::WorkSpaceFactor;
std::size_t sizeB = sizeW + kc*size;
Scalar* allocatedBlockB = ei_aligned_stack_new(Scalar, sizeB);
Scalar* blockB = allocatedBlockB + sizeW;
// note that the actual rhs is the transpose/adjoint of mat
enum {
ConjLhs = NumTraits<Scalar>::IsComplex && !AAT,
ConjRhs = NumTraits<Scalar>::IsComplex && AAT
};
ei_gebp_kernel<Scalar, Scalar, Index, Traits::mr, Traits::nr, ConjLhs, ConjRhs> gebp_kernel;
ei_gemm_pack_rhs<Scalar, Index, Traits::nr,MatStorageOrder==RowMajor ? ColMajor : RowMajor> pack_rhs;
ei_gemm_pack_lhs<Scalar, Index, Traits::mr, Traits::LhsProgress, MatStorageOrder, false> pack_lhs;
ei_sybb_kernel<Scalar, Index, Traits::mr, Traits::nr, ConjLhs, ConjRhs, UpLo> sybb;
for(Index k2=0; k2<depth; k2+=kc)
{
const Index actual_kc = std::min(k2+kc,depth)-k2;
// note that the actual rhs is the transpose/adjoint of mat
pack_rhs(blockB, &mat(0,k2), matStride, actual_kc, size);
for(Index i2=0; i2<size; i2+=mc)
{
const Index actual_mc = std::min(i2+mc,size)-i2;
pack_lhs(blockA, &mat(i2, k2), matStride, actual_kc, actual_mc);
// the selected actual_mc * size panel of res is split into three different part:
// 1 - before the diagonal => processed with gebp or skipped
// 2 - the actual_mc x actual_mc symmetric block => processed with a special kernel
// 3 - after the diagonal => processed with gebp or skipped
if (UpLo==Lower)
gebp_kernel(res+i2, resStride, blockA, blockB, actual_mc, actual_kc, std::min(size,i2), alpha,
-1, -1, 0, 0, allocatedBlockB);
sybb(res+resStride*i2 + i2, resStride, blockA, blockB + actual_kc*i2, actual_mc, actual_kc, alpha, allocatedBlockB);
if (UpLo==Upper)
{
Index j2 = i2+actual_mc;
gebp_kernel(res+resStride*j2+i2, resStride, blockA, blockB+actual_kc*j2, actual_mc, actual_kc, std::max(Index(0), size-j2), alpha,
-1, -1, 0, 0, allocatedBlockB);
}
}
}
ei_aligned_stack_delete(Scalar, blockA, kc*mc);
ei_aligned_stack_delete(Scalar, allocatedBlockB, sizeB);
}
};
// high level API
template<typename MatrixType, unsigned int UpLo>
template<typename DerivedU>
SelfAdjointView<MatrixType,UpLo>& SelfAdjointView<MatrixType,UpLo>
::rankUpdate(const MatrixBase<DerivedU>& u, Scalar alpha)
{
typedef ei_blas_traits<DerivedU> UBlasTraits;
typedef typename UBlasTraits::DirectLinearAccessType ActualUType;
typedef typename ei_cleantype<ActualUType>::type _ActualUType;
const ActualUType actualU = UBlasTraits::extract(u.derived());
Scalar actualAlpha = alpha * UBlasTraits::extractScalarFactor(u.derived());
enum { IsRowMajor = (ei_traits<MatrixType>::Flags&RowMajorBit) ? 1 : 0 };
ei_selfadjoint_product<Scalar, Index,
_ActualUType::Flags&RowMajorBit ? RowMajor : ColMajor,
MatrixType::Flags&RowMajorBit ? RowMajor : ColMajor,
!UBlasTraits::NeedToConjugate, UpLo>
::run(_expression().cols(), actualU.cols(), &actualU.coeff(0,0), actualU.outerStride(),
const_cast<Scalar*>(_expression().data()), _expression().outerStride(), actualAlpha);
return *this;
}
// Optimized SYmmetric packed Block * packed Block product kernel.
// This kernel is built on top of the gebp kernel:
// - the current selfadjoint block (res) is processed per panel of actual_mc x BlockSize
// where BlockSize is set to the minimal value allowing gebp to be as fast as possible
// - then, as usual, each panel is split into three parts along the diagonal,
// the sub blocks above and below the diagonal are processed as usual,
// while the selfadjoint block overlapping the diagonal is evaluated into a
// small temporary buffer which is then accumulated into the result using a
// triangular traversal.
template<typename Scalar, typename Index, int mr, int nr, bool ConjLhs, bool ConjRhs, int UpLo>
struct ei_sybb_kernel
{
enum {
PacketSize = ei_packet_traits<Scalar>::size,
BlockSize = EIGEN_PLAIN_ENUM_MAX(mr,nr)
};
void operator()(Scalar* res, Index resStride, const Scalar* blockA, const Scalar* blockB, Index size, Index depth, Scalar alpha, Scalar* workspace)
{
ei_gebp_kernel<Scalar, Scalar, Index, mr, nr, ConjLhs, ConjRhs> gebp_kernel;
Matrix<Scalar,BlockSize,BlockSize,ColMajor> buffer;
// let's process the block per panel of actual_mc x BlockSize,
// again, each is split into three parts, etc.
for (Index j=0; j<size; j+=BlockSize)
{
Index actualBlockSize = std::min<Index>(BlockSize,size - j);
const Scalar* actual_b = blockB+j*depth;
if(UpLo==Upper)
gebp_kernel(res+j*resStride, resStride, blockA, actual_b, j, depth, actualBlockSize, alpha,
-1, -1, 0, 0, workspace);
// selfadjoint micro block
{
Index i = j;
buffer.setZero();
// 1 - apply the kernel on the temporary buffer
gebp_kernel(buffer.data(), BlockSize, blockA+depth*i, actual_b, actualBlockSize, depth, actualBlockSize, alpha,
-1, -1, 0, 0, workspace);
// 2 - triangular accumulation
for(Index j1=0; j1<actualBlockSize; ++j1)
{
Scalar* r = res + (j+j1)*resStride + i;
for(Index i1=UpLo==Lower ? j1 : 0;
UpLo==Lower ? i1<actualBlockSize : i1<=j1; ++i1)
r[i1] += buffer(i1,j1);
}
}
if(UpLo==Lower)
{
Index i = j+actualBlockSize;
gebp_kernel(res+j*resStride+i, resStride, blockA+depth*i, actual_b, size-i, depth, actualBlockSize, alpha,
-1, -1, 0, 0, workspace);
}
}
}
};
#endif // EIGEN_SELFADJOINT_PRODUCT_H
| {
"content_hash": "93218dea082ca6c7b16d9576bda7f689",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 149,
"avg_line_length": 41.68636363636364,
"alnum_prop": 0.6675389815723476,
"repo_name": "LRMPUT/DiamentowyGrant",
"id": "8f431c2e45cc83c7d1b7c27287298842a3b38315",
"size": "9171",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "NavigationDG/jni/3rdParty/Eigen/src/Core/products/SelfadjointProduct.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "291264"
},
{
"name": "C++",
"bytes": "13785454"
},
{
"name": "CMake",
"bytes": "29391"
},
{
"name": "Java",
"bytes": "420298"
},
{
"name": "Makefile",
"bytes": "8468"
}
],
"symlink_target": ""
} |
<?php
namespace Atlantis\FileSystem;
use
Atlantis as Atlantis,
Nether as Nether,
League as League,
Aws as Aws;
class AwsBucket {
protected
String $PubKey;
protected
String $PrivKey;
protected
String $Region;
protected
String $Bucket;
protected
String $ACL;
protected
Aws\S3\S3Client $Client;
////////////////
////////////////
public function
__Construct($PubKey,$PrivKey,$Region,$Bucket,$ACL) {
$this->PubKey = $PubKey;
$this->PrivKey = $PrivKey;
$this->Region = $Region;
$this->Bucket = $Bucket;
$this->ACL = $ACL;
return;
}
public function
GetAdapter() {
$this->Client = new Aws\S3\S3Client([
'region' => $this->Region,
'version' => 'latest',
'credentials' => [
'key' => $this->PubKey,
'secret' => $this->PrivKey
]
]);
return new League\Flysystem\AwsS3v3\AwsS3Adapter(
$this->Client, $this->Bucket
);
}
public function
GetFileSystem() {
return new League\Flysystem\Filesystem($this->GetAdapter(),[
'visibility' => $this->ACL
]);
}
public function
GetURL(String $Path):
String {
return sprintf(
'https://%s.s3-%s.amazonaws.com/%s',
$this->Bucket,
$this->Region,
$Path
);
}
public function
GetSignedURL(String $Path, String $Expire='+1 Hour'):
String {
$URL = $this->Client->CreatePresignedRequest(
$this->Client->GetCommand('GetObject',[
'Bucket' => $this->Bucket,
'Key' => $Path
]),
$Expire
)->GetURI();
return (String)$URL;
}
}
| {
"content_hash": "f19214fbe4c85876ff912be5053056c3",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 62,
"avg_line_length": 15.204081632653061,
"alnum_prop": 0.6093959731543624,
"repo_name": "bobmagicii/atlantis",
"id": "fb684209eb04387930f74886a14d62f0fcabb966",
"size": "1490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/Atlantis/FileSystem/AwsBucket.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1677"
},
{
"name": "CSS",
"bytes": "13675"
},
{
"name": "HTML",
"bytes": "15679"
},
{
"name": "JavaScript",
"bytes": "247251"
},
{
"name": "PHP",
"bytes": "83712"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>Downloading GCC</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Downloading GCC">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="top" href="#Top">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with no
Invariant Sections, the Front-Cover texts being (a) (see below), and
with the Back-Cover Texts being (b) (see below). A copy of the
license is included in the section entitled "GNU Free Documentation License".
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<h1 class="settitle">Downloading GCC</h1>
<a name="index-Downloading-GCC-1"></a><a name="index-Downloading-the-Source-2"></a>
GCC is distributed via <a href="http://gcc.gnu.org/svn.html">SVN</a> and FTP
tarballs compressed with <samp><span class="command">gzip</span></samp> or
<samp><span class="command">bzip2</span></samp>. It is possible to download a full distribution or specific
components.
<p>Please refer to the <a href="http://gcc.gnu.org/releases.html">releases web page</a>
for information on how to obtain GCC.
<p>The full distribution includes the C, C++, Objective-C, Fortran, Java,
and Ada (in the case of GCC 3.1 and later) compilers. The full
distribution also includes runtime libraries for C++, Objective-C,
Fortran, and Java. In GCC 3.0 and later versions, the GNU compiler
testsuites are also included in the full distribution.
<p>If you choose to download specific components, you must download the core
GCC distribution plus any language specific distributions you wish to
use. The core distribution includes the C language front end as well as the
shared components. Each language has a tarball which includes the language
front end as well as the language runtime (when appropriate).
<p>Unpack the core distribution as well as any language specific
distributions in the same directory.
<p>If you also intend to build binutils (either to upgrade an existing
installation or for use in place of the corresponding tools of your
OS), unpack the binutils distribution either in the same directory or
a separate one. In the latter case, add symbolic links to any
components of the binutils you intend to build alongside the compiler
(<samp><span class="file">bfd</span></samp>, <samp><span class="file">binutils</span></samp>, <samp><span class="file">gas</span></samp>, <samp><span class="file">gprof</span></samp>, <samp><span class="file">ld</span></samp>,
<samp><span class="file">opcodes</span></samp>, <small class="dots">...</small>) to the directory containing the GCC sources.
<p><hr />
<p><a href="./index.html">Return to the GCC Installation page</a>
<!-- ***Configuration*********************************************************** -->
<!-- ***Building**************************************************************** -->
<!-- ***Testing***************************************************************** -->
<!-- ***Final install*********************************************************** -->
<!-- ***Binaries**************************************************************** -->
<!-- ***Specific**************************************************************** -->
<!-- ***Old documentation****************************************************** -->
<!-- ***GFDL******************************************************************** -->
<!-- *************************************************************************** -->
<!-- Part 6 The End of the Document -->
</body></html>
| {
"content_hash": "ffece079958d4a09dab8a44eaeea60bf",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 226,
"avg_line_length": 51.955555555555556,
"alnum_prop": 0.6278870829769033,
"repo_name": "shaotuanchen/sunflower_exp",
"id": "962715647941e172ab06d38ea338f3412acf51c3",
"size": "4676",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tools/source/gcc-4.2.4/INSTALL/download.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "459993"
},
{
"name": "Awk",
"bytes": "6562"
},
{
"name": "Batchfile",
"bytes": "9028"
},
{
"name": "C",
"bytes": "50326113"
},
{
"name": "C++",
"bytes": "2040239"
},
{
"name": "CSS",
"bytes": "2355"
},
{
"name": "Clarion",
"bytes": "2484"
},
{
"name": "Coq",
"bytes": "61440"
},
{
"name": "DIGITAL Command Language",
"bytes": "69150"
},
{
"name": "Emacs Lisp",
"bytes": "186910"
},
{
"name": "Fortran",
"bytes": "5364"
},
{
"name": "HTML",
"bytes": "2171356"
},
{
"name": "JavaScript",
"bytes": "27164"
},
{
"name": "Logos",
"bytes": "159114"
},
{
"name": "M",
"bytes": "109006"
},
{
"name": "M4",
"bytes": "100614"
},
{
"name": "Makefile",
"bytes": "5409865"
},
{
"name": "Mercury",
"bytes": "702"
},
{
"name": "Module Management System",
"bytes": "56956"
},
{
"name": "OCaml",
"bytes": "253115"
},
{
"name": "Objective-C",
"bytes": "57800"
},
{
"name": "Papyrus",
"bytes": "3298"
},
{
"name": "Perl",
"bytes": "70992"
},
{
"name": "Perl 6",
"bytes": "693"
},
{
"name": "PostScript",
"bytes": "3440120"
},
{
"name": "Python",
"bytes": "40729"
},
{
"name": "Redcode",
"bytes": "1140"
},
{
"name": "Roff",
"bytes": "3794721"
},
{
"name": "SAS",
"bytes": "56770"
},
{
"name": "SRecode Template",
"bytes": "540157"
},
{
"name": "Shell",
"bytes": "1560436"
},
{
"name": "Smalltalk",
"bytes": "10124"
},
{
"name": "Standard ML",
"bytes": "1212"
},
{
"name": "TeX",
"bytes": "385584"
},
{
"name": "WebAssembly",
"bytes": "52904"
},
{
"name": "Yacc",
"bytes": "510934"
}
],
"symlink_target": ""
} |
package org.apereo.cas.mfa.simple.web.flow;
import org.apereo.cas.authentication.adaptive.UnauthorizedAuthenticationException;
import org.apereo.cas.configuration.model.support.mfa.CasSimpleMultifactorProperties;
import org.apereo.cas.ticket.TransientSessionTicketFactory;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.util.io.CommunicationsManager;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.support.WebUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.action.EventFactorySupport;
import org.springframework.webflow.core.collection.LocalAttributeMap;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
/**
* This is {@link CasSimpleSendTokenAction}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Slf4j
@RequiredArgsConstructor
public class CasSimpleSendTokenAction extends AbstractAction {
private final TicketRegistry ticketRegistry;
private final CommunicationsManager communicationsManager;
private final TransientSessionTicketFactory ticketFactory;
private final CasSimpleMultifactorProperties properties;
@Override
protected Event doExecute(final RequestContext requestContext) {
val service = WebUtils.getService(requestContext);
val token = ticketFactory.create(service);
val authentication = WebUtils.getInProgressAuthentication();
val principal = authentication.getPrincipal();
val smsProperties = properties.getSms();
val text = StringUtils.isNotBlank(smsProperties.getText())
? String.format(smsProperties.getText(), token.getId())
: token.getId();
val emailProperties = properties.getMail();
val body = emailProperties.getFormattedBody(token.getId());
val smsSent = communicationsManager.sms(principal, smsProperties.getAttributeName(), text, smsProperties.getFrom());
val emailSent = communicationsManager.email(principal, emailProperties.getAttributeName(), emailProperties, body);
if (smsSent || emailSent) {
ticketRegistry.addTicket(token);
LOGGER.debug("Successfully submitted token via SMS and/or email to [{}]", principal.getId());
val attributes = new LocalAttributeMap("token", token.getId());
return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_SUCCESS, attributes);
}
throw new UnauthorizedAuthenticationException("Both email and SMS communication strategies failed to submit token to user");
}
}
| {
"content_hash": "1fa73a3f93c37f8eb685d3634e973556",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 132,
"avg_line_length": 44.83870967741935,
"alnum_prop": 0.766546762589928,
"repo_name": "philliprower/cas",
"id": "8064c0c738f8a83626eb1dab20c645a1451d51b0",
"size": "2780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "support/cas-server-support-simple-mfa/src/main/java/org/apereo/cas/mfa/simple/web/flow/CasSimpleSendTokenAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "750333"
},
{
"name": "Dockerfile",
"bytes": "2544"
},
{
"name": "Groovy",
"bytes": "19040"
},
{
"name": "HTML",
"bytes": "408841"
},
{
"name": "Java",
"bytes": "15178582"
},
{
"name": "JavaScript",
"bytes": "206200"
},
{
"name": "Python",
"bytes": "140"
},
{
"name": "Ruby",
"bytes": "1417"
},
{
"name": "Shell",
"bytes": "131196"
},
{
"name": "TypeScript",
"bytes": "251817"
}
],
"symlink_target": ""
} |
<?php
//twitterの全ログファイルからベースデータへ
date_default_timezone_set('Asia/Tokyo');
$ini_array = parse_ini_file(dirname(__FILE__) . "/../setting.ini");
$handle = new SQLite3($ini_array['sqlite_file']);
var_dump($argv);
$dh = opendir($argv[1]);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
foreach ($files as $value) {
if (strpos($value, '.js') > 1) {
hoge($argv[1] . '/' . $value, $handle, $argv[2]);
}
}
function hoge($path, $handle, $site) {
$aaa = file_get_contents($path, NULL, NULL, 32);
$bbb = json_decode($aaa, TRUE);
$query = 'INSERT INTO basedata (site,identifier,datetime,title,tags,body) VALUES ';
foreach ($bbb as $value) {
$timestamp = strtotime($value['created_at']);
$identifier = date('YmdHis000000', $timestamp);
if ($identifierold == $identifier) {
$identifier++;
} else {
$identifierold = $identifier;
}
$title = $identifier;
$datetime = date('Y-m-d H:i:s', $timestamp);
$tags = ' twitter_posted:' . $value['id'];
foreach ($value['entities']['hashtags'] as $value2) {
$tags .= ' #' . $value2['text'];
}
$tags .= ' ';
$body = SQLite3::escapeString($value['text']);
if (strpos($body, 'RT @') !== 0) {
$query .= "\n('$site','$identifier','$datetime','$title','$tags','$body'),";
}
}
$query = substr($query, 0, -1);
var_dump($query);
$result = $handle->query($query);
}
| {
"content_hash": "9e87472fe5eaa71be333b8597161cc1e",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 84,
"avg_line_length": 25.27777777777778,
"alnum_prop": 0.5904761904761905,
"repo_name": "ayziao/niascape",
"id": "175ac4175e87753d663ab6eecb455d4014622132",
"size": "1399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "試作/cli/twitter2basedata.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1212"
},
{
"name": "HTML",
"bytes": "10084"
},
{
"name": "PHP",
"bytes": "68163"
},
{
"name": "Python",
"bytes": "104176"
},
{
"name": "Shell",
"bytes": "608"
},
{
"name": "TSQL",
"bytes": "940"
}
],
"symlink_target": ""
} |
package etcd
import (
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/apis/extensions"
metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
genericapirequest "k8s.io/kubernetes/pkg/genericapiserver/api/request"
"k8s.io/kubernetes/pkg/registry/extensions/daemonset"
"k8s.io/kubernetes/pkg/registry/generic"
genericregistry "k8s.io/kubernetes/pkg/registry/generic/registry"
"k8s.io/kubernetes/pkg/runtime"
)
// rest implements a RESTStorage for DaemonSets against etcd
type REST struct {
*genericregistry.Store
}
// NewREST returns a RESTStorage object that will work against DaemonSets.
func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST) {
store := &genericregistry.Store{
NewFunc: func() runtime.Object { return &extensions.DaemonSet{} },
NewListFunc: func() runtime.Object { return &extensions.DaemonSetList{} },
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*extensions.DaemonSet).Name, nil
},
PredicateFunc: daemonset.MatchDaemonSet,
QualifiedResource: extensions.Resource("daemonsets"),
CreateStrategy: daemonset.Strategy,
UpdateStrategy: daemonset.Strategy,
DeleteStrategy: daemonset.Strategy,
}
options := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: daemonset.GetAttrs}
if err := store.CompleteWithOptions(options); err != nil {
panic(err) // TODO: Propagate error up
}
statusStore := *store
statusStore.UpdateStrategy = daemonset.StatusStrategy
return &REST{store}, &StatusREST{store: &statusStore}
}
// StatusREST implements the REST endpoint for changing the status of a daemonset
type StatusREST struct {
store *genericregistry.Store
}
func (r *StatusREST) New() runtime.Object {
return &extensions.DaemonSet{}
}
// Get retrieves the object from the storage. It is required to support Patch.
func (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
return r.store.Get(ctx, name, options)
}
// Update alters the status subset of an object.
func (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {
return r.store.Update(ctx, name, objInfo)
}
| {
"content_hash": "ac5cc3ef59dfa522dc8b82a444ab4d2d",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 135,
"avg_line_length": 34.640625,
"alnum_prop": 0.7645466847090663,
"repo_name": "emaildanwilson/kubernetes",
"id": "df210cab5efb1d7e78a53068cff6dc62620c83d0",
"size": "2786",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "pkg/registry/extensions/daemonset/etcd/etcd.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "978"
},
{
"name": "Go",
"bytes": "41037989"
},
{
"name": "HTML",
"bytes": "2587634"
},
{
"name": "Makefile",
"bytes": "77263"
},
{
"name": "Nginx",
"bytes": "1608"
},
{
"name": "Protocol Buffer",
"bytes": "590879"
},
{
"name": "Python",
"bytes": "1035558"
},
{
"name": "SaltStack",
"bytes": "54967"
},
{
"name": "Shell",
"bytes": "1620022"
}
],
"symlink_target": ""
} |
<?php
namespace Commentaires\CommentairesBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CommentairesBundle extends Bundle
{
}
| {
"content_hash": "9725623bc01ae4a21afa715b341ea9bc",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 16,
"alnum_prop": 0.8263888888888888,
"repo_name": "psykoterro/eCommerce_Symfony_3",
"id": "5bc69a27998a930887075e0cf317dcc07ba398bf",
"size": "144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Commentaires/CommentairesBundle/CommentairesBundle.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "246978"
},
{
"name": "HTML",
"bytes": "385979"
},
{
"name": "JavaScript",
"bytes": "26275"
},
{
"name": "PHP",
"bytes": "204294"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="21dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="21dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/image_alarm_thumbnail"
android:layout_width="44dp"
android:layout_height="44dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="21dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/text_alarm_content"
style="@style/FontTheme.R"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="6sp"
android:textColor="@color/colorDarkBlack"
android:textSize="12sp" />
</LinearLayout>
<TextView
style="@style/FontTheme.R"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:gravity="center"
android:lineSpacingExtra="4sp"
android:paddingBottom="4dp"
android:paddingEnd="14dp"
android:paddingStart="14dp"
android:paddingTop="4dp"
android:text="accept"
android:textColor="@color/colorWhite"
android:textSize="14sp"
android:visibility="invisible" />
</LinearLayout> | {
"content_hash": "fbc3c2759da56ef5523dd2969cbcc270",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 72,
"avg_line_length": 34.254901960784316,
"alnum_prop": 0.6445334859759588,
"repo_name": "yh-kim/gachi-android",
"id": "7ac1fb53a1aed678af6adb5b16e2003f1fa401f4",
"size": "1747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gachi/app/src/main/res/layout/item_alarm0.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "IDL",
"bytes": "1079"
},
{
"name": "Kotlin",
"bytes": "184446"
},
{
"name": "Prolog",
"bytes": "464"
}
],
"symlink_target": ""
} |
(function($){
//feature detection
var hasPlaceholder = 'placeholder' in document.createElement('input');
//sniffy sniff sniff -- just to give extra left padding for the older
//graphics for type=email and type=url
var isOldOpera = $.browser.opera && $.browser.version < 10.5;
$.fn.placeholder = function(options) {
//merge in passed in options, if any
var options = $.extend({}, $.fn.placeholder.defaults, options),
//cache the original 'left' value, for use by Opera later
o_left = options.placeholderCSS.left;
//first test for native placeholder support before continuing
//feature detection inspired by ye olde jquery 1.4 hawtness, with paul irish
return (hasPlaceholder) ? this : this.each(function() {
//TODO: if this element already has a placeholder, exit
//local vars
var $this = $(this),
inputVal = $.trim($this.val()),
inputWidth = $this.width(),
inputHeight = $this.height(),
//grab the inputs id for the <label @for>, or make a new one from the Date
inputId = (this.id) ? this.id : 'placeholder' + (Math.floor(Math.random() * 1123456789)),
placeholderText = $this.attr('placeholder'),
placeholder = $('<label for='+ inputId +'>'+ placeholderText + '</label>');
//stuff in some calculated values into the placeholderCSS object
options.placeholderCSS['width'] = inputWidth;
options.placeholderCSS['height'] = inputHeight;
options.placeholderCSS['color'] = options.color;
// adjust position of placeholder
options.placeholderCSS.left = (isOldOpera && (this.type == 'email' || this.type == 'url')) ?
'11%' : o_left;
placeholder.css(options.placeholderCSS);
//place the placeholder
$this.wrap(options.inputWrapper);
$this.attr('id', inputId).after(placeholder);
//if the input isn't empty
if (inputVal){
placeholder.hide();
};
//hide placeholder on focus
$this.focus(function(){
if (!$.trim($this.val())){
placeholder.hide();
};
});
//show placeholder if the input is empty
$this.blur(function(){
if (!$.trim($this.val())){
placeholder.show();
};
});
});
};
//expose defaults
$.fn.placeholder.defaults = {
//you can pass in a custom wrapper
inputWrapper: '<span style="position:relative; display:block;"></span>',
//more or less just emulating what webkit does here
//tweak to your hearts content
placeholderCSS: {
'font':'0.75em sans-serif',
'color':'#bababa',
'position': 'absolute',
'left':'5px',
'top':'3px',
'overflow-x': 'hidden',
'display': 'block'
}
};
})(jQuery);
$(function(){
$(':input[placeholder]').placeholder();
});
| {
"content_hash": "3460442e371584ed68ae29884e750d4f",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 99,
"avg_line_length": 33.2183908045977,
"alnum_prop": 0.5961937716262976,
"repo_name": "engineer-itpnu/E-Learning",
"id": "a85fcbb32a5509e269edeb98ae5f8c6de0fe898f",
"size": "3304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/bundles/elearningmain/js/html5placeholder.jquery.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2164745"
},
{
"name": "JavaScript",
"bytes": "4017499"
},
{
"name": "PHP",
"bytes": "133753"
},
{
"name": "Shell",
"bytes": "182"
}
],
"symlink_target": ""
} |
package org.semanticweb.elk.matching.inferences;
import java.util.Collections;
import org.semanticweb.elk.matching.conclusions.ConclusionMatchExpressionFactory;
import org.semanticweb.elk.matching.conclusions.SubClassInclusionComposedMatch1;
import org.semanticweb.elk.matching.conclusions.SubClassInclusionComposedMatch1Watch;
import org.semanticweb.elk.matching.root.IndexedContextRootMatch;
import org.semanticweb.elk.owl.interfaces.ElkClassExpression;
import org.semanticweb.elk.reasoner.saturation.conclusions.model.SubClassInclusionComposed;
public class SubClassInclusionComposedEmptyObjectUnionOfMatch1
extends AbstractSubClassInclusionComposedCanonizerMatch1
implements SubClassInclusionComposedMatch1Watch {
SubClassInclusionComposedEmptyObjectUnionOfMatch1(
SubClassInclusionComposed parent,
IndexedContextRootMatch destinationMatch) {
super(parent, destinationMatch);
}
@Override
public SubClassInclusionComposedMatch1 getPremiseMatch(
ConclusionMatchExpressionFactory factory) {
return factory.getSubClassInclusionComposedMatch1(getParent(),
getDestinationMatch(), factory.getOwlNothing());
}
@Override
SubClassInclusionComposedMatch1 getConclusionMatch(
ConclusionMatchExpressionFactory factory) {
return factory.getSubClassInclusionComposedMatch1(getParent(),
getDestinationMatch(), factory.getObjectUnionOf(
Collections.<ElkClassExpression> emptyList()));
}
@Override
public <O> O accept(InferenceMatch.Visitor<O> visitor) {
return visitor.visit(this);
}
@Override
public <O> O accept(
SubClassInclusionComposedMatch1Watch.Visitor<O> visitor) {
return visitor.visit(this);
}
/**
* The visitor pattern for instances
*
* @author Yevgeny Kazakov
*
* @param <O>
* the type of the output
*/
public interface Visitor<O> {
O visit(SubClassInclusionComposedEmptyObjectUnionOfMatch1 inferenceMatch1);
}
/**
* A factory for creating instances
*
* @author Yevgeny Kazakov
*
*/
public interface Factory {
SubClassInclusionComposedEmptyObjectUnionOfMatch1 getSubClassInclusionComposedEmptyObjectUnionOfMatch1(
SubClassInclusionComposed parent,
IndexedContextRootMatch destinationMatch);
}
}
| {
"content_hash": "b1ac1a0cd759bfd41f1597cb837f9c08",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 105,
"avg_line_length": 28.151898734177216,
"alnum_prop": 0.8066546762589928,
"repo_name": "live-ontologies/elk-reasoner",
"id": "05200396c219bfb0f6820cfe84675982e0c3649d",
"size": "2942",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "elk-proofs/src/main/java/org/semanticweb/elk/matching/inferences/SubClassInclusionComposedEmptyObjectUnionOfMatch1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "42367"
},
{
"name": "Java",
"bytes": "4027459"
},
{
"name": "Web Ontology Language",
"bytes": "41202"
}
],
"symlink_target": ""
} |
/*
* The following is auto-generated. Do not manually edit. See scripts/loops.js.
*/
#include "stdlib/strided/base/nullary/d_as_b.h"
#include "stdlib/strided/base/nullary/macros.h"
#include <stdint.h>
/**
* Applies a nullary callback and assigns results to elements in a strided output array.
*
* @param arrays array whose only element is a pointer to a strided output array
* @param shape array whose only element is the number of elements over which to iterate
* @param strides array containing strides (in bytes) for each strided array
* @param fcn callback
*
* @example
* #include "stdlib/strided/base/nullary/d_as_b.h"
* #include <stdint.h>
*
* // Create underlying byte arrays:
* uint8_t out[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define a pointer to an array containing pointers to strided arrays:
* uint8_t *arrays[] = { out };
*
* // Define the strides:
* int64_t strides[] = { 8 };
*
* // Define the number of elements over which to iterate:
* int64_t shape[] = { 3 };
*
* // Define a callback:
* uint8_t fcn() {
* return 3;
* }
*
* // Apply the callback:
* stdlib_strided_d_as_b( arrays, shape, strides, (void *)fcn );
*/
void stdlib_strided_d_as_b( uint8_t *arrays[], int64_t *shape, int64_t *strides, void *fcn ) {
typedef uint8_t func_type();
func_type *f = (func_type *)fcn;
STDLIB_STRIDED_NULLARY_LOOP_CLBK( double )
}
| {
"content_hash": "9c56bc1c2d61c8bdaeb2df8796084c5e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 94,
"avg_line_length": 29.893617021276597,
"alnum_prop": 0.6612099644128114,
"repo_name": "stdlib-js/stdlib",
"id": "65b48197f1f3d22d38f7dd81b0e20943667b28d9",
"size": "2021",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/node_modules/@stdlib/strided/base/nullary/src/d_as_b.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "21739"
},
{
"name": "C",
"bytes": "15336495"
},
{
"name": "C++",
"bytes": "1349482"
},
{
"name": "CSS",
"bytes": "58039"
},
{
"name": "Fortran",
"bytes": "198059"
},
{
"name": "HTML",
"bytes": "56181"
},
{
"name": "Handlebars",
"bytes": "16114"
},
{
"name": "JavaScript",
"bytes": "85975525"
},
{
"name": "Julia",
"bytes": "1508654"
},
{
"name": "Makefile",
"bytes": "4806816"
},
{
"name": "Python",
"bytes": "3343697"
},
{
"name": "R",
"bytes": "576612"
},
{
"name": "Shell",
"bytes": "559315"
},
{
"name": "TypeScript",
"bytes": "19309407"
},
{
"name": "WebAssembly",
"bytes": "5980"
}
],
"symlink_target": ""
} |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_user_device_group
except ImportError:
pytest.skip("Could not load required modules for testing", allow_module_level=True)
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_user_device_group.Connection')
return connection_class_mock
fos_instance = FortiOSHandler(connection_mock)
def test_user_device_group_creation(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'user_device_group': {
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
expected_data = {
'comment': 'Comment.',
'name': 'default_name_4',
}
set_method_mock.assert_called_with('user', 'device-group', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert changed
assert response['status'] == 'success'
assert response['http_status'] == 200
def test_user_device_group_creation_fails(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'user_device_group': {
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
expected_data = {
'comment': 'Comment.',
'name': 'default_name_4',
}
set_method_mock.assert_called_with('user', 'device-group', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert is_error
assert not changed
assert response['status'] == 'error'
assert response['http_status'] == 500
def test_user_device_group_removal(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
delete_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result)
input_data = {
'username': 'admin',
'state': 'absent',
'user_device_group': {
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
delete_method_mock.assert_called_with('user', 'device-group', mkey=ANY, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert changed
assert response['status'] == 'success'
assert response['http_status'] == 200
def test_user_device_group_deletion_fails(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
delete_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500}
delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result)
input_data = {
'username': 'admin',
'state': 'absent',
'user_device_group': {
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
delete_method_mock.assert_called_with('user', 'device-group', mkey=ANY, vdom='root')
schema_method_mock.assert_not_called()
assert is_error
assert not changed
assert response['status'] == 'error'
assert response['http_status'] == 500
def test_user_device_group_idempotent(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'user_device_group': {
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
expected_data = {
'comment': 'Comment.',
'name': 'default_name_4',
}
set_method_mock.assert_called_with('user', 'device-group', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert not changed
assert response['status'] == 'error'
assert response['http_status'] == 404
def test_user_device_group_filter_foreign_attributes(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'user_device_group': {
'random_attribute_not_valid': 'tag',
'comment': 'Comment.',
'name': 'default_name_4',
},
'vdom': 'root'}
is_error, changed, response = fortios_user_device_group.fortios_user(input_data, fos_instance)
expected_data = {
'comment': 'Comment.',
'name': 'default_name_4',
}
set_method_mock.assert_called_with('user', 'device-group', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert changed
assert response['status'] == 'success'
assert response['http_status'] == 200
| {
"content_hash": "65c589f78cf64cc46338af3fc10d3078",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 142,
"avg_line_length": 34.02463054187192,
"alnum_prop": 0.6525264224699581,
"repo_name": "thaim/ansible",
"id": "c5f79f6c4c98633e5472e6f21dead9a8f0399c97",
"size": "7603",
"binary": false,
"copies": "20",
"ref": "refs/heads/fix-broken-link",
"path": "test/units/modules/network/fortios/test_fortios_user_device_group.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "246"
}
],
"symlink_target": ""
} |
package cz.metacentrum.perun.core.api;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.NumericField;
import java.io.Serializable;
/**
* Holder of an attribute. Represents who does the attribute belong to. Holder is identified by id and type (member, group..)
*
* @author Simona Kruppova
*/
@Indexed
public class Holder implements Serializable {
@Field
@NumericField
private int id;
@Field(analyze = Analyze.NO)
private HolderType type;
public enum HolderType {
FACILITY, MEMBER, VO, GROUP, HOST, RESOURCE, USER, UES
}
public Holder(int id, HolderType type) {
this.id = id;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public HolderType getType() {
return type;
}
public void setType(HolderType type) {
this.type = type;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Holder{");
sb.append("id=").append(id);
sb.append(", type=").append(type);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Holder holder = (Holder) o;
if (id != holder.id) return false;
if (type != holder.type) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + type.hashCode();
return result;
}
}
| {
"content_hash": "9924907395a780007b0efcf1e295ca4a",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 125,
"avg_line_length": 20.155844155844157,
"alnum_prop": 0.6881443298969072,
"repo_name": "stavamichal/perun",
"id": "85ff8a8304257087cff24a4abaa427c4e7483b4c",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "perun-base/src/main/java/cz/metacentrum/perun/core/api/Holder.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "100498"
},
{
"name": "FreeMarker",
"bytes": "380"
},
{
"name": "HTML",
"bytes": "160359"
},
{
"name": "Java",
"bytes": "16315666"
},
{
"name": "JavaScript",
"bytes": "190155"
},
{
"name": "PHP",
"bytes": "5902"
},
{
"name": "PLSQL",
"bytes": "84213"
},
{
"name": "PLpgSQL",
"bytes": "5267"
},
{
"name": "Perl",
"bytes": "808774"
},
{
"name": "Python",
"bytes": "4106"
},
{
"name": "Shell",
"bytes": "32682"
}
],
"symlink_target": ""
} |
package boltcluster
import (
"log"
"os"
)
// Logger makes able to set Verbosity using the standard logger
type Logger struct {
logger *log.Logger
Verbosity bool
}
func newLogger() *Logger {
return &Logger{logger: log.New(os.Stderr, "Cluster - ", log.LstdFlags), Verbosity: false}
}
// Printf calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Printf.
func (l *Logger) Printf(format string, v ...interface{}) {
if l.Verbosity {
l.logger.Printf(format, v...)
}
}
// Print calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Print.
func (l *Logger) Print(v ...interface{}) {
if l.Verbosity {
l.logger.Print(v...)
}
}
// Println calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Println.
func (l *Logger) Println(v ...interface{}) {
if l.Verbosity {
l.logger.Println(v...)
}
}
// Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
func (l *Logger) Fatal(v ...interface{}) {
if l.Verbosity {
l.logger.Fatal(v...)
}
}
// Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
func (l *Logger) Fatalf(format string, v ...interface{}) {
if l.Verbosity {
l.logger.Fatalf(format, v...)
}
}
// Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
func (l *Logger) Fatalln(v ...interface{}) {
if l.Verbosity {
l.logger.Fatalln(v...)
}
}
| {
"content_hash": "0ae67560289dab29ac162d778f1157c4",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 90,
"avg_line_length": 23.21311475409836,
"alnum_prop": 0.6680790960451978,
"repo_name": "LxDB/boltcluster",
"id": "84a0186faecbc78dd497ef2910d4408aef9c1894",
"size": "1416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "logger.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "20631"
}
],
"symlink_target": ""
} |
Displays a backtrace for each query in Rails' development console and log.
Allows you to track down where queries are executed in your application.
Useful for performance optimizations and for finding where to start when making
changes to a large application.
When enabled, every query will be logged like:
```
D, [2019-03-03T19:50:41.061115 #25560] DEBUG -- : User Load (0.1ms) SELECT "users".* FROM "users"
D, [2019-03-03T19:50:41.062492 #25560] DEBUG -- : Query Trace:
app/models/concerns/is_active.rb:11:in `active?'
app/models/user.rb:67:in `active?'
app/decorators/concerns/status_methods.rb:42:in `colored_status'
app/views/shared/companies/_user.html.slim:28:in `block in _app_views_users_html_slim___2427456029761612502_70304705622200'
app/views/shared/companies/_user.html.slim:27:in `_app_views_users_html_slim___2427456029761612502_70304705622200'
```
## Requirements
- Ruby >= 2.4;
- Rails 4.2, 5.2, or 6.
## Usage
1. Add the following to your Gemfile:
```ruby
group :development do
gem 'active_record_query_trace'
end
```
2. Create an initializer such as `config/initializers/active_record_query_trace.rb`
to enable the gem. If you want to customize how the gem behaves, you can add any
combination of the following [options](#options) to the initializer as well.
```ruby
if Rails.env.development?
ActiveRecordQueryTrace.enabled = true
# Optional: other gem config options go here
end
```
3. Restart the Rails development server.
## Options
#### Backtrace level
There are three levels of debug.
- `:app` - includes only application trace lines (files in the `Rails.root` directory);
- `:rails` - includes all trace lines except the ones from the application (all files except those in `Rails.root`).
- `:full` - full backtrace (includes all files), useful for debugging gems.
```ruby
ActiveRecordQueryTrace.level = :app # default
```
If you need more control you can provide a custom bactrace cleaner using the `:custom` level. For example:
```ruby
ActiveRecordQueryTrace.level = :custom
require "rails/backtrace_cleaner"
ActiveRecordQueryTrace.backtrace_cleaner = Rails::BacktraceCleaner.new.tap do |bc|
bc.remove_filters!
bc.remove_silencers!
bc.add_silencer { |line| line =~ /\b(active_record_query_trace|active_support|active_record|another_gem)\b/ }
end
```
It's not necessary to create an instance of `Rails::BacktraceCleaner`, you can use any object responding to `#clean` or even
a lambda/proc:
```ruby
ActiveRecordQueryTrace.backtrace_cleaner = ->(trace) {
trace.reject { |line| line =~ /\b(active_record_query_trace|active_support|active_record|another_gem)\b/ }
}
```
#### Display the trace only for read or write queries
You can choose to display the backtrace only for DB reads, writes or both.
- `:all` - display backtrace for all queries;
- `:read` - display backtrace only for DB read operations (SELECT);
- `:write` - display the backtrace only for DB write operations (INSERT, UPDATE, DELETE).
```ruby
ActiveRecordQueryTrace.query_type = :all # default
```
#### Suppress DB read queries
If set to `true`, this option will suppress all log lines generated by DB
read (SELECT) operations, leaving only the lines generated by DB write queries
(INSERT, UPDATE, DELETE). **Beware, the entire log line is suppressed, not only
the backtrace.** Useful to reduce noise in the logs (e.g., N+1 queries) when you
only care about queries that write to the DB.
```ruby
ActiveRecordQueryTrace.suppress_logging_of_db_reads = false # default
```
#### Ignore cached queries
By default, a backtrace will be logged for every query, even cached queries that
do not actually hit the database. You might find it useful not to print the backtrace
for cached queries:
```ruby
ActiveRecordQueryTrace.ignore_cached_queries = true # Default is false.
```
#### Limit the number of lines in the backtrace
If you are working with a large app, you may wish to limit the number of lines
displayed for each query. If you set `level` to `:full`, you might want to set
`lines` to `0` so you can see the entire trace.
```ruby
ActiveRecordQueryTrace.lines = 10 # Default is 5. Setting to 0 includes entire trace.
```
#### Colorize the backtrace
To colorize the output:
```ruby
ActiveRecordQueryTrace.colorize = false # No colorization (default)
ActiveRecordQueryTrace.colorize = :light_purple # Colorize in specific color
```
Valid colors are: `:black`, `:red`, `:green`, `:brown`, `:blue`, `:purple`, `:cyan`,
`:gray`, `:dark_gray`, `:light_red`, `:light_green`, `:yellow`, `:light_blue`,
`:light_purple`, `:light_cyan`, `:white`.
## Authors
- **Cody Caughlan** - Original author.
- **Bruno Facca** - Current maintainer. [LinkedIn](https://www.linkedin.com/in/brunofacca/)
## Contributing
#### Bug reports
Please use the issue tracker to report any bugs.
#### Test environment
This gem uses RSpec for testing. You can run the test suite by executing the
`rspec` command. It has a decent test coverage and the test suite takes less than
a second to run as it uses an in-memory SQLite DB.
#### Developing
1. Create an issue and describe your idea
2. Fork it
3. Create your feature branch (`git checkout -b my-new-feature`)
4. Implement your changes;
5. Run the test suite (`rspec`)
6. Commit your changes (`git commit -m 'Add some feature'`)
7. Publish the branch (`git push origin my-new-feature`)
8. Create a Pull Request
## License
Released under the [MIT License](https://opensource.org/licenses/MIT).
| {
"content_hash": "1e3fd8e01850259b6b2b5c8d8deafb43",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 129,
"avg_line_length": 34.63125,
"alnum_prop": 0.7255008121277747,
"repo_name": "ruckus/active-record-query-trace",
"id": "dce1e378c5afcfe163be23dacee4a2f8de77c385",
"size": "5541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4816"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="Source to the Rust file `src/utils.rs`.">
<meta name="keywords" content="rust, rustlang, rust-lang">
<title>utils.rs.html -- source</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
<link rel="shortcut icon" href="https://lambdastackio.github.io/static/images/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../../ceph_rust/index.html'><img src='https://lambdastackio.github.io/static/images/lambdastack-200x200.png' alt='logo' width='100'></a>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content source"><pre class="line-numbers"><span id="1"> 1</span>
<span id="2"> 2</span>
<span id="3"> 3</span>
<span id="4"> 4</span>
<span id="5"> 5</span>
<span id="6"> 6</span>
<span id="7"> 7</span>
<span id="8"> 8</span>
<span id="9"> 9</span>
<span id="10">10</span>
<span id="11">11</span>
<span id="12">12</span>
<span id="13">13</span>
<span id="14">14</span>
<span id="15">15</span>
<span id="16">16</span>
<span id="17">17</span>
<span id="18">18</span>
<span id="19">19</span>
<span id="20">20</span>
<span id="21">21</span>
<span id="22">22</span>
<span id="23">23</span>
<span id="24">24</span>
<span id="25">25</span>
<span id="26">26</span>
<span id="27">27</span>
<span id="28">28</span>
<span id="29">29</span>
<span id="30">30</span>
<span id="31">31</span>
<span id="32">32</span>
<span id="33">33</span>
</pre><pre class='rust '>
<span class='comment'>// Copyright 2017 LambdaStack All rights reserved.</span>
<span class='comment'>//</span>
<span class='comment'>// Licensed under the Apache License, Version 2.0 (the "License");</span>
<span class='comment'>// you may not use this file except in compliance with the License.</span>
<span class='comment'>// You may obtain a copy of the License at</span>
<span class='comment'>//</span>
<span class='comment'>// http://www.apache.org/licenses/LICENSE-2.0</span>
<span class='comment'>//</span>
<span class='comment'>// Unless required by applicable law or agreed to in writing, software</span>
<span class='comment'>// distributed under the License is distributed on an "AS IS" BASIS,</span>
<span class='comment'>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class='comment'>// See the License for the specific language governing permissions and</span>
<span class='comment'>// limitations under the License.</span>
<span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>io</span>::<span class='prelude-ty'>Result</span>;
<span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>process</span>::{<span class='ident'>Command</span>, <span class='ident'>Output</span>};
<span class='doccomment'>/// run_cli - pass in a String of a normal command line</span>
<span class='doccomment'>///</span>
<span class='doccomment'>/// The function will split the options into words to supply to the low_level std::process::Command</span>
<span class='doccomment'>/// which returns Result<(Output)></span>
<span class='doccomment'>/// # Example</span>
<span class='doccomment'>///</span>
<span class='doccomment'>/// ```</span>
<span class='doccomment'>/// run_cli("ps aux");</span>
<span class='doccomment'>/// ```</span>
<span class='comment'>// NOTE: Add Into so a "" can also be passed in...</span>
<span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>run_cli</span>(<span class='ident'>cmd_line</span>: <span class='kw-2'>&</span><span class='ident'>str</span>) <span class='op'>-></span> <span class='prelude-ty'>Result</span><span class='op'><</span>(<span class='ident'>Output</span>)<span class='op'>></span> {
<span class='kw'>let</span> <span class='ident'>output</span> <span class='op'>=</span> <span class='macro'>try</span><span class='macro'>!</span>(<span class='ident'>Command</span>::<span class='ident'>new</span>(<span class='string'>"sh"</span>).<span class='ident'>arg</span>(<span class='string'>"-c"</span>).<span class='ident'>arg</span>(<span class='ident'>cmd_line</span>).<span class='ident'>output</span>());
<span class='prelude-val'>Ok</span>(<span class='ident'>output</span>)
}
</pre>
</section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "ceph_rust";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html> | {
"content_hash": "b1a3fb6528e73fbfd99cb17422acee32",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 442,
"avg_line_length": 40.67816091954023,
"alnum_prop": 0.5719129697654705,
"repo_name": "lambdastackio/ceph-rust",
"id": "3ebfdc9d1c2e7f4ad3d53a7cd0e92d682931c29c",
"size": "7088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/src/ceph_rust/src/utils.rs.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Rust",
"bytes": "121882"
},
{
"name": "Shell",
"bytes": "674"
}
],
"symlink_target": ""
} |
require "rails_ext/multi_tenant"
require "archie/model"
require "archie/otp"
class User < ActiveRecord::Base
include Archie::Model
include Archie::OTP::Model
has_and_belongs_to_many :roles, -> { includes :role_permissions }, :join_table => :users_roles
has_many :user_permissions, -> { includes :permissions }
# has_many :permissions, :through => :user_permissions
has_many :tokens, :dependent => :destroy
belongs_to :invited_by, :foreign_key => :invited_by_id, :class_name => User
belongs_to :org, -> { includes :tenant }
multi_tenant :via => :org
def self.find_by_username_or_email(login)
return nil if login.blank?
if login.include? "@" then
where("email = ? OR username = ?", login, login).first
else
where("username = ?", login).first
end
end
# Get all users in the same org (TODO tenant?) as the given user
def self.for_user(user)
where(:org_id => user.org_id)
end
# Set of all permissions, either directly assigned or via an active role assignment
#
# @return [Array<UserPermission> + Array<RolePermission>]
def permissions
@permissions ||= (self.user_permissions.to_a + self.roles.map{ |r| r.role_permissions.to_a }).flatten
end
# Test if this user has the given permission. Optionally tests access to the given object.
#
# @param [String] permission
# @param [Object] object (optional, default: nil)
#
# @return [Boolean] true if user has the given access
def can?(permission, object=nil)
if object.nil? then
# test for an object-less permission
# ex: impersonate_users
return !self.permissions.find{ |p| p.resource.nil? && p.name == permission.to_s }.nil?
end
# match the resource type & optionally the instance id
return !self.permissions.find{ |p|
p.resource == object.class.name &&
(p.resource_id.nil? || p.resource_id == object.id)
}.nil?
end
alias_method :can, :can?
def cant?(permission, object=nil)
!can?(permission, object)
end
alias_method :cant, :cant?
def display_name
self.name || self.username
end
def email_address
name = self.display_name
if name.blank? then
self.email
else
"#{name} <#{self.email}>"
end
end
end
| {
"content_hash": "36f250466488dd849db30d78709a4fab",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 105,
"avg_line_length": 28.2875,
"alnum_prop": 0.652673442333186,
"repo_name": "chetan/bixby-manager",
"id": "a17d83b0b99176c4d64318bd9fbeac6f1318c061",
"size": "5275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/user.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11422"
},
{
"name": "CoffeeScript",
"bytes": "208013"
},
{
"name": "HTML",
"bytes": "13732"
},
{
"name": "JavaScript",
"bytes": "1316"
},
{
"name": "Nginx",
"bytes": "5555"
},
{
"name": "Ruby",
"bytes": "524605"
},
{
"name": "Shell",
"bytes": "6455"
}
],
"symlink_target": ""
} |
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import './reset.css';
import '../../geovis.css';
import {App} from '../App';
import {attacks} from '../attacks/reducer';
import {controls} from '../controls/reducer';
const rootReducer = combineReducers({attacks, controls});
const middleware = process.env.NODE_ENV === 'production' ?
undefined :
applyMiddleware(
require('redux-logger')({
level: 'info',
collapsed: true,
timestamp: false,
duration: true
})
);
const store = createStore(rootReducer, {}, middleware);
const appRoot = document.createElement('div');
appRoot.id = 'app';
document.body.appendChild(appRoot);
ReactDOM.render(<Provider store={store}><App /></Provider>, appRoot);
| {
"content_hash": "e0f221a4423be8e3820234741d9e086e",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 69,
"avg_line_length": 26.625,
"alnum_prop": 0.6889671361502347,
"repo_name": "nkbt/geovis",
"id": "d22ebd45aa0d9321de816f476e0d3306d5469fc9",
"size": "852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/example/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2845"
},
{
"name": "JavaScript",
"bytes": "29442"
},
{
"name": "Shell",
"bytes": "110"
}
],
"symlink_target": ""
} |
<form class="form-horizontal" role="form" ng-submit="addBook()">
<div ng-include="'bookApp/partials/static_form_book.html'"></div>
</form> | {
"content_hash": "02a7f2644935ca09c173e26cac560eae",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 69,
"avg_line_length": 47.333333333333336,
"alnum_prop": 0.6901408450704225,
"repo_name": "nady/BookDealerApp",
"id": "77de57bbee3eaf187ba806426fa5277c6a056922",
"size": "142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/bookApp/partials/book-add.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "533"
},
{
"name": "CSS",
"bytes": "15745"
},
{
"name": "HTML",
"bytes": "30291"
},
{
"name": "JavaScript",
"bytes": "24222"
},
{
"name": "PHP",
"bytes": "175548"
},
{
"name": "Shell",
"bytes": "2477"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
/*global angular */
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).
value('version', '0.1');
}()); | {
"content_hash": "bb1554448289e57b4ea82febc1da9d5f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 49,
"avg_line_length": 21.083333333333332,
"alnum_prop": 0.5652173913043478,
"repo_name": "jutley/jutley-co",
"id": "46f514d02f09b649e6e0925cadf337453317f544",
"size": "253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/services.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1460"
},
{
"name": "HTML",
"bytes": "6835"
},
{
"name": "JavaScript",
"bytes": "22998"
}
],
"symlink_target": ""
} |
package me.chanjar.weixin.cp.tp.service.impl;
/**
* <pre>
* 默认接口实现类,使用apache httpclient实现
* Created by zhenjun cai.
* </pre>
*
* @author zhenjun cai
*/
public class WxCpTpServiceImpl extends WxCpTpServiceApacheHttpClientImpl {
}
| {
"content_hash": "5dea9ae4ff3f2559214115b3f7911e4e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 74,
"avg_line_length": 19.833333333333332,
"alnum_prop": 0.726890756302521,
"repo_name": "Wechat-Group/WxJava",
"id": "58fb09cf97982bfb992bc7b9f6b09c5c388fb08d",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "weixin-java-cp/src/main/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7118450"
},
{
"name": "Shell",
"bytes": "276"
}
],
"symlink_target": ""
} |
This directory contains [CasperJS](http://casperjs.org) tests that ensure the
stability of the site.
## Installation
Clone this repository anywhere in your project. Ideally, next to the docroot.
The contents of this repository do not need to be available to a web browser.
### OSX - Homebrew
Homebrew will install the phantomjs dependency automatically.
```bash
brew install casperjs --devel
```
### From Source
```bash
cd /usr/share
sudo git clone git://github.com/n1k0/casperjs.git
cd casperjs
sudo ln -sf `pwd`/bin/casperjs /usr/local/bin/casperjs
# Download phantomjs http://phantomjs.org/download.html to /usr/share
cd /usr/share/phantomjs-1.9.2-linux-x86_64/bin
sudo ln -sf `pwd`/phantomjs /usr/local/bin/phantomjs
# Next, install Python 2.6 or greater for casperjs in the bin/ directory.
# Finally, when running `casperjs`, the output should be:
casperjs
CasperJS version 1.1.0-beta3 at /usr/share/casperjs, using phantomjs version 1.9.2
```
## Running tests
Asuming your local environment is set up at http://localhost, all tests may
be run with the following command:
```bash
./testrun
```
You can also run a specific test by giving it as an argument to the command.
homepage.js is a sample test for http://www.msnbc.com. Here is how you could
run it:
```bash
./testrun -u http://www.msnbc.com homepage.js
```
*NOTE* `test` is a wrapper for `casperjs` which sets some useful defaults when
running tests. Run `./testrun -h` for a list of all the available options.
## Writing tests
Tests are JavaScript files which are located at the `tests` directory.
They can be organized depending on different aspects of the site such as the
homepage, the external header and footer, or the search engine.
`common.js` contains useful methods for all tests and it is included
automatically when running tests.
Some useful resources for writing tests are:
* [Navigation steps](http://docs.casperjs.org/en/latest/faq.html#how-does-then-and-the-step-stack-work)
let you wait for certain events such a page getting fully rendered before
running assertions over it.
* The [casper](http://docs.casperjs.org/en/latest/modules/casper.html) object has
commands to interact with the browser such as opening a URL or filling
out a form.
* The [test](http://docs.casperjs.org/en/latest/modules/tester.html)
object contains methods to run assertions over the current context.
## Cookies
PhantomJS (the browser that CasperJS uses for navitation) stores session
data in a cookie file. Future test runs will reuse the cookie if the file is
present. This is the reason why the `test` executable creates a file called
`cookies.txt` while running tests to store cookie information and deletes it
the next time tests are run.
## Tips
### Taking screenshots
You can take a screenshot with `casper.capture('filename');`.
Alternatively, you can use `casper.captureSelector('filename', 'div.some-class');`
to take a screenshot of a given selector.
Find more examples at http://docs.casperjs.org/en/latest/modules/casper.html#capture.
### Evaluating code
[casper.evaluate()](http://docs.casperjs.org/en/latest/modules/casper.html#evaluate)
method (and its alternatives such as `casper.evaluateOrDie()`, `casper.thenEvaluate()` or
`test.assertEvaluate()`) are highly powerful methods since they will run JavaScript
code on the page just as if you were debugging with the browser's JavaScript console.
| {
"content_hash": "e7b3750f63f50fc19754763ed4af038b",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 105,
"avg_line_length": 38.80681818181818,
"alnum_prop": 0.763103953147877,
"repo_name": "xuxingbgi/VoyagerTest_CasperJS",
"id": "ba1cea1f43a5ba259476ead823fdc290add70f08",
"size": "3436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "84622"
},
{
"name": "Shell",
"bytes": "1378"
}
],
"symlink_target": ""
} |
"Here is some text\n"
| {
"content_hash": "1edf88db20993f4b866a4ddc4179414d",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 21,
"avg_line_length": 22,
"alnum_prop": 0.6818181818181818,
"repo_name": "corinthia/corinthia-editor",
"id": "15b463ab61a1ad32b354ff39ccbb8f93b50489c0",
"size": "22",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "tests/range/getText07-expected.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1240"
},
{
"name": "HTML",
"bytes": "2137899"
},
{
"name": "JavaScript",
"bytes": "205085"
},
{
"name": "Perl",
"bytes": "1558"
},
{
"name": "Shell",
"bytes": "1657"
},
{
"name": "TypeScript",
"bytes": "648217"
}
],
"symlink_target": ""
} |
'use strict';
import {IDisposable, disposeAll} from 'vs/base/common/lifecycle';
import * as dom from 'vs/base/browser/dom';
import {IPosition} from 'vs/editor/common/editorCommon';
import {Position} from 'vs/editor/common/core/position';
import {ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition} from 'vs/editor/browser/editorBrowser';
export class LightBulpWidget implements IContentWidget, IDisposable {
private editor: ICodeEditor;
private position: IPosition;
private domNode: HTMLElement;
private visible: boolean;
private onclick: (pos: IPosition) => void;
private toDispose:IDisposable[];
// Editor.IContentWidget.allowEditorOverflow
public allowEditorOverflow = true;
constructor(editor: ICodeEditor, onclick: (pos: IPosition) => void) {
this.editor = editor;
this.onclick = onclick;
this.toDispose = [];
this.editor.addContentWidget(this);
}
public dispose(): void {
this.editor.removeContentWidget(this);
this.toDispose = disposeAll(this.toDispose);
}
public getId(): string {
return '__lightBulpWidget';
}
public getDomNode(): HTMLElement {
if (!this.domNode) {
this.domNode = document.createElement('div');
this.domNode.style.width = '20px';
this.domNode.style.height = '20px';
this.domNode.className = 'lightbulp-glyph';
this.toDispose.push(dom.addDisposableListener(this.domNode, 'click',(e) => {
this.editor.focus();
this.onclick(this.position);
}));
}
return this.domNode;
}
public getPosition(): IContentWidgetPosition {
return this.visible
? { position: this.position, preference: [ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.ABOVE] }
: null;
}
public show(where:IPosition): void {
if (this.visible && Position.equals(this.position, where)) {
return;
}
this.position = where;
this.visible = true;
this.editor.layoutContentWidget(this);
}
public hide(): void {
if (!this.visible) {
return;
}
this.visible = false;
this.editor.layoutContentWidget(this);
}
}
| {
"content_hash": "215c2b44f235a42b1365759f1becdb39",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 133,
"avg_line_length": 26.32051282051282,
"alnum_prop": 0.7252800779347297,
"repo_name": "alexandrudima/vscode",
"id": "3ba2942af2086bb0799092c6aee6664b142a50cb",
"size": "2404",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/vs/editor/contrib/quickFix/browser/lightBulpWidget.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "2179"
},
{
"name": "Batchfile",
"bytes": "1222"
},
{
"name": "CSS",
"bytes": "406021"
},
{
"name": "HTML",
"bytes": "30321"
},
{
"name": "JavaScript",
"bytes": "8381468"
},
{
"name": "Shell",
"bytes": "6098"
},
{
"name": "TypeScript",
"bytes": "10271625"
}
],
"symlink_target": ""
} |
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | See @GHC.LanguageExtensions@ for an explanation
-- on why this is needed
module GHC.ForeignSrcLang
( module GHC.ForeignSrcLang.Type
) where
import Data.Binary
import GHC.ForeignSrcLang.Type
instance Binary ForeignSrcLang
| {
"content_hash": "f2612866a8550979bb457520a95e9073",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 52,
"avg_line_length": 22.583333333333332,
"alnum_prop": 0.7638376383763837,
"repo_name": "shlevy/ghc",
"id": "9ca4f04cf71725a7036e4afab715403cddda546c",
"size": "271",
"binary": false,
"copies": "19",
"ref": "refs/heads/master",
"path": "libraries/ghc-boot/GHC/ForeignSrcLang.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "8752"
},
{
"name": "Batchfile",
"bytes": "394"
},
{
"name": "C",
"bytes": "2939599"
},
{
"name": "C++",
"bytes": "114368"
},
{
"name": "CSS",
"bytes": "984"
},
{
"name": "DTrace",
"bytes": "4068"
},
{
"name": "Emacs Lisp",
"bytes": "734"
},
{
"name": "Gnuplot",
"bytes": "103851"
},
{
"name": "HTML",
"bytes": "6144"
},
{
"name": "Haskell",
"bytes": "22341394"
},
{
"name": "Haxe",
"bytes": "218"
},
{
"name": "Logos",
"bytes": "138312"
},
{
"name": "M4",
"bytes": "57247"
},
{
"name": "Makefile",
"bytes": "583780"
},
{
"name": "Nix",
"bytes": "2162"
},
{
"name": "Objective-C",
"bytes": "7276"
},
{
"name": "Objective-C++",
"bytes": "535"
},
{
"name": "Pascal",
"bytes": "128141"
},
{
"name": "Perl",
"bytes": "18385"
},
{
"name": "Perl 6",
"bytes": "59030"
},
{
"name": "PostScript",
"bytes": "63"
},
{
"name": "Python",
"bytes": "117392"
},
{
"name": "Roff",
"bytes": "3841"
},
{
"name": "Shell",
"bytes": "94851"
},
{
"name": "TeX",
"bytes": "667"
},
{
"name": "Terra",
"bytes": "480987"
},
{
"name": "Yacc",
"bytes": "64411"
}
],
"symlink_target": ""
} |
import * as React from 'react';
import {SvgIconProps} from '../../SvgIcon';
export default function MovieFilter(props: SvgIconProps): React.ReactElement<SvgIconProps>;
| {
"content_hash": "c6f936c5fc10086047f46889ad8e7c17",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 91,
"avg_line_length": 42.25,
"alnum_prop": 0.7633136094674556,
"repo_name": "mattiamanzati/typings-material-ui",
"id": "7f2377b099dde297c70a94fc15e096f2c56c300c",
"size": "169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "svg-icons/image/movie-filter.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "171"
},
{
"name": "JavaScript",
"bytes": "2513"
}
],
"symlink_target": ""
} |
Description
===========
Configures various APT components on Debian-like systems. Also includes a LWRP.
Recipes
=======
default
-------
The default recipe runs apt-get update during the Compile Phase of the Chef run to ensure that the system's package cache is updated with the latest. It is recommended that this recipe appear first in a node's run list (directly or through a role) to ensure that when installing packages, Chef will be able to download the latest version available on the remote APT repository.
This recipe also sets up a local cache directory for preseeding packages.
cacher
------
Installs the apt-cacher package and service so the system can be an APT cache.
proxy
-----
Installs the apt-proxy package and service so the system can be an APT proxy.
Resources/Providers
===================
This cookbook contains an LWRP, `apt_repository`, which provides the `add` and `remove` actions for managing additional software repositories with entries in the `/etc/apt/sources.list.d/` directory. The LWRP also supports passing in a `key` and `keyserver` as attributes.
* `add` takes a number of attributes and creates a repository file and builds the repository listing.
* `remove` deletes the `/etc/apt/sources.list.d/#{new_resource.repo_name}-sources.list` file identified by the `repo_name` passed as the resource name.
Usage
=====
Put `recipe[apt]` first in the run list. If you have other recipes that you want to use to configure how apt behaves, like new sources, notify the execute resource to run, e.g.:
template "/etc/apt/sources.list.d/my_apt_sources.list" do
notifies :run, resources(:execute => "apt-get update"), :immediately
end
The above will run during execution phase since it is a normal template resource, and should appear before other package resources that need the sources in the template.
An example of The LWRP `apt_repository` `add` action:
apt_repository "zenoss" do
uri "http://dev.zenoss.org/deb"
distribution "main"
components ["stable"]
action :add
end
and the `remove` action:
apt_repository "zenoss" do
action :remove
end
License and Author
==================
Author:: Joshua Timberman (<joshua@opscode.com>)
Author:: Matt Ray (<matt@opscode.com>)
Copyright 2009, 2010 Opscode, Inc.
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.
| {
"content_hash": "918c2f38868a3f28329ca748418a8194",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 377,
"avg_line_length": 35.9746835443038,
"alnum_prop": 0.7392681210415201,
"repo_name": "infochimps-away/cluster_chef",
"id": "e9367ff8cf843f75e6fab09de4415701f70235f0",
"size": "2842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cookbooks/apt/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Emacs Lisp",
"bytes": "5235"
},
{
"name": "Groovy",
"bytes": "1666"
},
{
"name": "Perl",
"bytes": "9095"
},
{
"name": "Python",
"bytes": "1343"
},
{
"name": "Ruby",
"bytes": "691994"
},
{
"name": "Shell",
"bytes": "8960"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.