text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
name 'kafka'
maintainer 'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license 'All rights reserved'
description 'Installs/Configures kafka'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
| {'content_hash': '8244ad7573bd96e7b15cf7d03bc6689a', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 72, 'avg_line_length': 39.142857142857146, 'alnum_prop': 0.6496350364963503, 'repo_name': 'asarraf/chef-recipes', 'id': '02e750e68fe11f261f7357f4e7b7bc2a54ce5600', 'size': '274', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cookbook/kafka/metadata.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '42594'}, {'name': 'Ruby', 'bytes': '39320'}]} |
package org.apache.hadoop.fs.viewfs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.BlockStoragePolicySpi;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.FsConstants;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.Trash;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.fs.contract.ContractTestUtils;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.AclUtil;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.viewfs.ViewFileSystem.MountPoint;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Assume;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.hadoop.fs.FileSystemTestHelper.*;
import static org.apache.hadoop.fs.viewfs.Constants.PERMISSION_555;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
import org.junit.Ignore;
/**
* <p>
* A collection of tests for the {@link ViewFileSystem}.
* This test should be used for testing ViewFileSystem that has mount links to
* a target file system such localFs or Hdfs etc.
* </p>
* <p>
* To test a given target file system create a subclass of this
* test and override {@link #setUp()} to initialize the <code>fsTarget</code>
* to point to the file system to which you want the mount targets
*
* Since this a junit 4 you can also do a single setup before
* the start of any tests.
* E.g.
* @BeforeClass public static void clusterSetupAtBegining()
* @AfterClass public static void ClusterShutdownAtEnd()
* </p>
*/
abstract public class ViewFileSystemBaseTest {
FileSystem fsView; // the view file system - the mounts are here
FileSystem fsTarget; // the target file system - the mount will point here
Path targetTestRoot;
Configuration conf;
final FileSystemTestHelper fileSystemTestHelper;
private static final Logger LOG =
LoggerFactory.getLogger(ViewFileSystemBaseTest.class);
public ViewFileSystemBaseTest() {
this.fileSystemTestHelper = createFileSystemHelper();
}
protected FileSystemTestHelper createFileSystemHelper() {
return new FileSystemTestHelper();
}
@Before
public void setUp() throws Exception {
initializeTargetTestRoot();
// Make user and data dirs - we creates links to them in the mount table
fsTarget.mkdirs(new Path(targetTestRoot,"user"));
fsTarget.mkdirs(new Path(targetTestRoot,"data"));
fsTarget.mkdirs(new Path(targetTestRoot,"dir2"));
fsTarget.mkdirs(new Path(targetTestRoot,"dir3"));
FileSystemTestHelper.createFile(fsTarget, new Path(targetTestRoot,"aFile"));
// Now we use the mount fs to set links to user and dir
// in the test root
// Set up the defaultMT in the config with our mount point links
conf = ViewFileSystemTestSetup.createConfig();
setupMountPoints();
fsView = FileSystem.get(FsConstants.VIEWFS_URI, conf);
}
@After
public void tearDown() throws Exception {
fsTarget.delete(fileSystemTestHelper.getTestRootPath(fsTarget), true);
}
void initializeTargetTestRoot() throws IOException {
targetTestRoot = fileSystemTestHelper.getAbsoluteTestRootPath(fsTarget);
// In case previous test was killed before cleanup
fsTarget.delete(targetTestRoot, true);
fsTarget.mkdirs(targetTestRoot);
}
void setupMountPoints() {
ConfigUtil.addLink(conf, "/targetRoot", targetTestRoot.toUri());
ConfigUtil.addLink(conf, "/user", new Path(targetTestRoot, "user").toUri());
ConfigUtil.addLink(conf, "/user2", new Path(targetTestRoot,"user").toUri());
ConfigUtil.addLink(conf, "/data", new Path(targetTestRoot,"data").toUri());
ConfigUtil.addLink(conf, "/internalDir/linkToDir2",
new Path(targetTestRoot,"dir2").toUri());
ConfigUtil.addLink(conf, "/internalDir/internalDir2/linkToDir3",
new Path(targetTestRoot,"dir3").toUri());
ConfigUtil.addLink(conf, "/danglingLink",
new Path(targetTestRoot, "missingTarget").toUri());
ConfigUtil.addLink(conf, "/linkToAFile",
new Path(targetTestRoot, "aFile").toUri());
}
@Test
public void testGetMountPoints() {
ViewFileSystem viewfs = (ViewFileSystem) fsView;
MountPoint[] mountPoints = viewfs.getMountPoints();
for (MountPoint mountPoint : mountPoints) {
LOG.info("MountPoint: " + mountPoint.getMountedOnPath() + " => "
+ mountPoint.getTargetFileSystemURIs()[0]);
}
Assert.assertEquals(getExpectedMountPoints(), mountPoints.length);
}
int getExpectedMountPoints() {
return 8;
}
/**
* This default implementation is when viewfs has mount points
* into file systems, such as LocalFs that do no have delegation tokens.
* It should be overridden for when mount points into hdfs.
*/
@Ignore
@Test
public void testGetDelegationTokens() throws IOException {
Token<?>[] delTokens =
fsView.addDelegationTokens("sanjay", new Credentials());
Assert.assertEquals(getExpectedDelegationTokenCount(), delTokens.length);
}
int getExpectedDelegationTokenCount() {
return 0;
}
@Ignore
@Test
public void testGetDelegationTokensWithCredentials() throws IOException {
Credentials credentials = new Credentials();
List<Token<?>> delTokens =
Arrays.asList(fsView.addDelegationTokens("sanjay", credentials));
int expectedTokenCount = getExpectedDelegationTokenCountWithCredentials();
Assert.assertEquals(expectedTokenCount, delTokens.size());
Credentials newCredentials = new Credentials();
for (int i = 0; i < expectedTokenCount / 2; i++) {
Token<?> token = delTokens.get(i);
newCredentials.addToken(token.getService(), token);
}
List<Token<?>> delTokens2 =
Arrays.asList(fsView.addDelegationTokens("sanjay", newCredentials));
Assert.assertEquals((expectedTokenCount + 1) / 2, delTokens2.size());
}
int getExpectedDelegationTokenCountWithCredentials() {
return 0;
}
@Test
public void testBasicPaths() {
Assert.assertEquals(FsConstants.VIEWFS_URI,
fsView.getUri());
Assert.assertEquals(fsView.makeQualified(
new Path("/user/" + System.getProperty("user.name"))),
fsView.getWorkingDirectory());
Assert.assertEquals(fsView.makeQualified(
new Path("/user/" + System.getProperty("user.name"))),
fsView.getHomeDirectory());
Assert.assertEquals(
new Path("/foo/bar").makeQualified(FsConstants.VIEWFS_URI, null),
fsView.makeQualified(new Path("/foo/bar")));
}
@Test
public void testLocatedOperationsThroughMountLinks() throws IOException {
testOperationsThroughMountLinksInternal(true);
}
@Test
public void testOperationsThroughMountLinks() throws IOException {
testOperationsThroughMountLinksInternal(false);
}
/**
* Test modify operations (create, mkdir, delete, etc)
* on the mount file system where the pathname references through
* the mount points. Hence these operation will modify the target
* file system.
*
* Verify the operation via mountfs (ie fSys) and *also* via the
* target file system (ie fSysLocal) that the mount link points-to.
*/
private void testOperationsThroughMountLinksInternal(boolean located)
throws IOException {
// Create file
fileSystemTestHelper.createFile(fsView, "/user/foo");
Assert.assertTrue("Created file should be type file",
fsView.isFile(new Path("/user/foo")));
Assert.assertTrue("Target of created file should be type file",
fsTarget.isFile(new Path(targetTestRoot,"user/foo")));
// Delete the created file
Assert.assertTrue("Delete should succeed",
fsView.delete(new Path("/user/foo"), false));
Assert.assertFalse("File should not exist after delete",
fsView.exists(new Path("/user/foo")));
Assert.assertFalse("Target File should not exist after delete",
fsTarget.exists(new Path(targetTestRoot,"user/foo")));
// Create file with a 2 component dirs
fileSystemTestHelper.createFile(fsView, "/internalDir/linkToDir2/foo");
Assert.assertTrue("Created file should be type file",
fsView.isFile(new Path("/internalDir/linkToDir2/foo")));
Assert.assertTrue("Target of created file should be type file",
fsTarget.isFile(new Path(targetTestRoot,"dir2/foo")));
// Delete the created file
Assert.assertTrue("Delete should succeed",
fsView.delete(new Path("/internalDir/linkToDir2/foo"), false));
Assert.assertFalse("File should not exist after delete",
fsView.exists(new Path("/internalDir/linkToDir2/foo")));
Assert.assertFalse("Target File should not exist after delete",
fsTarget.exists(new Path(targetTestRoot,"dir2/foo")));
// Create file with a 3 component dirs
fileSystemTestHelper.createFile(fsView, "/internalDir/internalDir2/linkToDir3/foo");
Assert.assertTrue("Created file should be type file",
fsView.isFile(new Path("/internalDir/internalDir2/linkToDir3/foo")));
Assert.assertTrue("Target of created file should be type file",
fsTarget.isFile(new Path(targetTestRoot,"dir3/foo")));
// Recursive Create file with missing dirs
fileSystemTestHelper.createFile(fsView,
"/internalDir/linkToDir2/missingDir/miss2/foo");
Assert.assertTrue("Created file should be type file",
fsView.isFile(new Path("/internalDir/linkToDir2/missingDir/miss2/foo")));
Assert.assertTrue("Target of created file should be type file",
fsTarget.isFile(new Path(targetTestRoot,"dir2/missingDir/miss2/foo")));
// Delete the created file
Assert.assertTrue("Delete should succeed",
fsView.delete(
new Path("/internalDir/internalDir2/linkToDir3/foo"), false));
Assert.assertFalse("File should not exist after delete",
fsView.exists(new Path("/internalDir/internalDir2/linkToDir3/foo")));
Assert.assertFalse("Target File should not exist after delete",
fsTarget.exists(new Path(targetTestRoot,"dir3/foo")));
// mkdir
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView, "/user/dirX"));
Assert.assertTrue("New dir should be type dir",
fsView.isDirectory(new Path("/user/dirX")));
Assert.assertTrue("Target of new dir should be of type dir",
fsTarget.isDirectory(new Path(targetTestRoot,"user/dirX")));
fsView.mkdirs(
fileSystemTestHelper.getTestRootPath(fsView, "/user/dirX/dirY"));
Assert.assertTrue("New dir should be type dir",
fsView.isDirectory(new Path("/user/dirX/dirY")));
Assert.assertTrue("Target of new dir should be of type dir",
fsTarget.isDirectory(new Path(targetTestRoot,"user/dirX/dirY")));
// Delete the created dir
Assert.assertTrue("Delete should succeed",
fsView.delete(new Path("/user/dirX/dirY"), false));
Assert.assertFalse("File should not exist after delete",
fsView.exists(new Path("/user/dirX/dirY")));
Assert.assertFalse("Target File should not exist after delete",
fsTarget.exists(new Path(targetTestRoot,"user/dirX/dirY")));
Assert.assertTrue("Delete should succeed",
fsView.delete(new Path("/user/dirX"), false));
Assert.assertFalse("File should not exist after delete",
fsView.exists(new Path("/user/dirX")));
Assert.assertFalse(fsTarget.exists(new Path(targetTestRoot,"user/dirX")));
// Rename a file
fileSystemTestHelper.createFile(fsView, "/user/foo");
fsView.rename(new Path("/user/foo"), new Path("/user/fooBar"));
Assert.assertFalse("Renamed src should not exist",
fsView.exists(new Path("/user/foo")));
Assert.assertFalse("Renamed src should not exist in target",
fsTarget.exists(new Path(targetTestRoot,"user/foo")));
Assert.assertTrue("Renamed dest should exist as file",
fsView.isFile(fileSystemTestHelper.getTestRootPath(fsView,"/user/fooBar")));
Assert.assertTrue("Renamed dest should exist as file in target",
fsTarget.isFile(new Path(targetTestRoot,"user/fooBar")));
fsView.mkdirs(new Path("/user/dirFoo"));
fsView.rename(new Path("/user/dirFoo"), new Path("/user/dirFooBar"));
Assert.assertFalse("Renamed src should not exist",
fsView.exists(new Path("/user/dirFoo")));
Assert.assertFalse("Renamed src should not exist in target",
fsTarget.exists(new Path(targetTestRoot,"user/dirFoo")));
Assert.assertTrue("Renamed dest should exist as dir",
fsView.isDirectory(fileSystemTestHelper.getTestRootPath(fsView,"/user/dirFooBar")));
Assert.assertTrue("Renamed dest should exist as dir in target",
fsTarget.isDirectory(new Path(targetTestRoot,"user/dirFooBar")));
// Make a directory under a directory that's mounted from the root of another FS
fsView.mkdirs(new Path("/targetRoot/dirFoo"));
Assert.assertTrue(fsView.exists(new Path("/targetRoot/dirFoo")));
boolean dirFooPresent = false;
for (FileStatus fileStatus :
listStatusInternal(located, new Path("/targetRoot/"))) {
if (fileStatus.getPath().getName().equals("dirFoo")) {
dirFooPresent = true;
}
}
Assert.assertTrue(dirFooPresent);
}
// rename across mount points that point to same target also fail
@Test
public void testRenameAcrossMounts1() throws IOException {
fileSystemTestHelper.createFile(fsView, "/user/foo");
try {
fsView.rename(new Path("/user/foo"), new Path("/user2/fooBarBar"));
ContractTestUtils.fail("IOException is not thrown on rename operation");
} catch (IOException e) {
GenericTestUtils
.assertExceptionContains("Renames across Mount points not supported",
e);
}
}
// rename across mount points fail if the mount link targets are different
// even if the targets are part of the same target FS
@Test
public void testRenameAcrossMounts2() throws IOException {
fileSystemTestHelper.createFile(fsView, "/user/foo");
try {
fsView.rename(new Path("/user/foo"), new Path("/data/fooBar"));
ContractTestUtils.fail("IOException is not thrown on rename operation");
} catch (IOException e) {
GenericTestUtils
.assertExceptionContains("Renames across Mount points not supported",
e);
}
}
// RenameStrategy SAME_TARGET_URI_ACROSS_MOUNTPOINT enabled
// to rename across mount points that point to same target URI
@Test
public void testRenameAcrossMounts3() throws IOException {
Configuration conf2 = new Configuration(conf);
conf2.set(Constants.CONFIG_VIEWFS_RENAME_STRATEGY,
ViewFileSystem.RenameStrategy.SAME_TARGET_URI_ACROSS_MOUNTPOINT
.toString());
FileSystem fsView2 = FileSystem.newInstance(FsConstants.VIEWFS_URI, conf2);
fileSystemTestHelper.createFile(fsView2, "/user/foo");
fsView2.rename(new Path("/user/foo"), new Path("/user2/fooBarBar"));
ContractTestUtils
.assertPathDoesNotExist(fsView2, "src should not exist after rename",
new Path("/user/foo"));
ContractTestUtils
.assertPathDoesNotExist(fsTarget, "src should not exist after rename",
new Path(targetTestRoot, "user/foo"));
ContractTestUtils.assertIsFile(fsView2,
fileSystemTestHelper.getTestRootPath(fsView2, "/user2/fooBarBar"));
ContractTestUtils
.assertIsFile(fsTarget, new Path(targetTestRoot, "user/fooBarBar"));
}
// RenameStrategy SAME_FILESYSTEM_ACROSS_MOUNTPOINT enabled
// to rename across mount points where the mount link targets are different
// but are part of the same target FS
@Test
public void testRenameAcrossMounts4() throws IOException {
Configuration conf2 = new Configuration(conf);
conf2.set(Constants.CONFIG_VIEWFS_RENAME_STRATEGY,
ViewFileSystem.RenameStrategy.SAME_FILESYSTEM_ACROSS_MOUNTPOINT
.toString());
FileSystem fsView2 = FileSystem.newInstance(FsConstants.VIEWFS_URI, conf2);
fileSystemTestHelper.createFile(fsView2, "/user/foo");
fsView2.rename(new Path("/user/foo"), new Path("/data/fooBar"));
ContractTestUtils
.assertPathDoesNotExist(fsView2, "src should not exist after rename",
new Path("/user/foo"));
ContractTestUtils
.assertPathDoesNotExist(fsTarget, "src should not exist after rename",
new Path(targetTestRoot, "user/foo"));
ContractTestUtils.assertIsFile(fsView2,
fileSystemTestHelper.getTestRootPath(fsView2, "/data/fooBar"));
ContractTestUtils
.assertIsFile(fsTarget, new Path(targetTestRoot, "data/fooBar"));
}
static protected boolean SupportsBlocks = false; // local fs use 1 block
// override for HDFS
@Test
public void testGetBlockLocations() throws IOException {
Path targetFilePath = new Path(targetTestRoot,"data/largeFile");
FileSystemTestHelper.createFile(fsTarget,
targetFilePath, 10, 1024);
Path viewFilePath = new Path("/data/largeFile");
Assert.assertTrue("Created File should be type File",
fsView.isFile(viewFilePath));
BlockLocation[] viewBL = fsView.getFileBlockLocations(fsView.getFileStatus(viewFilePath), 0, 10240+100);
Assert.assertEquals(SupportsBlocks ? 10 : 1, viewBL.length);
BlockLocation[] targetBL = fsTarget.getFileBlockLocations(fsTarget.getFileStatus(targetFilePath), 0, 10240+100);
compareBLs(viewBL, targetBL);
// Same test but now get it via the FileStatus Parameter
fsView.getFileBlockLocations(
fsView.getFileStatus(viewFilePath), 0, 10240+100);
targetBL = fsTarget.getFileBlockLocations(
fsTarget.getFileStatus(targetFilePath), 0, 10240+100);
compareBLs(viewBL, targetBL);
}
void compareBLs(BlockLocation[] viewBL, BlockLocation[] targetBL) {
Assert.assertEquals(targetBL.length, viewBL.length);
int i = 0;
for (BlockLocation vbl : viewBL) {
Assert.assertEquals(vbl.toString(), targetBL[i].toString());
Assert.assertEquals(targetBL[i].getOffset(), vbl.getOffset());
Assert.assertEquals(targetBL[i].getLength(), vbl.getLength());
i++;
}
}
@Test
public void testLocatedListOnInternalDirsOfMountTable() throws IOException {
testListOnInternalDirsOfMountTableInternal(true);
}
/**
* Test "readOps" (e.g. list, listStatus)
* on internal dirs of mount table
* These operations should succeed.
*/
// test list on internal dirs of mount table
@Test
public void testListOnInternalDirsOfMountTable() throws IOException {
testListOnInternalDirsOfMountTableInternal(false);
}
private void testListOnInternalDirsOfMountTableInternal(boolean located)
throws IOException {
// list on Slash
FileStatus[] dirPaths = listStatusInternal(located, new Path("/"));
FileStatus fs;
verifyRootChildren(dirPaths);
// list on internal dir
dirPaths = listStatusInternal(located, new Path("/internalDir"));
Assert.assertEquals(2, dirPaths.length);
fs = fileSystemTestHelper.containsPath(fsView, "/internalDir/internalDir2", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isDirectory());
fs = fileSystemTestHelper.containsPath(fsView, "/internalDir/linkToDir2",
dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isSymlink());
}
private void verifyRootChildren(FileStatus[] dirPaths) throws IOException {
FileStatus fs;
Assert.assertEquals(getExpectedDirPaths(), dirPaths.length);
fs = fileSystemTestHelper.containsPath(fsView, "/user", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isSymlink());
fs = fileSystemTestHelper.containsPath(fsView, "/data", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isSymlink());
fs = fileSystemTestHelper.containsPath(fsView, "/internalDir", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isDirectory());
fs = fileSystemTestHelper.containsPath(fsView, "/danglingLink", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isSymlink());
fs = fileSystemTestHelper.containsPath(fsView, "/linkToAFile", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("A mount should appear as symlink", fs.isSymlink());
}
int getExpectedDirPaths() {
return 7;
}
@Test
public void testListOnMountTargetDirs() throws IOException {
testListOnMountTargetDirsInternal(false);
}
@Test
public void testLocatedListOnMountTargetDirs() throws IOException {
testListOnMountTargetDirsInternal(true);
}
private void testListOnMountTargetDirsInternal(boolean located)
throws IOException {
final Path dataPath = new Path("/data");
FileStatus[] dirPaths = listStatusInternal(located, dataPath);
FileStatus fs;
Assert.assertEquals(0, dirPaths.length);
// add a file
long len = fileSystemTestHelper.createFile(fsView, "/data/foo");
dirPaths = listStatusInternal(located, dataPath);
Assert.assertEquals(1, dirPaths.length);
fs = fileSystemTestHelper.containsPath(fsView, "/data/foo", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("Created file shoudl appear as a file", fs.isFile());
Assert.assertEquals(len, fs.getLen());
// add a dir
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView, "/data/dirX"));
dirPaths = listStatusInternal(located, dataPath);
Assert.assertEquals(2, dirPaths.length);
fs = fileSystemTestHelper.containsPath(fsView, "/data/foo", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("Created file shoudl appear as a file", fs.isFile());
fs = fileSystemTestHelper.containsPath(fsView, "/data/dirX", dirPaths);
Assert.assertNotNull(fs);
Assert.assertTrue("Created dir should appear as a dir", fs.isDirectory());
}
private FileStatus[] listStatusInternal(boolean located, Path dataPath) throws IOException {
FileStatus[] dirPaths = new FileStatus[0];
if (located) {
RemoteIterator<LocatedFileStatus> statIter =
fsView.listLocatedStatus(dataPath);
ArrayList<LocatedFileStatus> tmp = new ArrayList<LocatedFileStatus>(10);
while (statIter.hasNext()) {
tmp.add(statIter.next());
}
dirPaths = tmp.toArray(dirPaths);
} else {
dirPaths = fsView.listStatus(dataPath);
}
return dirPaths;
}
@Test
public void testFileStatusOnMountLink() throws IOException {
Assert.assertTrue(fsView.getFileStatus(new Path("/")).isDirectory());
checkFileStatus(fsView, "/", fileType.isDir);
checkFileStatus(fsView, "/user", fileType.isDir); // link followed => dir
checkFileStatus(fsView, "/data", fileType.isDir);
checkFileStatus(fsView, "/internalDir", fileType.isDir);
checkFileStatus(fsView, "/internalDir/linkToDir2", fileType.isDir);
checkFileStatus(fsView, "/internalDir/internalDir2/linkToDir3",
fileType.isDir);
checkFileStatus(fsView, "/linkToAFile", fileType.isFile);
}
@Test(expected=FileNotFoundException.class)
public void testgetFSonDanglingLink() throws IOException {
fsView.getFileStatus(new Path("/danglingLink"));
}
@Test(expected=FileNotFoundException.class)
public void testgetFSonNonExistingInternalDir() throws IOException {
fsView.getFileStatus(new Path("/internalDir/nonExisting"));
}
/*
* Test resolvePath(p)
*/
@Test
public void testResolvePathInternalPaths() throws IOException {
Assert.assertEquals(new Path("/"), fsView.resolvePath(new Path("/")));
Assert.assertEquals(new Path("/internalDir"),
fsView.resolvePath(new Path("/internalDir")));
}
@Test
public void testResolvePathMountPoints() throws IOException {
Assert.assertEquals(new Path(targetTestRoot,"user"),
fsView.resolvePath(new Path("/user")));
Assert.assertEquals(new Path(targetTestRoot,"data"),
fsView.resolvePath(new Path("/data")));
Assert.assertEquals(new Path(targetTestRoot,"dir2"),
fsView.resolvePath(new Path("/internalDir/linkToDir2")));
Assert.assertEquals(new Path(targetTestRoot,"dir3"),
fsView.resolvePath(new Path("/internalDir/internalDir2/linkToDir3")));
}
@Test
public void testResolvePathThroughMountPoints() throws IOException {
fileSystemTestHelper.createFile(fsView, "/user/foo");
Assert.assertEquals(new Path(targetTestRoot,"user/foo"),
fsView.resolvePath(new Path("/user/foo")));
fsView.mkdirs(
fileSystemTestHelper.getTestRootPath(fsView, "/user/dirX"));
Assert.assertEquals(new Path(targetTestRoot,"user/dirX"),
fsView.resolvePath(new Path("/user/dirX")));
fsView.mkdirs(
fileSystemTestHelper.getTestRootPath(fsView, "/user/dirX/dirY"));
Assert.assertEquals(new Path(targetTestRoot,"user/dirX/dirY"),
fsView.resolvePath(new Path("/user/dirX/dirY")));
}
@Test(expected=FileNotFoundException.class)
public void testResolvePathDanglingLink() throws IOException {
fsView.resolvePath(new Path("/danglingLink"));
}
@Test(expected=FileNotFoundException.class)
public void testResolvePathMissingThroughMountPoints() throws IOException {
fsView.resolvePath(new Path("/user/nonExisting"));
}
@Test(expected=FileNotFoundException.class)
public void testResolvePathMissingThroughMountPoints2() throws IOException {
fsView.mkdirs(
fileSystemTestHelper.getTestRootPath(fsView, "/user/dirX"));
fsView.resolvePath(new Path("/user/dirX/nonExisting"));
}
/**
* Test modify operations (create, mkdir, rename, etc)
* on internal dirs of mount table
* These operations should fail since the mount table is read-only or
* because the internal dir that it is trying to create already
* exits.
*/
// Mkdir on existing internal mount table succeed except for /
@Test(expected=AccessControlException.class)
public void testInternalMkdirSlash() throws IOException {
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView, "/"));
}
public void testInternalMkdirExisting1() throws IOException {
Assert.assertTrue("mkdir of existing dir should succeed",
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView,
"/internalDir")));
}
public void testInternalMkdirExisting2() throws IOException {
Assert.assertTrue("mkdir of existing dir should succeed",
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView,
"/internalDir/linkToDir2")));
}
// Mkdir for new internal mount table should fail
@Test(expected=AccessControlException.class)
public void testInternalMkdirNew() throws IOException {
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView, "/dirNew"));
}
@Test(expected=AccessControlException.class)
public void testInternalMkdirNew2() throws IOException {
fsView.mkdirs(fileSystemTestHelper.getTestRootPath(fsView, "/internalDir/dirNew"));
}
// Create File on internal mount table should fail
@Test(expected=AccessControlException.class)
public void testInternalCreate1() throws IOException {
fileSystemTestHelper.createFile(fsView, "/foo"); // 1 component
}
@Test(expected=AccessControlException.class)
public void testInternalCreate2() throws IOException { // 2 component
fileSystemTestHelper.createFile(fsView, "/internalDir/foo");
}
@Test(expected=AccessControlException.class)
public void testInternalCreateMissingDir() throws IOException {
fileSystemTestHelper.createFile(fsView, "/missingDir/foo");
}
@Test(expected=AccessControlException.class)
public void testInternalCreateMissingDir2() throws IOException {
fileSystemTestHelper.createFile(fsView, "/missingDir/miss2/foo");
}
@Test(expected=AccessControlException.class)
public void testInternalCreateMissingDir3() throws IOException {
fileSystemTestHelper.createFile(fsView, "/internalDir/miss2/foo");
}
// Delete on internal mount table should fail
@Test(expected=FileNotFoundException.class)
public void testInternalDeleteNonExisting() throws IOException {
fsView.delete(new Path("/NonExisting"), false);
}
@Test(expected=FileNotFoundException.class)
public void testInternalDeleteNonExisting2() throws IOException {
fsView.delete(new Path("/internalDir/NonExisting"), false);
}
@Test(expected=AccessControlException.class)
public void testInternalDeleteExisting() throws IOException {
fsView.delete(new Path("/internalDir"), false);
}
@Test(expected=AccessControlException.class)
public void testInternalDeleteExisting2() throws IOException {
fsView.getFileStatus(
new Path("/internalDir/linkToDir2")).isDirectory();
fsView.delete(new Path("/internalDir/linkToDir2"), false);
}
@Test
public void testMkdirOfMountLink() throws IOException {
// data exists - mkdirs returns true even though no permission in internal
// mount table
Assert.assertTrue("mkdir of existing mount link should succeed",
fsView.mkdirs(new Path("/data")));
}
// Rename on internal mount table should fail
@Test(expected=AccessControlException.class)
public void testInternalRename1() throws IOException {
fsView.rename(new Path("/internalDir"), new Path("/newDir"));
}
@Test(expected=AccessControlException.class)
public void testInternalRename2() throws IOException {
fsView.getFileStatus(new Path("/internalDir/linkToDir2")).isDirectory();
fsView.rename(new Path("/internalDir/linkToDir2"),
new Path("/internalDir/dir1"));
}
@Test(expected=AccessControlException.class)
public void testInternalRename3() throws IOException {
fsView.rename(new Path("/user"), new Path("/internalDir/linkToDir2"));
}
@Test(expected=AccessControlException.class)
public void testInternalRenameToSlash() throws IOException {
fsView.rename(new Path("/internalDir/linkToDir2/foo"), new Path("/"));
}
@Test(expected=AccessControlException.class)
public void testInternalRenameFromSlash() throws IOException {
fsView.rename(new Path("/"), new Path("/bar"));
}
@Test(expected=AccessControlException.class)
public void testInternalSetOwner() throws IOException {
fsView.setOwner(new Path("/internalDir"), "foo", "bar");
}
@Test
public void testCreateNonRecursive() throws IOException {
Path path = fileSystemTestHelper.getTestRootPath(fsView, "/user/foo");
fsView.createNonRecursive(path, false, 1024, (short)1, 1024L, null);
FileStatus status = fsView.getFileStatus(new Path("/user/foo"));
Assert.assertTrue("Created file should be type file",
fsView.isFile(new Path("/user/foo")));
Assert.assertTrue("Target of created file should be type file",
fsTarget.isFile(new Path(targetTestRoot, "user/foo")));
}
@Test
public void testRootReadableExecutable() throws IOException {
testRootReadableExecutableInternal(false);
}
@Test
public void testLocatedRootReadableExecutable() throws IOException {
testRootReadableExecutableInternal(true);
}
private void testRootReadableExecutableInternal(boolean located)
throws IOException {
// verify executable permission on root: cd /
//
Assert.assertFalse("In root before cd",
fsView.getWorkingDirectory().isRoot());
fsView.setWorkingDirectory(new Path("/"));
Assert.assertTrue("Not in root dir after cd",
fsView.getWorkingDirectory().isRoot());
// verify readable
//
verifyRootChildren(listStatusInternal(located,
fsView.getWorkingDirectory()));
// verify permissions
//
final FileStatus rootStatus =
fsView.getFileStatus(fsView.getWorkingDirectory());
final FsPermission perms = rootStatus.getPermission();
Assert.assertTrue("User-executable permission not set!",
perms.getUserAction().implies(FsAction.EXECUTE));
Assert.assertTrue("User-readable permission not set!",
perms.getUserAction().implies(FsAction.READ));
Assert.assertTrue("Group-executable permission not set!",
perms.getGroupAction().implies(FsAction.EXECUTE));
Assert.assertTrue("Group-readable permission not set!",
perms.getGroupAction().implies(FsAction.READ));
Assert.assertTrue("Other-executable permission not set!",
perms.getOtherAction().implies(FsAction.EXECUTE));
Assert.assertTrue("Other-readable permission not set!",
perms.getOtherAction().implies(FsAction.READ));
}
/**
* Verify the behavior of ACL operations on paths above the root of
* any mount table entry.
*/
@Test(expected=AccessControlException.class)
public void testInternalModifyAclEntries() throws IOException {
fsView.modifyAclEntries(new Path("/internalDir"),
new ArrayList<AclEntry>());
}
@Test(expected=AccessControlException.class)
public void testInternalRemoveAclEntries() throws IOException {
fsView.removeAclEntries(new Path("/internalDir"),
new ArrayList<AclEntry>());
}
@Test(expected=AccessControlException.class)
public void testInternalRemoveDefaultAcl() throws IOException {
fsView.removeDefaultAcl(new Path("/internalDir"));
}
@Test(expected=AccessControlException.class)
public void testInternalRemoveAcl() throws IOException {
fsView.removeAcl(new Path("/internalDir"));
}
@Test(expected=AccessControlException.class)
public void testInternalSetAcl() throws IOException {
fsView.setAcl(new Path("/internalDir"), new ArrayList<AclEntry>());
}
@Test
public void testInternalGetAclStatus() throws IOException {
final UserGroupInformation currentUser =
UserGroupInformation.getCurrentUser();
AclStatus aclStatus = fsView.getAclStatus(new Path("/internalDir"));
assertEquals(aclStatus.getOwner(), currentUser.getUserName());
assertEquals(aclStatus.getGroup(), currentUser.getGroupNames()[0]);
assertEquals(aclStatus.getEntries(),
AclUtil.getMinimalAcl(PERMISSION_555));
assertFalse(aclStatus.isStickyBit());
}
@Test(expected=AccessControlException.class)
public void testInternalSetXAttr() throws IOException {
fsView.setXAttr(new Path("/internalDir"), "xattrName", null);
}
@Test(expected=NotInMountpointException.class)
public void testInternalGetXAttr() throws IOException {
fsView.getXAttr(new Path("/internalDir"), "xattrName");
}
@Test(expected=NotInMountpointException.class)
public void testInternalGetXAttrs() throws IOException {
fsView.getXAttrs(new Path("/internalDir"));
}
@Test(expected=NotInMountpointException.class)
public void testInternalGetXAttrsWithNames() throws IOException {
fsView.getXAttrs(new Path("/internalDir"), new ArrayList<String>());
}
@Test(expected=NotInMountpointException.class)
public void testInternalListXAttr() throws IOException {
fsView.listXAttrs(new Path("/internalDir"));
}
@Test(expected=AccessControlException.class)
public void testInternalRemoveXAttr() throws IOException {
fsView.removeXAttr(new Path("/internalDir"), "xattrName");
}
@Test(expected = AccessControlException.class)
public void testInternalCreateSnapshot1() throws IOException {
fsView.createSnapshot(new Path("/internalDir"));
}
@Test(expected = AccessControlException.class)
public void testInternalCreateSnapshot2() throws IOException {
fsView.createSnapshot(new Path("/internalDir"), "snap1");
}
@Test(expected = AccessControlException.class)
public void testInternalRenameSnapshot() throws IOException {
fsView.renameSnapshot(new Path("/internalDir"), "snapOldName",
"snapNewName");
}
@Test(expected = AccessControlException.class)
public void testInternalDeleteSnapshot() throws IOException {
fsView.deleteSnapshot(new Path("/internalDir"), "snap1");
}
@Test(expected = AccessControlException.class)
public void testInternalSetStoragePolicy() throws IOException {
fsView.setStoragePolicy(new Path("/internalDir"), "HOT");
}
@Test(expected = AccessControlException.class)
public void testInternalUnsetStoragePolicy() throws IOException {
fsView.unsetStoragePolicy(new Path("/internalDir"));
}
@Test(expected = NotInMountpointException.class)
public void testInternalgetStoragePolicy() throws IOException {
fsView.getStoragePolicy(new Path("/internalDir"));
}
@Test
public void testInternalGetAllStoragePolicies() throws IOException {
Collection<? extends BlockStoragePolicySpi> policies =
fsView.getAllStoragePolicies();
for (FileSystem fs : fsView.getChildFileSystems()) {
try {
for (BlockStoragePolicySpi s : fs.getAllStoragePolicies()) {
assertTrue("Missing policy: " + s, policies.contains(s));
}
} catch (UnsupportedOperationException e) {
// ignore
}
}
}
@Test
public void testConfLinkSlash() throws Exception {
String clusterName = "ClusterX";
URI viewFsUri = new URI(FsConstants.VIEWFS_SCHEME, clusterName,
"/", null, null);
Configuration newConf = new Configuration();
ConfigUtil.addLink(newConf, clusterName, "/",
new Path(targetTestRoot, "/").toUri());
String mtPrefix = Constants.CONFIG_VIEWFS_PREFIX + "." + clusterName + ".";
try {
FileSystem.get(viewFsUri, newConf);
fail("ViewFileSystem should error out on mount table entry: "
+ mtPrefix + Constants.CONFIG_VIEWFS_LINK + "." + "/");
} catch (Exception e) {
if (e instanceof UnsupportedFileSystemException) {
String msg = " Use " + Constants.CONFIG_VIEWFS_LINK_MERGE_SLASH +
" instead";
assertThat(e.getMessage(), containsString(msg));
} else {
fail("Unexpected exception: " + e.getMessage());
}
}
}
@Test
public void testTrashRoot() throws IOException {
Path mountDataRootPath = new Path("/data");
Path fsTargetFilePath = new Path("debug.log");
Path mountDataFilePath = new Path(mountDataRootPath, fsTargetFilePath);
Path mountDataNonExistingFilePath = new Path(mountDataRootPath, "no.log");
fileSystemTestHelper.createFile(fsTarget, fsTargetFilePath);
// Get Trash roots for paths via ViewFileSystem handle
Path mountDataRootTrashPath = fsView.getTrashRoot(mountDataRootPath);
Path mountDataFileTrashPath = fsView.getTrashRoot(mountDataFilePath);
// Get Trash roots for the same set of paths via the mounted filesystem
Path fsTargetRootTrashRoot = fsTarget.getTrashRoot(mountDataRootPath);
Path fsTargetFileTrashPath = fsTarget.getTrashRoot(mountDataFilePath);
// Verify if Trash roots from ViewFileSystem matches that of the ones
// from the target mounted FileSystem.
assertEquals(mountDataRootTrashPath.toUri().getPath(),
fsTargetRootTrashRoot.toUri().getPath());
assertEquals(mountDataFileTrashPath.toUri().getPath(),
fsTargetFileTrashPath.toUri().getPath());
assertEquals(mountDataRootTrashPath.toUri().getPath(),
mountDataFileTrashPath.toUri().getPath());
// Verify trash root for an non-existing file but on a valid mountpoint.
Path trashRoot = fsView.getTrashRoot(mountDataNonExistingFilePath);
assertEquals(mountDataRootTrashPath.toUri().getPath(),
trashRoot.toUri().getPath());
// Verify trash root for invalid mounts.
Path invalidMountRootPath = new Path("/invalid_mount");
Path invalidMountFilePath = new Path(invalidMountRootPath, "debug.log");
try {
fsView.getTrashRoot(invalidMountRootPath);
fail("ViewFileSystem getTashRoot should fail for non-mountpoint paths.");
} catch (NotInMountpointException e) {
//expected exception
}
try {
fsView.getTrashRoot(invalidMountFilePath);
fail("ViewFileSystem getTashRoot should fail for non-mountpoint paths.");
} catch (NotInMountpointException e) {
//expected exception
}
try {
fsView.getTrashRoot(null);
fail("ViewFileSystem getTashRoot should fail for empty paths.");
} catch (NotInMountpointException e) {
//expected exception
}
// Move the file to trash
FileStatus fileStatus = fsTarget.getFileStatus(fsTargetFilePath);
Configuration newConf = new Configuration(conf);
newConf.setLong("fs.trash.interval", 1000);
Trash lTrash = new Trash(fsTarget, newConf);
boolean trashed = lTrash.moveToTrash(fsTargetFilePath);
Assert.assertTrue("File " + fileStatus + " move to " +
"trash failed.", trashed);
// Verify ViewFileSystem trash roots shows the ones from
// target mounted FileSystem.
Assert.assertTrue("", fsView.getTrashRoots(true).size() > 0);
}
@Test(expected = NotInMountpointException.class)
public void testViewFileSystemUtil() throws Exception {
Configuration newConf = new Configuration(conf);
FileSystem fileSystem = FileSystem.get(FsConstants.LOCAL_FS_URI,
newConf);
Assert.assertFalse("Unexpected FileSystem: " + fileSystem,
ViewFileSystemUtil.isViewFileSystem(fileSystem));
fileSystem = FileSystem.get(FsConstants.VIEWFS_URI,
newConf);
Assert.assertTrue("Unexpected FileSystem: " + fileSystem,
ViewFileSystemUtil.isViewFileSystem(fileSystem));
// Case 1: Verify FsStatus of root path returns all MountPoints status.
Map<MountPoint, FsStatus> mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem, InodeTree.SlashPath);
Assert.assertEquals(getExpectedMountPoints(), mountPointFsStatusMap.size());
// Case 2: Verify FsStatus of an internal dir returns all
// MountPoints status.
mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem, new Path("/internalDir"));
Assert.assertEquals(getExpectedMountPoints(), mountPointFsStatusMap.size());
// Case 3: Verify FsStatus of a matching MountPoint returns exactly
// the corresponding MountPoint status.
mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem, new Path("/user"));
Assert.assertEquals(1, mountPointFsStatusMap.size());
for (Entry<MountPoint, FsStatus> entry : mountPointFsStatusMap.entrySet()) {
Assert.assertEquals(entry.getKey().getMountedOnPath().toString(),
"/user");
}
// Case 4: Verify FsStatus of a path over a MountPoint returns the
// corresponding MountPoint status.
mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem, new Path("/user/cloud"));
Assert.assertEquals(1, mountPointFsStatusMap.size());
for (Entry<MountPoint, FsStatus> entry : mountPointFsStatusMap.entrySet()) {
Assert.assertEquals(entry.getKey().getMountedOnPath().toString(),
"/user");
}
// Case 5: Verify FsStatus of any level of an internal dir
// returns all MountPoints status.
mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem,
new Path("/internalDir/internalDir2"));
Assert.assertEquals(getExpectedMountPoints(), mountPointFsStatusMap.size());
// Case 6: Verify FsStatus of a MountPoint URI returns
// the MountPoint status.
mountPointFsStatusMap =
ViewFileSystemUtil.getStatus(fileSystem, new Path("viewfs:/user/"));
Assert.assertEquals(1, mountPointFsStatusMap.size());
for (Entry<MountPoint, FsStatus> entry : mountPointFsStatusMap.entrySet()) {
Assert.assertEquals(entry.getKey().getMountedOnPath().toString(),
"/user");
}
// Case 7: Verify FsStatus of a non MountPoint path throws exception
ViewFileSystemUtil.getStatus(fileSystem, new Path("/non-existing"));
}
@Test
public void testCheckOwnerWithFileStatus()
throws IOException, InterruptedException {
final UserGroupInformation userUgi = UserGroupInformation
.createUserForTesting("[email protected]", new String[]{"hadoop"});
userUgi.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws IOException {
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
String doAsUserName = ugi.getUserName();
assertEquals(doAsUserName, "[email protected]");
FileSystem vfs = FileSystem.get(FsConstants.VIEWFS_URI, conf);
FileStatus stat = vfs.getFileStatus(new Path("/internalDir"));
assertEquals(userUgi.getShortUserName(), stat.getOwner());
return null;
}
});
}
@Test
public void testUsed() throws IOException {
try {
fsView.getUsed();
fail("ViewFileSystem getUsed() should fail for slash root path when the" +
" slash root mount point is not configured.");
} catch (NotInMountpointException e) {
// expected exception.
}
long usedSpaceByPathViaViewFs = fsView.getUsed(new Path("/user"));
long usedSpaceByPathViaTargetFs =
fsTarget.getUsed(new Path(targetTestRoot, "user"));
assertEquals("Space used not matching between ViewFileSystem and " +
"the mounted FileSystem!",
usedSpaceByPathViaTargetFs, usedSpaceByPathViaViewFs);
Path mountDataRootPath = new Path("/data");
String fsTargetFileName = "debug.log";
Path fsTargetFilePath = new Path(targetTestRoot, "data/debug.log");
Path mountDataFilePath = new Path(mountDataRootPath, fsTargetFileName);
fileSystemTestHelper.createFile(fsTarget, fsTargetFilePath);
usedSpaceByPathViaViewFs = fsView.getUsed(mountDataFilePath);
usedSpaceByPathViaTargetFs = fsTarget.getUsed(fsTargetFilePath);
assertEquals("Space used not matching between ViewFileSystem and " +
"the mounted FileSystem!",
usedSpaceByPathViaTargetFs, usedSpaceByPathViaViewFs);
}
@Test
public void testLinkTarget() throws Exception {
Assume.assumeTrue(fsTarget.supportsSymlinks() &&
fsTarget.areSymlinksEnabled());
// Symbolic link
final String targetFileName = "debug.log";
final String linkFileName = "debug.link";
final Path targetFile = new Path(targetTestRoot, targetFileName);
final Path symLink = new Path(targetTestRoot, linkFileName);
FileSystemTestHelper.createFile(fsTarget, targetFile);
fsTarget.createSymlink(targetFile, symLink, false);
final Path mountTargetRootPath = new Path("/targetRoot");
final Path mountTargetSymLinkPath = new Path(mountTargetRootPath,
linkFileName);
final Path expectedMountLinkTarget = fsTarget.makeQualified(
new Path(targetTestRoot, targetFileName));
final Path actualMountLinkTarget = fsView.getLinkTarget(
mountTargetSymLinkPath);
assertEquals("Resolved link target path not matching!",
expectedMountLinkTarget, actualMountLinkTarget);
// Relative symbolic link
final String relativeFileName = "dir2/../" + targetFileName;
final String link2FileName = "dir2/rel.link";
final Path relTargetFile = new Path(targetTestRoot, relativeFileName);
final Path relativeSymLink = new Path(targetTestRoot, link2FileName);
fsTarget.createSymlink(relTargetFile, relativeSymLink, true);
final Path mountTargetRelativeSymLinkPath = new Path(mountTargetRootPath,
link2FileName);
final Path expectedMountRelLinkTarget = fsTarget.makeQualified(
new Path(targetTestRoot, relativeFileName));
final Path actualMountRelLinkTarget = fsView.getLinkTarget(
mountTargetRelativeSymLinkPath);
assertEquals("Resolved relative link target path not matching!",
expectedMountRelLinkTarget, actualMountRelLinkTarget);
try {
fsView.getLinkTarget(new Path("/linkToAFile"));
fail("Resolving link target for a ViewFs mount link should fail!");
} catch (Exception e) {
LOG.info("Expected exception: " + e);
assertThat(e.getMessage(),
containsString("not a symbolic link"));
}
try {
fsView.getLinkTarget(fsView.makeQualified(
new Path(mountTargetRootPath, targetFileName)));
fail("Resolving link target for a non sym link should fail!");
} catch (Exception e) {
LOG.info("Expected exception: " + e);
assertThat(e.getMessage(),
containsString("not a symbolic link"));
}
try {
fsView.getLinkTarget(new Path("/targetRoot/non-existing-file"));
fail("Resolving link target for a non existing link should fail!");
} catch (Exception e) {
LOG.info("Expected exception: " + e);
assertThat(e.getMessage(),
containsString("File does not exist:"));
}
}
}
| {'content_hash': 'ba7c319b1d879dac26ac2efd99f289a0', 'timestamp': '', 'source': 'github', 'line_count': 1258, 'max_line_length': 116, 'avg_line_length': 39.59220985691574, 'alnum_prop': 0.7159435420723994, 'repo_name': 'hopshadoop/hops', 'id': '8d7fdfeec1fbe63bf39c429d12f4f3f499386009', 'size': '50613', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/viewfs/ViewFileSystemBaseTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '31146'}, {'name': 'Batchfile', 'bytes': '77936'}, {'name': 'C', 'bytes': '1728229'}, {'name': 'C++', 'bytes': '1959516'}, {'name': 'CMake', 'bytes': '61606'}, {'name': 'CSS', 'bytes': '52920'}, {'name': 'Dockerfile', 'bytes': '6880'}, {'name': 'HTML', 'bytes': '123864'}, {'name': 'Handlebars', 'bytes': '193969'}, {'name': 'Java', 'bytes': '74856197'}, {'name': 'JavaScript', 'bytes': '1071281'}, {'name': 'Perl', 'bytes': '9496'}, {'name': 'Python', 'bytes': '65367'}, {'name': 'SCSS', 'bytes': '23287'}, {'name': 'Shell', 'bytes': '427454'}, {'name': 'SystemVerilog', 'bytes': '83593'}, {'name': 'TLA', 'bytes': '14993'}, {'name': 'TSQL', 'bytes': '17692'}, {'name': 'TeX', 'bytes': '19322'}, {'name': 'XSLT', 'bytes': '23464'}]} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// 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: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.types._1;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for zfcs_documentComplianceEnum.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="zfcs_documentComplianceEnum">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="A"/>
* <enumeration value="U"/>
* <enumeration value="O"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "zfcs_documentComplianceEnum")
@XmlEnum
public enum ZfcsDocumentComplianceEnum {
A,
U,
O;
public String value() {
return name();
}
public static ZfcsDocumentComplianceEnum fromValue(String v) {
return valueOf(v);
}
}
| {'content_hash': 'd0cd04eb33140c23883b6b0b85db86ca', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 122, 'avg_line_length': 25.80851063829787, 'alnum_prop': 0.6784830997526793, 'repo_name': 'simokhov/schemas44', 'id': '50a665dcd059727ff6021470efa739f3d44f755e', 'size': '1213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsDocumentComplianceEnum.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '22048974'}]} |
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';
import { isScheduler } from '../util/isScheduler';
import { isArray } from '../util/isArray';
import { Subscriber } from '../Subscriber';
import { OuterSubscriber } from '../OuterSubscriber';
import { Operator } from '../Operator';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { fromArray } from './fromArray';
const NONE = {};
/* tslint:disable:max-line-length */
// If called with a single array, it "auto-spreads" the array, with result selector
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, R>(sources: [O1], resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(sources: [O1, O2], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(sources: [O1, O2, O3], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5, O6], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O extends ObservableInput<any>, R>(sources: O[], resultSelector: (...args: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;
// standard call, but with a result selector
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, R>(v1: O1, resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;
// With a scheduler (deprecated)
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>>(sources: [O1], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>>(sources: O[], scheduler: SchedulerLike): Observable<ObservedValueOf<O>[]>;
// Best case
export function combineLatest<O1 extends ObservableInput<any>>(sources: [O1]): Observable<[ObservedValueOf<O1>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
export function combineLatest<O extends ObservableInput<any>>(sources: O[]): Observable<ObservedValueOf<O>[]>;
// Standard calls
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>>(v1: O1, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O extends ObservableInput<any>>(...observables: O[]): Observable<any[]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O extends ObservableInput<any>, R>(array: O[], resultSelector: (...values: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>>(...observables: Array<O | SchedulerLike>): Observable<any[]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike>): Observable<R>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R) | SchedulerLike>): Observable<R>;
/* tslint:enable:max-line-length */
/**
* Combines multiple Observables to create an Observable whose values are
* calculated from the latest values of each of its input Observables.
*
* <span class="informal">Whenever any input Observable emits a value, it
* computes a formula using the latest values from all the inputs, then emits
* the output of that formula.</span>
*
* 
*
* `combineLatest` combines the values from all the Observables passed in the
* observables array. This is done by subscribing to each Observable in order and,
* whenever any Observable emits, collecting an array of the most recent
* values from each Observable. So if you pass `n` Observables to this operator,
* the returned Observable will always emit an array of `n` values, in an order
* corresponding to the order of the passed Observables (the value from the first Observable
* will be at index 0 of the array and so on).
*
* Static version of `combineLatest` accepts an array of Observables. Note that an array of
* Observables is a good choice, if you don't know beforehand how many Observables
* you will combine. Passing an empty array will result in an Observable that
* completes immediately.
*
* To ensure the output array always has the same length, `combineLatest` will
* actually wait for all input Observables to emit at least once,
* before it starts emitting results. This means if some Observable emits
* values before other Observables started emitting, all these values but the last
* will be lost. On the other hand, if some Observable does not emit a value but
* completes, resulting Observable will complete at the same moment without
* emitting anything, since it will now be impossible to include a value from the
* completed Observable in the resulting array. Also, if some input Observable does
* not emit any value and never completes, `combineLatest` will also never emit
* and never complete, since, again, it will wait for all streams to emit some
* value.
*
* If at least one Observable was passed to `combineLatest` and all passed Observables
* emitted something, the resulting Observable will complete when all combined
* streams complete. So even if some Observable completes, the result of
* `combineLatest` will still emit values when other Observables do. In case
* of a completed Observable, its value from now on will always be the last
* emitted value. On the other hand, if any Observable errors, `combineLatest`
* will error immediately as well, and all other Observables will be unsubscribed.
*
* ## Examples
* ### Combine two timer Observables
* ```ts
* import { combineLatest, timer } from 'rxjs';
*
* const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
* const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
* const combinedTimers = combineLatest([firstTimer, secondTimer]);
* combinedTimers.subscribe(value => console.log(value));
* // Logs
* // [0, 0] after 0.5s
* // [1, 0] after 1s
* // [1, 1] after 1.5s
* // [2, 1] after 2s
* ```
*
* ### Combine an array of Observables
* ```ts
* import { combineLatest, of } from 'rxjs';
* import { delay, startWith } from 'rxjs/operators';
*
* const observables = [1, 5, 10].map(
* n => of(n).pipe(
* delay(n * 1000), // emit 0 and then emit n after n seconds
* startWith(0),
* )
* );
* const combined = combineLatest(observables);
* combined.subscribe(value => console.log(value));
* // Logs
* // [0, 0, 0] immediately
* // [1, 0, 0] after 1s
* // [1, 5, 0] after 5s
* // [1, 5, 10] after 10s
* ```
*
*
* ### Use map operator to dynamically calculate the Body-Mass Index
* ```ts
* import { combineLatest, of } from 'rxjs';
* import { map } from 'rxjs/operators';
*
* const weight = of(70, 72, 76, 79, 75);
* const height = of(1.76, 1.77, 1.78);
* const bmi = combineLatest([weight, height]).pipe(
* map(([w, h]) => w / (h * h)),
* );
* bmi.subscribe(x => console.log('BMI is ' + x));
*
* // With output to console:
* // BMI is 24.212293388429753
* // BMI is 23.93948099205209
* // BMI is 23.671253629592222
* ```
*
* @see {@link combineAll}
* @see {@link merge}
* @see {@link withLatestFrom}
*
* @param {ObservableInput} [observables] An array of input Observables to combine with each other.
* An array of Observables must be given as the first argument.
* @param {function} [project] An optional function to project the values from
* the combined latest values into a new value on the output Observable.
* @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to
* each input Observable.
* @return {Observable} An Observable of projected values from the most recent
* values from each input Observable, or an array of the most recent values from
* each input Observable.
*/
export function combineLatest<O extends ObservableInput<any>, R>(
...observables: (O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike)[]
): Observable<R> {
let resultSelector: ((...values: Array<any>) => R) | undefined = undefined;
let scheduler: SchedulerLike | undefined = undefined;
if (isScheduler(observables[observables.length - 1])) {
scheduler = observables.pop() as SchedulerLike;
}
if (typeof observables[observables.length - 1] === 'function') {
resultSelector = observables.pop() as (...values: Array<any>) => R;
}
// if the first and only other argument besides the resultSelector is an array
// assume it's been called with `combineLatest([obs1, obs2, obs3], resultSelector)`
if (observables.length === 1 && isArray(observables[0])) {
observables = observables[0] as any;
}
return fromArray(observables, scheduler).lift(new CombineLatestOperator<ObservedValueOf<O>, R>(resultSelector));
}
export class CombineLatestOperator<T, R> implements Operator<T, R> {
constructor(private resultSelector?: (...values: Array<any>) => R) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class CombineLatestSubscriber<T, R> extends OuterSubscriber<T, R> {
private active: number = 0;
private values: any[] = [];
private observables: any[] = [];
private toRespond: number | undefined;
constructor(destination: Subscriber<R>, private resultSelector?: (...values: Array<any>) => R) {
super(destination);
}
protected _next(observable: any) {
this.values.push(NONE);
this.observables.push(observable);
}
protected _complete() {
const observables = this.observables;
const len = observables.length;
if (len === 0) {
this.destination.complete();
} else {
this.active = len;
this.toRespond = len;
for (let i = 0; i < len; i++) {
const observable = observables[i];
this.add(subscribeToResult(this, observable, observable, i));
}
}
}
notifyComplete(unused: Subscriber<R>): void {
if ((this.active -= 1) === 0) {
this.destination.complete();
}
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
const values = this.values;
const oldVal = values[outerIndex];
const toRespond = !this.toRespond
? 0
: oldVal === NONE ? --this.toRespond : this.toRespond;
values[outerIndex] = innerValue;
if (toRespond === 0) {
if (this.resultSelector) {
this._tryResultSelector(values);
} else {
this.destination.next(values.slice());
}
}
}
private _tryResultSelector(values: any[]) {
let result: any;
try {
result = this.resultSelector!.apply(this, values);
} catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
| {'content_hash': 'cf0f542fd04fde056530adf4d4e161ac', 'timestamp': '', 'source': 'github', 'line_count': 318, 'max_line_length': 494, 'avg_line_length': 69.0251572327044, 'alnum_prop': 0.7325284738041002, 'repo_name': 'trxcllnt/RxJS', 'id': 'c9c0e0a0aaf99ae41c575bfef036252b9f29e2c2', 'size': '21950', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/internal/observable/combineLatest.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '7766'}, {'name': 'JavaScript', 'bytes': '180081'}, {'name': 'Shell', 'bytes': '457'}, {'name': 'TypeScript', 'bytes': '1944185'}]} |
<?php
declare(strict_types=1);
namespace DI\Test\UnitTest\Annotation;
use DI\Annotation\Injectable;
use DI\Definition\Source\AnnotationBasedAutowiring;
use DI\Test\UnitTest\Annotation\Fixtures\Injectable1;
use DI\Test\UnitTest\Annotation\Fixtures\Injectable2;
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
use ReflectionClass;
/**
* Injectable annotation test class.
*
* @covers \DI\Annotation\Injectable
*/
class InjectableTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DoctrineAnnotationReader
*/
private $annotationReader;
public function setUp()
{
$definitionReader = new AnnotationBasedAutowiring();
$this->annotationReader = $definitionReader->getAnnotationReader();
}
public function testEmptyAnnotation()
{
$class = new ReflectionClass(Injectable1::class);
/** @var $annotation Injectable */
$annotation = $this->annotationReader->getClassAnnotation($class, Injectable::class);
$this->assertInstanceOf(Injectable::class, $annotation);
$this->assertNull($annotation->isLazy());
}
public function testLazy()
{
$class = new ReflectionClass(Injectable2::class);
/** @var $annotation Injectable */
$annotation = $this->annotationReader->getClassAnnotation($class, Injectable::class);
$this->assertInstanceOf(Injectable::class, $annotation);
$this->assertTrue($annotation->isLazy());
}
}
| {'content_hash': '7a7f35989f2c8591588a36090036a61a', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 93, 'avg_line_length': 29.254901960784313, 'alnum_prop': 0.7010723860589813, 'repo_name': 'jaakon/PHP-DI', 'id': '1695519ea7612e0df85c2370d4ba973e5e151e3b', 'size': '1492', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/UnitTest/Annotation/InjectableTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9801'}, {'name': 'HTML', 'bytes': '34428'}, {'name': 'Makefile', 'bytes': '727'}, {'name': 'PHP', 'bytes': '450809'}]} |
function f = fliplr(f) %#ok<INUSD>
%FLIPLR Flip columns of an array-valued SINGFUN object.
% Since SINGFUN objects cannot be array-valued FLIPLR(F) returns F.
% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.
end
| {'content_hash': '50ab9aa8a52939e7db6e74650454affc', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 72, 'avg_line_length': 37.125, 'alnum_prop': 0.7542087542087542, 'repo_name': 'alshedivat/chebfun', 'id': '7fdf543af51317497250b351a5797cce91bb015c', 'size': '297', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': '@singfun/fliplr.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'M', 'bytes': '4938'}, {'name': 'Matlab', 'bytes': '6012627'}, {'name': 'Objective-C', 'bytes': '977'}]} |
package me.caprei.crazyctf.classes;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.caprei.crazyctf.game.GamePlayer;
public class ClassManager {
private static ClassManager manager = new ClassManager();
private ClassManager(){};
public ClassManager getClassManager(){
return manager;
}
public static void assignKit(GamePlayer player){
for(ItemStack itemStack:player.getKit().getClassInstance().getInventoryItems()){
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
itemStack.setItemMeta(itemMeta);
}
for(ItemStack itemStack:player.getKit().getClassInstance().getWearableItems()){
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
itemStack.setItemMeta(itemMeta);
}
player.getPlayer().getInventory().clear();
player.getPlayer().getInventory().setArmorContents((ItemStack[]) player.getKit().getClassInstance().wearableItems.toArray());
player.getPlayer().getInventory().addItem((ItemStack[]) player.getKit().getClassInstance().inventoryItems.toArray());
}
}
| {'content_hash': 'a658ca1a500c5979afce7dab2119f5b0', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 127, 'avg_line_length': 33.108108108108105, 'alnum_prop': 0.7444897959183674, 'repo_name': 'Caprei/CrazyCTF', 'id': 'f89856a9093ae19047752829f00aa261c9366dc1', 'size': '1225', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CrazyCTF/src/me/caprei/crazyctf/classes/ClassManager.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '41699'}]} |
DROP table if exists PERSONS;
create table if not exists PERSONS (
ID int identity primary key,
FIRST_NAME varchar,
LAST_NAME varchar
)
| {'content_hash': '08206f3254626347003c68e6aa62dfc7', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 36, 'avg_line_length': 23.666666666666668, 'alnum_prop': 0.7535211267605634, 'repo_name': 'mwaleria/jdbchelper', 'id': 'b3f56ba5001ed037e05ff57fa68d110037531c32', 'size': '142', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/resources/schema.sql', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '23930'}]} |
const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const baseWebPackConfig = require('./webpack.server');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsPlugin = require('@soda/friendly-errors-webpack-plugin');
const buildpaths = require('../buildpaths');
baseWebPackConfig.entry.unshift('webpack-hot-middleware/client?reload=true');
module.exports = merge(baseWebPackConfig, {
mode: 'development',
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
}),
new webpack.HotModuleReplacementPlugin()
]
}); | {'content_hash': '14b993f0be16d001dbfbc91bb5bcab11', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 77, 'avg_line_length': 34.1, 'alnum_prop': 0.7023460410557185, 'repo_name': 'Cobbleopolis/DragonConTimer', 'id': '86e374eccd47bac70809eb5b6e4c8cef754a4504', 'size': '682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/webpack.server.dev.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '446'}, {'name': 'HTML', 'bytes': '234'}, {'name': 'JavaScript', 'bytes': '56674'}, {'name': 'Sass', 'bytes': '8664'}, {'name': 'Vue', 'bytes': '41882'}]} |
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rMargen_gNivelRotacion"
'-------------------------------------------------------------------------------------------'
Partial Class rMargen_gNivelRotacion
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8))
Dim lcParametro9Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(9))
Dim lcParametro9Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(9))
Dim lcParametro10Desde As String = cusAplicacion.goReportes.paParametrosIniciales(10)
Dim lcParametro11Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(11))
Dim lcParametro11Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(11))
Dim lcParametro12Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(12))
Dim lcParametro12Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(12))
Dim lcParametro13Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(13))
Dim lcParametro13Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(13))
Dim lcParametro14Desde As String = cusAplicacion.goReportes.paParametrosIniciales(14)
Dim lcParametro15Desde As String = cusAplicacion.goReportes.paParametrosIniciales(15)
Dim lcParametro16Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(16))
Dim lcParametro16Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(16))
Dim lcParametro17Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(17))
Dim lcParametro17Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(17))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim lcCosto As String = ""
Select Case lcParametro10Desde
Case "Promedio MP"
lcCosto = "Cos_Pro1"
Case "Ultimo MP"
lcCosto = "Cos_Ult1"
Case "Anterior MP"
lcCosto = "Cos_Ant1"
Case "Promedio MS"
lcCosto = "Cos_Pro2"
Case "Ultimo MS"
lcCosto = "Cos_Ult2"
Case "Anterior MS"
lcCosto = "Cos_Ant2"
End Select
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("CREATE TABLE #tmpGanancia( Cod_Art CHAR(30), ")
loComandoSeleccionar.AppendLine(" Can_Art DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Can_Fac DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Can_Dev DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Base_A DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Base_B DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Costo_A DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Costo_B DECIMAL(28, 10)) ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine("CREATE TABLE #tmpFinal( Cod_Art CHAR(30), ")
loComandoSeleccionar.AppendLine(" Can_Art DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Can_Fac DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Can_Dev DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Base_A DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Base_B DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Costo_A DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Costo_B DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Ganancia_A DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Ganancia_B DECIMAL(28, 10), ")
loComandoSeleccionar.AppendLine(" Nivel INT) ")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("/* Datos de Venta */")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("INSERT INTO #tmpGanancia(Cod_Art, Can_Art, Can_Fac, Can_Dev, Base_A, Base_B, Costo_A, Costo_B)")
loComandoSeleccionar.AppendLine("SELECT Articulos.Cod_Art AS Cod_Art,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Facturas.Can_Art1) AS Can_Art,")
loComandoSeleccionar.AppendLine(" COUNT(DISTINCT Facturas.Documento) AS Can_Fac,")
loComandoSeleccionar.AppendLine(" 0 AS Can_Dev,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Facturas.Mon_Net) AS Base_A,")
loComandoSeleccionar.AppendLine(" 0 AS Base_B,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Facturas.Can_Art1*Renglones_Facturas." & lcCosto & ") AS Costo_A,")
loComandoSeleccionar.AppendLine(" 0 AS Costo_B")
loComandoSeleccionar.AppendLine("FROM Clientes")
loComandoSeleccionar.AppendLine(" JOIN Facturas ")
loComandoSeleccionar.AppendLine(" ON Facturas.Cod_Cli = Clientes.Cod_Cli")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Facturas ")
loComandoSeleccionar.AppendLine(" ON Renglones_Facturas.Documento = Facturas.Documento")
loComandoSeleccionar.AppendLine(" JOIN Vendedores ")
loComandoSeleccionar.AppendLine(" ON Vendedores.Cod_Ven = Facturas.Cod_Ven")
loComandoSeleccionar.AppendLine(" JOIN Articulos ")
loComandoSeleccionar.AppendLine(" ON Renglones_Facturas.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine("WHERE Facturas.Documento BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Cli BETWEEN " & lcParametro2Desde & " AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Clientes.Cod_Tip BETWEEN " & lcParametro3Desde & " AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Clientes.Cod_Cla BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Ven BETWEEN " & lcParametro5Desde & " AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Tip BETWEEN " & lcParametro6Desde & " AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Status IN (" & lcParametro7Desde & ")")
'loComandoSeleccionar.AppendLine(" AND Facturas.Status IN ('Confirmado', 'Afectado', 'Procesado')")
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Cod_Art BETWEEN " & lcParametro8Desde & " AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro9Desde & " AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Mon BETWEEN " & lcParametro11Desde & " AND " & lcParametro11Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Tra BETWEEN " & lcParametro12Desde & " AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_For BETWEEN " & lcParametro13Desde & " AND " & lcParametro13Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Rev BETWEEN " & lcParametro16Desde & " AND " & lcParametro16Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Suc BETWEEN " & lcParametro17Desde & " AND " & lcParametro17Hasta)
loComandoSeleccionar.AppendLine("GROUP BY Articulos.Cod_Art")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("/* Datos de Devoluciones */")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("INSERT INTO #tmpGanancia(Cod_Art, Can_Art, Can_Fac, Can_Dev, Base_A, Base_B, Costo_A, Costo_B)")
loComandoSeleccionar.AppendLine("SELECT Articulos.Cod_Art AS Cod_Art,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_dClientes.Can_Art1) AS Can_Art,")
loComandoSeleccionar.AppendLine(" 0 AS Can_Fac,")
loComandoSeleccionar.AppendLine(" COUNT(DISTINCT Devoluciones_Clientes.Documento) AS Can_Dev,")
loComandoSeleccionar.AppendLine(" 0 AS Base_A,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_dClientes.Mon_Net) AS Base_B,")
loComandoSeleccionar.AppendLine(" 0 AS Costo_A,")
loComandoSeleccionar.AppendLine(" SUM(Renglones_dClientes.Can_Art1*Renglones_dClientes.Cos_Pro1) AS Costo_B")
loComandoSeleccionar.AppendLine("FROM Clientes")
loComandoSeleccionar.AppendLine(" JOIN Devoluciones_Clientes ")
loComandoSeleccionar.AppendLine(" ON Devoluciones_Clientes.Cod_Cli = Clientes.Cod_Cli")
loComandoSeleccionar.AppendLine(" JOIN Renglones_dClientes ")
loComandoSeleccionar.AppendLine(" ON Renglones_dClientes.Documento = Devoluciones_Clientes.Documento")
loComandoSeleccionar.AppendLine(" AND Renglones_dClientes.tip_Ori = 'Facturas'")
loComandoSeleccionar.AppendLine(" JOIN Vendedores ")
loComandoSeleccionar.AppendLine(" ON Vendedores.Cod_Ven = Devoluciones_Clientes.Cod_Ven")
loComandoSeleccionar.AppendLine(" JOIN Articulos ")
loComandoSeleccionar.AppendLine(" ON Renglones_dClientes.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine("WHERE Devoluciones_Clientes.Documento BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Fec_Ini BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Cli BETWEEN " & lcParametro2Desde & " AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Clientes.Cod_Tip BETWEEN " & lcParametro3Desde & " AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Clientes.Cod_Cla BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Ven BETWEEN " & lcParametro5Desde & " AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Tip BETWEEN " & lcParametro6Desde & " AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Status IN (" & lcParametro7Desde & ")")
'loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Status IN ('Confirmado', 'Afectado', 'Procesado')")
loComandoSeleccionar.AppendLine(" AND Renglones_dClientes.Cod_Art BETWEEN " & lcParametro8Desde & " AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro9Desde & " AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Mon BETWEEN " & lcParametro11Desde & " AND " & lcParametro11Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Tra BETWEEN " & lcParametro12Desde & " AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_For BETWEEN " & lcParametro13Desde & " AND " & lcParametro13Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Rev BETWEEN " & lcParametro16Desde & " AND " & lcParametro16Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Suc BETWEEN " & lcParametro17Desde & " AND " & lcParametro17Hasta)
loComandoSeleccionar.AppendLine("GROUP BY Articulos.Cod_Art")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("DECLARE @lnMaximo DECIMAL(28, 10);")
loComandoSeleccionar.AppendLine("SET @lnMaximo = (SELECT MAX(Can_Art) AS Maximo FROM #tmpGanancia)")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("/* Cálculo de ganancia y nivel */ ")
loComandoSeleccionar.AppendLine("/*------------------------------------------------------------------------------------------*/")
loComandoSeleccionar.AppendLine("INSERT INTO #tmpFinal(Cod_Art, Can_Art, Can_Fac, Can_Dev, Base_A, Base_B, Costo_A, Costo_B, Ganancia_A, Ganancia_B, Nivel)")
loComandoSeleccionar.AppendLine("SELECT Cod_Art AS Cod_Art,")
loComandoSeleccionar.AppendLine(" SUM(Can_Art) AS Can_Art,")
loComandoSeleccionar.AppendLine(" SUM(Can_Fac) AS Can_Fac,")
loComandoSeleccionar.AppendLine(" SUM(Can_Dev) AS Can_Dev,")
loComandoSeleccionar.AppendLine(" SUM(Base_A) AS Base_A,")
loComandoSeleccionar.AppendLine(" SUM(Base_B) AS Base_B,")
loComandoSeleccionar.AppendLine(" SUM(Costo_A) AS Costo_A,")
loComandoSeleccionar.AppendLine(" SUM(Costo_B) AS Costo_B,")
loComandoSeleccionar.AppendLine(" 0 AS Ganancia_A,")
loComandoSeleccionar.AppendLine(" 0 AS Ganancia_B,")
loComandoSeleccionar.AppendLine(" (CASE ")
loComandoSeleccionar.AppendLine(" WHEN SUM(Can_Art)*100/@lnMaximo <= 25 THEN 25")
loComandoSeleccionar.AppendLine(" WHEN SUM(Can_Art)*100/@lnMaximo <= 50 THEN 50")
loComandoSeleccionar.AppendLine(" WHEN SUM(Can_Art)*100/@lnMaximo <= 75 THEN 75")
loComandoSeleccionar.AppendLine(" ELSE 100")
loComandoSeleccionar.AppendLine(" END) AS Nivel")
loComandoSeleccionar.AppendLine("FROM #tmpGanancia")
loComandoSeleccionar.AppendLine("GROUP BY Cod_Art")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("UPDATE #tmpFinal")
loComandoSeleccionar.AppendLine("SET Ganancia_A = (Base_A -Base_B) - (Costo_A - Costo_B)")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT SUM(Can_Dev) AS Can_Dev,")
loComandoSeleccionar.AppendLine(" SUM(Base_A) AS Base_A,")
loComandoSeleccionar.AppendLine(" SUM(Base_B) AS Base_B,")
loComandoSeleccionar.AppendLine(" SUM(Costo_A) AS Costo_A,")
loComandoSeleccionar.AppendLine(" SUM(Costo_B) AS Costo_B,")
loComandoSeleccionar.AppendLine(" SUM(Ganancia_A) AS Ganancia_A,")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN SUM(Base_A - Base_B) <> 0")
loComandoSeleccionar.AppendLine(" THEN SUM(Ganancia_A)*100 / SUM(Base_A - Base_B)")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Ganancia_B,")
loComandoSeleccionar.AppendLine(" Nivel AS Nivel")
loComandoSeleccionar.AppendLine("INTO #tmpFinal2")
loComandoSeleccionar.AppendLine("FROM #tmpFinal")
loComandoSeleccionar.AppendLine("GROUP BY Nivel")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT Can_Dev AS Can_Dev,")
loComandoSeleccionar.AppendLine(" Base_A AS Base_A,")
loComandoSeleccionar.AppendLine(" Base_B AS Base_B,")
loComandoSeleccionar.AppendLine(" Costo_A AS Costo_A,")
loComandoSeleccionar.AppendLine(" Costo_B AS Costo_B,")
loComandoSeleccionar.AppendLine(" Ganancia_A AS Ganancia_A,")
loComandoSeleccionar.AppendLine(" Ganancia_B AS Ganancia_B, ")
loComandoSeleccionar.AppendLine(" Nivel AS Nivel")
loComandoSeleccionar.AppendLine("FROM #tmpFinal2")
Select Case lcParametro14Desde
Case "Mayor"
loComandoSeleccionar.AppendLine("WHERE Ganancia_B > " & lcParametro15Desde)
Case "Menor"
loComandoSeleccionar.AppendLine("WHERE Ganancia_B < " & lcParametro15Desde)
Case "Igual"
loComandoSeleccionar.AppendLine("WHERE Ganancia_B = " & lcParametro15Desde)
Case "Todos"
'No filtra por Ganancia_B
End Select
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("DROP TABLE #tmpFinal")
loComandoSeleccionar.AppendLine("DROP TABLE #tmpFinal2")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("")
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rMargen_gNivelRotacion", laDatosReporte)
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrMargen_gNivelRotacion.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' CMS: 05/06/10: Programacion inicial
'-------------------------------------------------------------------------------------------'
' RJG: 04/09/12: Corrección de SELECT.
'-------------------------------------------------------------------------------------------'
| {'content_hash': '584dcc0a3d6034c8f2c0b4702a320b62', 'timestamp': '', 'source': 'github', 'line_count': 310, 'max_line_length': 186, 'avg_line_length': 77.27741935483871, 'alnum_prop': 0.6249373852062113, 'repo_name': 'kodeitsolutions/ef-reports', 'id': '82f5c2e6da52db349a52fd957f64f18e4885298b', 'size': '23963', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rMargen_gNivelRotacion.aspx.vb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '6246816'}, {'name': 'Visual Basic', 'bytes': '25803337'}]} |
<section class="row" data-ng-controller="AuthenticationController">
<!---<h3 class="col-md-12 text-center">Sign up using your social accounts</h3>
<div class="col-md-12 text-center">
<a href="/auth/facebook" class="undecorated-link">
<img src="/modules/users/img/buttons/facebook.png">
</a>
<a href="/auth/twitter" class="undecorated-link">
<img src="/modules/users/img/buttons/twitter.png">
</a>
<a href="/auth/google" class="undecorated-link">
<img src="/modules/users/img/buttons/google.png">
</a>
<a href="/auth/linkedin" class="undecorated-link">
<img src="/modules/users/img/buttons/linkedin.png">
</a>
<a href="/auth/github" class="undecorated-link">
<img src="/modules/users/img/buttons/github.png">
</a>
</div>-->
<div class="SIcontainer">
<h3 class="col-md-12 text-center">Sign up</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
<fieldset>
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="First Name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Last Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email">
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">
</div>
<div class="text-center form-group">
<button type="submit" class="btn btn-large btn-primary">Sign up</button> or
<button class="btn btn-primary" onclick="window.location.href='/#!/signin'">Sign in</button>
</div>
<div data-ng-show="error" class="text-center text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</div>
</section> | {'content_hash': 'e3354b0b04f9ac4f3b6e7d03c31054ae', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 149, 'avg_line_length': 45.44642857142857, 'alnum_prop': 0.6699410609037328, 'repo_name': 'keegansanford/Colab', 'id': 'be78825302f9dff45c0fe05d4a6d8d9dba5238d7', 'size': '2545', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/modules/users/views/authentication/signup.client.view.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13890'}, {'name': 'HTML', 'bytes': '39021'}, {'name': 'JavaScript', 'bytes': '149517'}, {'name': 'Perl', 'bytes': '48'}, {'name': 'Shell', 'bytes': '1428'}]} |
package com.vk.api.sdk.queries.stats;
import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.base.responses.OkResponse;
import java.util.Arrays;
import java.util.List;
/**
* Query for Stats.trackVisitor method
*/
public class StatsTrackVisitorQuery extends AbstractQueryBuilder<StatsTrackVisitorQuery, OkResponse> {
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
*/
public StatsTrackVisitorQuery(VkApiClient client, UserActor actor) {
super(client, "stats.trackVisitor", OkResponse.class);
accessToken(actor.getAccessToken());
}
@Override
protected StatsTrackVisitorQuery getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Arrays.asList("access_token");
}
}
| {'content_hash': '28ccbdce0daa2d18ef2ca9390159a470', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 108, 'avg_line_length': 29.714285714285715, 'alnum_prop': 0.7201923076923077, 'repo_name': 'kokorin/vk-java-sdk', 'id': '4fcfdc698b0c39eba3e3d8dadc6c87c38470e340', 'size': '1040', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'sdk/src/main/java/com/vk/api/sdk/queries/stats/StatsTrackVisitorQuery.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2634022'}]} |
require 'ref_parsers'
class RefParsers::RISParser
def initialize
@type_key = "TY"
@types = %w(ABST ADVS ART BILL BOOK CASE CHAP COMP CONF CTLG DATA ELEC GEN HEAR ICOMM INPR JFULL JOUR MAP MGZN MPCT MUSIC NEWS PAMP PAT PCOMM RPRT SER SLIDE SOUND STAT THES UNBILl UNPB VIDEO WEB)
@terminator_key = "ER"
@line_regex = /^([A-Z][A-Z0-9]) -( (.*))?$/
@key_regex_order = 1
@value_regex_order = 3
@regex_match_length = 4
@key_value_separator = " - "
@file_type = "RIS"
@key_prefix = ""
end
end
class RefParsers::EndNoteParser
def initialize
@type_key = "0"
@types = ["Generic", "Artwork", "Audiovisual Material", "Bill", "Book", "Book Section", "Case", "Chart or Table", "Classical Work", "Computer Program", "Conference Paper", "Conference Proceedings", "Edited Book", "Equation", "Electronic Article", "Electronic Book", "Electronic Source", "Figure", "Film or Broadcast", "Government Document", "Hearing", "Journal Article", "Legal Rule/Regulation", "Magazine Article", "Manuscript", "Map", "Newspaper Article", "Online Database", "Online Multimedia", "Patent", "Personal Communication", "Report", "Statute", "Thesis", "Unpublished Work", "Unused 1", "Unused 2", "Unused 3"]
@terminator_key = nil
@line_regex = /^%([A-NP-Z0-9\?\@\!\#\$\]\&\(\)\*\+\^\>\<\[\=\~])\s+(.*)$/
@key_regex_order = 1
@value_regex_order = 2
@regex_match_length = 3
@key_value_separator = " "
@file_type = "EndNote"
@key_prefix = "%"
end
end
class RefParsers::LineParser
def open(filename)
# Read the file content, but remove the initial bom characters
body = File.open(filename, "r:bom|utf-8").read().strip
# Add keys to values if multi-valued fields with new line characters
# as delimiters do not have a key for each value.
# Comment this out if you monkey patch the "parse_entry" method below to preserve new lines.
last_key = ""
data = ""
body.lines.each do |line|
if !line.blank?
m = line.match(@line_regex)
if m && m.length == @regex_match_length
last_key = m[@key_regex_order]
new_line = line
else
new_line = @key_prefix + last_key + @key_value_separator + line
end
else
new_line = line
end
data << new_line + "\n"
end
# Parse them into entries
entries = parse(data)
# Convert entries to reference objects
references = []
entries.each do |entry|
references << RefParsers::Reference.new(entry, @file_type)
end
references
end
# Monkey patch the "parse_entry" method to preserve the new line character
# if multi-valued fields with new line characters as delimiters do not have a key for each value.
# Comment this out if you do add keys to these values at file reading time.
# protected
# def parse_entry(lines, next_line)
# begin
# return next_line if next_line >= lines.length
# first = parse_first_line(lines[next_line])
# next_line = next_line + 1
# end while first.nil?
#
# fields = [first]
#
# last_parsed = {}
# begin
# parsed = parse_line(lines[next_line])
# next_line = next_line + 1
# if parsed
# stop = false
# if parsed[:key] == "-1"
# parsed[:key] = last_parsed[:key]
# # Preserve the newline character for better parsing.
# parsed[:value] = "#{last_parsed[:value]}\n#{parsed[:value]}"
# fields.delete_at fields.length - 1
# elsif @terminator_key && parsed[:key] == @terminator_key
# yield hash_entry(fields)
# return next_line
# end
# last_parsed = parsed
# fields << parsed
# elsif @terminator_key.nil?
# stop = true
# yield hash_entry(fields)
# return next_line
# else
# stop = false
# end
# end until stop
# end
end
class RefParsers::Reference
attr_accessor :hash, :file_type
def initialize(hash, file_type)
@hash = hash
@file_type = file_type
end
def addresses
if @file_type == "RIS"
fields = ["AD"]
elsif @file_type == "EndNote"
fields = ["+"]
else
fields = []
end
addresses = []
aos = []
fields.each do |field|
if !self.hash[field].nil?
if self.hash[field].is_a?(Array)
self.hash[field].each do |a|
addresses << a.split(/[\n\r;]/).collect{|a| a.strip}
end
elsif self.hash[field].is_a?(String)
addresses << self.hash[field].split(/[\n\r;]/).collect{|a| a.strip}
end
end
end
addresses.flatten.each do |a|
aos << Address.new(a)
end
return aos
end
def year
if @file_type == "RIS"
fields = ["PY", "Y1"]
elsif @file_type == "EndNote"
fields = ["D"]
else
fields = []
end
fields.each do |field|
if !self.hash[field].nil?
return self.hash[field][0..3]
end
end
end
def authors
if @file_type == "RIS"
fields = ["AU", "A1"]
elsif @file_type == "EndNote"
fields = ["A"]
else
fields = []
end
authors = []
fields.each do |field|
if !self.hash[field].nil?
if self.hash[field].is_a?(Array)
self.hash[field].each do |a|
authors << a.split(/[\n\r;]/).collect{|a| a.strip}
end
elsif self.hash[field].is_a?(String)
authors << self.hash[field].split(/[\n\r;]/).collect{|a| a.strip}
end
end
end
return authors.flatten
end
end
| {'content_hash': 'bccd62ebc3c55607b7828d593806407c', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 624, 'avg_line_length': 31.083798882681563, 'alnum_prop': 0.5785406182602444, 'repo_name': 'lw292/rimpact', 'id': '82a82a4a94c4467bb4281506567060acc15bab07', 'size': '5564', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/classes/ref_parsers.rb', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '41310'}]} |
package com.ajah.user.data;
import com.ajah.user.UserSetting;
import com.ajah.user.UserSettingId;
/**
* Thrown when an {@link UserSetting} was expected to be found, but was not.
*
* @author <a href="http://efsavage.com">Eric F. Savage</a>, <a
* href="mailto:[email protected]">[email protected]</a>.
*/
public class UserSettingNotFoundException extends Exception {
/**
* Thrown when an {@link UserSetting} could not be found by it's internal
* ID.
*
* @param id
* The internal ID that was sought.
*/
public UserSettingNotFoundException(final UserSettingId id) {
super("ID: " + id);
}
}
| {'content_hash': 'ee30946d95b144bf9d541f9fef86735b', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 76, 'avg_line_length': 24.384615384615383, 'alnum_prop': 0.668769716088328, 'repo_name': 'efsavage/ajah', 'id': '989c02b0732d3cad99740469caeb573324052df2', 'size': '1269', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ajah-user/src/main/java/com/ajah/user/data/UserSettingNotFoundException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2583386'}]} |
@protocol Mobilighter;
@protocol SQLighterDb;
@interface Bootstrap : NSObject
#pragma mark Public
+ (Bootstrap *)getInstance;
- (id<Mobilighter>)getMobilighter;
- (id<SQLighterDb>)getSqLighterDb;
- (void)setMobilighterWithMobilighter:(id<Mobilighter>)mobilighter;
- (void)setSqLighterDbWithSQLighterDb:(id<SQLighterDb>)sqLighterDb;
@end
J2OBJC_EMPTY_STATIC_INIT(Bootstrap)
FOUNDATION_EXPORT Bootstrap *Bootstrap_getInstance();
J2OBJC_TYPE_LITERAL_HEADER(Bootstrap)
@compatibility_alias ComProdValsAndr_demo_prjBootstrap Bootstrap;
#endif
#pragma pop_macro("INCLUDE_ALL_ComProdValsAndr_demo_prjBootstrap")
| {'content_hash': '60efed63f04baceb0f17001528e8a593', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 67, 'avg_line_length': 20.633333333333333, 'alnum_prop': 0.8012924071082391, 'repo_name': 'vals-productions/sqlighter', 'id': '0522f4781ce2d2f2a17495b756ecf8100fe741a4', 'size': '1233', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demo/ios-demo-prj/ios-demo-prj/com/prod/vals/andr_demo_prj/Bootstrap.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '244420'}, {'name': 'Objective-C', 'bytes': '370872'}]} |
<?php namespace App\Http\Controllers;
use App\Models\Domain;
use \Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
/**
* Class DomainController
* @package App\Http\Controllers
*
* @Middleware("Auth")
*/
class DomainController extends Controller
{
protected $profile;
/**
* DomainController constructor
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show all records (include soft-deleted records)
*
* @return Response
*/
public function index()
{
$domains = Domain::withTrashed()->get();
return response()->view('domains.index', [
'domains' => $domains,
]);
}
/**
* Display the create form
*
* @return Response
*/
public function create()
{
return response()->view('domains.form');
}
/**
* Delete a record
*
* @param $id
*
* @return Response
*/
public function destroy($id)
{
$domain = Domain::find($id);
$request = new Request();
try {
$domain->delete();
$request->session()->flash('success', 'Domain ' . $id . ' has been created!');
} catch (Exception $e) {
$request->session()->flash('danger', 'Domain ' . $id . ' was not created, please try again.');
}
return view('domains.index');
}
/**
* Store a record
*
* @param Request $request
*
* @return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'domain_name' => 'required|unique:name|min:4|max:255',
]);
$input = $request->only([
'domain_name',
'is_word_press',
'is_secure',
]);
$password = str_random(12);
try {
Domain::create([
'name' => $input['domain_name'],
'is_word_press' => $input['is_word_press'],
'username' => $input['domain_name'],
'password' => $password,
'user_id' => Auth::user()->id,
'is_secure' => $input['is_secure'],
]);
$request->session()->flash('success', $input['domain_name'] . ' has been created!');
Artisan::call('install:site');
} catch (Exception $e) {
$request->session()->flash('danger', $input['domain_name'] . ' was not created, please try again.');
}
return redirect()->route('domain.index');
}
}
| {'content_hash': 'c703b67d9b322e228ec0c80d043b2dad', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 112, 'avg_line_length': 23.434782608695652, 'alnum_prop': 0.5042671614100186, 'repo_name': 'erikcaineolson/Panelvel', 'id': 'dce7277dea49f0e3e31b4f8cb7c4535d8f160c1e', 'size': '2695', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/Http/Controllers/DomainController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '127'}, {'name': 'HTML', 'bytes': '24991'}, {'name': 'JavaScript', 'bytes': '503'}, {'name': 'PHP', 'bytes': '89964'}, {'name': 'Perl', 'bytes': '2369'}, {'name': 'Python', 'bytes': '999'}, {'name': 'Shell', 'bytes': '4769'}]} |
package com.desperado.customerlib.view.autolayout.attr;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by zhy on 15/12/5.
*/
public class MarginRightAttr extends AutoAttr
{
public MarginRightAttr(int pxVal, int baseWidth, int baseHeight)
{
super(pxVal, baseWidth, baseHeight);
}
@Override
protected int attrVal()
{
return Attrs.MARGIN_RIGHT;
}
@Override
protected boolean defaultBaseWidth()
{
return true;
}
@Override
protected void execute(View view, int val)
{
if(!(view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams))
{
return ;
}
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
lp.rightMargin = val;
}
}
| {'content_hash': 'a449fd42d776a8a7449b3460c8463a30', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 96, 'avg_line_length': 21.789473684210527, 'alnum_prop': 0.644927536231884, 'repo_name': 'foreverxiongtao/CustomerLib', 'id': 'df34caefef1cd892f36b6e734a6e1814be79478a', 'size': '828', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'customerlib/src/main/java/com/desperado/customerlib/view/autolayout/attr/MarginRightAttr.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '405721'}]} |
<span id="navbar_top"></span>
<table>
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<tbody>
<tr class="odd">
<td align="left"><span id="navbar_top_firstrow"></span>
<table>
<tbody>
<tr class="odd">
<td align="left"> <a href="../overview-summary.html.md"><strong>Overview</strong></a> </td>
<td align="left"> <a href="tld-summary.html.md"><strong>Library</strong></a> </td>
<td align="left"> Tag </td>
<td align="left"> <a href="../help-doc.html.md"><strong>Help</strong></a> </td>
</tr>
</tbody>
</table></td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left"></td>
<td align="left"> <a href="../index.html.md"><strong>FRAMES</strong></a> <a href="option.html"><strong>NO FRAMES</strong></a>
<a href="../alltags-noframe.html.md"><strong>All Tags</strong></a></td>
</tr>
</tbody>
</table>
------------------------------------------------------------------------
html
Tag option
-----------
------------------------------------------------------------------------
**Render A Select Option**
Render an HTML `<option>` element, representing one of the choices for an enclosing `<select>` element. The text displayed to the user comes from either the body of this tag, or from a message string looked up based on the `bundle`, `locale`, and `key` attributes.
If the value of the corresponding bean property matches the specified value, this option will be marked selected. This tag is only valid when nested inside a `.html.md:select>` tag body.
------------------------------------------------------------------------
**Tag Information**
Tag Class
org.apache.struts.taglib.html.md.OptionTag
TagExtraInfo Class
*None*
Body Content
JSP
Display Name
*None*
**Attributes**
**Name**
**Required**
**Request-time**
**Type**
**Description**
bundle
false
true
`java.lang.String`
The servlet context attributes key for the MessageResources instance to use. If not specified, defaults to the application resources configured for our action servlet.
dir
false
true
`java.lang.String`
The direction for weak/neutral text for this element.
**Since:**
Struts 1.3.6
disabled
false
true
`boolean`
Set to `true` if this option should be disabled.
filter
false
true
`boolean`
Set to `true` if you want the option label to be filtered for sensitive characters in HTML. By default, such a value is NOT filtered.
lang
false
true
`java.lang.String`
The language code for this element.
**Since:**
Struts 1.3.6
key
false
true
`java.lang.String`
If specified, defines the message key to be looked up in the resource bundle specified by `bundle` for the text displayed to the user for this option. If not specified, the text to be displayed is taken from the body content of this tag.
locale
false
true
`java.lang.String`
The session attributes key for the Locale instance to use for looking up the message specified by the `key` attribute. If not specified, uses the standard Struts session attribute name.
style
false
true
`java.lang.String`
CSS styles to be applied to this HTML element.
styleId
false
true
`java.lang.String`
Identifier to be assigned to this HTML element (renders an "id" attribute).
styleClass
false
true
`java.lang.String`
CSS stylesheet class to be applied to this HTML element (renders a "class" attribute).
value
true
true
`java.lang.String`
Value to be submitted for this field if this option is selected by the user.
|-------------------------|
| **Variables** |
| *No Variables Defined.* |
<span id="navbar_bottom"></span>
<table>
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<tbody>
<tr class="odd">
<td align="left"><span id="navbar_bottom_firstrow"></span>
<table>
<tbody>
<tr class="odd">
<td align="left"> <a href="../overview-summary.html.md"><strong>Overview</strong></a> </td>
<td align="left"> <a href="tld-summary.html.md"><strong>Library</strong></a> </td>
<td align="left"> Tag </td>
<td align="left"> <a href="../help-doc.html.md"><strong>Help</strong></a> </td>
</tr>
</tbody>
</table></td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left"></td>
<td align="left"> <a href="../index.html.md"><strong>FRAMES</strong></a> <a href="option.html"><strong>NO FRAMES</strong></a>
<a href="../alltags-noframe.html.md"><strong>All Tags</strong></a></td>
</tr>
</tbody>
</table>
------------------------------------------------------------------------
*Output Generated by [Tag Library Documentation Generator](http://taglibrarydoc.dev.java.net/). Java, JSP, and JavaServer Pages are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries. Copyright 2002-4 Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054, U.S.A. All Rights Reserved.*
| {'content_hash': 'd4736c11cfe428c65cfbad08f08ab68c', 'timestamp': '', 'source': 'github', 'line_count': 229, 'max_line_length': 336, 'avg_line_length': 20.807860262008735, 'alnum_prop': 0.649317943336831, 'repo_name': 'ExclamationLabs/struts-1.3.10_docs', 'id': 'cf1350ae3948841d70ea164b034620ce8f71f1d6', 'size': '4793', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'struts-taglib/tlddoc/html/option.html.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '2487'}, {'name': 'CSS', 'bytes': '165112'}, {'name': 'JavaScript', 'bytes': '18038'}]} |
package org.elasticsearch.index.reindex;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.min;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
import static org.elasticsearch.action.search.ShardSearchFailure.readShardSearchFailure;
/**
* Response used for actions that index many documents using a scroll request.
*/
public class BulkIndexByScrollResponse extends ActionResponse implements ToXContent {
private TimeValue took;
private BulkByScrollTask.Status status;
private List<Failure> indexingFailures;
private List<ShardSearchFailure> searchFailures;
public BulkIndexByScrollResponse() {
}
public BulkIndexByScrollResponse(TimeValue took, BulkByScrollTask.Status status, List<Failure> indexingFailures,
List<ShardSearchFailure> searchFailures) {
this.took = took;
this.status = requireNonNull(status, "Null status not supported");
this.indexingFailures = indexingFailures;
this.searchFailures = searchFailures;
}
public TimeValue getTook() {
return took;
}
protected BulkByScrollTask.Status getStatus() {
return status;
}
public long getUpdated() {
return status.getUpdated();
}
public int getBatches() {
return status.getBatches();
}
public long getVersionConflicts() {
return status.getVersionConflicts();
}
public long getNoops() {
return status.getNoops();
}
/**
* The reason that the request was canceled or null if it hasn't been.
*/
public String getReasonCancelled() {
return status.getReasonCancelled();
}
/**
* All of the indexing failures. Version conflicts are only included if the request sets abortOnVersionConflict to true (the
* default).
*/
public List<Failure> getIndexingFailures() {
return indexingFailures;
}
/**
* All search failures.
*/
public List<ShardSearchFailure> getSearchFailures() {
return searchFailures;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
took.writeTo(out);
status.writeTo(out);
out.writeVInt(indexingFailures.size());
for (Failure failure: indexingFailures) {
failure.writeTo(out);
}
out.writeVInt(searchFailures.size());
for (ShardSearchFailure failure: searchFailures) {
failure.writeTo(out);
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
took = TimeValue.readTimeValue(in);
status = new BulkByScrollTask.Status(in);
int indexingFailuresCount = in.readVInt();
List<Failure> indexingFailures = new ArrayList<>(indexingFailuresCount);
for (int i = 0; i < indexingFailuresCount; i++) {
indexingFailures.add(Failure.PROTOTYPE.readFrom(in));
}
this.indexingFailures = unmodifiableList(indexingFailures);
int searchFailuresCount = in.readVInt();
List<ShardSearchFailure> searchFailures = new ArrayList<>(searchFailuresCount);
for (int i = 0; i < searchFailuresCount; i++) {
searchFailures.add(readShardSearchFailure(in));
}
this.searchFailures = unmodifiableList(searchFailures);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field("took", took.millis());
status.innerXContent(builder, params, false, false);
builder.startArray("failures");
for (Failure failure: indexingFailures) {
builder.startObject();
failure.toXContent(builder, params);
builder.endObject();
}
for (ShardSearchFailure failure: searchFailures) {
builder.startObject();
failure.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
return builder;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BulkIndexByScrollResponse[");
builder.append("took=").append(took).append(',');
status.innerToString(builder, false, false);
builder.append(",indexing_failures=").append(getIndexingFailures().subList(0, min(3, getIndexingFailures().size())));
builder.append(",search_failures=").append(getSearchFailures().subList(0, min(3, getSearchFailures().size())));
return builder.append(']').toString();
}
} | {'content_hash': '932fe3957bfb7d713bfcb476001d8c5c', 'timestamp': '', 'source': 'github', 'line_count': 152, 'max_line_length': 128, 'avg_line_length': 33.9078947368421, 'alnum_prop': 0.6792782305005821, 'repo_name': 'episerver/elasticsearch', 'id': 'ca1a53ef99930d5ef17822c9013d644ee3c33fd8', 'size': '5942', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/reindex/src/main/java/org/elasticsearch/index/reindex/BulkIndexByScrollResponse.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '299'}, {'name': 'Java', 'bytes': '25622769'}, {'name': 'Perl', 'bytes': '5913'}, {'name': 'Python', 'bytes': '47339'}, {'name': 'Ruby', 'bytes': '31602'}, {'name': 'Shell', 'bytes': '28248'}]} |
# PhantomJS bridge for NodeJS
[](https://travis-ci.org/amir20/phantomjs-node) [](https://badge.fury.io/js/phantom)
"It sure would be neat if [PhantomJS](http://phantomjs.org/) was a NodeJS module", I hear you say. Well, wait no longer! This node module implements a nauseatingly clever bridge between Phantom and Node, so that you can use all your favourite PhantomJS functions without leaving NPM behind and living in a cave.
## Installation
First, make sure PhantomJS is installed. This module expects the ```phantomjs``` binary to be in PATH somewhere. In other words, type this:
$ phantomjs
If that works, so will phantomjs-node. It's only been tested with PhantomJS 1.3, and almost certainly doesn't work with anything older.
Install it like this:
npm install phantom
For a brief introduction continue reading, otherwise **go to the [Wiki page](https://github.com/amir20/phantomjs-node/wiki) for more information!**
## How do I use it?
Use it like this in Coffeescript:
```coffeescript
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
page.open "http://www.google.com", (status) ->
console.log "opened google? ", status
page.evaluate (-> document.title), (result) ->
console.log 'Page title is ' + result
ph.exit()
```
In Javascript:
```js
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
console.log("opened google? ", status);
page.evaluate(function () { return document.title; }, function (result) {
console.log('Page title is ' + result);
ph.exit();
});
});
});
});
```
### Use it in Windows
It would use `dnode` with `weak` module by default. It means that you need to setup `node-gyp` with Microsoft VS2010 or VS2012, which is a huge installation on Windows.
`dnodeOpts` property could help you to control dnode settings, so you could disable `weak` by setting it `false` to avoid that complicated installations.
```js
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
/* the page actions */
});
}, {
dnodeOpts: {
weak: false
}
});
```
### Use it in restricted enviroments
Some enviroments (eg. [OpenShift](https://help.openshift.com/hc/en-us/articles/202185874-I-can-t-bind-to-a-port)) have special requirements that are difficult or impossible to change, especifficaly: hostname/ip and port restrictions for the internal communication server and path for the phantomjs binary.
By default, the hostname/ip used for this will be `localhost`, the port will be port `0` and the phantomjs binary is going to be assumed to be in the `PATH` enviroment variable, but you can use specific configurations using an `options` object like this:
```js
var options = {
port: 16000,
hostname: "192.168.1.3",
path: "/phantom_path/"
}
phantom.create(function, options);
```
## Functionality details
You can use all the methods listed on the [PhantomJS API page](http://phantomjs.org/api/)
Due to the async nature of the bridge, some things have changed, though:
* Return values (ie, of ```page.evaluate```) are returned in a callback instead
* ```page.render()``` takes a callback so you can tell when it's done writing the file
* Properties can't be get/set directly, instead use ```page.get('version', callback)``` or ```page.set('viewportSize', {width:640,height:480})```, etc. Nested objects can be accessed by including dots in keys, such as ```page.set('settings.loadImages', false)```
* Callbacks can't be set directly, instead use ```page.set('callbackName', callback)```, e.g. ```page.set('onLoadFinished', function(success) {})```
* onResourceRequested takes a function that executes in the scope of phantom which has access to ```request.abort()```, ```request.changeUrl(url)```, and ```request.setHeader(key,value)```. The second argument is the callback which can execute in the scope of your code, with access to just the requestData. This function can apply extra arguments which can be passed into the first function e.g.
```
page.onResourceRequested(
function(requestData, request, arg1, arg2) { request.abort(); },
function(requestData) { console.log(requestData.url) },
arg1, arg2
);
```
```ph.createPage()``` makes new PhantomJS WebPage objects, so use that if you want to open lots of webpages. You can also make multiple phantomjs processes by calling ```phantom.create('flags', { port: someDiffNumber})``` multiple times, so if you need that for some crazy reason, knock yourself out!
Also, you can set exit callback, which would be invoked after ```phantom.exit()``` or after phantom process crash:
```
phantom.create({ port: 8080, onExit: exitCallback}, createCallback)
```
You can also pass command line switches to the phantomjs process by specifying additional args to ```phantom.create()```, eg:
```coffeescript
phantom.create '--load-images=no', '--local-to-remote-url-access=yes', (page) ->
```
or by specifying them in the options object:
```coffeescript
phantom.create {parameters: {'load-images': 'no', 'local-to-remote-url-access': 'yes'}}, (page) ->
```
If you need to access the [ChildProcess](http://nodejs.org/api/child_process.html#child_process_class_childprocess) of the phantom process to get its PID, for instance, you can access it through the `process` property like this:
```
phantom.create(function (ph) {
console.log('phantom process pid:', ph.process.pid);
});
```
##Note for Mac users
Phantom requires you to have the XCode Command Line Tools installed on your box, or else you will get some nasty errors (`xcode` not found or `make` not found). If you haven't already, simply install XCode through the App Store, then [install the command line tools](http://stackoverflow.com/questions/6767481/where-can-i-find-make-program-for-mac-os-x-lion).
## How does it work?
Don't ask. The things these eyes have seen.
## No really, how does it work?
I will answer that question with a question. How do you communicate with a process that doesn't support shared memory, sockets, FIFOs, or standard input?
Well, there's one thing PhantomJS does support, and that's opening webpages. In fact, it's really good at opening web pages. So we communicate with PhantomJS by spinning up an instance of ExpressJS, opening Phantom in a subprocess, and pointing it at a special webpage that turns socket.io messages into ```alert()``` calls. Those ```alert()``` calls are picked up by Phantom and there you go!
The communication itself happens via James Halliday's fantastic [dnode](https://github.com/substack/dnode) library, which fortunately works well enough when combined with [browserify](https://github.com/substack/node-browserify) to run straight out of PhantomJS's pidgin Javascript environment.
If you'd like to hack on phantom, please do! You can run the tests with ```cake test``` or ```npm test```, and rebuild the coffeescript/browserified code with ```cake build```. You might need to ```npm install -g coffee-script``` for cake to work.
| {'content_hash': '4cd9c16c5562d2639a6ef8ef96b9503b', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 396, 'avg_line_length': 47.08441558441559, 'alnum_prop': 0.7259688318852572, 'repo_name': 'vvsuperman/fkEstate', 'id': '5d308ac549aef628e032832ba7b50e66027c3252', 'size': '7251', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/phantom/README.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1142'}, {'name': 'HTML', 'bytes': '48232'}, {'name': 'JavaScript', 'bytes': '71593'}]} |
package org.supercsv.ext;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
/**
* @author T.TSUCHIE
*
*/
public class Utils {
public static String join(final String[] arrays, final String seperator) {
final int len = arrays.length;
if(arrays == null || len == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i < len; i++) {
sb.append(arrays[i]);
if(seperator != null && (i < len-1)) {
sb.append(seperator);
}
}
return sb.toString();
}
public static String join(final Collection<?> col, final String seperator) {
final int size = col.size();
if(col == null || size == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for(Iterator<?> itr = col.iterator(); itr.hasNext();) {
final Object item = itr.next();
sb.append(item.toString());
if(seperator != null && itr.hasNext()) {
sb.append(seperator);
}
}
return sb.toString();
}
public static boolean isEmpty(final String value) {
if(value == null || value.isEmpty()) {
return true;
}
return false;
}
/**
* 文字列形式のロケールをオブジェクトに変換する。
* <p>アンダーバーで区切った'ja_JP'を分解して、Localeに渡す。
* @since 1.2
* @param str
* @return 引数が空の時はデフォルトロケールを返す。
*/
public static Locale getLocale(final String str) {
if(isEmpty(str)) {
return Locale.getDefault();
}
if(!str.contains("_")) {
return new Locale(str);
}
final String[] split = str.split("_");
if(split.length == 2) {
return new Locale(split[0], split[1]);
} else {
return new Locale(split[0], split[1], split[2]);
}
}
}
| {'content_hash': '28b4ac5057a09ff629488a053e506408', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 80, 'avg_line_length': 23.629213483146067, 'alnum_prop': 0.46790299572039945, 'repo_name': 'mygreen/super-csv-annotation1', 'id': 'f2e0b0a9192a5cf3131edf6ac4254acc8e534a7a', 'size': '2231', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/supercsv/ext/Utils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '297960'}, {'name': 'Shell', 'bytes': '918'}]} |
describe('Testing timeline settings controller', function () {
var controller, scope, gridService;
beforeEach(function () {
// load the module
module('app');
inject(function($controller, $rootScope,_$q_){
deferredTimelineEvents = _$q_.defer();
gridService = jasmine.createSpyObj('gridService',
['loadTimelineEvents']);
scope = $rootScope.$new();
scope.widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: [],
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
gridService.loadTimelineEvents.and.callFake(function() {
return deferredTimelineEvents.promise;
});
controller = $controller('timelineSettingsCtrl', {
$scope: scope,
gridService: gridService,
});
});
});
it('timeline settings controller should be defined', function() {
expect(controller).toBeDefined();
});
it("should not add timezone if it already exists in the timeline",function(){
scope.selected = {
type: {
value: 'Timezone'
}
}
scope.selected.timezone = {
name:"UTC",
utcoffset : "+00:00",
id:"utc",
labeloffset : "+ 00"
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
widget.settings.timezones = [{
name:"UTC",
utcoffset : "+00:00",
id:"utc",
labeloffset : "+ 00"
}];
scope.saveSettings(widget);
expect(scope.timezoneErrMsg).toEqual("This time axis already exists in the qwidget");
expect(scope.eventErrMsg).toEqual("");
expect(scope.selected.timezone).toEqual({});
expect(widget.settings.timezones.length).toEqual(1);
});
it("should add timezone if it is a new timezone in the timeline",function(){
scope.selected = {
type: {
value: 'Timezone'
}
}
scope.selected.timezone = {
name:"San Francisco",
utcoffset: "-08:00",
id:"sfo",
labeloffset : "- 08"
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
widget.settings.timezones = [{
name:"UTC",
utcoffset : "+00:00",
id:"utc",
labeloffset : "+ 00"
}];
scope.saveSettings(widget);
expect(scope.timezoneErrMsg).toEqual("");
expect(scope.eventErrMsg).toEqual("");
expect(widget.settings.timezones.length).toEqual(2);
});
it("should not save the changes made if close button is clicked in timezone selection",function(){
scope.selected = {
type: {
value: 'Timezone'
}
}
scope.selected.timezone = {
name:"San Francisco",
utcoffset: "-08:00",
id:"sfo",
labeloffset : "- 08"
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
widget.settings.timezones = [{
name:"UTC",
utcoffset : "+00:00",
id:"utc",
labeloffset : "+ 00"
}];
scope.closeSettings(widget);
expect(scope.timezoneErrMsg).toEqual("");
expect(scope.eventErrMsg).toEqual("");
expect(widget.settings.timezones.length).toEqual(1);
expect(widget.main).toEqual(true);
expect(widget.settings.active).toEqual(false);
});
it("should alert the user if no events are selected",function(){
scope.selectByGroupModel = [];
scope.selected = {
type: {
value: 'Events'
}
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
scope.saveSettings(widget);
expect(scope.eventErrMsg).toEqual("Select atleast one event");
expect(scope.timezoneErrMsg).toEqual("");
});
it("should save the events and its order when save is clicked",function(){
scope.selectByGroupModel = [{
"label":"A0_Launch"
},{
"label":"A1_Launch"
}];
scope.itemsList = {
items1: []
}
scope.itemsList.items1 = [ 'A0','A1'
]
scope.selected = {
type: {
value: 'Events'
}
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
scope.saveSettings(widget);
expect(scope.eventErrMsg).toEqual("");
expect(scope.timezoneErrMsg).toEqual("");
});
it("should not save the changes if the close button is clicked in event selection",function(){
scope.selectByGroupModel = [{
"label":"A0_Launch"
},{
"label":"A1_Launch"
}];
scope.itemsList = {
items1: []
}
scope.itemsList.items1 = [ 'A0','A1'
]
scope.selected = {
type: {
value: 'Events'
}
}
var widget = {
sizeY: 3,
sizeX: 4,
name: "Timeline",
directive: "timeLine",
directiveSettings: "timelinesettings",
id: "timeline",
icon: {
id: "timeline",
type: "fa-tasks"
},
main: true,
settings: {
active: false,
timezones: {},
grouporder: {
items1: []
},
events:[]
},
saveLoad: false,
delete: false
}
scope.closeSettings(widget);
expect(scope.timezoneErrMsg).toEqual("");
expect(scope.eventErrMsg).toEqual("");
expect(widget.settings.events.length).toEqual(0);
expect(widget.main).toEqual(true);
expect(widget.settings.active).toEqual(false);
});
}) | {'content_hash': '4f6d781f4744ca66807ba18bd24302cf', 'timestamp': '', 'source': 'github', 'line_count': 340, 'max_line_length': 102, 'avg_line_length': 27.41470588235294, 'alnum_prop': 0.4210921574938311, 'repo_name': 'quindar/quindar-ux', 'id': '9ed1773ab98085471335ea063632b2e583aa4dfa', 'size': '9321', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/directives/timeline/timelinesettings.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '22963'}, {'name': 'HTML', 'bytes': '35947'}, {'name': 'JavaScript', 'bytes': '290063'}]} |
using System.Web.Mvc;
using Root.Analytics.Models;
namespace Root.Analytics.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "D3.js";
var model = GetOptions();
return View(model);
}
private AnalyticsOptions GetOptions()
{
var options = new AnalyticsOptions
{
Services =
{
GetStatsViewDataMethod = "GetStatsData",
GetGraphViewDataMethod = "GetGraphData",
GetMapViewDataMethod = "GetMapData",
GetChoroplethViewDataMethod = "GetChoroplethData",
ServiceRoot = "Analytics"
}
};
return options;
}
}
}
| {'content_hash': '208a2f7b381c5531a0661324a294dbf9', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 70, 'avg_line_length': 26.40625, 'alnum_prop': 0.5041420118343195, 'repo_name': 'kolotygin/RootPosition', 'id': '89776181debb29f2ab8b443f9472ece9461db671', 'size': '847', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Root.Analytics/Controllers/HomeController.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '213'}, {'name': 'C#', 'bytes': '154318'}, {'name': 'CSS', 'bytes': '94915'}, {'name': 'HTML', 'bytes': '53'}, {'name': 'JavaScript', 'bytes': '596348'}]} |
// -*- C++ -*-
//=============================================================================
/**
* @file Array_Map.h
*
* $Id: Array_Map.h 2622 2015-08-13 18:30:00Z mitza $
*
* Light weight array-based map with fast iteration but linear
* (i.e. O(n)) search times. STL-style interface is exposed.
*
* @note This class requires the STL generic algorithms and
* reverse_iterator adapter.
*
* @author Ossama Othman
*/
//=============================================================================
#ifndef ACE_ARRAY_MAP_H
#define ACE_ARRAY_MAP_H
#include /**/ "ace/pre.h"
#include "ace/config-lite.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include <utility>
#include <iterator>
#include <functional>
#include <memory>
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
/**
* @class ACE_Array_Map
*
* @brief Light weight array-based map with fast iteration, but linear
* (i.e. O(n)) search times.
*
* Map implementation that focuses on small footprint and fast
* iteration. Search times are, however, linear (O(n)) meaning that
* this map isn't suitable for large data sets that will be searched
* in performance critical areas of code. Iteration over large data
* sets, however, is faster than linked list-based maps, for example,
* since spatial locality is maximized through the use of contiguous
* arrays as the underlying storage.
* @par
* An @c ACE_Array_Map is a unique associative container, meaning that
* duplicate values may not be added to the map. It is also pair
* associative (value_type is a std::pair<>). It is not a sorted
* container.
* @par
* An STL @c std::map -like interface is exposed by this class
* portability. Furthermore, this map's iterators are compatible with
* STL algorithms.
* @par
* <b> Requirements and Performance Characteristics</b>
* - Internal Structure
* Array
* - Duplicates allowed?
* No
* - Random access allowed?
* Yes
* - Search speed
* O(n)
* - Insert/replace speed
* O(n), can be longer if the map has to resize
* - Iterator still valid after change to container?
* No
* - Frees memory for removed elements?
* Yes
* - Items inserted by
* Value
* - Requirements for key type
* -# Default constructor
* -# Copy constructor
* -# operator=
* -# operator==
* - Requirements for object type
* -# Default constructor
* -# Copy constructor
* -# operator=
*/
template<typename Key, typename Value, class EqualTo = std::equal_to<Key>, class Alloc = std::allocator<std::pair<Key, Value> > >
class ACE_Array_Map
{
public:
// STL-style typedefs/traits.
typedef Key key_type;
typedef Value mapped_type;
typedef Value data_type;
typedef std::pair<key_type, mapped_type> value_type;
typedef Alloc allocator_type;
typedef value_type & reference;
typedef value_type const & const_reference;
typedef value_type * pointer;
typedef value_type const * const_pointer;
typedef value_type * iterator;
typedef value_type const * const_iterator;
ACE_DECLARE_STL_REVERSE_ITERATORS
typedef ptrdiff_t difference_type;
typedef size_t size_type;
/// Default Constructor.
/**
* Create an empty map with a preallocated buffer of size @a s.
*/
ACE_Array_Map (size_type s = 0);
template<typename InputIterator>
ACE_Array_Map (InputIterator f, InputIterator l);
ACE_Array_Map (ACE_Array_Map const & map);
ACE_Array_Map & operator= (ACE_Array_Map const & map);
/// Destructor.
~ACE_Array_Map (void);
/**
* @name Forward Iterator Accessors
*
* Forward iterator accessors.
*/
//@{
iterator begin (void);
iterator end (void);
const_iterator begin (void) const;
const_iterator end (void) const;
//@}
/**
* @name Reverse Iterator Accessors
*
* Reverse iterator accessors.
*/
//@{
reverse_iterator rbegin (void);
reverse_iterator rend (void);
const_reverse_iterator rbegin (void) const;
const_reverse_iterator rend (void) const;
//@}
/// Return current size of map.
/**
* @return The number of elements in the map.
*/
size_type size (void) const;
/// Maximum number of elements the map can hold.
size_type max_size (void) const;
/// Return @c true if the map is empty, else @c false.
bool is_empty (void) const; // ACE style
/**
* Return @c true if the map is empty, else @c false. We recommend
* using @c is_empty() instead since it's more consistent with the
* ACE container naming conventions.
*/
bool empty (void) const; // STL style
/// Swap the contents of this map with the given @a map in an
/// exception-safe manner.
void swap (ACE_Array_Map & map);
/// Insert the value @a x into the map.
/**
* STL-style map insertion method.
*
* @param x @c std::pair containing key and datum.
*
* @return @c std::pair::second will be @c false if the map already
* contains a value with the same key as @a x.
*/
std::pair<iterator, bool> insert (value_type const & x);
/// Insert range of elements into map.
template<typename InputIterator>
void insert (InputIterator f, InputIterator l);
/// Remove element at position @a pos from the map.
void erase (iterator pos);
/// Remove element corresponding to key @a k from the map.
/**
* @return Number of elements that were erased.
*/
size_type erase (key_type const & k);
/// Remove range of elements [@a first, @a last) from the map.
/**
* @note [@a first, @a last) must be valid range within the map.
*/
void erase (iterator first, iterator last);
/// Clear contents of map.
/**
* @note This a constant time (O(1)) operation.
*/
void clear (void);
/**
* @name Search Operations
*
* Search the map for data corresponding to key @a k.
*/
//@{
/**
* @return @c end() if data corresponding to key @a k is not in the
* map.
*/
iterator find (key_type const & k);
/**
* @return @c end() if data corresponding to key @a k is not in the
* map.
*/
const_iterator find (key_type const & k) const;
//@}
/// Count the number of elements corresponding to key @a k.
/**
* @return In the case of this map, the count will always be one if
* such exists in the map.
*/
size_type count (key_type const & k);
/// Convenience array index operator.
/**
* Array index operator that allows insertion and retrieval of
* elements using an array index syntax, such as:
* @par
* map["Foo"] = 12;
*/
mapped_type & operator[] (key_type const & k);
allocator_type get_allocator() const { return alloc_; }
private:
/// Increase size of underlying buffer by @a s.
void grow (size_type s);
private:
/// The allocator.
allocator_type alloc_;
/// Number of elements in the map.
size_type size_;
/// Current size of underlying array.
/**
* @note @c capacity_ is always greater than or equal to @c size_;
*/
size_type capacity_;
/// Underlying array containing keys and data.
value_type * nodes_;
};
// --------------------------------------------------------------
/// @c ACE_Array_Map equality operator.
template <typename Key, typename Value, class EqualTo, class Alloc>
bool operator== (ACE_Array_Map<Key, Value, EqualTo, Alloc> const & lhs,
ACE_Array_Map<Key, Value, EqualTo, Alloc> const & rhs);
/// @c ACE_Array_Map lexicographical comparison operator.
template <typename Key, typename Value, class EqualTo, class Alloc>
bool operator< (ACE_Array_Map<Key, Value, EqualTo, Alloc> const & lhs,
ACE_Array_Map<Key, Value, EqualTo, Alloc> const & rhs);
// --------------------------------------------------------------
ACE_END_VERSIONED_NAMESPACE_DECL
#ifdef __ACE_INLINE__
# include "ace/Array_Map.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
# include "ace/Array_Map.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */
#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Array_Map.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */
#include /**/ "ace/post.h"
#endif /* ACE_ARRAY_MAP_H */
| {'content_hash': '2e937106381eb72f3be9eaf9b74350b4', 'timestamp': '', 'source': 'github', 'line_count': 296, 'max_line_length': 129, 'avg_line_length': 28.908783783783782, 'alnum_prop': 0.6047680261773987, 'repo_name': 'binary42/OCI', 'id': '5aff6bf59a0e7c4cd978984ee164409d31d7aa35', 'size': '8557', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ace/Array_Map.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '176672'}, {'name': 'C++', 'bytes': '28193015'}, {'name': 'HTML', 'bytes': '19914'}, {'name': 'IDL', 'bytes': '89802'}, {'name': 'LLVM', 'bytes': '4067'}, {'name': 'Lex', 'bytes': '6305'}, {'name': 'Makefile', 'bytes': '509509'}, {'name': 'Yacc', 'bytes': '18367'}]} |
package org.mitre.medfacts.uima;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.apache.ctakes.core.ae.DocumentIdPrinterAnalysisEngine;
import org.apache.ctakes.core.cc.XmiWriterCasConsumerCtakes;
import org.apache.ctakes.core.cr.TextReader;
import org.apache.log4j.Logger;
import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.fit.factory.AggregateBuilder;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.factory.CollectionReaderFactory;
import org.apache.uima.fit.factory.TypeSystemDescriptionFactory;
import org.apache.uima.fit.pipeline.SimplePipeline;
import org.apache.uima.resource.metadata.TypeSystemDescription;
public class RunZoner
{
private static Logger logger = Logger.getLogger(RunZoner.class.getName());
File inputDirectory;
List<File> inputFiles;
File outputDirectory;
public static void main(String args[]) throws UIMAException, IOException, URISyntaxException
{
if (args.length != 2)
{
System.err.format("Syntax: %s input_directory output_directory%n", RunZoner.class.getName());
}
File inputDirectory = new File(args[0]);
File outputDirectory = new File(args[1]);
List<File> inputFiles = listContentsAll(inputDirectory);
RunZoner runner = new RunZoner();
runner.setInputDirectory(inputDirectory);
runner.setInputFiles(inputFiles);
runner.setOutputDirectory(outputDirectory);
runner.execute();
}
public static List<File> listContentsAll(File inputDirectory)
{
File fileArray[] = inputDirectory.listFiles();
List<File> fileList = Arrays.asList(fileArray);
return fileList;
}
public static List<File> listContentsXmiOnly(File inputDirectory)
{
File fileArray[] = inputDirectory.listFiles(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".xmi");
}
});
List<File> fileList = Arrays.asList(fileArray);
return fileList;
}
public void execute() throws UIMAException, IOException, URISyntaxException
{
AggregateBuilder builder = new AggregateBuilder();
TypeSystemDescription typeSystemDescription = TypeSystemDescriptionFactory.createTypeSystemDescriptionFromPath();
// CollectionReader reader =
// CollectionReaderFactory.createReader(
// XMIReader.class,
// typeSystemDescription,
// XMIReader.PARAM_FILES,
// inputFiles);
CollectionReader reader =
CollectionReaderFactory.createReader(
TextReader.class,
typeSystemDescription,
TextReader.PARAM_FILES,
inputFiles);
AnalysisEngineDescription documentIdPrinter =
AnalysisEngineFactory.createEngineDescription(DocumentIdPrinterAnalysisEngine.class);
builder.add(documentIdPrinter);
String generalSectionRegexFileUri =
"org/mitre/medfacts/uima/section_regex.xml";
//URI generalSectionRegexFileUri =
// this.getClass().getClassLoader().getResource("org/mitre/medfacts/zoner/section_regex.xml").toURI();
// ExternalResourceDescription generalSectionRegexDescription = ExternalResourceFactory.createExternalResourceDescription(
// SectionRegexConfigurationResource.class, new File(generalSectionRegexFileUri));
AnalysisEngineDescription zonerAnnotator =
AnalysisEngineFactory.createEngineDescription(ZoneAnnotator.class,
ZoneAnnotator.PARAM_SECTION_REGEX_FILE_URI,
generalSectionRegexFileUri
);
builder.add(zonerAnnotator);
String mayoSectionRegexFileUri =
"org/mitre/medfacts/uima/mayo_sections.xml";
// URI mayoSectionRegexFileUri =
// this.getClass().getClassLoader().getResource("org/mitre/medfacts/zoner/mayo_sections.xml").toURI();
// ExternalResourceDescription mayoSectionRegexDescription = ExternalResourceFactory.createExternalResourceDescription(
// SectionRegexConfigurationResource.class, new File(mayoSectionRegexFileUri));
AnalysisEngineDescription mayoZonerAnnotator =
AnalysisEngineFactory.createEngineDescription(ZoneAnnotator.class,
ZoneAnnotator.PARAM_SECTION_REGEX_FILE_URI,
mayoSectionRegexFileUri
);
builder.add(mayoZonerAnnotator);
AnalysisEngineDescription xWriter = AnalysisEngineFactory.createEngineDescription(
XmiWriterCasConsumerCtakes.class,
typeSystemDescription,
XmiWriterCasConsumerCtakes.PARAM_OUTPUTDIR,
outputDirectory.toString()
);
builder.add(xWriter);
logger.info("BEFORE RUNNING PIPELINE...");
SimplePipeline.runPipeline(reader, builder.createAggregateDescription());
logger.info("AFTER RUNNING PIPELINE...COMPLETED");
}
public File getInputDirectory()
{
return inputDirectory;
}
public void setInputDirectory(File inputDirectory)
{
this.inputDirectory = inputDirectory;
}
public List<File> getInputFiles()
{
return inputFiles;
}
public void setInputFiles(List<File> inputFiles)
{
this.inputFiles = inputFiles;
}
public File getOutputDirectory()
{
return outputDirectory;
}
public void setOutputDirectory(File outputDirectory)
{
this.outputDirectory = outputDirectory;
}
}
| {'content_hash': '0f691e20de7e051c249245bf571bb25d', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 127, 'avg_line_length': 32.445086705202314, 'alnum_prop': 0.727240334936754, 'repo_name': 'TCU-MI/ctakes', 'id': '36f20ca24590c097bf1ae8f9ca6438c55de5a85d', 'size': '6421', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ctakes-assertion-zoner/src/main/java/org/mitre/medfacts/uima/RunZoner.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '23017'}, {'name': 'Bluespec', 'bytes': '3571'}, {'name': 'CSS', 'bytes': '2714'}, {'name': 'Groovy', 'bytes': '31169'}, {'name': 'HTML', 'bytes': '28750'}, {'name': 'Java', 'bytes': '6437520'}, {'name': 'PLSQL', 'bytes': '4571'}, {'name': 'Perl', 'bytes': '1610'}, {'name': 'SQLPL', 'bytes': '26511'}, {'name': 'Shell', 'bytes': '5446'}, {'name': 'XSLT', 'bytes': '1909'}]} |
<LINK REL="stylesheet" HREF="../static/styles.css">
<HTML>
<HEAD>
<TITLE>Geometry::setPolygonVertex</TITLE>
</HEAD>
<BODY TOPMARGIN="0" class="api_reference">
<p class="header">Firelight Technologies FMOD Studio API</p>
<H1>Geometry::setPolygonVertex</H1>
<P>
<p>Alters the position of a polygon's vertex inside a geometry object.</p>
</P>
<h3>C++ Syntax</h3>
<PRE class=syntax><CODE>FMOD_RESULT Geometry::setPolygonVertex(
int <I>index</I>,
int <I>vertexindex</I>,
const FMOD_VECTOR *<I>vertex</I>
);
</CODE></PRE>
<h3>C Syntax</h3>
<PRE class=syntax><CODE>FMOD_RESULT FMOD_Geometry_SetPolygonVertex(
FMOD_GEOMETRY *<I>geometry</I>,
int <I>index</I>,
int <I>vertexindex</I>,
const FMOD_VECTOR *<I>vertex</I>
);
</CODE></PRE>
<h3>C# Syntax</h3>
<PRE class=syntax><CODE>RESULT Geometry.setPolygonVertex(
int <i>index</i>,
int <i>vertexindex</i>,
ref VECTOR <i>vertex</i>
);
</CODE></PRE>
<h2>Parameters</h2>
<dl>
<dt>index</dt>
<dd>Polygon index. This must be in the range of 0 to <A HREF="FMOD_Geometry_GetNumPolygons.html">Geometry::getNumPolygons</A> minus 1.</dd>
<dt>vertexindex</dt>
<dd>Vertex index inside the polygon. This must be in the range of 0 to <A HREF="FMOD_Geometry_GetPolygonNumVertices.html">Geometry::getPolygonNumVertices</A> minus 1.</dd>
<dt>vertex</dt>
<dd>Address of an <A HREF="FMOD_VECTOR.html">FMOD_VECTOR</A> which holds the new vertex location.</dd>
</dl>
<h2>Return Values</h2><P>
If the function succeeds then the return value is <A HREF="FMOD_RESULT.html">FMOD_OK</A>.<BR>
If the function fails then the return value will be one of the values defined in the <A HREF="FMOD_RESULT.html">FMOD_RESULT</A> enumeration.<BR>
</P>
<h2>Remarks</h2><P>
<p><strong>Note!</strong> There may be some significant overhead with this function as it may cause some reconfiguration of internal
data structures used to speed up sound-ray testing.</p>
<p>You may get better results if you want to modify your object by using <A HREF="FMOD_Geometry_SetPosition.html">Geometry::setPosition</A>, <A HREF="FMOD_Geometry_SetScale.html">Geometry::setScale</A> and
<A HREF="FMOD_Geometry_SetRotation.html">Geometry::setRotation</A>.</p>
</P>
<h2>See Also</h2>
<UL type=disc>
<LI><A HREF="FMOD_Geometry_GetPolygonNumVertices.html">Geometry::getPolygonNumVertices</A></LI>
<LI><A HREF="FMOD_Geometry_GetPolygonNumVertices.html">Geometry::getPolygonNumVertices</A></LI>
<LI><A HREF="FMOD_Geometry_SetPosition.html">Geometry::setPosition</A></LI>
<LI><A HREF="FMOD_Geometry_SetScale.html">Geometry::setScale</A></LI>
<LI><A HREF="FMOD_Geometry_SetRotation.html">Geometry::setRotation</A></LI>
<LI><A HREF="FMOD_Geometry_GetNumPolygons.html">Geometry::getNumPolygons</A></LI>
<LI><A HREF="FMOD_VECTOR.html">FMOD_VECTOR</A></LI>
</UL>
<BR><BR><BR>
<P align=center><font size=-2>Version 1.08.02 Built on Apr 14, 2016</font></P>
<BR>
</HTML>
| {'content_hash': 'd7b36f3a5fe1b437ae026b4b59160ac3', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 205, 'avg_line_length': 42.71641791044776, 'alnum_prop': 0.7187281621243885, 'repo_name': 'Silveryard/Car_System', 'id': 'ba489908217c2327b5b47a53e2565a610525f886', 'size': '2862', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Old/3rdParty/fmodstudioapi10802linux/doc/FMOD Studio Programmers API for Linux/content/generated/FMOD_Geometry_SetPolygonVertex.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1067'}, {'name': 'C', 'bytes': '50059951'}, {'name': 'C#', 'bytes': '62366'}, {'name': 'C++', 'bytes': '48819993'}, {'name': 'CMake', 'bytes': '94005'}, {'name': 'CSS', 'bytes': '8053'}, {'name': 'FORTRAN', 'bytes': '109708'}, {'name': 'HTML', 'bytes': '2447714'}, {'name': 'JavaScript', 'bytes': '5283'}, {'name': 'Logos', 'bytes': '214154'}, {'name': 'Objective-C', 'bytes': '2032834'}, {'name': 'Protocol Buffer', 'bytes': '28889'}, {'name': 'Shell', 'bytes': '670'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Dashboard</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/adminlte/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/adminlte/skins/_all-skins.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/iCheck/flat/blue.css">
<!-- Morris chart -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/morris/morris.css">
<!-- jvectormap -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<!-- Date Picker -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/datepicker/datepicker3.css">
<!-- Daterange picker -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/daterangepicker/daterangepicker-bs3.css">
<!-- bootstrap wysihtml5 - text editor -->
<link rel="stylesheet" href="<?php echo base_url(); ?>plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/my-styles.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
/* Note: Try to remove the following lines to see the effect of CSS positioning */
</style>
</head>
<body>
<div class="wrapper">
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div>
<center><img src="<?php echo base_url()?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image"></center>
</div>
<div >
<center><h4 class="pumpkin">Alexander Pierce</h4></center>
<hr>
</div>
</div>
<!-- sidebar menu panel -->
<ul class="sidebar-menu">
<li>
<a href="<?php echo base_url()?>profile">
<i class="fa fa-dashboard"></i><span>Dashboard</span>
</a>
</li>
<li>
<a href="<?php echo base_url()?>profile/MyDonation">
<i class="fa fa-money"></i><span>Donasi Saya</span>
</a>
</li>
<li>
<a href="<?php echo base_url()?>profile/MyCampaign">
<i class="fa fa-life-saver"></i><span>Kampanye Saya</span>
</a>
</li>
<!--multi-->
<li class="treeview active">
<a href="#">
<i class="fa fa-cogs"></i><span>Setting</span> <i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu menu-open">
<li><a href="<?php echo base_url(); ?>Profile/MyInfo"><i class="fa fa-user"></i>Profil Saya</a></li>
<li><a href="<?php echo base_url(); ?>Profile/EditPass"><i class="fa fa-key"></i>Edit Password</a></li>
<li><a href="<?php echo base_url(); ?>Profile/EditProfilePic"><i class="fa fa-photo"></i>Edit Profile Picture</a></li>
<li class="current"><a href="<?php echo base_url(); ?>Profile/VerifyAkun" ><i class="fa fa-check"></i>Verifikasi Akun</a></li>
</ul>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Main content -->
<section class="content">
<!-- Main row -->
<h2 class="box-title">Verify Akun</h2>
<div class="box box-warning" style="width:85%; margin-left: 7.5%; min-height: 600px;">
<div class="row" style="width: 80%; margin-left: 10%;">
<div class="box-header with-border">
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal" style="padding-left: 80px; padding-right: 50px;">
<div class="box-body">
<div class="form-group">
<label for="FB-URL" class="col-sm-2 control-label">Facebook URL</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="FB-URL" placeholder="Enter Facebook URL">
</div>
</div>
<div class="form-group">
<label for="telp" class="col-sm-2 control-label">No Telepon</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="telp" placeholder="08XXXXXXXXX">
</div>
</div>
<div class="form-group">
<label for="alamat" class="col-sm-2 control-label">Alamat</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" cols="50" placeholder="Alamat" id="alamat"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label for="scanid" class="col-sm-2 control-label">Scan Foto Identitas: KTP/Identitas Lain</label>
<div class="col-sm-10">
<img src="//placehold.it/500" class="avatar img" alt="avatar">
<input type="file" id="scanid">
</div>
</div>
<div class="form-group">
<label for="scanfoto" class="col-sm-2 control-label">Scan Foto Terbaru</label>
<div class="col-sm-10">
<img src="//placehold.it/500" class="avatar img" alt="avatar">
<input type="file" id="scanfoto">
</div>
</div>
</div>
<!--<div class="form-group">
<label for="telp">No Telepon</label>
<input type="password" class="form-control" id="telp" placeholder="08XXXXXXXXX">
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<textarea class="form-control" rows="4" cols="50" placeholder="Alamat" id="alamat"></textarea>
</div>
<div class="form-group">
<label for="scanid">Upload Scan Foto Identitas KTP/Identitas Lain</label>
<img src="//placehold.it/300" class="avatar img" alt="avatar" style="margin-left: 250px;">
<input type="file" id="scanid" style="margin-left: 550px;">
</div>
<div class="form-group">
<label for="scanfoto">Upload Scan Foto Terbaru</label>
<img src="//placehold.it/300" class="avatar img" alt="avatar" style="margin-left: 350px;">
<input type="file" id="scanid" style="margin-left: 550px;">
</div>-->
<!-- /.box-body -->
<div class="box-footer">
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
</form>
</div>
<!-- /.row (main row) -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<div class="control-sidebar-bg"></div></div>
<!-- ./wrapper -->
<!-- jQuery 2.2.0 -->
<script src="<?php echo base_url(); ?>plugins/jQuery/jQuery-2.2.0.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="<?php echo base_url(); ?>plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="<?php echo base_url(); ?>plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="<?php echo base_url(); ?>plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="<?php echo base_url(); ?>plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="<?php echo base_url(); ?>plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="<?php echo base_url(); ?>plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="<?php echo base_url(); ?>plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="<?php echo base_url(); ?>plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="<?php echo base_url(); ?>plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="<?php echo base_url(); ?>plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url(); ?>assets/js/adminlte/app.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="<?php echo base_url(); ?>assets/js/adminlte/pages/dashboard.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo base_url(); ?>assets/js/adminlte/demo.js"></script>
</body>
</html> | {'content_hash': 'd4860b197586d96b5ffecaed609f1bde', 'timestamp': '', 'source': 'github', 'line_count': 227, 'max_line_length': 138, 'avg_line_length': 46.202643171806166, 'alnum_prop': 0.5619755911517925, 'repo_name': 'irsyadhs/sharehappy', 'id': '3df87f8289d6d39cf370c5254e4ed8398218a9be', 'size': '10488', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/views/Profile/VerifyAkun.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '427'}, {'name': 'CSS', 'bytes': '770032'}, {'name': 'HTML', 'bytes': '10147713'}, {'name': 'JavaScript', 'bytes': '2981285'}, {'name': 'PHP', 'bytes': '2204747'}]} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Common Functions
*
* Loads the base classes and executes the request.
*
* @package CodeIgniter
* @subpackage CodeIgniter
* @category Common Functions
* @author EllisLab Dev Team
* @link https://codeigniter.com/user_guide/
*/
// ------------------------------------------------------------------------
if ( ! function_exists('is_php'))
{
/**
* Determines if the current version of PHP is equal to or greater than the supplied value
*
* @param string
* @return bool TRUE if the current version is $version or higher
*/
function is_php($version)
{
static $_is_php;
$version = (string) $version;
if ( ! isset($_is_php[$version]))
{
$_is_php[$version] = version_compare(PHP_VERSION, $version, '>=');
}
return $_is_php[$version];
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('is_really_writable'))
{
/**
* Tests for file writability
*
* is_writable() returns TRUE on Windows servers when you really can't write to
* the file, based on the read-only attribute. is_writable() is also unreliable
* on Unix servers if safe_mode is on.
*
* @link https://bugs.php.net/bug.php?id=54709
* @param string
* @return bool
*/
function is_really_writable($file)
{
// If we're on a Unix server with safe_mode off we call is_writable
if (DIRECTORY_SEPARATOR === '/' && (is_php('5.4') OR ! ini_get('safe_mode')))
{
return is_writable($file);
}
/* For Windows servers and safe_mode "on" installations we'll actually
* write a file then read it. Bah...
*/
if (is_dir($file))
{
$file = rtrim($file, '/').'/'.md5(mt_rand());
if (($fp = @fopen($file, 'ab')) === FALSE)
{
return FALSE;
}
fclose($fp);
@chmod($file, 0777);
@unlink($file);
return TRUE;
}
elseif ( ! is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE)
{
return FALSE;
}
fclose($fp);
return TRUE;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('load_class'))
{
/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* @param string the class name being requested
* @param string the directory where the class should be found
* @param string an optional argument to pass to the class constructor
* @return object
*/
function &load_class($class, $directory = 'libraries', $param = NULL)
{
static $_classes = array();
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
}
$name = FALSE;
// Look for the class first in the local app/libraries folder
// then in the native system/libraries folder
foreach (array(APPPATH, BASEPATH) as $path)
{
if (file_exists($path.$directory.'/'.$class.'.php'))
{
$name = 'CI_'.$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once($path.$directory.'/'.$class.'.php');
}
break;
}
}
// Is the request a class extension? If so we load it too
if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
{
$name = config_item('subclass_prefix').$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once(APPPATH.$directory.'/'.$name.'.php');
}
}
// Did we find the class?
if ($name === FALSE)
{
// Note: We use exit() rather than show_error() in order to avoid a
// self-referencing loop with the Exceptions class
set_status_header(503);
echo 'Unable to locate the specified class: '.$class.'.php';
exit(5); // EXIT_UNK_CLASS
}
// Keep track of what we just loaded
is_loaded($class);
$_classes[$class] = isset($param)
? new $name($param)
: new $name();
return $_classes[$class];
}
}
// --------------------------------------------------------------------
if ( ! function_exists('is_loaded'))
{
/**
* Keeps track of which libraries have been loaded. This function is
* called by the load_class() function above
*
* @param string
* @return array
*/
function &is_loaded($class = '')
{
static $_is_loaded = array();
if ($class !== '')
{
$_is_loaded[strtolower($class)] = $class;
}
return $_is_loaded;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('get_config'))
{
/**
* Loads the main config.php file
*
* This function lets us grab the config file even if the Config class
* hasn't been instantiated yet
*
* @param array
* @return array
*/
function &get_config(Array $replace = array())
{
static $config;
if (empty($config))
{
$file_path = APPPATH.'config/config.php';
$found = FALSE;
if (file_exists($file_path))
{
$found = TRUE;
require($file_path);
}
// Is the config file in the environment folder?
if (file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
{
require($file_path);
}
elseif ( ! $found)
{
set_status_header(503);
echo 'The configuration file does not exist.';
exit(3); // EXIT_CONFIG
}
// Does the $config array exist in the file?
if ( ! isset($config) OR ! is_array($config))
{
set_status_header(503);
echo 'Your config file does not appear to be formatted correctly.';
exit(3); // EXIT_CONFIG
}
}
// Are any values being dynamically added or replaced?
foreach ($replace as $key => $val)
{
$config[$key] = $val;
}
return $config;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('config_item'))
{
/**
* Returns the specified config item
*
* @param string
* @return mixed
*/
function config_item($item)
{
static $_config;
if (empty($_config))
{
// references cannot be directly assigned to static variables, so we use an array
$_config[0] =& get_config();
}
return isset($_config[0][$item]) ? $_config[0][$item] : NULL;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('get_mimes'))
{
/**
* Returns the MIME types array from config/mimes.php
*
* @return array
*/
function &get_mimes()
{
static $_mimes;
if (empty($_mimes))
{
if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
$_mimes = include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (file_exists(APPPATH.'config/mimes.php'))
{
$_mimes = include(APPPATH.'config/mimes.php');
}
else
{
$_mimes = array();
}
}
return $_mimes;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('is_https'))
{
/**
* Is HTTPS?
*
* Determines if the app is accessed via an encrypted
* (HTTPS) connection.
*
* @return bool
*/
function is_https()
{
if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
{
return TRUE;
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
{
return TRUE;
}
elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
{
return TRUE;
}
return FALSE;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('is_cli'))
{
/**
* Is CLI?
*
* Test to see if a request was made from the command line.
*
* @return bool
*/
function is_cli()
{
return (PHP_SAPI === 'cli' OR defined('STDIN'));
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('show_error'))
{
/**
* Error Handler
*
* This function lets us invoke the exception class and
* display errors using the standard error template located
* in app/views/errors/error_general.php
* This function will send the error page directly to the
* browser and exit.
*
* @param string
* @param int
* @param string
* @return void
*/
function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
{
$status_code = abs($status_code);
if ($status_code < 100)
{
$exit_status = $status_code + 9; // 9 is EXIT__AUTO_MIN
if ($exit_status > 125) // 125 is EXIT__AUTO_MAX
{
$exit_status = 1; // EXIT_ERROR
}
$status_code = 500;
}
else
{
$exit_status = 1; // EXIT_ERROR
}
$_error =& load_class('Exceptions', 'core');
echo $_error->show_error($heading, $message, 'error_general', $status_code);
exit($exit_status);
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('show_404'))
{
/**
* 404 Page Handler
*
* This function is similar to the show_error() function above
* However, instead of the standard error template it displays
* 404 errors.
*
* @param string
* @param bool
* @return void
*/
function show_404($page = '', $log_error = TRUE)
{
$_error =& load_class('Exceptions', 'core');
$_error->show_404($page, $log_error);
exit(4); // EXIT_UNKNOWN_FILE
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('log_message'))
{
/**
* Error Logging Interface
*
* We use this as a simple mechanism to access the logging
* class and send messages to be logged.
*
* @param string the error level: 'error', 'debug' or 'info'
* @param string the error message
* @return void
*/
function log_message($level, $message)
{
static $_log;
if ($_log === NULL)
{
// references cannot be directly assigned to static variables, so we use an array
$_log[0] =& load_class('Log', 'core');
}
$_log[0]->write_log($level, $message);
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('set_status_header'))
{
/**
* Set HTTP Status Header
*
* @param int the status code
* @param string
* @return void
*/
function set_status_header($code = 200, $text = '')
{
if (is_cli())
{
return;
}
if (empty($code) OR ! is_numeric($code))
{
show_error('Status codes must be numeric', 500);
}
if (empty($text))
{
is_int($code) OR $code = (int) $code;
$stati = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
if (isset($stati[$code]))
{
$text = $stati[$code];
}
else
{
show_error('No status text available. Please check your status code number or supply your own message text.', 500);
}
}
if (strpos(PHP_SAPI, 'cgi') === 0)
{
header('Status: '.$code.' '.$text, TRUE);
}
else
{
$server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
header($server_protocol.' '.$code.' '.$text, TRUE, $code);
}
}
}
// --------------------------------------------------------------------
if ( ! function_exists('_error_handler'))
{
/**
* Error Handler
*
* This is the custom error handler that is declared at the (relative)
* top of CodeIgniter.php. The main reason we use this is to permit
* PHP errors to be logged in our own log files since the user may
* not have access to server logs. Since this function effectively
* intercepts PHP errors, however, we also need to display errors
* based on the current error_reporting level.
* We do that with the use of a PHP error template.
*
* @param int $severity
* @param string $message
* @param string $filepath
* @param int $line
* @return void
*/
function _error_handler($severity, $message, $filepath, $line)
{
$is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $severity) === $severity);
// When an error occurred, set the status header to '500 Internal Server Error'
// to indicate to the client something went wrong.
// This can't be done within the $_error->show_php_error method because
// it is only called when the display_errors flag is set (which isn't usually
// the case in a production environment) or when errors are ignored because
// they are above the error_reporting threshold.
if ($is_error)
{
set_status_header(500);
}
// Should we ignore the error? We'll get the current error_reporting
// level and add its bits with the severity bits to find out.
if (($severity & error_reporting()) !== $severity)
{
return;
}
$_error =& load_class('Exceptions', 'core');
$_error->log_exception($severity, $message, $filepath, $line);
// Should we display the error?
if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
{
$_error->show_php_error($severity, $message, $filepath, $line);
}
// If the error is fatal, the execution of the script should be stopped because
// errors can't be recovered from. Halting the script conforms with PHP's
// default error handling. See http://www.php.net/manual/en/errorfunc.constants.php
if ($is_error)
{
exit(1); // EXIT_ERROR
}
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('_exception_handler'))
{
/**
* Exception Handler
*
* Sends uncaught exceptions to the logger and displays them
* only if display_errors is On so that they don't show up in
* production environments.
*
* @param Exception $exception
* @return void
*/
function _exception_handler($exception)
{
$_error =& load_class('Exceptions', 'core');
$_error->log_exception('error', 'Exception: '.$exception->getMessage(), $exception->getFile(), $exception->getLine());
// Should we display the error?
if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
{
$_error->show_exception($exception);
}
exit(1); // EXIT_ERROR
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('_shutdown_handler'))
{
/**
* Shutdown Handler
*
* This is the shutdown handler that is declared at the top
* of CodeIgniter.php. The main reason we use this is to simulate
* a complete custom exception handler.
*
* E_STRICT is purposively neglected because such events may have
* been caught. Duplication or none? None is preferred for now.
*
* @link http://insomanic.me.uk/post/229851073/php-trick-catching-fatal-errors-e-error-with-a
* @return void
*/
function _shutdown_handler()
{
$last_error = error_get_last();
if (isset($last_error) &&
($last_error['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING)))
{
_error_handler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']);
}
}
}
// --------------------------------------------------------------------
if ( ! function_exists('remove_invisible_characters'))
{
/**
* Remove Invisible Characters
*
* This prevents sandwiching null characters
* between ascii characters, like Java\0script.
*
* @param string
* @param bool
* @return string
*/
function remove_invisible_characters($str, $url_encoded = TRUE)
{
$non_displayables = array();
// every control character except newline (dec 10),
// carriage return (dec 13) and horizontal tab (dec 09)
if ($url_encoded)
{
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do
{
$str = preg_replace($non_displayables, '', $str, -1, $count);
}
while ($count);
return $str;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('html_escape'))
{
/**
* Returns HTML escaped variable.
*
* @param mixed $var The input string or array of strings to be escaped.
* @param bool $double_encode $double_encode set to FALSE prevents escaping twice.
* @return mixed The escaped string or array of strings as a result.
*/
function html_escape($var, $double_encode = TRUE)
{
if (empty($var))
{
return $var;
}
if (is_array($var))
{
foreach (array_keys($var) as $key)
{
$var[$key] = html_escape($var[$key], $double_encode);
}
return $var;
}
return htmlspecialchars($var, ENT_QUOTES, config_item('charset'), $double_encode);
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('_stringify_attributes'))
{
/**
* Stringify attributes for use in HTML tags.
*
* Helper function used to convert a string, array, or object
* of attributes to a string.
*
* @param mixed string, array, object
* @param bool
* @return string
*/
function _stringify_attributes($attributes, $js = FALSE)
{
$atts = NULL;
if (empty($attributes))
{
return $atts;
}
if (is_string($attributes))
{
return ' '.$attributes;
}
$attributes = (array) $attributes;
foreach ($attributes as $key => $val)
{
$atts .= ($js) ? $key.'='.$val.',' : ' '.$key.'="'.$val.'"';
}
return rtrim($atts, ',');
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('function_usable'))
{
/**
* Function usable
*
* Executes a function_exists() check, and if the Suhosin PHP
* extension is loaded - checks whether the function that is
* checked might be disabled in there as well.
*
* This is useful as function_exists() will return FALSE for
* functions disabled via the *disable_functions* php.ini
* setting, but not for *suhosin.executor.func.blacklist* and
* *suhosin.executor.disable_eval*. These settings will just
* terminate script execution if a disabled function is executed.
*
* The above described behavior turned out to be a bug in Suhosin,
* but even though a fix was commited for 0.9.34 on 2012-02-12,
* that version is yet to be released. This function will therefore
* be just temporary, but would probably be kept for a few years.
*
* @link http://www.hardened-php.net/suhosin/
* @param string $function_name Function to check for
* @return bool TRUE if the function exists and is safe to call,
* FALSE otherwise.
*/
function function_usable($function_name)
{
static $_suhosin_func_blacklist;
if (function_exists($function_name))
{
if ( ! isset($_suhosin_func_blacklist))
{
$_suhosin_func_blacklist = extension_loaded('suhosin')
? explode(',', trim(ini_get('suhosin.executor.func.blacklist')))
: array();
}
return ! in_array($function_name, $_suhosin_func_blacklist, TRUE);
}
return FALSE;
}
}
| {'content_hash': '15850cabae2c46c4dee802637b41e9e4', 'timestamp': '', 'source': 'github', 'line_count': 816, 'max_line_length': 120, 'avg_line_length': 24.488970588235293, 'alnum_prop': 0.574988740429365, 'repo_name': 'shr1th1k/0fferc1t1', 'id': 'efcabbd56fcb7b36de141a64ded90a50e0fe8223', 'size': '21635', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'system/core/Common.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '549'}, {'name': 'CSS', 'bytes': '678813'}, {'name': 'HTML', 'bytes': '8447358'}, {'name': 'JavaScript', 'bytes': '387910'}, {'name': 'PHP', 'bytes': '2321116'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ko">
<head>
<!-- Generated by javadoc (1.8.0_112) on Fri Apr 14 03:26:08 KST 2017 -->
<title>com.scene.ingsta.beans</title>
<meta name="date" content="2017-04-14">
<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="com.scene.ingsta.beans";
}
}
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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Package</li>
<li><a href="../../../../com/scene/ingsta/controllers/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/scene/ingsta/beans/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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">
<h1 title="Package" class="title">Package com.scene.ingsta.beans</h1>
<div class="docSummary">
<div class="block">Entities</div>
</div>
<p>See: <a href="#package.description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Code.html" title="class in com.scene.ingsta.beans">Code</a></td>
<td class="colLast">
<div class="block">
코드 빈
코드 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Heart.html" title="class in com.scene.ingsta.beans">Heart</a></td>
<td class="colLast">
<div class="block">
하트 빈
하트 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Ing.html" title="class in com.scene.ingsta.beans">Ing</a></td>
<td class="colLast">
<div class="block">
잉 빈
잉 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Ingsta.html" title="class in com.scene.ingsta.beans">Ingsta</a></td>
<td class="colLast">
<div class="block">
잉스타 빈
잉스타 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Notify.html" title="class in com.scene.ingsta.beans">Notify</a></td>
<td class="colLast">
<div class="block">
알림 빈
알림 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Scene.html" title="class in com.scene.ingsta.beans">Scene</a></td>
<td class="colLast">
<div class="block">
씬 빈
씬 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Star.html" title="class in com.scene.ingsta.beans">Star</a></td>
<td class="colLast">
<div class="block">
스타 빈
스타 콩
엔티티 빈
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/scene/ingsta/beans/Talk.html" title="class in com.scene.ingsta.beans">Talk</a></td>
<td class="colLast">
<div class="block">
톡 빈
톡 콩
엔티티 빈
</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package.description">
<!-- -->
</a>
<h2 title="Package com.scene.ingsta.beans Description">Package com.scene.ingsta.beans Description</h2>
<div class="block">Entities</div>
</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Package</li>
<li><a href="../../../../com/scene/ingsta/controllers/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/scene/ingsta/beans/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 ======= -->
</body>
</html>
| {'content_hash': '7078f796406360da713966dd8b9fa554', 'timestamp': '', 'source': 'github', 'line_count': 323, 'max_line_length': 137, 'avg_line_length': 21.343653250773993, 'alnum_prop': 0.6041485349579344, 'repo_name': 'sistfers/ingsta', 'id': 'eaf125c5e6ca3c4a134988f303945b0dc658c802', 'size': '7046', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/com/scene/ingsta/beans/package-summary.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '33448'}, {'name': 'Java', 'bytes': '361003'}, {'name': 'JavaScript', 'bytes': '20683'}, {'name': 'PLSQL', 'bytes': '9293'}]} |
fn main() {
let n = 1;
let a = [0; n]; //~ ERROR expected constant integer for repeat count, found variable
let b = [0; ()];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `()`
//~| expected usize
//~| found ()
//~| ERROR expected constant integer for repeat count, found non-constant expression
let c = [0; true];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `bool`
//~| expected usize
//~| found bool
//~| ERROR expected positive integer for repeat count, found boolean
let d = [0; 0.5];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `_`
//~| expected usize
//~| found floating-point variable
//~| ERROR expected positive integer for repeat count, found float
let e = [0; "foo"];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `&'static str`
//~| expected usize
//~| found &-ptr
//~| ERROR expected positive integer for repeat count, found string
let f = [0; -4_isize];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `isize`
//~| expected usize
//~| found isize
//~| ERROR expected positive integer for repeat count, found negative integer
let f = [0_usize; -1_isize];
//~^ ERROR mismatched types
//~| expected `usize`
//~| found `isize`
//~| expected usize
//~| found isize
//~| ERROR expected positive integer for repeat count, found negative integer
}
| {'content_hash': '35c39845632c7574b931b23bf1287ef2', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 88, 'avg_line_length': 32.21739130434783, 'alnum_prop': 0.5910931174089069, 'repo_name': 'untitaker/rust', 'id': '9b3e2668042eaa0545513a8a5b5d4525e7c2a2e3', 'size': '1990', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/test/compile-fail/repeat_count.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4990'}, {'name': 'Assembly', 'bytes': '20064'}, {'name': 'Awk', 'bytes': '159'}, {'name': 'Bison', 'bytes': '78113'}, {'name': 'C', 'bytes': '681776'}, {'name': 'C++', 'bytes': '69777'}, {'name': 'CSS', 'bytes': '22360'}, {'name': 'JavaScript', 'bytes': '33714'}, {'name': 'Makefile', 'bytes': '224872'}, {'name': 'Puppet', 'bytes': '16270'}, {'name': 'Python', 'bytes': '138216'}, {'name': 'Rust', 'bytes': '18563581'}, {'name': 'Shell', 'bytes': '283425'}, {'name': 'TeX', 'bytes': '57'}]} |
/**
* JDBC Interface to Mysql functions
*
* <p>
* This class provides information about the database as a whole.
*
* <p>
* Many of the methods here return lists of information in ResultSets.
* You can use the normal ResultSet methods such as getString and getInt
* to retrieve the data from these ResultSets. If a given form of
* metadata is not available, these methods show throw a java.sql.SQLException.
*
* <p>
* Some of these methods take arguments that are String patterns. These
* methods all have names such as fooPattern. Within a pattern String "%"
* means match any substring of 0 or more characters and "_" means match
* any one character.
*
* @author Mark Matthews <[email protected]>
* @version $Id: DatabaseMetaData.java,v 1.1.1.1 2002-11-20 20:30:11 yfkuo Exp $
*/
package org.gjt.mm.mysql.jdbc1;
import java.sql.*;
public class DatabaseMetaData extends org.gjt.mm.mysql.DatabaseMetaData
implements java.sql.DatabaseMetaData
{
public DatabaseMetaData(org.gjt.mm.mysql.Connection Conn, String Database)
{
super(Conn, Database);
}
protected java.sql.ResultSet buildResultSet(org.gjt.mm.mysql.Field[] Fields,
java.util.Vector Rows,
org.gjt.mm.mysql.Connection Conn)
{
return new org.gjt.mm.mysql.jdbc1.ResultSet(Fields, Rows, Conn);
}
};
| {'content_hash': '6b6730c503784fdd87cd0c91d50d2523', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 81, 'avg_line_length': 32.88095238095238, 'alnum_prop': 0.6951484431571325, 'repo_name': 'elliottbiondo/ALARA', 'id': 'f34960ad8e972e7baf03507b5db3f6905b980878', 'size': '1381', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tools/jALARA/org/gjt/mm/mysql/jdbc1/DatabaseMetaData.java', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '432564'}, {'name': 'C++', 'bytes': '267418'}, {'name': 'FORTRAN', 'bytes': '2268'}, {'name': 'JavaScript', 'bytes': '304'}, {'name': 'Perl', 'bytes': '3908'}, {'name': 'Shell', 'bytes': '6758'}, {'name': 'TeX', 'bytes': '238102'}]} |
const _ = require('lodash');
const { getCamelCase, getClassName, getFilesInPath } = require('./helper');
const getLibComponentConfig = (cName, cType, withTest) => {
const cNameCamelCase = getCamelCase(cName);
const cNameClassName = getClassName(cNameCamelCase);
const templatePath = 'dev/templates/lib';
const templateFile = `${cType}.handlebars`;
const templateStyle = 'style.handlebars';
const templateTest = 'test.handlebars';
const templateKeep = 'keep.handlebars';
const destPath = 'client/lib';
const componentFiles = [{
src: `${templatePath}/${templateFile}`,
dest: `${destPath}/${cName}/${cName}.js`,
}, {
src: `${templatePath}/${templateStyle}`,
dest: `${destPath}/${cName}/${cName}.scss`,
}];
const testFiles = withTest ?
[{
src: `${templatePath}/${templateTest}`,
dest: `${destPath}/${cName}/tests/${cName}.spec.js`,
},
] : [{
src: `${templatePath}/${templateKeep}`,
dest: `${destPath}/${cName}/tests/.gitkeep`,
}];
return {
files: [...componentFiles, ...testFiles],
templateData: {
cName,
cNameClassName,
},
};
};
module.exports = {
getLibComponentConfig,
};
| {'content_hash': 'bfba7019cd92d350b385a9089b1241eb', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 75, 'avg_line_length': 28.214285714285715, 'alnum_prop': 0.6253164556962025, 'repo_name': 'kifahhk/nerm-boilerplate', 'id': '546b3ddb5491541cbff7e7bb926d8b120f9b2a91', 'size': '1185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dev/tasks/lib-component-task.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1647'}, {'name': 'HTML', 'bytes': '6020'}, {'name': 'JavaScript', 'bytes': '64140'}]} |
/**
* @file rc_calibrate_gyro.c
* @example rc_calibrate_gyro
*
* @brief runs the mpu gyroscope calibration routine
*
* If the routine is successful, a new gyroscope calibration file
* will be saved which is loaded automatically the next time the MPU
* is used.
*
*
* @author James Strawson
* @date 1/29/2018
*/
#include <stdio.h>
#include <rc/mpu.h>
// bus for Robotics Cape and BeagleBone Blue is 2
// change this for your platform
#define I2C_BUS 2
int main()
{
printf("\nThis program will generate a new gyro calibration file\n");
printf("keep your board very still for this procedure.\n");
printf("Press any key to continue\n");
getchar();
printf("Starting calibration routine\n");
rc_mpu_config_t config = rc_mpu_default_config();
config.i2c_bus = I2C_BUS;
if(rc_mpu_calibrate_gyro_routine(config)<0){
printf("Failed to complete gyro calibration\n");
return -1;
}
printf("\ngyro calibration file written\n");
printf("run rc_test_mpu to check performance\n");
return 0;
}
| {'content_hash': 'e1771f136462874e78d842435f79ece3', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 80, 'avg_line_length': 24.25, 'alnum_prop': 0.6682286785379569, 'repo_name': 'StrawsonDesign/Robotics_Cape_Installer', 'id': 'dc82b993a5f505502c6758668f9ed89d78b263f3', 'size': '1067', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/src/rc_calibrate_gyro.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '8376'}, {'name': 'Batchfile', 'bytes': '3505'}, {'name': 'C', 'bytes': '4061181'}, {'name': 'C++', 'bytes': '169056'}, {'name': 'CMake', 'bytes': '4731'}, {'name': 'Makefile', 'bytes': '12944'}, {'name': 'Shell', 'bytes': '6722'}]} |
function run(args) {
ObjC.import("stdlib");
let browser = $.getenv("browser");
let chrome = Application(browser);
let query = args[0];
let [arg1, arg2] = query.split(",");
let windowIndex = parseInt(arg1);
let tabIndex = parseInt(arg2);
chrome.activate();
chrome.windows[windowIndex].visible = true;
chrome.windows[windowIndex].activeTabIndex = tabIndex + 1;
chrome.windows[windowIndex].index = 1;
}
| {'content_hash': '0571e1e9c6d46206070dc3c0982f9323', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 60, 'avg_line_length': 30.214285714285715, 'alnum_prop': 0.6855791962174941, 'repo_name': 'seansu4you87/dottie', 'id': '6b0995313649535930c2aad4f2e4a6633ce9b4ab', 'size': '463', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'alfred/Alfred.alfredpreferences/workflows/user.workflow.7561758B-C386-4C28-A0A0-D248779DDF69/focus-tab.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'AppleScript', 'bytes': '19029'}, {'name': 'CoffeeScript', 'bytes': '67666'}, {'name': 'JavaScript', 'bytes': '3447'}, {'name': 'PHP', 'bytes': '106430'}, {'name': 'Python', 'bytes': '40880'}, {'name': 'Ruby', 'bytes': '61062'}, {'name': 'Shell', 'bytes': '29620'}]} |
namespace open_spiel {
namespace coop_box_pushing {
// To indicate the status of each agent's action.
enum class ActionStatusType {
kUnresolved,
kSuccess,
kFail,
};
// Direction each agent can be facing.
enum OrientationType {
kNorth = 0,
kEast = 1,
kSouth = 2,
kWest = 3,
kInvalid = 4
};
// When not fully-observable, the number of observations (taken from Seuken &
// Zilberstein '12): empty field, wall, other agent, small box, large box.
enum ObservationType {
kEmptyFieldObs,
kWallObs,
kOtherAgentObs,
kSmallBoxObs,
kBigBoxObs
};
constexpr int kNumObservations = 5;
// Different actions used by the agent.
enum class ActionType { kTurnLeft, kTurnRight, kMoveForward, kStay };
class CoopBoxPushingState : public SimMoveState {
public:
CoopBoxPushingState(std::shared_ptr<const Game> game, int horizon,
bool fully_observable);
std::string ActionToString(Player player, Action action) const override;
std::string ToString() const override;
bool IsTerminal() const override;
std::vector<double> Returns() const override;
std::vector<double> Rewards() const override;
void ObservationTensor(Player player,
absl::Span<float> values) const override;
std::string ObservationString(Player player) const override;
Player CurrentPlayer() const override {
return IsTerminal() ? kTerminalPlayerId : cur_player_;
}
std::unique_ptr<State> Clone() const override;
ActionsAndProbs ChanceOutcomes() const override;
void Reset(const GameParameters& params);
std::vector<Action> LegalActions(Player player) const override;
protected:
void DoApplyAction(Action action) override;
void DoApplyActions(const std::vector<Action>& actions) override;
private:
void SetField(std::pair<int, int> coord, char v);
void SetPlayer(std::pair<int, int> coord, Player player,
OrientationType orientation);
void SetPlayer(std::pair<int, int> coord, Player player);
void AddReward(double reward);
char field(std::pair<int, int> coord) const;
void ResolveMoves();
void MoveForward(Player player);
bool InBounds(std::pair<int, int> coord) const;
bool SameAsPlayer(std::pair<int, int> coord, Player player) const;
// Partial observation of the specific agent.
ObservationType PartialObservation(Player player) const;
// Observation planes for the fully-observable case.
int ObservationPlane(std::pair<int, int> coord, Player player) const;
// Fields sets to bad/invalid values. Use Game::NewInitialState().
double total_rewards_ = -1;
int horizon_ = -1; // Limit on the total number of moves.
Player cur_player_ = kSimultaneousPlayerId;
int total_moves_ = 0;
int initiative_; // player id of player to resolve actions first.
bool win_; // True if agents push the big box to the goal.
bool fully_observable_;
// Most recent rewards.
double reward_;
// All coordinates below are (row, col).
std::array<std::pair<int, int>, 2> player_coords_; // Players' coordinates.
// Players' orientations.
std::array<OrientationType, 2> player_orient_;
// Moves chosen by agents.
std::array<ActionType, 2> moves_;
// The status of each of the players' moves.
std::array<ActionStatusType, 2> action_status_;
// Actual field used by the players.
std::vector<char> field_;
};
class CoopBoxPushingGame : public SimMoveGame {
public:
explicit CoopBoxPushingGame(const GameParameters& params);
int NumDistinctActions() const override;
std::unique_ptr<State> NewInitialState() const override;
int MaxChanceOutcomes() const override { return 4; }
int NumPlayers() const override;
double MinUtility() const override;
double MaxUtility() const override;
std::vector<int> ObservationTensorShape() const override;
int MaxGameLength() const override { return horizon_; }
// TODO: verify whether this bound is tight and/or tighten it.
int MaxChanceNodesInHistory() const override { return MaxGameLength(); }
private:
int horizon_;
bool fully_observable_;
};
} // namespace coop_box_pushing
} // namespace open_spiel
#endif // OPEN_SPIEL_GAMES_COOP_BOX_PUSHING
| {'content_hash': '963848a779968e780d54576794c10fe4', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 78, 'avg_line_length': 33.2, 'alnum_prop': 0.7202409638554217, 'repo_name': 'deepmind/open_spiel', 'id': '37bf40da12e9f3997bce717d7494964e58d90fb9', 'size': '5462', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'open_spiel/games/coop_box_pushing.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '6640'}, {'name': 'C++', 'bytes': '4649139'}, {'name': 'CMake', 'bytes': '78467'}, {'name': 'Go', 'bytes': '18010'}, {'name': 'Julia', 'bytes': '16727'}, {'name': 'Jupyter Notebook', 'bytes': '148663'}, {'name': 'Python', 'bytes': '2823600'}, {'name': 'Rust', 'bytes': '18562'}, {'name': 'Shell', 'bytes': '51087'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" >
<test name="Test" verbose="2">
<classes>
<class name="com.github.harrischu.UI_Smoke.testcase.FortuneMainTest">
<methods>
<!--<include name="Test_01_AutoMatch" />-->
<include name="Test_01_AutoMatch" />
</methods>
</class>
<!-- <class name="com.zendaimoney.autotest.fortunesmoke.testcase.CRMTest">
<methods>
<include name="Test_01_CRM_CreateProduct"/>
<include name="Test_02_CRM_ReviewTest" />
</methods>
</class>-->
</classes>
</test> <!-- Test -->
<listeners>
<!--<listener class-name="org.uncommons.reportng.HTMLReporter" />-->
<listener class-name="com.github.harrischu.webAuto.listener.PowerEmailableReporter" />
<listener class-name="com.github.harrischu.webAuto.listener.TestResultListener" />
</listeners>
<!--<usedefaultlisteners name="false" />-->
</suite> <!-- Suite -->
| {'content_hash': '474d99c253b8d17c2957960213e6d142', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 88, 'avg_line_length': 35.74074074074074, 'alnum_prop': 0.6580310880829016, 'repo_name': 'HarrisChu/webUIAuto', 'id': '5a2a42a98a60fde4745bf21afdd36d9214bb6143', 'size': '965', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UIAuto/UI_Smoke/testng.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '117648'}, {'name': 'Shell', 'bytes': '173'}]} |
xsection.js - Interactive timeline visualization
Demo: http://elplatt.com/demo/xsection
To create your own, just modify the data.js file.
| {'content_hash': 'ef837568a41442e26ae46c053d7c7612', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 49, 'avg_line_length': 28.0, 'alnum_prop': 0.7857142857142857, 'repo_name': 'elplatt/xsection', 'id': '8a52340fe042f9b0c05b56f4d5e33ae9a6b8940c', 'size': '140', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '540'}, {'name': 'JavaScript', 'bytes': '23931'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycologia 68(2): 256 (1976)
#### Original name
Chlorociboria musae Dennis
### Remarks
null | {'content_hash': '16b09101028b80c400f4de5b90a2377b', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 27, 'avg_line_length': 11.846153846153847, 'alnum_prop': 0.7077922077922078, 'repo_name': 'mdoering/backbone', 'id': '4821567f565dd57c2d3c6011ecef6d649bb06ef1', 'size': '221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Rutstroemiaceae/Moellerodiscus/Moellerodiscus musae/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
module PscbIntegration
class BaseApiError
ERROR_CODES = {
timeout: 'timeout error',
connection_failed: 'connection failed error',
}.freeze
attr_reader :error_code
def initialize(error_code)
@error_code = error_code
end
def to_s
ERROR_CODES[error_code]
end
def message
to_s
end
def timeout?
:timeout == error_code
end
def connection_failed?
:connection_failed == error_code
end
def unknown_payment?
false
end
end
end | {'content_hash': '180409b5b398c23bfc4c2324de413d7a', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 51, 'avg_line_length': 15.705882352941176, 'alnum_prop': 0.6048689138576779, 'repo_name': 'holyketzer/pscb_integration', 'id': '239f25483ff39d06a9be75238cb48788db9c2c0f', 'size': '534', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/pscb_integration/base_api_error.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '686'}, {'name': 'HTML', 'bytes': '4883'}, {'name': 'JavaScript', 'bytes': '596'}, {'name': 'Ruby', 'bytes': '38698'}, {'name': 'Shell', 'bytes': '131'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '37f9cb8cbe08d916e83a411a93144753', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '6719a07c09916578ccf295e08c4b66a28366280b', 'size': '200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Petrophytum/Petrophytum caespitosum/Luetkea caespitosa elatior/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
@interface NSProcessInfo (Extensions)
+ (BOOL)osVersionIsAtLeastMajorVersion:(NSInteger)majorVersion
minorVersion:(NSInteger)minorVersion
patchVersion:(NSInteger)patchVersion;
@end | {'content_hash': '842a6dc36373290879739b2ccd887240', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 63, 'avg_line_length': 33.42857142857143, 'alnum_prop': 0.6666666666666666, 'repo_name': 'twg/TWGExtensions', 'id': '0af0444de6c04eb86e8d61df165f1fdb238905b6', 'size': '270', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'Pod/Classes/NSProcessInfo/NSProcessInfo+TWGOsVersionChecker.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '103'}, {'name': 'Objective-C', 'bytes': '277854'}, {'name': 'Ruby', 'bytes': '868'}, {'name': 'Shell', 'bytes': '18036'}, {'name': 'Swift', 'bytes': '5421'}]} |
#include "CodeFoldingArea.h"
CodeFoldingArea::CodeFoldingArea(FileGui* file) : QWidget(file)
{
this->fileGuiPtr = file;
}
void CodeFoldingArea::mousePressEvent(QMouseEvent* e)
{
cout << "Detected mouse press event at CodeFoldingArea::mousePressEvent(...)" << endl;
/*if(codeFoldArea->contentsRect().contains(e->pos()) )
{
cout << "\n\nat FileGui::mousePressEvent(...)\n\n" << endl;
}
else
{
highlightCurrentLine();
}*/
}
QSize CodeFoldingArea::sizeHint() const
{
;//return QSize(file->codeFoldingAreaWidth(), 0);
}
void CodeFoldingArea::paintEvent(QPaintEvent* event)
{
fileGuiPtr->codeFoldingAreaPaintEvent(event);
}
void CodeFoldingArea::setFileGuiPtr(FileGui* file)
{
this->fileGuiPtr = file;
}
FileGui* CodeFoldingArea::getFileGuiPtr() const
{
return fileGuiPtr;
}
QString* CodeFoldingArea::toString()
{
QString* tmp = new QString();
tmp->append("***method stub***");
return tmp;
}
CodeFoldingArea::~CodeFoldingArea()
{
;
} | {'content_hash': 'f6ad04231716f51a2541a60939590165', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 90, 'avg_line_length': 17.258064516129032, 'alnum_prop': 0.6345794392523364, 'repo_name': 'DeepBlue14/rqt_ide', 'id': 'd0cf98c81cabd85eebcf5d8fdec937c98d8721eb', 'size': '1070', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/text_editor/src/CodeFoldingArea.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '13672'}, {'name': 'C++', 'bytes': '1557042'}, {'name': 'CMake', 'bytes': '11201'}, {'name': 'CSS', 'bytes': '6669'}, {'name': 'Makefile', 'bytes': '2645477'}, {'name': 'Python', 'bytes': '1379'}, {'name': 'QMake', 'bytes': '51941'}, {'name': 'Shell', 'bytes': '88679'}]} |
SELECT *
FROM
(SELECT 1 AS 'category', Ek_atte.ekatte, Ek_atte.t_v_m, Ek_atte.name, IFNULL(Ek_kmet.name, Ek_atte.name) AS 'kmetstvo',
Ek_obst.name AS 'obstina', Ek_obl.name AS 'oblast', Ek_reg2.name AS 'region',
Ek_atte.altitude AS 'visochina', Ek_tsb.name AS 'statistika'
FROM Ek_atte
INNER JOIN Ek_obl ON Ek_atte.oblast=Ek_obl.oblast
INNER JOIN Ek_obst ON Ek_atte.obstina=Ek_obst.obstina
INNER JOIN Ek_reg2 ON Ek_obl.region=Ek_reg2.region
INNER JOIN Ek_tsb ON Ek_atte.tsb=Ek_tsb.tsb
LEFT JOIN Ek_kmet ON Ek_atte.kmetstvo = Ek_kmet.kmetstvo) allSettlements
WHERE allSettlements.name =
| {'content_hash': '0135455d3516caac2349a81205520d75', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 124, 'avg_line_length': 50.416666666666664, 'alnum_prop': 0.7272727272727273, 'repo_name': 'Elenchev/HackerSchool', 'id': 'f0a587b5ddd50eaa27cbadc21ca0b1fecc836f75', 'size': '1185', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Projects/EKATTE/060-selectAllSettlements.sql', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '8072'}, {'name': 'CSS', 'bytes': '167'}, {'name': 'HTML', 'bytes': '10489605'}, {'name': 'Java', 'bytes': '30125'}, {'name': 'JavaScript', 'bytes': '29843'}, {'name': 'Makefile', 'bytes': '23545'}, {'name': 'PHP', 'bytes': '180059'}, {'name': 'PLpgSQL', 'bytes': '22165'}, {'name': 'Perl', 'bytes': '2783'}, {'name': 'Python', 'bytes': '2888'}]} |
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
| {'content_hash': '3cd0064e7a046aa29b04c8e39bd0f2ca', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 73, 'avg_line_length': 17.157894736842106, 'alnum_prop': 0.7300613496932515, 'repo_name': 'CosmicInc/HowToDoWudu', 'id': 'db44189e42d21b4e0caee8eb6830055cea9c46ab', 'size': '502', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HowToDoWudu/HowToDoWudu/ViewController.m', 'mode': '33188', 'license': 'mit', 'language': []} |
require 'nokogiri'
# require 'omf-sfa/resource/sliver'
# require 'omf-sfa/resource/node'
# require 'omf-sfa/resource/link'
# require 'omf-sfa/resource/interface'
require 'set'
require 'json'
require 'omf_common/lobject'
require 'omf-sfa/am/am_manager'
module OMF::SFA::AM::Rest
class RackException < Exception
attr_reader :reply
def initialize(err_code, reason)
super reason
body = {:exception => {
:code => err_code,
:reason => reason
}}
@reply = [err_code, { 'Content-Type' => 'text/json', 'Access-Control-Allow-Origin' => '*' , 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS' }, JSON.pretty_generate(body) + "\n"]
end
end
class BadRequestException < RackException
def initialize(reason)
super 400, reason
end
end
class EmptyBodyException < RackException
def initialize()
super 400, "Message body is empty"
end
end
class UnsupportedBodyFormatException < RackException
def initialize(format = 'unknown')
super 400, "Message body format '#{format}' is unsupported"
end
end
class NotAuthorizedException < RackException
def initialize(reason)
super 401, reason
end
end
class IllegalMethodException < RackException
def initialize(reason)
super 403, reason
end
end
class UnsupportedMethodException < RackException
def initialize()
super 403, "Unsupported Method"
end
end
class UnknownResourceException < RackException
def initialize(reason)
super 404, reason
end
end
class MissingResourceException < RackException
def initialize(reason)
super 404, reason
end
end
class RestHandler < OMF::Common::LObject
def initialize(am_manager, opts = {})
#debug "INIT>>> #{am_manager}::#{self}"
@am_manager = am_manager
@opts = opts
@return_struct = { # hash
:code => {
:geni_code => ""
},
:value => '',
:output => ''
}
end
def call(env)
debug "call"
begin
req = ::Rack::Request.new(env)
if req.request_method == 'OPTIONS'
return [200 ,{
'Access-Control-Allow-Origin' => '*' ,
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'origin, x-csrftoken, content-type, accept'
}, ""]
end
content_type, body = dispatch(req)
return [200 ,{ 'Content-Type' => content_type, 'Access-Control-Allow-Origin' => '*' , 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS' }, body]
rescue RackException => rex
debug rex.to_s
# debug rex.backtrace.join("\n")
return rex.reply
rescue OMF::SFA::AM::InsufficientPrivilegesException => iex
debug iex.to_s
# debug iex.backtrace.join("\n")
return RackException.new(401, iex.to_s).reply
rescue OMF::SFA::AM::AMManagerException => mex
debug mex.to_s
# debug mex.backtrace.join("\n")
return RackException.new(400, mex.to_s).reply
rescue ArgumentError => aex
debug aex.to_s
# debug aex.backtrace.join("\n")
return RackException.new(400, aex.to_s).reply
rescue Exception => ex
body = {
:error => {
:reason => ex.to_s,
:bt => ex.backtrace #.select {|l| !l.start_with?('/') }
}
}
warn "ERROR: #{ex}"
debug ex.backtrace.join("\n")
# root = _create_response('error', req = nil)
# doc = root.document
# reason = root.add_child(Nokogiri::XML::Element.new('reason', doc))
# reason.content = ex.to_s
# reason = root.add_child(Nokogiri::XML::Element.new('bt', doc))
# reason.content = ex.backtrace.join("\n\t")
return [500, { "Content-Type" => 'application/json', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS' }, JSON.pretty_generate(body) + "\n"]
end
end
def on_get(resource_uri, opts)
debug 'get: resource_uri: "', resource_uri, '"'
if resource_uri
resource = opts[:resource]
show_resource_status(resource, opts)
else
show_resource_list(opts)
end
end
def on_post(resource_uri, opts)
#debug 'POST: resource_uri "', resource_uri, '" - ', opts.inspect
description, format = parse_body(opts, [:json, :form])
debug 'POST(', resource_uri, '): body(', format, '): "', description, '"'
if resource = opts[:resource]
debug 'POST: Modify ', resource
modify_resource(resource, description, opts)
else
debug 'POST: Create? ', description.class
if description.is_a? Array
resources = description.map do |d|
create_resource(d, opts)
end
return show_resources(resources, nil, opts)
else
debug 'POST: Create ', resource_uri
if resource_uri
if UUID.validate(resource_uri)
description[:uuid] = resource_uri
else
description[:name] = resource_uri
end
end
resource = create_resource(description, opts, resource_uri)
end
end
if resource
show_resource_status(resource, opts)
elsif context = opts[:context]
show_resource_status(context, opts)
else
raise "Report me. Should never get here"
end
end
def on_delete(resource_uri, opts)
if resource = opts[:resource]
if (context = opts[:context])
remove_resource_from_context(resource, context)
res = show_resource_status(resource, opts)
else
debug "Delete resource #{resource}"
res = show_deleted_resource(resource.uuid)
resource.destroy
end
else
# Delete ALL resources of this type
raise OMF::SFA::AM::Rest::BadRequestException.new "I'm sorry, Dave. I'm afraid I can't do that."
end
resource.reload
return res
end
def find_handler(path, opts)
debug "rest handler"
debug "find_handler: path; '#{path}' opts: #{opts}"
resource_id = opts[:resource_uri] = path.shift
opts[:resource] = nil
if resource_id
resource = opts[:resource] = find_resource(resource_id)
end
return self if path.empty? # auto sumvainei stin apli periptwsi
raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown resource '#{resource_id}'." unless resource
opts[:context] = resource
comp = path.shift
if (handler = @coll_handlers[comp.to_sym])
opts[:resource_uri] = path.join('/')
if handler.is_a? Proc
return handler.call(path, opts)
end
return handler.find_handler(path, opts)
end
raise UnknownResourceException.new "Unknown sub collection '#{comp}' for '#{resource_id}:#{resource.class}'."
end
protected
def modify_resource(resource, description, opts)
if description[:uuid]
raise "Can't change uuid" unless description[:uuid] == resource.uuid.to_s
end
description.delete(:href)
resource.update(description) ? resource : nil
#raise UnsupportedMethodException.new
end
def create_resource(description, opts, resource_uri = nil)
debug "Create: #{description.class}--#{description}"
if resource_uri
if UUID.validate(resource_uri)
description[:uuid] = resource_uri
else
description[:name] = resource_uri
end
end
# Let's find if the resource already exists. If yes, just modify it
if uuid = description[:uuid]
debug 'Trying to find resource ', uuid, "'"
resource = @resource_class.first(uuid: uuid)
end
if resource
modify_resource(resource, description, opts)
else
resource = @resource_class.create(description)
debug "Created: #{resource}"
end
if (context = opts[:context])
add_resource_to_context(resource, context)
end
return resource
end
def add_resource_to_context(user, context)
raise UnsupportedMethodException.new
end
def remove_resource_from_context(user, context)
raise UnsupportedMethodException.new
end
# Extract information from the request object and
# store them in +opts+.
#
# Extract information from the request object and
# store them in +opts+.
#
def populate_opts(req, opts)
path = req.path_info.split('/').select { |p| !p.empty? }
opts[:req] = req
if @opts[:semantic] # TODO OPTIMIZE
opts[:format] = 'ttl'
else
opts[:format] = req['format'] || 'json' #json by default
end
debug "populate opts"
opts[:target] = find_handler(path, opts) # gyrnatai o resource_handler
#opts[:target].inspect
opts
end
def parse_body(opts, allowed_formats = [:json, :xml])
req = opts[:req]
body = req.body #req.POST
raise EmptyBodyException.new unless body
if body.is_a? Hash
raise UnsupportedBodyFormatException.new('Send body raw, not as form data')
end
(body = body.string) if body.is_a? StringIO # A node-set is converted to a string by returning the string-value
if body.is_a? Tempfile
tmp = body
body = body.read
tmp.rewind
end
debug 'PARSE_BODY(ct: ', req.content_type, '): ', body.inspect # req.content_type = application/json, body.inspect = "[ { \"name\": \"node1\", \"hostname\": \"node1\", ... "
unless content_type = req.content_type
body.strip! # Removes leading and trailing whitespace from <i>str</i>.
if ['/', '{', '['].include?(body[0])
content_type = 'application/json'
else
if body.empty?
params = req.params.inject({}){|h,(k,v)| h[k.to_sym] = v; h}
if allowed_formats.include?(:json)
return [params, :json]
elsif allowed_formats.include?(:form)
return [params, :form]
end
end
# default is XML
content_type = 'text/xml'
end
end
begin
case content_type
when 'application/json'
raise UnsupportedBodyFormatException.new(:json) unless allowed_formats.include?(:json)
jb = JSON.parse(body) # Parse the JSON document _source_ into an array of hashes and return it
return [_rec_sym_keys(jb), :json]
when 'text/xml'
xb = Nokogiri::XML(body)
raise UnsupportedBodyFormatException.new(:xml) unless allowed_formats.include?(:xml)
return [xb, :xml]
when 'application/x-www-form-urlencoded'
raise UnsupportedBodyFormatException.new(:xml) unless allowed_formats.include?(:form)
fb = req.POST
puts "FORM: #{fb.inspect}"
return [fb, :form]
end
rescue Exception => ex
raise BadRequestException.new "Problems parsing body (#{ex})"
end
raise UnsupportedBodyFormatException.new(content_type)
end
private
# Don't override
def dispatch(req)
debug "dispatch"
opts = {}
populate_opts(req, opts)
#debug "OPTS>>>> #{opts.inspect}"
method = req.request_method # GET
target = opts[:target] #|| self
resource_uri = opts[:resource_uri]
case method
when 'GET'
res = target.on_get(resource_uri, opts)
when 'PUT'
res = target.on_put(resource_uri, opts)
when 'POST'
res = target.on_post(resource_uri, opts)
when 'DELETE'
res = target.on_delete(resource_uri, opts)
else
raise IllegalMethodException.new method
end
end
def show_resource_status(resource, opts)
if resource
about = opts[:req].path
props = resource.to_hash({}, :href_use_class_prefix => true, :max_levels => 1)
props.delete(:type)
res = {
#:about => about,
:type => resource.resource_type,
}.merge!(props)
#res = {"#{resource.resource_type}_response" => res}
else
res = {:error => 'Unknown resource'}
end
['application/json', JSON.pretty_generate(res)]
end
def find_resource(resource_uri, description = {})
descr = description.dup
descr.delete(:resource_uri)
if UUID.validate(resource_uri)
descr[:uuid] = resource_uri
else
descr[:name] = resource_uri
end
if resource_uri.start_with?('urn')
descr[:urn] = resource_uri
end
#authenticator = Thread.current["authenticator"]
debug "Finding #{@resource_class}.first(#{descr})"
@resource_class.first(descr)
end
def show_resources(resources, resource_name, opts)
res_hash = resources.map do |a|
a.to_hash_brief(:href_use_class_prefix => true)
end
if resource_name
prefix = about = opts[:req].path
res = {
#:about => opts[:req].path,
resource_name => res_hash
}
else
res = res_hash
end
['application/json', JSON.pretty_generate(res)]
end
def show_deleted_resource(uuid)
res = {
uuid: uuid,
deleted: true
}
['application/json', JSON.pretty_generate(res)]
end
def show_deleted_resources(uuid_a)
res = {
uuids: uuid_a,
deleted: true
}
['application/json', JSON.pretty_generate(res)]
end
# Recursively Symbolize keys of hash
#
def _rec_sym_keys(array_or_hash)
if array_or_hash.is_a? Array
return array_or_hash.map {|e| e.is_a?(Hash) ? _rec_sym_keys(e) : e }
end
h = {}
array_or_hash.each do |k, v|
if v.is_a? Hash
v = _rec_sym_keys(v)
elsif v.is_a? Array
v = v.map {|e| e.is_a?(Hash) ? _rec_sym_keys(e) : e }
end
h[k.to_sym] = v
end
h
end
end
end
| {'content_hash': '9ac7726b35192d593a928facc55eae3c', 'timestamp': '', 'source': 'github', 'line_count': 474, 'max_line_length': 203, 'avg_line_length': 29.9957805907173, 'alnum_prop': 0.5814460542973695, 'repo_name': 'nikoskal/samant', 'id': '20e72ee11b3836227e4c5870804368267e50ad9e', 'size': '14220', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/omf-sfa/am/am-rest/rest_handler.rb', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8160'}, {'name': 'HTML', 'bytes': '820'}, {'name': 'JavaScript', 'bytes': '2163'}, {'name': 'Ruby', 'bytes': '1091973'}, {'name': 'Web Ontology Language', 'bytes': '267526'}]} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About GDPcoin</source>
<translation>Tietoa GDPcoinista</translation>
</message>
<message>
<location line="+39"/>
<source><b>GDPcoin</b> version</source>
<translation><b>GDPcoin</b> versio</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The GDPcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Tämä on kokeellista ohjelmistoa.
Levitetään MIT/X11 ohjelmistolisenssin alaisuudessa. Tarkemmat tiedot löytyvät tiedostosta COPYING tai osoitteesta http://www.opensource.org/licenses/mit-license.php.
Tämä tuote sisältää OpenSSL-projektin kehittämää ohjelmistoa OpenSSL-työkalupakettia varten (http://www.openssl.org/), Eric Youngin ([email protected]) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP-ohjelmiston.
</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Osoitekirja</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Kaksoisnapauta muokataksesi osoitetta tai nimikettä</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Luo uusi osoite</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopioi valittu osoite järjestelmän leikepöydälle</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Uusi osoite</translation>
</message>
<message>
<location line="-46"/>
<source>These are your GDPcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Nämä ovat GDPcoin-osoitteesi rahansiirtojen vastaanottoa varten. Jos haluat, voit antaa jokaiselle lähettäjälle oman osoitteen jotta voit pitää kirjaa sinulle rahaa siirtäneistä henkilöistä.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Kopioi osoite</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Näytä &QR-koodi</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a GDPcoin address</source>
<translation>Allekirjoita viesti osoittaaksesi GDPcoin-osoitteesi omistajuus</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Allekirjoita &Viesti</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Poista valittu osoite listalta</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified GDPcoin address</source>
<translation>Vahvista viesti varmistaaksesi että kyseinen GDPcoin-osoitteesi on allekirjoittanut sen</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Varmista viesti</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Poista</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Kopioi &nimi</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Muokkaa</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Vie osoitekirjasta tietoja</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Pilkuilla eroteltu tiedosto (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Virhe vietäessä</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ei voida kirjoittaa tiedostoon %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Nimi</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ei nimeä)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Tunnuslauseen Dialogi</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Syötä tunnuslause</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Uusi tunnuslause</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Toista uusi tunnuslause uudelleen</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Sallii estettäväksi yksinkertaiset rahansiirrot kun käyttöjärjestelmän käyttäjätunnuksen turvallisuutta on rikottu. Tämä ei takaa oikeasti turvallisuutta.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Vain osakkuutta varten</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Anna lompakolle uusi tunnuslause.<br/>Käytä tunnuslausetta, jossa on ainakin <b>10 satunnaista merkkiä</b> tai <b>kahdeksan sanaa</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Salaa lompakko</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause sen avaamiseksi.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Avaa lompakko lukituksestaan</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Pura lompakon salaus</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Vaihda tunnuslause</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Anna vanha ja uusi tunnuslause.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Vahvista lompakon salaus</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Varoitus: Jos salaat lompakkosi ja hukkaat salasanasi, <b>MENETÄT KAIKKI KOLIKKOSI</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Haluatko varmasti salata lompakkosi?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>TÄRKEÄÄ: Kaikki vanhat lompakon varmuuskopiot tulisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat käyttökelvottomiksi, kun aloitat uuden salatun lompakon käytön.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Varoitus: Caps Lock-näppäin on käytössä!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Lompakko salattu</translation>
</message>
<message>
<location line="-58"/>
<source>GDPcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>GDPcoin-ohjelma sulkee itsensä päättääkseen salauksen luonnin. Muista, että lompakon salaaminen ei täysin turvaa kolikoitasi haittaohjelmien aiheuttamien varkauksien uhalta.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Lompakon salaus epäonnistui</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoasi ei salattu.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Annetut tunnuslauseet eivät täsmää.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Lompakon avaaminen epäonnistui.</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Annettu tunnuslause oli väärä.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Lompakon salauksen purku epäonnistui.</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Lompakon tunnuslause vaihdettiin onnistuneesti.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Allekirjoita &viesti...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Synkronoidaan verkon kanssa...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Yleisnäkymä</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Lompakon tilanteen yleiskatsaus</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Rahansiirrot</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Selaa rahansiirtohistoriaa</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>%Osoitekirja</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Muokkaa tallennettujen osoitteiden ja nimien listaa</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Vastaanota kolikoita</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Näytä osoitelista vastaanottaaksesi maksuja</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&Lähetä kolikoita</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>L&opeta</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sulje ohjelma</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about GDPcoin</source>
<translation>Näytä tietoja GDPcoinista</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Tietoja &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Näytä tietoja Qt:sta</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Asetukset...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Salaa lompakko...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Varmuuskopioi lompakko...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Vaihda tunnuslause...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n lohko jäljellä</numerusform><numerusform>~%n lohkoa jäljellä</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Ladattu %1 lohkoa %2 lohkosta rahansiirtohistoriassa (%3% ladattu).</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>Vie...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a GDPcoin address</source>
<translation>Lähetä kolikkoja GDPcoin osoitteeseen</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for GDPcoin</source>
<translation>Mukauta GDPcoinin konfigurointiasetuksia</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Vie data tämänhetkisestä välilehdestä tiedostoon</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Salaa tai pura salaus lompakosta</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Varmuuskopioi lompakko toiseen sijaintiin</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Testausikkuna</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Avaa debuggaus- ja diagnostiikkakonsoli</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Vahvista viesti...</translation>
</message>
<message>
<location line="-202"/>
<source>GDPcoin</source>
<translation>GDPcoin</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Lompakko</translation>
</message>
<message>
<location line="+180"/>
<source>&About GDPcoin</source>
<translation>&Tietoa GDPcoinista</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Näytä / Piilota</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>Avaa Lompakko</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Lukitse Lompakko</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Lukitse lompakko</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Tiedosto</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Asetukset</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Apua</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Välilehtipalkki</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Toimintopalkki</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>GDPcoin client</source>
<translation>GDPcoin-asiakas</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to GDPcoin network</source>
<translation><numerusform>%n aktiivinen yhteys GDPcoin-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä GDPcoin-verkkoon</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Ladattu %1 lohkoa rahansiirtohistoriasta.</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Osakkaana.<br>Osuutesi on %1<br>Verkon osuus on %2<br>Odotettu aika palkkion ansaitsemiselle on %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Ei osakkaana koska lompakko on lukittu</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Ei osakkaana koska lompakko on offline-tilassa</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Ei osakkaana koska lompakko synkronoituu</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Ei osakkaana koska sinulle ei ole erääntynyt kolikoita</translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n sekunti sitten</numerusform><numerusform>%n sekuntia sitten</numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About GDPcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about GDPcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>&Aukaise lompakko</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n minuutti sitten</numerusform><numerusform>%n minuuttia sitten</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n tunti sitten</numerusform><numerusform>%n tuntia sitten</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n päivä sitten</numerusform><numerusform>%n päivää sitten</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Rahansiirtohistoria on ajan tasalla</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Saavutetaan verkkoa...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Viimeinen vastaanotettu lohko generoitu %1.</translation>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Tämä rahansiirto ylittää siirtorajan. Voit silti lähettää sen %1 rahansiirtopalkkiota vastaan, joka siirretään rahansiirtoasi käsitteleville solmuille jotta se auttaisi ja tukisi verkkoa. Haluatko maksaa rahansiirtopalkkion?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Hyväksy rahansiirtopalkkio</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Lähetetyt rahansiirrot</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Saapuva rahansiirto</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Päivä: %1
Määrä: %2
Tyyppi: %3
Osoite: %4</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI-merkkijonojen käsittely</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid GDPcoin address or malformed URI parameters.</source>
<translation>URI-merkkijonoa ei voida jäsentää! Tämä voi johtua väärästä GDPcoin-osoitteesta tai väärässä muodossa olevista URI-parametreistä.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lompakko on <b>salattu</b> ja tällä hetkellä <b>avoinna</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lompakko on <b>salattu</b> ja tällä hetkellä <b>lukittuna</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Varmuuskopioi lompakkosi</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lompakkodata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Varmuuskopion luonti epäonnistui</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Virhe tallentaessa lompakkotiedostoa uuteen sijaintiinsa.</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n sekunti</numerusform><numerusform>%n sekuntia</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minuutti</numerusform><numerusform>%n minuuttia</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n tunti</numerusform><numerusform>%n tuntia</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n päivä</numerusform><numerusform>%n päivää</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>Ei osakkaana</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. GDPcoin can no longer continue safely and will quit.</source>
<translation>Vakava virhe kohdattu. GDPcoin-ohjelma ei voi enää jatkaa turvallisesti ja sulkee itsensä.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Verkkohälytys</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Rahan hallinta</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Tavua:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioriteetti:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Kulu:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Heikko ulosanti:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>ei</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Kulujen jälkeen:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Vaihdos:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(tai ei)Valitse kaikki</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Puunäkymä</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Listanäkymä</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Nimike</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Päivämäärä</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Vahvistukset</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Vahvistettu</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioriteetti</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Kopioi osoite</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopioi nimi</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopioi siirtotunnus</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopioi kulu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopioi kulun jälkeen</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopioi tavuja</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopioi prioriteetti</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopioi heikko ulosanti</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopioi vaihdos</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>korkein</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>korkea</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>keskikorkea</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>keski</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>keskimatala</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>matala</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>matalin</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>pölyä</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>kyllä</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Tämä nimike muuttuu punaiseksi, jos rahansiirron koko on suurempi kuin 10000 tavua.
Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan.
Voi vaihdella välillä +/- 1 Tavu per syöte.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Suuremman prioriteetin rahansiirrot pääsevät suuremmalla todennäköisyydellä lohkoketjuun.
Tämä nimike muuttuu punaiseksi, jos prioriteetti on pienempi kuin "keskikokoinen".
Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Tämä nimike muuttuu punaiseksi, jos jokin asiakas saa pienemmän määrän kuin %1.
Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan.
Määrät alle 0.546 kertaa pienimmän rahansiirtokulun verran näytetään pölynä.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Tämä nimike muuttuu punaiseksi, jos vaihdos on pienempi kuin %1.
Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan.</translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(ei nimeä)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>vaihdos %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(vaihdos)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Muokkaa osoitetta</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Nimi</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Tämän syötteen nimike osoitekirjassa</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Osoite</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Tämän syötteen nimike osoitekirjassa. Nimikettä voidaan muuttaa vain lähetysosoitteille.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Uusi vastaanottava osoite</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Uusi lähettävä osoite</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Muokkaa vastaanottajan osoitetta</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Muokkaa lähtevää osoitetta</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Osoite "%1" on jo osoitekirjassa.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid GDPcoin address.</source>
<translation>Syöttämäsi osoite "%1" ei ole hyväksytty GDPcoin-osoite.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Lompakkoa ei voitu avata.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Uuden avaimen luonti epäonnistui.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>GDPcoin-Qt</source>
<translation>GDPcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versio</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Kulutus:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komentokehotteen asetukset</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Käyttäjärajapinnan asetukset</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Aseta kieli, esimerkiksi "fi_FI" (oletus: järjestelmän oma)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Käynnistä pienennettynä</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Näytä logo käynnistettäessä (oletus: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Asetukset</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Yleiset</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Vapaavalintainen rahansiirtopalkkio kilotavua kohden auttaa varmistamaan että rahansiirtosi käsitellään nopeasti. Suurin osa rahansiirroista on alle yhden kilotavun. Palkkiota 0.01 suositellaan.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Maksa rahansiirtopalkkio</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Varattu määrä ei vaadi osakkuutta jonka vuoksi se on mahdollista käyttää milloin tahansa.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Varattuna</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start GDPcoin after logging in to the system.</source>
<translation>Käynnistä GDPcoin-asiakasohjelma automaattisesti kun olet kirjautunut järjestelmään.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start GDPcoin on system login</source>
<translation>%Käynnistä GDPcoin-asiakasohjelma kirjautuessasi</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Irroita lohko- ja osoitetietokannat lopetettaessa. Tämä tarkoittaa, että tietokannat voidaan siirtää eri hakemistoon mutta se hidastaa ohjelman sammumista. Lompakko on aina irroitettuna.</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>%Irroita tietokannat lopetettaessa</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Verkko</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the GDPcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Avaa GDPcoin-asiakkaalle automaattisesti portti reitittimestä. Tämä toimii vain, kun reitittimesi tukee UPnP:tä ja se on aktivoituna.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portin uudelleenohjaus &UPnP:llä</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the GDPcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Yhdistä GDPcoin-verkkoon SOCKS-välityspalvelimen lävitse. (esim. yhdistettäessä Tor:n läpi).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>%Yhdistä SOCKS-välityspalvelimen läpi:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxyn &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Välityspalvelimen IP-osoite (esim. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Portti</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyn Portti (esim. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versio:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Proxyn SOCKS-versio (esim. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ikkuna</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Näytä ainoastaan ilmaisinalueella ikkunan pienentämisen jälkeen.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Pienennä ilmaisinalueelle työkalurivin sijasta</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ikkunaa suljettaessa vain pienentää Bitcoin-ohjelman ikkunan lopettamatta itse ohjelmaa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>P&ienennä suljettaessa</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Käyttöliittymä</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Käyttöliittymän kieli</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting GDPcoin.</source>
<translation>Käyttöliittymän kieli voidaan valita tästä. Tämä asetus tulee voimaan vasta GDPcoin-asiakasohjelman uudelleenkäynnistyksen jälkeen.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Yksikkö jona bitcoin-määrät näytetään</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Valitse mitä yksikköä käytetään ensisijaisesti bitcoin-määrien näyttämiseen.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show GDPcoin addresses in the transaction list or not.</source>
<translation>Näytä tai piilota GDPcoin-osoitteet rahansiirtolistassa.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Näytä osoitteet rahansiirrot listassa</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Näytä tai piilota rahanhallintaominaisuudet.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Näytä rahan&hallinnan ominaisuudet (vain kokeneille käyttäjille!)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Peruuta</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>%Käytä</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>oletus</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Varoitus</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting GDPcoin.</source>
<translation>Tämä asetus tulee voimaan vasta GDPcoin-asiakasohjelman uudelleenkäynnistyksen jälkeen.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Antamasi proxy-osoite on virheellinen.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Lomake</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the GDPcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Näytettävät tiedot voivat olla vanhentuneet. Lompakkosi synkronoituu automaattisesti GDPcoin-verkon kanssa kun yhteys on muodostettu, mutta tätä prosessia ei ole viety vielä päätökseen.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>Vaihdos:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Hyväksymätöntä:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Lompakko</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Käytettävissä:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Käytettävissä olevat varat:</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Epäkypsää:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Louhittu saldo, joka ei ole vielä kypsynyt</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Yhteensä:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Tililläsi tällä hetkellä olevien Bitcoinien määrä</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Viimeisimmät rahansiirrot</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Kaikki vahvistamattomat rahansiirrot yhteensä, joita ei vielä lasketa saldoosi.</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Kolikoiden kokoinaismäärä, jotka eivät vielä ole laskettu tämänhetkiseen saldoon.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>Ei ajan tasalla</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR-koodidialogi</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Pyydä rahansiirtoa</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Nimike:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Viesti:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>%Tallenna nimellä...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Virhe koodatessa linkkiä QR-koodiin.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Syötetty määrä on epäkelpoinen; tarkista.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Tuloksena liian pitkä URI, yritä lyhentää nimikkeen tai viestin pituutta.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Tallenna QR-koodi</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG-kuvat (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Pääteohjelman nimi</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Ei saatavilla</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Pääteohjelman versio</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>T&ietoa</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Käytössä oleva OpenSSL-versio</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Käynnistysaika</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Verkko</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Yhteyksien lukumäärä</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testiverkossa</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Lohkoketju</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nykyinen Lohkojen määrä</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Arvioitu lohkojen kokonaismäärä</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Viimeisimmän lohkon aika</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Avaa</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komentokehotteen ominaisuudet</translation>
</message>
<message>
<location line="+7"/>
<source>Show the GDPcoin-Qt help message to get a list with possible GDPcoin command-line options.</source>
<translation>Näytä GDPcoin-Qt:n avustusohje saadaksesi listan käytettävistä GDPcoinin komentokehotteen määritteistä.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>%Näytä</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoli</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kääntöpäiväys</translation>
</message>
<message>
<location line="-104"/>
<source>GDPcoin - Debug window</source>
<translation>GDPcoin - Debug-ikkuna</translation>
</message>
<message>
<location line="+25"/>
<source>GDPcoin Core</source>
<translation>GDPcoinin ydin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug lokitiedosto</translation>
</message>
<message>
<location line="+7"/>
<source>Open the GDPcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Avaa GDPcoin-asiakasohjelman debug-lokitiedosto nykyisestä hakemistostaan. Tämä voi kestää muutaman sekunnin avattaessa suuria lokitiedostoja.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tyhjennä konsoli</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the GDPcoin RPC console.</source>
<translation>Tervetuloa GDPcoinin RPC-konsoliin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Ylös- ja alas-nuolet selaavat historiaa ja <b>Ctrl-L</b> tyhjentää ruudun.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Kirjoita <b>help</b> nähdäksesi yleiskatsauksen käytettävissä olevista komennoista.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Lähetä Bitcoineja</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Kolikoidenhallinnan ominaisuudet</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Syötteet...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automaattisesti valittu</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Ei tarpeeksi varoja!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Tavua:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BTC</source>
<translation>123.456 BTC {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioriteetti:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>keskikokoinen</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Kulu:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Heikko ulosanti:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>ei</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Kulujen jälkeen:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Vaihtoraha</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>erikseen määritetty vaihtorahaosoite</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Lähetä monelle vastaanottajalle</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Lisää &Vastaanottaja</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Tyhjennä kaikki rahansiirtokentät</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Tyhjennnä Kaikki</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Vahvista lähetys</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Lähetä</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a GDPcoin address (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Syötä GDPcoin-osoite (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopioi rahansiirtokulu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopioi rahansiirtokulun jälkeen</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopioi tavuja</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopioi prioriteetti</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopioi heikko ulosanti</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopioi vaihtoraha</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b>:sta %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Hyväksy Bitcoinien lähettäminen</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Oletko varma että haluat lähettää %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>ja</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Vastaanottajan osoite on virheellinen. Tarkista osoite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Maksettavan summan tulee olla suurempi kuin 0 Bitcoinia.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Määrä ylittää käytettävissä olevan saldon.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kokonaismäärä ylittää saldosi kun %1 maksukulu lisätään summaan.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Sama osoite toistuu useamman kerran. Samaan osoitteeseen voi lähettää vain kerran per maksu.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Virhe: Rahansiirron luonti epäonnistui.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Virhe: Rahansiirto evätty. Tämä voi tapahtua kun jotkut kolikot lompakossasi ovat jo käytetty, kuten myös tilanteessa jos käytit wallet.dat-tiedoston kopiota ja rahat olivat käytetty kopiossa, mutta eivät ole merkitty käytetyiksi tässä.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid GDPcoin address</source>
<translation>VAROITUS: Epäkelpo GDPcoin-osoite</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(ei nimeä)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>VAROITUS: Tuntematon vaihtorahaosoite</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Kaavake</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>M&äärä:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Maksun saaja:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Anna nimi tälle osoitteelle, jos haluat lisätä sen osoitekirjaan</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Nimi:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Osoite, johon maksu lähetetään (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Valitse osoite osoitekirjasta</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Liitä osoite leikepöydältä</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Poista tämä vastaanottaja</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a GDPcoin address (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Syötä GDPcoin-osoite (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Allekirjoitukset - Allekirjoita / Varmista viesti</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Allekirjoita viesti</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, ettet allekirjoita mitään epämääräistä, sillä phishing-hyökkääjät voivat yrittää huijata sinua allekirjoittamaan henkilöllisyytesi heidän hyväksi. Allekirjoita vain se, mihin olet sitoutunut.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Osoite, jolle viesti kirjataan (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Valitse osoite osoitekirjasta</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Liitä osoite leikepöydältä</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Kirjoita viesti, jonka haluat allekirjoittaa tähän</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopioi tämänhetkinen allekirjoitus järjestelmän leikepöydälle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this GDPcoin address</source>
<translation>Allekirjoita viesti vahvistaaksesi, että omistat tämän GDPcoin-osoitteen</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tyhjennä kaikki allekirjoita-viesti-kentät</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Tyhjennä Kaikki</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Varmista viesti</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Syötä allekirjoittava osoite, viesti ja allekirjoitus alla oleviin kenttiin varmistaaksesi allekirjoituksen aitouden. Varmista että kopioit kaikki kentät täsmälleen oikein, myös rivinvaihdot, välilyönnit, tabulaattorit, jne.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Osoite, jolla viesti on allekirjoitettu (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2) </translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified GDPcoin address</source>
<translation>Vahvista viesti varmistaaksesi että se on allekirjoitettu kyseisellä GDPcoin-osoitteella</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tyhjennä kaikki varmista-viesti-kentät</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a GDPcoin address (e.g. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Syötä GDPcoin-osoite (esim. GDPcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikkaa "Allekirjoita Viesti luodaksesi allekirjoituksen </translation>
</message>
<message>
<location line="+3"/>
<source>Enter GDPcoin signature</source>
<translation>Syötä GDPcoin-allekirjoitus</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Syötetty osoite on virheellinen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Tarkista osoite ja yritä uudelleen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Syötetyn osoitteen avainta ei löydy.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Lompakon avaaminen peruttiin.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Yksityistä avainta syötetylle osoitteelle ei ole saatavilla.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Viestin allekirjoitus epäonnistui.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Viesti allekirjoitettu.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Allekirjoitusta ei pystytty tulkitsemaan.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Tarkista allekirjoitus ja yritä uudelleen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Allekirjoitus ei täsmää viestin tiivisteeseen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Viestin varmistus epäonnistui.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Viesti varmistettu.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Avoinna %1 asti</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Avoinna %n:lle lohkolle</numerusform><numerusform>Avoinna %n lohkolle</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>törmännyt</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/vahvistamaton</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 vahvistusta</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Tila</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>lähetetty %n noodin läpi</numerusform><numerusform>lähetetty %n noodin läpi</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Päivämäärä</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Lähde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generoitu</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Lähettäjä</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Saaja</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>oma osoite</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>nimi</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>kypsyy %n lohkon kuluttua</numerusform><numerusform>kypsyy %n lohkon kuluttua</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ei hyväksytty</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Maksukulu</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto määrä</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Viesti</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Viesti</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Siirtotunnus</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Luotujen kolikoiden on eräännyttävä 510 lohkon ajan ennenkuin niitä voidaan käyttää. Kun loit tämän lohkon, se oli lähetetty verkkoon lohkoketjuun lisättäväksi. Jos lohkon siirtyminen ketjuun epäonnistuu, tilaksi muuttuu "ei hyväksytty" ja sillon sitä ei voida käyttää. Tämä voi tapahtua joskus jos toinen verkon noodi luo lohkon muutaman sekunnin sisällä luodusta lohkostasi.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug tiedot</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Rahansiirto</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Sisääntulot</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>tosi</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>epätosi</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ei ole vielä onnistuneesti lähetetty</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>tuntematon</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Rahansiirron yksityiskohdat</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Tämä ruutu näyttää yksityiskohtaisen tiedon rahansiirrosta</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Päivämäärä</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Laatu</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Avoinna %1 asti</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Vahvistettu (%1 vahvistusta)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Avoinna %n lohkolle</numerusform><numerusform>Avoinna %n lohkolle</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Offline-tila</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Vahvistamaton</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Vahvistetaan (%1 %2:sta suositellusta vahvistuksesta)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Törmännyt</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Ei vahvistettu (%1 vahvistusta, on saatavilla %2:n jälkeen)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generoitu mutta ei hyväksytty</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Vastaanotettu osoitteella</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Vastaanotettu</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Saaja</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Maksu itsellesi</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Louhittu</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(ei saatavilla)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Rahansiirron laatu.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Rahansiirron kohteen Bitcoin-osoite</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Saldoon lisätty tai siitä vähennetty määrä.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Kaikki</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Tänään</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Tällä viikolla</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Tässä kuussa</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Viime kuussa</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Tänä vuonna</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Alue...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Vastaanotettu osoitteella</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Saaja</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Itsellesi</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Louhittu</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Muu</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Anna etsittävä osoite tai tunniste</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimimäärä</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopioi osoite</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopioi nimi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopioi rahansiirron ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Muokkaa nimeä</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Näytä rahansiirron yksityiskohdat</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Vie tiedot rahansiirrosta</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Vahvistettu</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Aika</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Laatu</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Nimi</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Virhe vietäessä</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ei voida kirjoittaa tiedostoon %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Alue:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>kenelle</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Lähetetään...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>GDPcoin version</source>
<translation>GDPcoinin versio</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Käyttö:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or GDPcoind</source>
<translation>Syötä komento kohteeseen -server tai GDPcoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lista komennoista</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Hanki apua käskyyn</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Asetukset:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: GDPcoin.conf)</source>
<translation>Määritä asetustiedosto (oletus: GDPcoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: GDPcoind.pid)</source>
<translation>Määritä prosessitiedosto (oletus: GDPcoin.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Määritä lompakkotiedosto (datahakemiston sisällä)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Määritä data-hakemisto</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Aseta tietokannan lokien maksimikoko megatavuissa (oletus: 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Kuuntele yhteyksiä portissa <port> (oletus: 15714 tai testiverkko: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Pidä enintään <n> yhteyttä verkkoihin (oletus: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Yhdistä noodiin hakeaksesi naapurien osoitteet ja katkaise yhteys</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Määritä julkinen osoitteesi</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Liitä annettuun osoitteeseen. Käytä [host]:port merkintää IPv6:lle</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>Panosta rahasi tukeaksi verkkoa ja saadaksesi palkkiota (oletus: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekuntien määrä, kuinka kauan uudelleenkytkeydytään verkkoihin (oletus: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Virhe valmisteltaessa RPC-portin %u avaamista kuunneltavaksi: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Irroita lohko- ja osoitetietokannat lopetuksessa. Nostaa ohjelman lopetusaikaa (oletus: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Virhe: Rahansiirto on evätty. Tämä voi tapahtua jos joitakin kolikoistasi lompakossasi on jo käytetty, tai jos olet käyttänyt wallet.dat-tiedoston kopiota ja rahat olivat käytetyt kopiossa, mutta ei merkitty käytetyksi tässä.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Virhe: Tämä rahansiirto tarvitsee rahansiirtopalkkion, kooltaan %s, kokonsa, monimutkaisuutensa tai aikaisemmin saatujen varojen käytön takia.</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Kuuntele JSON-RPC-yhteyksiä portissa <port> (oletus: 15715 tai testiverkko: 25715)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Virhe: Rahansiirron luonti epäonnistui</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Virhe: Lompakko lukittu, rahansiirtoa ei voida luoda</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Tuodaan lohkoketjun datatiedostoa.</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Tuodaan esilatausohjelma lohkoketjun datatiedostolle.</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Aja taustalla daemonina ja hyväksy komennot</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Käytä test -verkkoa</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Hyväksy yhteyksiä ulkopuolelta (vakioasetus: 1 jos -proxy tai -connect ei määritelty)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Virhe ilmennyt asetettaessa RPC-porttia %u IPv6:n kuuntelemiseksi, palataan takaisin IPv4:ään %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Virhe alustettaessa tietokantaympäristöä %s! Palauttaaksesi sen, TEE VARMUUSKOPIO HAKEMISTOSTA ja poista tämän jälkeen kaikki hakemiston tiedostot paitsi wallet.dat-tiedosto.</translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Aseta maksimikoko korkean prioriteetin/pienen siirtokulun maksutapahtumille tavuina (oletus: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Varoitus: -paytxfee on asetettu erittäin korkeaksi! Tämä on maksukulu jonka tulet maksamaan kun lähetät siirron.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong GDPcoin will not work properly.</source>
<translation>Varoitus: Tarkista, että tietokoneesi aika ja päivämäärä ovat oikeassa! Jos kellosi on väärässä, GDPcoin ei toimi oikein.</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Varoitus: Virhe luettaessa wallet.dat-tiedostoa! Kaikki avaimet luettiin oikein, mutta rahansiirtodata tai osoitekirjan kentät voivat olla puuttuvat tai väärät.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Varoitus: wallet.dat-tiedosto on korruptoitunut, data pelastettu! Alkuperäinen wallet.dat on tallennettu nimellä wallet.{aikaleima}.bak kohteeseen %s; Jos saldosi tai rahansiirrot ovat väärät, sinun tulee palauttaa lompakko varmuuskopiosta.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Yritetään palauttaa yksityisiä salausavaimia korruptoituneesta wallet.dat-tiedostosta</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Lohkon luonnin asetukset:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Yhidstä ainoastaan määrättyihin noodeihin</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Hae oma IP osoite (vakioasetus: 1 kun kuuntelemassa ja ei -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ei onnistuttu kuuntelemaan missään portissa. Käytä -listen=0 jos haluat tätä.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Etsi vertaisiasi käyttäen DNS-nimihakua (oletus: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Synkronoi tallennuspisteiden käytännöt (oletus: strict)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Epäkelpo -tor-osoite: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Epäkelpo määrä -reservebalance=<amount></translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, <n>*1000 tavua (vakioasetus: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, <n>*1000 tavua (vakioasetus: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Yhdistä vain noodeihin verkossa <net> (IPv4, IPv6 tai Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Tulosta lisäksi debug-tietoa, seuraa kaikkia muita -debug*-asetuksia</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Tulosta lisäksi verkon debug-tietoa</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Lisää debug-tulosteiden alkuun aikaleimat</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL asetukset (katso Bitcoin Wikistä tarkemmat SSL ohjeet)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Valitse SOCKS-välityspalvelimen versio (4-5, oletus 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Lähetä debug-tuloste kehittäjille</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Aseta lohkon maksimikoko tavuissa (oletus: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Asetan pienin lohkon koko tavuissa (vakioasetus: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Pienennä debug.log tiedosto käynnistyksen yhteydessä (vakioasetus: 1 kun ei -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>Ei voitu kirjata tallennuspistettä, väärä checkpointkey?
</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 1 kun kuuntelemassa)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Käytä välityspalvelinta saavuttaaksesi tor:n piilotetut palvelut (oletus: sama kuin -proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Tarkistetaan tietokannan eheyttä...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>VAROITUS: synkronoidun tallennuspisteen rikkomista havaittu, mutta ohitettu!</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Varoitus: Kiintolevytila on vähissä!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat on korruptoitunut, pelastusyritys epäonnistui</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Salasana JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=GDPcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "GDPcoin Alert" [email protected]
</source>
<translation>%s, sinun on asetettava rpcpassword asetustiedostoon:
%s
On suositeltavaa, että käytät seuraavaa arvottua salasanaa:
rpcuser=GDPcoinrpc
rpcpassword=%s
(Sinun ei tarvitse muistaa tätä salasanaa)
Käyttäjänimen ja salasanan EI TULE OLLA SAMOJA.
Jos tiedostoa ei ole olemassa, luo se asettaen samalla omistajan lukuoikeudet.
On myös suositeltavaa asettaa alertnotify jolloin olet tiedotettu ongelmista; esimerkiksi: alertnotify=echo %%s | mail -s "GDPcoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Etsi vertaisiasi käyttäen Internet Relay Chatia (oletus: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synkronoi kello muiden noodien kanssa. Poista käytöstä, jos järjestelmäsi aika on tarkka esim. päivittää itsensä NTP-palvelimelta. (oletus: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Rahansiirtoja luodessa jätä huomioimatta syötteet joiden arvo on vähemmän kuin tämä (oletus: 0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Lähetä käskyjä solmuun osoitteessa <ip> (oletus: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Suorita komento kun lompakon rahansiirrossa muutoksia (%s komennossa on korvattu TxID:llä)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Vaadi vaihtorahalle vahvistus (oletus: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>Vahvista, että rahansiirtoskriptit käyttävät sääntöjen mukaisia PUSH-toimijoita (oletus: 1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Suorita komento kun olennainen varoitus on saatu (%s komennossa korvattu viestillä)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Päivitä lompakko uusimpaan formaattiin</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Aseta avainpoolin koko arvoon <n> (oletus: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Kuinka monta lohkoa tarkistetaan käynnistyksen yhteydessä (oletus: 2500, 0 = kaikki)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Kuinka perusteellisesti lohko vahvistetaan (0-6, oletus: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Tuo lohkoja erillisestä blk000?.dat-tiedostosta</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Palvelimen sertifikaatti-tiedosto (oletus: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Palvelimen yksityisavain (oletus: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Hyväksytyt salaustyypit (oletus: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Virhe: Lompakko avattu vain osakkuutta varten, rahansiirtoja ei voida luoda.</translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>VAROITUS: Epäkelpo tarkistuspiste löydetty! Ilmoitetut rahansiirrot eivät välttämättä pidä paikkaansa! Sinun täytyy päivittää asiakasohjelma, tai ilmoittaa kehittäjille ongelmasta.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Tämä ohjeviesti</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Lompakko %s on datahakemiston %s ulkopuolella.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. GDPcoin is probably already running.</source>
<translation>Ei voida saavuttaa lukkoa datatiedostossa %s. GDPcoin-asiakasohjelma on ehkä jo käynnissä.</translation>
</message>
<message>
<location line="-98"/>
<source>GDPcoin</source>
<translation>GDPcoin</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kytkeytyminen %s tällä tietokonella ei onnistu (kytkeytyminen palautti virheen %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Yhdistä SOCKS-välityspalvelimen lävitse</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Ladataan osoitteita...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Virhe ladattaessa blkindex.dat-tiedostoa</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of GDPcoin</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko tarvitsee uudemman version GDPcoin-asiakasohjelmasta</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart GDPcoin to complete</source>
<translation>Lompakko on kirjoitettava uudelleen: käynnistä GDPcoin-asiakasohjelma uudelleen päättääksesi toiminnon</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Virheellinen proxy-osoite '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Tuntematon verkko -onlynet parametrina: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Tuntematon -socks proxy versio pyydetty: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind osoitteen '%s' selvittäminen epäonnistui</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip osoitteen '%s' selvittäminen epäonnistui</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<amount>: '%s' on virheellinen</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Virhe: Ei voitu käynnistää noodia</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Lähetetään...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Virheellinen määrä</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Lompakon saldo ei riitä</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Ladataan lohkoindeksiä...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. GDPcoin is probably already running.</source>
<translation>Ei voitu liittää %s tällä tietokoneella. GDPcoin-asiakasohjelma on jo ehkä päällä.</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Rahansiirtopalkkio kilotavua kohden lähetettäviin rahansiirtoihisi</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Epäkelpo määrä parametrille -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Ladataan lompakkoa...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Ei voida alustaa avainallasta</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Oletusosoitetta ei voi kirjoittaa</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Skannataan uudelleen...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Lataus on valmis</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Käytä %s optiota</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Virhe</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Sinun täytyy asettaa rpcpassword=<password> asetustiedostoon:
%s
Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation>
</message>
</context>
</TS> | {'content_hash': '42c8cfae464990cd068bd32b7b95fa60', 'timestamp': '', 'source': 'github', 'line_count': 3320, 'max_line_length': 421, 'avg_line_length': 39.06506024096385, 'alnum_prop': 0.6366657414261041, 'repo_name': 'GDPX11/GDPcoin', 'id': '8fc2726fa568c20e228c28d64c0393bcdc9ccb23', 'size': '130742', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/bitcoin_fi.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '51312'}, {'name': 'C', 'bytes': '777840'}, {'name': 'C++', 'bytes': '2548199'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'IDL', 'bytes': '15553'}, {'name': 'Objective-C++', 'bytes': '3537'}, {'name': 'Python', 'bytes': '2819'}, {'name': 'Shell', 'bytes': '1026'}, {'name': 'TypeScript', 'bytes': '7746744'}]} |
/*
File Generated by NetTiers templates [www.nettiers.com]
Important: Do not modify this file. Edit the file Nettiers.AdventureWorks.Entities.WorkOrder.cs instead.
*/
#region Using directives
using System;
using System.Data;
using System.Collections;
using System.Diagnostics;
using System.Web.Services.Protocols;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data.Bases;
#endregion
namespace Nettiers.AdventureWorks.Data.WebServiceClient
{
///<summary>
/// This class is the webservice client implementation that exposes CRUD methods for Nettiers.AdventureWorks.Entities.WorkOrder objects.
///</summary>
public abstract partial class WsWorkOrderProviderBase : WorkOrderProviderBase
{
#region Declarations
/// <summary>
/// the Url of the webservice.
/// </summary>
private string url;
#endregion Declarations
#region Constructors
/// <summary>
/// Creates a new <see cref="WsWorkOrderProviderBase"/> instance.
/// Uses connection string to connect to datasource.
/// </summary>
public WsWorkOrderProviderBase()
{
}
/// <summary>
/// Creates a new <see cref="WsWorkOrderProviderBase"/> instance.
/// Uses connection string to connect to datasource.
/// </summary>
/// <param name="url">The url to the nettiers webservice.</param>
public WsWorkOrderProviderBase(string url)
{
this.Url = url;
}
#endregion Constructors
#region Url
///<summary>
/// Current URL for webservice endpoint.
///</summary>
public string Url
{
get {return url;}
set {url = value;}
}
#endregion
#region Convertion utility
/// <summary>
/// Convert a collection from the ws proxy to a nettiers collection.
/// </summary>
public static Nettiers.AdventureWorks.Entities.TList<WorkOrder> Convert(WsProxy.WorkOrder[] items)
{
Nettiers.AdventureWorks.Entities.TList<WorkOrder> outItems = new Nettiers.AdventureWorks.Entities.TList<WorkOrder>();
foreach(WsProxy.WorkOrder item in items)
{
outItems.Add(Convert(item));
}
return outItems;
}
/// <summary>
/// Convert a nettiers collection to the ws proxy collection.
/// </summary>
public static Nettiers.AdventureWorks.Entities.WorkOrder Convert(WsProxy.WorkOrder item)
{
Nettiers.AdventureWorks.Entities.WorkOrder outItem = item == null ? null : new Nettiers.AdventureWorks.Entities.WorkOrder();
Convert(outItem, item);
return outItem;
}
/// <summary>
/// Convert a nettiers collection to the ws proxy collection.
/// </summary>
public static Nettiers.AdventureWorks.Entities.WorkOrder Convert(Nettiers.AdventureWorks.Entities.WorkOrder outItem , WsProxy.WorkOrder item)
{
if (item != null && outItem != null)
{
outItem.WorkOrderId = item.WorkOrderId;
outItem.ProductId = item.ProductId;
outItem.OrderQty = item.OrderQty;
outItem.StockedQty = item.StockedQty;
outItem.ScrappedQty = item.ScrappedQty;
outItem.StartDate = item.StartDate;
outItem.EndDate = item.EndDate;
outItem.DueDate = item.DueDate;
outItem.ScrapReasonId = item.ScrapReasonId;
outItem.ModifiedDate = item.ModifiedDate;
outItem.AcceptChanges();
}
return outItem;
}
/// <summary>
/// Convert a nettiers entity to the ws proxy entity.
/// </summary>
public static WsProxy.WorkOrder Convert(Nettiers.AdventureWorks.Entities.WorkOrder item)
{
WsProxy.WorkOrder outItem = new WsProxy.WorkOrder();
outItem.WorkOrderId = item.WorkOrderId;
outItem.ProductId = item.ProductId;
outItem.OrderQty = item.OrderQty;
outItem.StockedQty = item.StockedQty;
outItem.ScrappedQty = item.ScrappedQty;
outItem.StartDate = item.StartDate;
outItem.EndDate = item.EndDate;
outItem.DueDate = item.DueDate;
outItem.ScrapReasonId = item.ScrapReasonId;
outItem.ModifiedDate = item.ModifiedDate;
return outItem;
}
/// <summary>
/// Convert a collection from to a nettiers collection to a the ws proxy collection.
/// </summary>
public static WsProxy.WorkOrder[] Convert(Nettiers.AdventureWorks.Entities.TList<WorkOrder> items)
{
WsProxy.WorkOrder[] outItems = new WsProxy.WorkOrder[items.Count];
int count = 0;
foreach (Nettiers.AdventureWorks.Entities.WorkOrder item in items)
{
outItems[count++] = Convert(item);
}
return outItems;
}
#endregion
#region Get from Many To Many Relationship Functions
#endregion
#region Delete Methods
/// <summary>
/// Deletes a row from the DataSource.
/// </summary>
/// <param name="_workOrderId">Primary key for WorkOrder records.. Primary Key.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <remarks>Deletes based on primary key(s).</remarks>
/// <returns>Returns true if operation suceeded.</returns>
public override bool Delete(TransactionManager transactionManager, System.Int32 _workOrderId)
{
try
{
// call the proxy
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
bool result = proxy.WorkOrderProvider_Delete(_workOrderId);
return result;
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion Delete Methods
#region Find Methods
/// <summary>
/// Returns rows meeting the whereclause condition from the DataSource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pagelen">Number of rows to return.</param>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="count">Number of rows in the DataSource.</param>
/// <remarks>Operators must be capitalized (OR, AND)</remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.WorkOrder objects.</returns>
public override Nettiers.AdventureWorks.Entities.TList<WorkOrder> Find(TransactionManager transactionManager, string whereClause, int start, int pagelen, out int count)
{
try
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder[] items = proxy.WorkOrderProvider_Find(whereClause, start, pagelen, out count);
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion Find Methods
#region GetAll Methods
/// <summary>
/// Gets All rows from the DataSource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out parameter to get total records for query</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.WorkOrder objects.</returns>
public override Nettiers.AdventureWorks.Entities.TList<WorkOrder> GetAll(TransactionManager transactionManager, int start, int pageLength, out int count)
{
try
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder[] items = proxy.WorkOrderProvider_GetAll(start, pageLength, out count);
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion GetAll Methods
#region GetPaged Methods
/// <summary>
/// Gets a page of rows from the DataSource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.WorkOrder objects.</returns>
public override Nettiers.AdventureWorks.Entities.TList<WorkOrder> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count)
{
try
{
whereClause = whereClause ?? string.Empty;
orderBy = orderBy ?? string.Empty;
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder[] items = proxy.WorkOrderProvider_GetPaged(whereClause, orderBy, start, pageLength, out count);
// Create a collection and fill it with the dataset
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion GetPaged Methods
#region Get By Foreign Key Functions
#endregion
#region Get By Index Functions
/// <summary>
/// Gets rows from the datasource based on the IX_WorkOrder_ProductID index.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="count">out parameter to get total records for query</param>
/// <remarks></remarks>
/// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TList<WorkOrder>"/> class.</returns>
public override Nettiers.AdventureWorks.Entities.TList<WorkOrder> GetByProductId(TransactionManager transactionManager, System.Int32 _productId, int start, int pageLength, out int count)
{
try
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder[] items = proxy.WorkOrderProvider_GetByProductId(_productId, start, pageLength, out count);
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
/// <summary>
/// Gets rows from the datasource based on the IX_WorkOrder_ScrapReasonID index.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="_scrapReasonId">Reason for inspection failure.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="count">out parameter to get total records for query</param>
/// <remarks></remarks>
/// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TList<WorkOrder>"/> class.</returns>
public override Nettiers.AdventureWorks.Entities.TList<WorkOrder> GetByScrapReasonId(TransactionManager transactionManager, System.Int16? _scrapReasonId, int start, int pageLength, out int count)
{
try
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder[] items = proxy.WorkOrderProvider_GetByScrapReasonId(_scrapReasonId, start, pageLength, out count);
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
/// <summary>
/// Gets rows from the datasource based on the PK_WorkOrder_WorkOrderID index.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="_workOrderId">Primary key for WorkOrder records.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="count">out parameter to get total records for query</param>
/// <remarks></remarks>
/// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.WorkOrder"/> class.</returns>
public override Nettiers.AdventureWorks.Entities.WorkOrder GetByWorkOrderId(TransactionManager transactionManager, System.Int32 _workOrderId, int start, int pageLength, out int count)
{
try
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
WsProxy.WorkOrder items = proxy.WorkOrderProvider_GetByWorkOrderId(_workOrderId, start, pageLength, out count);
return Convert(items);
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion Get By Index Functions
#region Insert Methods
/// <summary>
/// Inserts a Nettiers.AdventureWorks.Entities.WorkOrder object into the datasource using a transaction.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="entity">Nettiers.AdventureWorks.Entities.WorkOrder object to insert.</param>
/// <remarks></remarks>
/// <returns>Returns true if operation is successful.</returns>
public override bool Insert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.WorkOrder entity)
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
try
{
WsProxy.WorkOrder result = proxy.WorkOrderProvider_Insert(Convert(entity));
Convert(entity, result);
return true;
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
/// <summary>
/// Lets you efficiently bulk many entity to the database.
/// </summary>
/// <param name="transactionManager">NOTE: The transaction manager should be null for the web service client implementation.</param>
/// <param name="entityList">The entities.</param>
/// <remarks>
/// After inserting into the datasource, the Nettiers.AdventureWorks.Entities.WorkOrder object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
public override void BulkInsert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TList<WorkOrder> entityList)
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
try
{
proxy.WorkOrderProvider_BulkInsert(Convert(entityList));
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion Insert Methods
#region Update Methods
/// <summary>
/// Update an existing row in the datasource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="entity">Nettiers.AdventureWorks.Entities.WorkOrder object to update.</param>
/// <remarks></remarks>
/// <returns>Returns true if operation is successful.</returns>
public override bool Update(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.WorkOrder entity)
{
WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices();
proxy.Url = Url;
try
{
WsProxy.WorkOrder result = proxy.WorkOrderProvider_Update(Convert(entity));
Convert(entity, result);
entity.AcceptChanges();
return true;
}
catch(SoapException soex)
{
System.Diagnostics.Debug.WriteLine(soex);
throw soex;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw ex;
}
}
#endregion Update Methods
#region Custom Methods
#endregion
}//end class
} // end namespace
| {'content_hash': '1f250f669ec469f8b2d01da74b15ad30', 'timestamp': '', 'source': 'github', 'line_count': 526, 'max_line_length': 197, 'avg_line_length': 33.460076045627375, 'alnum_prop': 0.678409090909091, 'repo_name': 'Giten2004/netTiers', 'id': 'b5eeb322176f2f46cd28b1ab80c974e0395613e4', 'size': '17602', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data.WebServiceClient/WsWorkOrderProviderBase.generated.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '620'}, {'name': 'C#', 'bytes': '331739'}, {'name': 'CSS', 'bytes': '9299'}, {'name': 'JavaScript', 'bytes': '18312'}, {'name': 'XSLT', 'bytes': '25193'}]} |
A non-empty zero-indexed array `A` consisting of N integers is given. `A` pair of integers `(P, Q)`, such that `0 ≤ P < Q < N`, is called a slice of array `A` (notice that the slice contains at least two elements). The average of a slice `(P, Q)` is the sum of `A[P] + A[P + 1] + ... + A[Q]` divided by the length of the slice. To be precise, the average equals `(A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1)`.
For example, array `A` such that:
```c
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
```
contains the following example slices:
- slice `(1, 2)`, whose average is `(2 + 2) / 2 = 2`;
- slice `(3, 4)`, whose average is `(5 + 1) / 2 = 3`;
- slice `(1, 4)`, whose average is `(2 + 2 + 5 + 1) / 4 = 2.5`.
The goal is to find the starting position of a slice whose average is minimal.
Write a function:
```c
int solution(std::vector<int> &A);
```
that, given a non-empty zero-indexed array `A` consisting of `N` integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
For example, given array A such that:
```c
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
```
the function should return `1`, as explained above.
Assume that:
- `N` is an integer within the range [2..100,000];
- each element of array `A` is an integer within the range [−10,000..10,000].
Complexity:
- expected worst-case time complexity is **O(N)**;
- expected worst-case space complexity is **O(N)**, beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
[Link to Codility](https://codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/)
| {'content_hash': '66f9dc09e07e46c78fc96c1d32658728', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 409, 'avg_line_length': 35.96078431372549, 'alnum_prop': 0.6330425299890948, 'repo_name': 'zhelybalov/codility', 'id': 'cc5cf178a1715fb5f39792024ca24b82700c24d7', 'size': '1840', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Lesson 5 - Prefix Sums/MinAvgTwoSlice.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '13764'}, {'name': 'Python', 'bytes': '8362'}]} |
<?php
while ( have_posts() ) : the_post();
$id = get_the_id();
$header_text = get_post_header_text($id);
$header_image = get_header_image_url($id);
$sc = get_shares($id);
?>
<meta name="shares-count" content="<?=$sc;?>">
<meta name="post-id" content="<?=$id;?>">
<meta name="description" content="<?=$header_text;?>">
<meta property="og:title" content="<?=get_the_title();?>" />
<meta property="og:site_name" content="<?php bloginfo('name'); ?>"/>
<meta property="og:url" content="<?=get_permalink($id);?>" />
<meta property="og:description" content="<?=$header_text;?>" />
<meta property="og:image" content="<?=$header_image;?>" />
<meta property="image" content="<?=$header_image;?>" />
<meta name="post-id" content="<?=get_the_id();?>">
<?php
endwhile;
?>
| {'content_hash': 'acd6441a718eb1117c8c006f86cf7383', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 72, 'avg_line_length': 40.75, 'alnum_prop': 0.5717791411042945, 'repo_name': 'SashaSansay/nanabe-wp', 'id': '135c00ae54bb8c7cb954bd795fb7f8672d663d6b', 'size': '815', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wp-content/themes/naba/inc/meta.single.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '304805'}, {'name': 'JavaScript', 'bytes': '265226'}, {'name': 'PHP', 'bytes': '216602'}]} |
package metadata
import (
"io"
"os"
"time"
"github.com/containerd/stargz-snapshotter/estargz"
digest "github.com/opencontainers/go-digest"
)
// Attr reprensents the attributes of a node.
type Attr struct {
// Size, for regular files, is the logical size of the file.
Size int64
// ModTime is the modification time of the node.
ModTime time.Time
// LinkName, for symlinks, is the link target.
LinkName string
// Mode is the permission and mode bits.
Mode os.FileMode
// UID is the user ID of the owner.
UID int
// GID is the group ID of the owner.
GID int
// DevMajor is the major device number for device.
DevMajor int
// DevMinor is the major device number for device.
DevMinor int
// Xattrs are the extended attribute for the node.
Xattrs map[string][]byte
// NumLink is the number of names pointing to this node.
NumLink int
}
// Store reads the provided eStargz blob and creates a metadata reader.
type Store func(sr *io.SectionReader, opts ...Option) (Reader, error)
// Reader provides access to file metadata of a blob.
type Reader interface {
RootID() uint32
TOCDigest() digest.Digest
GetOffset(id uint32) (offset int64, err error)
GetAttr(id uint32) (attr Attr, err error)
GetChild(pid uint32, base string) (id uint32, attr Attr, err error)
ForeachChild(id uint32, f func(name string, id uint32, mode os.FileMode) bool) error
OpenFile(id uint32) (File, error)
Clone(sr *io.SectionReader) (Reader, error)
Close() error
}
type File interface {
ChunkEntryForOffset(offset int64) (off int64, size int64, dgst string, ok bool)
ReadAt(p []byte, off int64) (n int, err error)
}
type Decompressor interface {
estargz.Decompressor
// DecompressTOC decompresses the passed blob and returns a reader of TOC JSON.
DecompressTOC(io.Reader) (tocJSON io.ReadCloser, err error)
}
type Options struct {
TOCOffset int64
Telemetry *Telemetry
Decompressors []Decompressor
}
// Option is an option to configure the behaviour of reader.
type Option func(o *Options) error
// WithTOCOffset option specifies the offset of TOC
func WithTOCOffset(tocOffset int64) Option {
return func(o *Options) error {
o.TOCOffset = tocOffset
return nil
}
}
// WithTelemetry option specifies the telemetry hooks
func WithTelemetry(telemetry *Telemetry) Option {
return func(o *Options) error {
o.Telemetry = telemetry
return nil
}
}
// WithDecompressors option specifies decompressors to use.
// Default is gzip-based decompressor.
func WithDecompressors(decompressors ...Decompressor) Option {
return func(o *Options) error {
o.Decompressors = decompressors
return nil
}
}
// A func which takes start time and records the diff
type MeasureLatencyHook func(time.Time)
// A struct which defines telemetry hooks. By implementing these hooks you should be able to record
// the latency metrics of the respective steps of estargz open operation.
type Telemetry struct {
GetFooterLatency MeasureLatencyHook // measure time to get stargz footer (in milliseconds)
GetTocLatency MeasureLatencyHook // measure time to GET TOC JSON (in milliseconds)
DeserializeTocLatency MeasureLatencyHook // measure time to deserialize TOC JSON (in milliseconds)
}
| {'content_hash': 'bb1ce20a9bfe3989bfd83dcc45df8e1d', 'timestamp': '', 'source': 'github', 'line_count': 120, 'max_line_length': 99, 'avg_line_length': 26.841666666666665, 'alnum_prop': 0.7494566904687985, 'repo_name': 'tonistiigi/buildkit_poc', 'id': '1774d0818d6af0b11116237104b906f0fd649bc9', 'size': '3815', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/containerd/stargz-snapshotter/metadata/metadata.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '98756'}, {'name': 'Makefile', 'bytes': '928'}, {'name': 'Protocol Buffer', 'bytes': '2995'}, {'name': 'Shell', 'bytes': '2032'}]} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE xliff PUBLIC "-//XLIFF//DTD XLIFF//EN" "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd" >
<xliff version="1.0">
<file original="global" source-language="en" datatype="plaintext">
<header />
<body>
<!-- Actions -->
<trans-unit>
<source>New</source>
<target>新規作成</target>
</trans-unit>
<trans-unit>
<source>Edit</source>
<target>編集</target>
</trans-unit>
<trans-unit>
<source>Delete</source>
<target>削除</target>
</trans-unit>
<trans-unit>
<source>List</source>
<target>一覧</target>
</trans-unit>
<trans-unit>
<source>Save</source>
<target>保存</target>
</trans-unit>
<trans-unit>
<source>Save and add</source>
<target>保存して更に追加</target>
</trans-unit>
<trans-unit>
<source>Cancel</source>
<target>キャンセル</target>
</trans-unit>
<trans-unit>
<source>Choose an action</source>
<target>アクションを選択</target>
</trans-unit>
<trans-unit>
<source>go</source>
<target>実行</target>
</trans-unit>
<trans-unit>
<source>Back to list</source>
<target>リストに戻る</target>
</trans-unit>
<!-- Filters -->
<trans-unit>
<source>Reset</source>
<target>リセット</target>
</trans-unit>
<trans-unit>
<source>Filter</source>
<target>検索</target>
</trans-unit>
<!-- List -->
<trans-unit>
<source>No result</source>
<target>データがありません</target>
</trans-unit>
<trans-unit>
<source>Actions</source>
<target>操作</target>
</trans-unit>
<trans-unit>
<source>(page %%page%%/%%nb_pages%%)</source>
<target>(ページ %%page%%/%%nb_pages%%)</target>
</trans-unit>
<trans-unit>
<source>asc</source>
<target>降順</target>
</trans-unit>
<trans-unit>
<source>desc</source>
<target>昇順</target>
</trans-unit>
<trans-unit>
<source>[0] no result|[1] 1 result|(1,+Inf] %1% results</source>
<target>[0] 0件|[1] 1件|(1,+Inf] %1% 件</target>
</trans-unit>
<!-- Pagination -->
<trans-unit>
<source>First page</source>
<target>最初のページ</target>
</trans-unit>
<trans-unit>
<source>Previous page</source>
<target>前のページ</target>
</trans-unit>
<trans-unit>
<source>Next page</source>
<target>次のページ</target>
</trans-unit>
<trans-unit>
<source>Last page</source>
<target>最後のページ</target>
</trans-unit>
<!-- Form -->
<trans-unit>
<source>The item was created successfully.</source>
<target>アイテムを作成しました</target>
</trans-unit>
<trans-unit>
<source>The item was updated successfully.</source>
<target>アイテムを更新しました</target>
</trans-unit>
<trans-unit>
<source>The item was created successfully. You can add another one below.</source>
<target>アイテムを作成しました。以下で別のアイテムを追加できます。</target>
</trans-unit>
<trans-unit>
<source>The item was updated successfully. You can add another one below.</source>
<target>アイテムを更新しました。以下で別のアイテムを追加できます。</target>
</trans-unit>
<trans-unit>
<source>The item has not been saved due to some errors.</source>
<target>エラーのためアイテムを保存できませんでした</target>
</trans-unit>
<trans-unit>
<source>The item was deleted successfully.</source>
<target>アイテムを削除しました</target>
</trans-unit>
<trans-unit>
<source>You must at least select one item.</source>
<target>最低でも1つを選択してください。</target>
</trans-unit>
<trans-unit>
<source>You must select an action to execute on the selected items.</source>
<target>選択されたアイテムを処理するためにアクションを選択してください。</target>
</trans-unit>
<trans-unit>
<source>A problem occurs when deleting the selected items as some items do not exist anymore.</source>
<target>すでに存在しないアイテムを削除しようとしてエラーが発生しました。</target>
</trans-unit>
<trans-unit>
<source>The selected items have been deleted successfully.</source>
<target>選択されたアイテムを削除しました。</target>
</trans-unit>
<trans-unit>
<source>A problem occurs when deleting the selected items.</source>
<target>選択されたアイテムを削除するときにエラーが発生しました。</target>
</trans-unit>
<trans-unit>
<source>is empty</source>
<target>空の値も含む</target>
</trans-unit>
<trans-unit>
<source>yes or no</source>
<target>全て</target>
</trans-unit>
<trans-unit>
<source>yes</source>
<target>はい</target>
</trans-unit>
<trans-unit>
<source>no</source>
<target>いいえ</target>
</trans-unit>
<trans-unit>
<source><![CDATA[from %from_date% to %to_date%]]></source>
<target><![CDATA[%from_date% から %to_date%]]></target>
</trans-unit>
<trans-unit>
<source><![CDATA[from %from_date%<br />to %to_date%]]></source>
<target><![CDATA[%from_date% から<br /> %to_date%]]></target>
</trans-unit>
<!-- Form Error Messages -->
<trans-unit>
<source>Required.</source>
<target>必須項目です。</target>
</trans-unit>
<trans-unit>
<source>Invalid.</source>
<target>無効な値です。</target>
</trans-unit>
<trans-unit>
<source>"%value%" is not an integer.</source>
<target>"%value%" は数値でありません。</target>
</trans-unit>
<trans-unit>
<source>"%value%" is not an number.</source>
<target>"%value%" は数字でありません。</target>
</trans-unit>
<trans-unit>
<source>At least %min% values must be selected (%count% values selected).</source>
<target>%min% 個以上選択してください(現在 %count% が選択されています)。</target>
</trans-unit>
<trans-unit>
<source>At most %max% values must be selected (%count% values selected).</source>
<target>%min% 個以内で選択してください(現在 %count% が選択されています)。</target>
</trans-unit>
<trans-unit>
<source>CSRF attack detected.</source>
<target>画面遷移が確認できませんでした</target>
</trans-unit>
<trans-unit>
<source>"%value%" does not match the date format (%date_format%).</source>
<target>"%value%" が日付のフォーマット (%date_format%)に一致しません</target>
</trans-unit>
<trans-unit>
<source>The date must be before %max%.</source>
<target>日付は %max% より前を指定してください</target>
</trans-unit>
<trans-unit>
<source>The date must be after %min%.</source>
<target>日付は %min% より後を指定してください</target>
</trans-unit>
<trans-unit>
<source>The begin date must be before the end date.</source>
<target>開始日は終了日より前でなければなりません。</target>
</trans-unit>
<trans-unit>
<source>File is too large (maximum is %max_size% bytes).</source>
<target>ファイルのサイズが大きすぎます(アップロードできるファイルサイズは%max_size%バイトです)。</target>
</trans-unit>
<trans-unit>
<source>Invalid mime type (%mime_type%).</source>
<target>無効なmimeタイプです(%mime_type%)。</target>
</trans-unit>
<trans-unit>
<source>The uploaded file was only partially uploaded.</source>
<target>アップロードされたファイルは不十分な状態でアップロードされました。</target>
</trans-unit>
<trans-unit>
<source>Missing a temporary folder.</source>
<target>テンポラリフォルダーがありません。</target>
</trans-unit>
<trans-unit>
<source>Failed to write file to disk.</source>
<target>ディスクへのファイル書き込みに失敗しました。</target>
</trans-unit>
<trans-unit>
<source>File upload stopped by extension.</source>
<target>ファイルの拡張子の制限でアップロードは中止しました。</target>
</trans-unit>
<trans-unit>
<source>Unexpected extra form field named "%field%".</source>
<target>"%field%" という不明のフィールドがあります</target>
</trans-unit>
<trans-unit>
<source>"%value%" is too long (%max_length% characters max).</source>
<target>入力文字数がオーバーしています (%max_length%文字以下)</target>
</trans-unit>
<trans-unit>
<source>"%value%" is too short (%min_length% characters min).</source>
<target>入力文字数が不足しています (%min_length%文字以上)</target>
</trans-unit>
<trans-unit>
<source>"%value%" does not match the time format (%time_format%).</source>
<target>"%value%"が時刻のフォーマット (%time_format%)に一致しません</target>
</trans-unit>
<trans-unit>
<source>"%value%" must be at most %max%.</source>
<target>"%value%" は %max% より小さくなければなりません。</target>
</trans-unit>
<trans-unit>
<source>"%value%" must be at least %min.</source>
<target>"%value%" %min% より大きくなければなりません。</target>
</trans-unit>
<trans-unit>
<source>The date must be before %max%.</source>
<target>日付は %max% より前の日付でなければなりません。</target>
</trans-unit>
<trans-unit>
<source>The date must be after %min%.</source>
<target>日付は %mix% より後の日付でなければなりません。</target>
</trans-unit>
<trans-unit>
<source>The form submission cannot be processed. It probably means that you have uploaded a file that is too big.</source>
<target>フォームの処理ができませんでした。アップロードしたファイルのサイズが大きすぎるのかもしれません。</target>
</trans-unit>
<!-- Old -->
<trans-unit>
<source>"%value%" must be less than %max%.</source>
<target>"%value%" は %max% より小さい値を指定してください</target>
</trans-unit>
<trans-unit>
<source>"%value%" must be greater than %min%.</source>
<target>"%value%" は %min% より大きい値を指定してください</target>
</trans-unit>
<trans-unit>
<source>An object with the same "%column%" already exist.</source>
<target>既に登録されています</target>
</trans-unit>
</body>
</file>
</xliff>
| {'content_hash': 'ff60b0ac16ec7b226dea2891fccce565', 'timestamp': '', 'source': 'github', 'line_count': 294, 'max_line_length': 130, 'avg_line_length': 34.925170068027214, 'alnum_prop': 0.5574600701207635, 'repo_name': 'kamguir/salleSport', 'id': '09be94fa505625c1f20b9fc7d1d9a722219ce332', 'size': '12032', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/sfPropelORMPlugin/i18n/sf_admin.ja.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '215628'}, {'name': 'JavaScript', 'bytes': '29491'}, {'name': 'PHP', 'bytes': '5027363'}, {'name': 'Shell', 'bytes': '614'}]} |
<?php
declare(strict_types=1);
namespace Cake\I18n;
use Aura\Intl\FormatterInterface;
use Aura\Intl\Package;
use Aura\Intl\TranslatorFactory as BaseTranslatorFactory;
use Aura\Intl\TranslatorInterface;
use RuntimeException;
/**
* Factory to create translators
*
* @internal
*/
class TranslatorFactory extends BaseTranslatorFactory
{
/**
* The class to use for new instances.
*
* @var string
*/
protected $class = Translator::class;
/**
* Returns a new Translator.
*
* @param string $locale The locale code for the translator.
* @param \Aura\Intl\Package $package The Package containing keys and translations.
* @param \Aura\Intl\FormatterInterface $formatter The formatter to use for interpolating token values.
* @param \Aura\Intl\TranslatorInterface $fallback A fallback translator to use, if any.
* @throws \Cake\Core\Exception\Exception If fallback class does not match Cake\I18n\Translator
* @return \Cake\I18n\Translator
*/
public function newInstance(
$locale,
Package $package,
FormatterInterface $formatter,
?TranslatorInterface $fallback = null
) {
$class = $this->class;
if ($fallback !== null && get_class($fallback) !== $class) {
throw new RuntimeException(sprintf(
'Translator fallback class %s does not match Cake\I18n\Translator, try clearing your _cake_core_ cache',
get_class($fallback)
));
}
/** @var \Cake\I18n\Translator */
return new $class($locale, $package, $formatter, $fallback);
}
}
| {'content_hash': '8c9348b9bb14a4a2c2efbc0484604202', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 120, 'avg_line_length': 30.314814814814813, 'alnum_prop': 0.6530238240684179, 'repo_name': 'dakota/cakephp', 'id': 'a2072d1122c2bd8cb8aeacaca69b5f63929281ad', 'size': '2223', 'binary': False, 'copies': '1', 'ref': 'refs/heads/4.x', 'path': 'src/I18n/TranslatorFactory.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15730'}, {'name': 'HTML', 'bytes': '405'}, {'name': 'Hack', 'bytes': '752'}, {'name': 'JavaScript', 'bytes': '171'}, {'name': 'Makefile', 'bytes': '6407'}, {'name': 'PHP', 'bytes': '10180619'}, {'name': 'Shell', 'bytes': '723'}]} |
package com.alanrodas.scaland.cli
import com.alanrodas.scaland._
import com.alanrodas.scaland.cli.definitions.{ArgumentDefinition, FlagDefinition}
import org.scalatest._
import language.postfixOps
class BuildersSpec extends FlatSpec with Matchers with BeforeAndAfter {
val emptyString = ""
val foo = "foo"
val bar = "bar"
val baz = "baz"
val f = "f"
val b = "b"
val g = "g"
val shortSign = "-"
val longSign = "--"
val shortSignAlt = "/"
val longSignAlt = "/"
implicit var commandManager = new CommandManager()
before {
commandManager.setSigns(shortSign, longSign)
}
after {
commandManager = new CommandManager()
}
/* ********* Values ************ */
"A ValueDefinition as mandatory" should "form nicely if a valid name is given" in {
cli.value named foo mandatory
}
it should "form nicely if a name with spaces is given" in {
cli.value named s"$foo $bar $baz" mandatory
}
it should "throw an IllegalArgumentException if no name is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.value named emptyString mandatory
}
}
it should "not contain a default value" in {
(cli.value named foo mandatory).default should be (None)
}
"A ValueDefinition with default value" should "form nicely if a valid name is given" in {
cli.value named foo as "something"
}
it should "form nicely if a name with spaces is given" in {
cli.value named s"$foo $bar" as "something"
}
it should "throw an IllegalArgumentException if no name is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.value named emptyString as "something"
}
}
it should "take any value as default value" in {
cli.value named s"$foo $bar $baz" as ""
cli.value named s"$foo $bar" as 4
cli.value named s"$foo $baz $bar" as Seq(1,2,3,4)
cli.value named s"$bar $bar" as Some(("four", 4))
}
it should "retrieve the same value as passed when queried" in {
(cli.value named s"$foo $bar $baz" as "").default.get should be ("")
(cli.value named s"$foo $bar" as 4).default.get should be (4)
(cli.value named s"$foo $baz $bar" as Seq(1,2,3,4)).default.get should be (Seq(1,2,3,4))
(cli.value named s"$bar $bar" as Some(("four", 4))).default.get should be (Some(("four", 4)))
}
/* ********* Flags ************ */
"A FlagDefinition" should "form nicely if a valid name is given" in {
cli.flag named bar : FlagDefinition
}
it should "throw an IllegalArgumentException if no name is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named emptyString : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the passed name has spaces" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$bar $baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s" $baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$foo " : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$shortSign$foo" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$longSign$foo" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$shortSign$b" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$longSign$f" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named shortSign : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named longSign : FlagDefinition
}
commandManager.setSigns(shortSignAlt, longSignAlt)
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$shortSignAlt$baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$longSignAlt$foo" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$shortSignAlt$g" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named s"$longSignAlt$f" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named shortSignAlt : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named longSignAlt : FlagDefinition
}
}
it should "form nicely if the name has short or long sign in the middle or end" in {
cli.flag named s"$bar$shortSign$baz" : FlagDefinition
cli.flag named s"$foo$longSign$baz" : FlagDefinition
cli.flag named s"$baz$shortSign" : FlagDefinition
cli.flag named s"$bar$longSign" : FlagDefinition
cli.flag named s"$g$shortSign" : FlagDefinition
cli.flag named s"$b$longSign" : FlagDefinition
cli.flag named shortSignAlt : FlagDefinition
cli.flag named longSignAlt : FlagDefinition
commandManager.setSigns(shortSignAlt, longSignAlt)
cli.flag named s"$bar$shortSignAlt$baz" : FlagDefinition
cli.flag named s"$foo$longSignAlt$baz" : FlagDefinition
cli.flag named s"$baz$shortSignAlt" : FlagDefinition
cli.flag named s"$bar$longSignAlt" : FlagDefinition
cli.flag named s"$g$shortSignAlt" : FlagDefinition
cli.flag named s"$f$longSignAlt" : FlagDefinition
cli.flag named shortSign : FlagDefinition
cli.flag named longSign : FlagDefinition
}
it should "form nicely if a valid name and alias are given" in {
cli.flag named foo alias g : FlagDefinition
cli.flag named b alias bar : FlagDefinition
}
it should "throw an IllegalArgumentException if the alias is empty" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named baz alias emptyString : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the alias has spaces" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named f alias s"$foo $bar" : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the name and alias are both larger than one character" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named baz alias bar : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the name and alias are both of one character" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named b alias f : FlagDefinition
}
}
it should "throw an IllegalArgumentException if the alias starts with the short or long sign of the CommandManager" in {
an [IllegalArgumentException] should be thrownBy {
cli.flag named f alias s"$shortSign$baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named f alias s"$longSign$baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named foo alias s"$shortSign$b" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named bar alias s"$longSign$f" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named foo alias shortSign : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named bar alias longSign : FlagDefinition
}
commandManager.setSigns(shortSignAlt, longSignAlt)
an [IllegalArgumentException] should be thrownBy {
cli.flag named f alias s"$shortSignAlt$baz" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named b alias s"$longSignAlt$bar" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named bar alias s"$shortSignAlt$f" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named baz alias s"$longSignAlt$b" : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named foo alias shortSignAlt : FlagDefinition
}
an [IllegalArgumentException] should be thrownBy {
cli.flag named bar alias longSignAlt : FlagDefinition
}
}
it should "form nicely if the alias has short or long sign in the middle or end" in {
cli.flag named f alias s"$bar$shortSign$baz" : FlagDefinition
cli.flag named g alias s"$bar$longSign$baz" : FlagDefinition
cli.flag named g alias s"$bar$shortSign" : FlagDefinition
cli.flag named b alias s"$bar$longSign" : FlagDefinition
cli.flag named foo alias shortSignAlt : FlagDefinition
cli.flag named bar alias longSignAlt : FlagDefinition
commandManager.setSigns(shortSignAlt, longSignAlt)
cli.flag named g alias s"$bar$shortSignAlt$baz" : FlagDefinition
cli.flag named f alias s"$bar$longSignAlt$baz" : FlagDefinition
cli.flag named f alias s"$foo$shortSignAlt" : FlagDefinition
cli.flag named b alias s"$baz$longSignAlt" : FlagDefinition
cli.flag named foo alias shortSign : FlagDefinition
}
/* ********* Arguments ************ */
"An ArgumentDefinition" should "form nicely if a valid name is given" in {
cli.arg named foo taking 1 value : ArgumentDefinition[_]
}
it should "throw an IllegalArgumentException if no name is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named emptyString taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the passed name has spaces" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$foo $baz" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s" $foo" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$foo " taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$shortSign$foo" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$longSign$foo" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$shortSign$b" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$longSign$f" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named shortSign taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named longSign taking 1 value : ArgumentDefinition[_]
}
commandManager.setSigns(shortSignAlt, longSignAlt)
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$longSignAlt$foo" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$shortSignAlt$g" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named s"$longSignAlt$f" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named shortSignAlt taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named longSignAlt taking 1 value : ArgumentDefinition[_]
}
}
it should "form nicely if the name has short or long sign in the middle or end" in {
cli.arg named s"$bar$shortSign$baz" taking 7 values : ArgumentDefinition[_]
cli.arg named s"$foo$longSign$baz" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$baz$shortSign" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$bar$longSign" taking 4 values : ArgumentDefinition[_]
cli.arg named s"$g$shortSign" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$b$longSign" taking 1 value : ArgumentDefinition[_]
cli.arg named shortSignAlt taking 2 values : ArgumentDefinition[_]
cli.arg named longSignAlt taking 1 value : ArgumentDefinition[_]
commandManager.setSigns(shortSignAlt, longSignAlt)
cli.arg named s"$bar$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$foo$longSignAlt$baz" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$baz$shortSignAlt" taking 5 values : ArgumentDefinition[_]
cli.arg named s"$bar$longSignAlt" taking 1 value : ArgumentDefinition[_]
cli.arg named s"$g$shortSignAlt" taking 2 values : ArgumentDefinition[_]
cli.arg named s"$f$longSignAlt" taking 1 value : ArgumentDefinition[_]
cli.arg named shortSign taking 2 values : ArgumentDefinition[_]
cli.arg named longSign taking 1 value : ArgumentDefinition[_]
}
it should "form nicely if a valid name and alias are given" in {
cli.arg named foo alias g taking 1 value : ArgumentDefinition[_]
cli.arg named b alias baz taking 1 value : ArgumentDefinition[_]
}
it should "throw an IllegalArgumentException if the alias is empty" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz alias emptyString taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the alias has spaces" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named f alias s"$foo $bar" taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the name and alias are both larger than one character" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz alias bar taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the name and alias are both of one character" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named f alias g taking 1 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the alias starts with the short or long sign of the CommandManager" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named f alias s"$shortSign$baz" taking 1 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named f alias s"$longSign$baz" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo alias s"$shortSign$b" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar alias s"$longSign$f" taking 5 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo alias shortSign taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar alias longSign taking 1 value : ArgumentDefinition[_]
}
commandManager.setSigns(shortSignAlt, longSignAlt)
an [IllegalArgumentException] should be thrownBy {
cli.arg named f alias s"$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named b alias s"$longSignAlt$bar" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar alias s"$shortSignAlt$f" taking 2 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz alias s"$longSignAlt$b" taking 1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo alias shortSignAlt taking 4 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar alias longSignAlt taking 1 value : ArgumentDefinition[_]
}
}
it should "form nicely if the alias has short or long sign in the middle or end" in {
cli.arg named f alias s"$bar$shortSign$baz" taking 1 value : ArgumentDefinition[_];
cli.arg named g alias s"$bar$longSign$baz" taking 2 values : ArgumentDefinition[_];
cli.arg named g alias s"$bar$shortSign" taking 1 value : ArgumentDefinition[_];
cli.arg named b alias s"$bar$longSign" taking 1 value : ArgumentDefinition[_];
cli.arg named foo alias shortSignAlt taking 4 values : ArgumentDefinition[_];
cli.arg named bar alias longSignAlt taking 1 value : ArgumentDefinition[_];
commandManager.setSigns(shortSignAlt, longSignAlt)
cli.arg named g alias s"$bar$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_];
cli.arg named f alias s"$bar$longSignAlt$baz" taking 3 values : ArgumentDefinition[_];
cli.arg named f alias s"$foo$shortSignAlt" taking 1 value : ArgumentDefinition[_];
cli.arg named b alias s"$baz$longSignAlt" taking 2 values : ArgumentDefinition[_];
cli.arg named foo alias shortSign taking 1 value : ArgumentDefinition[_]
}
it should "throw an IllegalArgumentException if the number of arguments passed is lower than zero" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo taking -1 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar taking -5 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo taking -1 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar taking -5 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the number of arguments passed is zero" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz taking 0 values : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz taking 0 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if value is called when taking is more than one" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz taking 2 value : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz taking 8 value : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if values is called when taking is one" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named baz taking 1 values : ArgumentDefinition[_]
}
}
it should "throw an IllegalArgumentException if the number of default values is greater than taking" in {
an [IllegalArgumentException] should be thrownBy {
cli.arg named foo taking 3 as (1,2,3,4) : ArgumentDefinition[_]
}
an [IllegalArgumentException] should be thrownBy {
cli.arg named bar taking 1 as ("one", "two") : ArgumentDefinition[_]
}
}
it should "form nicely if a the number of arguments is less or equal than the number taken" in {
cli.arg named foo taking 1 as "one" : ArgumentDefinition[_]
cli.arg named f taking 3 as ("one", "two", "three") : ArgumentDefinition[_]
cli.arg named g taking 5 as (1,2,3,4) : ArgumentDefinition[_]
cli.arg named bar taking 3 as (None, Some("Wiiii")) : ArgumentDefinition[_]
}
it should "return the same value as inputed" in {
(cli.arg named baz taking 1 as "one").argumentValues should be (Array("one"))
(cli.arg named bar taking 3 as ("one", "two", "three")).argumentValues should be (Array("one", "two", "three"))
(cli.arg named f taking 5 as (1,2,3,4)).argumentValues should be (Array(1,2,3,4))
(cli.arg named foo taking 3 as (None, Some("Wiiii"))).argumentValues should be (Array(None, Some("Wiiii")))
}
/* ********* Commands ************ */
"A CommandDefinition" should "form nicely if a valid name is given" in {
// cli.command named foo receives () does {_=>}
cli.root does {_=>}
}
it should "throw an IllegalArgumentException if no name is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named emptyString does {_=>}
}
}
it should "throw an IllegalArgumentException if a name with spaces is passed" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$foo $bar" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s" $baz" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$foo " does {_=>}
}
}
it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$shortSign$foo" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$longSign$foo" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$shortSign$b" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$longSign$f" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named shortSign does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named longSign does {_=>}
}
commandManager.setSigns(shortSignAlt, longSignAlt)
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$shortSignAlt$baz" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$longSignAlt$foo" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$shortSignAlt$g" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named s"$longSignAlt$f" does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named shortSignAlt does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named longSignAlt does {_=>}
}
}
it should "form nicely if the name has short or long sign in the middle or end" in {
cli.command named s"$bar$shortSign$baz" does {_=>}
cli.command named s"$foo$longSign$baz" does {_=>}
cli.command named s"$baz$shortSign" does {_=>}
cli.command named s"$bar$longSign" does {_=>}
cli.command named s"$g$shortSign" does {_=>}
cli.command named s"$b$longSign" does {_=>}
cli.command named shortSignAlt does {_=>}
commandManager.setSigns(shortSignAlt, longSignAlt)
cli.command named s"$bar$shortSignAlt$baz" does {_=>}
cli.command named s"$foo$longSignAlt$baz" does {_=>}
cli.command named s"$baz$shortSignAlt" does {_=>}
cli.command named s"$bar$longSignAlt" does {_=>}
cli.command named s"$g$shortSignAlt" does {_=>}
cli.command named s"$b$longSignAlt" does {_=>}
cli.command named shortSign does {_=>}
cli.command named longSign does {_=>}
}
it should "throw an IllegalArgumentException if two values have the same name" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo receives (
cli.value named bar mandatory,
cli.value named bar mandatory
) does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
root receives(
cli.value named bar mandatory,
cli.value named bar as "barbar"
) does { _ =>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named foo receives (
cli.value named baz as "one",
cli.value named baz as "two"
) does {_=>}
}
}
it should "form nicely if mandatory values are in correct order" in {
cli.command named foo receives (
cli.value named foo mandatory,
cli.value named bar as "bar",
cli.value named baz as "baz"
) does {_=>}
root receives (
cli.value named foo mandatory,
cli.value named bar mandatory,
cli.value named baz as "baz"
) does {_=>}
}
it should "throw an IllegalArgumentException if mandatory values are not in order" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo receives (
cli.value named foo as "foo",
cli.value named bar mandatory,
cli.value named baz mandatory
) does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named foo receives (
cli.value named foo as "foo",
cli.value named bar mandatory,
cli.value named baz as "baz"
) does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
root receives (
cli.value named foo mandatory,
cli.value named bar as "bar",
cli.value named baz mandatory
) does {_=>}
}
}
it should "form nicely if minimum and maximum number of values are positive and maximum is greater than lower" in {
cli.command named foo minimumOf 1 does {_=>}
root maximumOf 7 does {_=>}
cli.command named bar maximumOf 1 does {_=>}
cli.command named baz minimumOf 4 maximumOf 10 does {_=>}
cli.command named f minimumOf 1 maximumOf 7 does {_=>}
}
it should "throw an IllegalArgumentException if minimum number of values is lower than zero" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo minimumOf -1 does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
root minimumOf -5 does {_=>}
}
}
it should "throw an IllegalArgumentException if minimum number of values is zero" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo minimumOf 0 does {_=>}
}
}
it should "throw an IllegalArgumentException if maximum number of values is lower than zero" in {
an [IllegalArgumentException] should be thrownBy {
root maximumOf -1 does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named foo maximumOf -5 does {_=>}
}
}
it should "throw an IllegalArgumentException if maximum number of values is zero" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo maximumOf 0 does {_=>}
}
}
it should "throw an IllegalArgumentException if minimum number of values is larger or equal than maximum" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo minimumOf 2 maximumOf 1 does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
root minimumOf 7 maximumOf 3 does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.command named foo minimumOf 3 maximumOf 3 does {_=>}
}
}
it should "form nicely if a set of valid arguments and flags are passed" in {
cli.command named foo accepts (
flag named foo,
flag named bar,
arg named baz alias f taking 1 value
) does {_=>}
cli.root accepts (
flag named g,
flag named bar alias b,
arg named foo alias f taking 1 value
) does {_=>}
cli.command named bar accepts (
flag named foo,
arg named bar alias b taking 3 as (1, 2, 3),
arg named baz alias g taking 1 value
) does {_=>}
cli.command named baz accepts (
flag named f alias foo,
arg named bar alias b taking 1 as "one",
arg named baz alias g taking 1 value
) does {_=>}
}
it should "throw an IllegalArgumentException if a flag or argument have same name" in {
an [IllegalArgumentException] should be thrownBy {
cli.command named foo accepts (
flag named foo,
flag named foo,
arg named baz alias f taking 1 value
) does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.root accepts (
flag named g,
flag named bar alias b,
arg named bar alias f taking 1 value
) does {_=>}
}
an [IllegalArgumentException] should be thrownBy {
cli.root accepts(
flag named bar alias b,
arg named f taking 1 as "one",
arg named f alias baz taking 1 value
) does { _ =>}
}
}
it should "throw an IllegalArgumentException if a command with the same name is defined twice" in {
an[IllegalArgumentException] should be thrownBy {
cli.command named foo does { _ =>}
cli.command named foo does { _ =>}
}
}
it should "throw an IllegalArgumentException if the root command is defined twice" in {
an[IllegalArgumentException] should be thrownBy {
root does { _ =>}
root does { _ =>}
}
}
} | {'content_hash': '0ad81e185cc57a89e7cc5e8a0bc63801', 'timestamp': '', 'source': 'github', 'line_count': 733, 'max_line_length': 122, 'avg_line_length': 39.76398362892224, 'alnum_prop': 0.6814423439805126, 'repo_name': 'alanrodas/scaland', 'id': '809f95f63701d2130aadf35ad4e59aa8df7c0564', 'size': '29738', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cli/src/test/scala/com/alanrodas/scaland/cli/BuildersSpec.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '39226'}, {'name': 'Java', 'bytes': '3649'}, {'name': 'Ruby', 'bytes': '121'}, {'name': 'Scala', 'bytes': '265491'}]} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/Users/applelike/Desktop/Camera2Video/Application/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.0/res/values-cs/values-cs.xml -->
<eat-comment/>
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"Přejít na plochu"</string>
<string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s – %2$s"</string>
<string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s – %3$s"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"Přejít nahoru"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Více možností"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"Hotovo"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Zobrazit vše"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Vybrat aplikaci"</string>
<string msgid="7723749260725869598" name="abc_search_hint">"Vyhledat…"</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"Smazat dotaz"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"Vyhledávací dotaz"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"Hledat"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"Odeslat dotaz"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"Hlasové vyhledávání"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Sdílet pomocí"</string>
<string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Sdílet pomocí %s"</string>
<string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Sbalit"</string>
<string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string>
</resources> | {'content_hash': '51402be85563b56c272984d4cec9e65d', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 174, 'avg_line_length': 93.73913043478261, 'alnum_prop': 0.7546382189239332, 'repo_name': 'DangHoach/Camera2Video', 'id': 'bbb5695826ff8474a14d6a40694241acaa41937b', 'size': '2180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'Application/build/intermediates/res/debug/values-cs/values-cs.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '621773'}, {'name': 'Shell', 'bytes': '5080'}]} |
package com.dopsun.bbutils;
import java.util.Objects;
/**
* A pool for same sized {@link FixedBuffer}.
*
* @author Dop Sun
* @since 1.0.0
*/
public interface FixedBufferPool extends Pool {
/**
* @return capacity for pooled {@link FixedBuffer}.
*/
int bufferCapacity();
@Override
FixedBuffer borrowBuffer();
/**
* @param buffer
* byte buffer to return.
*/
void returnBuffer(FixedBuffer buffer);
@Override
default void returnBuffer(Buffer buffer) {
Objects.requireNonNull(buffer);
if (!(buffer instanceof FixedBuffer)) {
throw new IllegalArgumentException("buffer is not FixedBuffer.");
}
returnBuffer((FixedBuffer) buffer);
}
}
| {'content_hash': 'c77f0abbf3635fc2f4aa9c5e390c92db', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 77, 'avg_line_length': 19.94736842105263, 'alnum_prop': 0.6160949868073878, 'repo_name': 'dopsun/bbutils', 'id': '943c68255f56c99e40d6379c6fd27cd0a65b71c8', 'size': '1371', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'bbutils/src/main/java/com/dopsun/bbutils/FixedBufferPool.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '55339'}, {'name': 'Shell', 'bytes': '3373'}]} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Dynamitey;
namespace Dynamitey.SupportLibrary
{
public class TestEvent
{
public event EventHandler<EventArgs> Event;
public void OnEvent(object obj, EventArgs args)
{
if (Event != null)
Event(obj, args);
}
}
public static class TestFuncs
{
public static Func<int, int> Plus3
{
get { return x => x + 3; }
}
}
public class PublicType
{
public static object InternalInstance => new InternalType();
public bool PrivateMethod(object param)
{
return param != null;
}
}
internal class InternalType
{
public bool InternalMethod(object param)
{
return param != null;
}
}
public interface IDynamicArg
{
dynamic ReturnIt(dynamic arg);
bool Params(params dynamic[] args);
}
public class PocoNonDynamicArg
{
public int ReturnIt(int i)
{
return i;
}
public List<string> ReturnIt(List<string> i)
{
return i;
}
public bool Params(object fallback)
{
return false;
}
public bool Params(params int[] args)
{
return true;
}
}
public static class StaticType
{
public static TReturn Create<TReturn>(int type)
{
return default(TReturn);
}
public static bool Test => true;
public static int TestSet { get; set; }
}
public interface ISimpeleClassProps
{
string Prop1 { get; }
long Prop2 { get; }
Guid Prop3 { get; }
}
public interface IInheritProp : ISimpeleClassProps
{
PropPoco ReturnProp { get; set; }
}
public interface IPropPocoProp
{
PropPoco ReturnProp { get; set; }
}
public interface IEventCollisions
{
int Event { get; set; }
}
public interface IEvent
{
event EventHandler<EventArgs> Event;
void OnEvent(object obj, EventArgs args);
}
public class PocoEvent
{
public event EventHandler<EventArgs> Event;
public void OnEvent(object obj, EventArgs args)
{
if (Event != null)
Event(obj, args);
}
}
public class PocoOptConstructor
{
public string One { get; set; }
public string Two { get; set; }
public string Three { get; set; }
public PocoOptConstructor(string one = "-1", string two = "-2", string three = "-3")
{
One = one;
Two = two;
Three = three;
}
}
public enum TestEnum
{
None,
One,
Two
}
public interface IDynamicDict
{
int Test1 { get; }
long Test2 { get; }
TestEnum Test3 { get; }
TestEnum Test4 { get; }
dynamic TestD { get; }
}
public interface INonDynamicDict
{
int Test1 { get; }
long Test2 { get; }
TestEnum Test3 { get; }
TestEnum Test4 { get; }
IDictionary<string, object> TestD { get; }
}
public interface ISimpleStringProperty
{
int Length { get; }
}
public interface IRobot
{
string Name { get; }
}
public class Robot
{
public string Name { get; set; }
}
public interface ISimpleStringMethod
{
bool StartsWith(string value);
}
public interface ISimpleStringMethodCollision
{
int StartsWith(string value);
}
public interface ISimpeleClassMeth
{
void Action1();
void Action2(bool value);
string Action3();
}
public interface ISimpeleClassMeth2 : ISimpeleClassMeth
{
string Action4(int arg);
}
public interface IGenericMeth
{
string Action<T>(T arg);
T Action2<T>(T arg);
}
public interface IStringIntIndexer
{
string this[int index] { get; set; }
}
public interface IObjectStringIndexer
{
object this[string index] { get; set; }
}
public interface IGenericMethWithConstraints
{
string Action<T>(T arg) where T : class;
string Action2<T>(T arg) where T : IComparable;
}
public interface IGenericType<T>
{
string Funct(T arg);
}
public interface IGenericTypeConstraints<T> where T : class
{
string Funct(T arg);
}
public interface IOverloadingMethod
{
string Func(int arg);
string Func(object arg);
}
public class PropPoco
{
public string Prop1 { get; set; }
public long Prop2 { get; set; }
public Guid Prop3 { get; set; }
public int Event { get; set; }
}
public struct PropStruct
{
public string Prop1 { get; set; }
public long Prop2 { get; set; }
public Guid Prop3 { get; set; }
public int Event { get; set; }
}
public interface IVoidMethod
{
void Action();
}
public class VoidMethodPoco
{
public void Action()
{
}
}
public class OverloadingMethPoco
{
public string Func(int arg)
{
return "int";
}
public string Func(object arg)
{
return "object";
}
public string Func(object arg, object arg2, object arg3, object arg4, object arg5, object arg6)
{
return "object 6";
}
public string Func(object one = null, object two = null, object three = null)
{
return "object named";
}
}
/// <summary>
/// Dynamic Delegates need to return object or void, first parameter should be a CallSite, second object, followed by the expected arguments
/// </summary>
public delegate object DynamicTryString(CallSite callsite, object target, out string result);
public class MethOutPoco
{
public bool Func(out string result)
{
result = "success";
return true;
}
}
public class Thing { }
public interface IGenericTest
{
List<T> GetThings<T>(Guid test) where T : Thing;
}
public class OtherThing
{
List<T> GetThings<T>(Guid test) where T : Thing
{
return new List<T>();
}
}
public class ForwardGenericMethodsTestClass
{
public string Value { get; set; }
public T Create<T>(int arg) where T : ForwardGenericMethodsTestClass, new()
{
return new T { Value = "test" + arg };
}
}
public class GenericMethOutPoco
{
public bool Func<T>(out T result)
{
result = default(T);
return true;
}
}
public interface IGenericMethodOut
{
bool Func<T>(out T result);
}
public interface IMethodOut2
{
bool Func(out int result);
}
public class MethRefPoco
{
public bool Func(ref int result)
{
result = result + 2;
return true;
}
}
public class PocoAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class PocoDoubleProp : IInheritProp, IPropPocoProp, IEnumerable
{
public string Prop1 => throw new NotImplementedException();
public long Prop2 => throw new NotImplementedException();
public Guid Prop3 => throw new NotImplementedException();
public PropPoco ReturnProp
{
get => throw new NotImplementedException();
set => throw new NotImplementedException(); //lgtm [cs/unused-property-value]
}
PropPoco IPropPocoProp.ReturnProp
{
get => throw new NotImplementedException();
set => throw new NotImplementedException(); //lgtm [cs/unused-property-value]
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public class PocoCollection : IList
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public int Count => throw new NotImplementedException();
public object SyncRoot => throw new NotImplementedException();
public bool IsSynchronized => throw new NotImplementedException();
public int Add(object value)
{
throw new NotImplementedException();
}
public bool Contains(object value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public int IndexOf(object value)
{
throw new NotImplementedException();
}
public void Insert(int index, object value)
{
throw new NotImplementedException();
}
public void Remove(object value)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public object this[int index]
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public bool IsReadOnly => throw new NotImplementedException();
public bool IsFixedSize => throw new NotImplementedException();
}
}
| {'content_hash': '4774cd5f8f4c4d5a5934dbd0643ab009', 'timestamp': '', 'source': 'github', 'line_count': 499, 'max_line_length': 144, 'avg_line_length': 19.975951903807616, 'alnum_prop': 0.5484550561797753, 'repo_name': 'ekonbenefits/dynamitey', 'id': '0a01a4156065415ffd9ab5d987f9c11fe61a8958', 'size': '9970', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SupportLibrary/SupportTypes.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '578997'}, {'name': 'Shell', 'bytes': '6006'}]} |
//===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
/// analysis.
///
/// Unlike other Sanitizer tools, this tool is not designed to detect a specific
/// class of bugs on its own. Instead, it provides a generic dynamic data flow
/// analysis framework to be used by clients to help detect application-specific
/// issues within their own code.
///
/// The analysis is based on automatic propagation of data flow labels (also
/// known as taint labels) through a program as it performs computation. Each
/// byte of application memory is backed by two bytes of shadow memory which
/// hold the label. On Linux/x86_64, memory is laid out as follows:
///
/// +--------------------+ 0x800000000000 (top of memory)
/// | application memory |
/// +--------------------+ 0x700000008000 (kAppAddr)
/// | |
/// | unused |
/// | |
/// +--------------------+ 0x200200000000 (kUnusedAddr)
/// | union table |
/// +--------------------+ 0x200000000000 (kUnionTableAddr)
/// | shadow memory |
/// +--------------------+ 0x000000010000 (kShadowAddr)
/// | reserved by kernel |
/// +--------------------+ 0x000000000000
///
/// To derive a shadow memory address from an application memory address,
/// bits 44-46 are cleared to bring the address into the range
/// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
/// account for the double byte representation of shadow labels and move the
/// address into the shadow memory range. See the function
/// DataFlowSanitizer::getShadowAddress below.
///
/// For more information, please refer to the design document:
/// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SpecialCaseList.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
// External symbol to be used when generating the shadow address for
// architectures with multiple VMAs. Instead of using a constant integer
// the runtime will set the external mask based on the VMA range.
static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
// The -dfsan-preserve-alignment flag controls whether this pass assumes that
// alignment requirements provided by the input IR are correct. For example,
// if the input IR contains a load with alignment 8, this flag will cause
// the shadow load to have alignment 16. This flag is disabled by default as
// we have unfortunately encountered too much code (including Clang itself;
// see PR14291) which performs misaligned access.
static cl::opt<bool> ClPreserveAlignment(
"dfsan-preserve-alignment",
cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
cl::init(false));
// The ABI list files control how shadow parameters are passed. The pass treats
// every function labelled "uninstrumented" in the ABI list file as conforming
// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
// additional annotations for those functions, a call to one of those functions
// will produce a warning message, as the labelling behaviour of the function is
// unknown. The other supported annotations are "functional" and "discard",
// which are described below under DataFlowSanitizer::WrapperKind.
static cl::list<std::string> ClABIListFiles(
"dfsan-abilist",
cl::desc("File listing native ABI functions and how the pass treats them"),
cl::Hidden);
// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
// functions (see DataFlowSanitizer::InstrumentedABI below).
static cl::opt<bool> ClArgsABI(
"dfsan-args-abi",
cl::desc("Use the argument ABI rather than the TLS ABI"),
cl::Hidden);
// Controls whether the pass includes or ignores the labels of pointers in load
// instructions.
static cl::opt<bool> ClCombinePointerLabelsOnLoad(
"dfsan-combine-pointer-labels-on-load",
cl::desc("Combine the label of the pointer with the label of the data when "
"loading from memory."),
cl::Hidden, cl::init(true));
// Controls whether the pass includes or ignores the labels of pointers in
// stores instructions.
static cl::opt<bool> ClCombinePointerLabelsOnStore(
"dfsan-combine-pointer-labels-on-store",
cl::desc("Combine the label of the pointer with the label of the data when "
"storing in memory."),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClDebugNonzeroLabels(
"dfsan-debug-nonzero-labels",
cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
"load or return with a nonzero label"),
cl::Hidden);
static StringRef GetGlobalTypeString(const GlobalValue &G) {
// Types of GlobalVariables are always pointer types.
Type *GType = G.getValueType();
// For now we support blacklisting struct types only.
if (StructType *SGType = dyn_cast<StructType>(GType)) {
if (!SGType->isLiteral())
return SGType->getName();
}
return "<unknown type>";
}
namespace {
class DFSanABIList {
std::unique_ptr<SpecialCaseList> SCL;
public:
DFSanABIList() = default;
void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
/// Returns whether either this function or its source file are listed in the
/// given category.
bool isIn(const Function &F, StringRef Category) const {
return isIn(*F.getParent(), Category) ||
SCL->inSection("dataflow", "fun", F.getName(), Category);
}
/// Returns whether this global alias is listed in the given category.
///
/// If GA aliases a function, the alias's name is matched as a function name
/// would be. Similarly, aliases of globals are matched like globals.
bool isIn(const GlobalAlias &GA, StringRef Category) const {
if (isIn(*GA.getParent(), Category))
return true;
if (isa<FunctionType>(GA.getValueType()))
return SCL->inSection("dataflow", "fun", GA.getName(), Category);
return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
Category);
}
/// Returns whether this module is listed in the given category.
bool isIn(const Module &M, StringRef Category) const {
return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
}
};
/// TransformedFunction is used to express the result of transforming one
/// function type into another. This struct is immutable. It holds metadata
/// useful for updating calls of the old function to the new type.
struct TransformedFunction {
TransformedFunction(FunctionType* OriginalType,
FunctionType* TransformedType,
std::vector<unsigned> ArgumentIndexMapping)
: OriginalType(OriginalType),
TransformedType(TransformedType),
ArgumentIndexMapping(ArgumentIndexMapping) {}
// Disallow copies.
TransformedFunction(const TransformedFunction&) = delete;
TransformedFunction& operator=(const TransformedFunction&) = delete;
// Allow moves.
TransformedFunction(TransformedFunction&&) = default;
TransformedFunction& operator=(TransformedFunction&&) = default;
/// Type of the function before the transformation.
FunctionType *OriginalType;
/// Type of the function after the transformation.
FunctionType *TransformedType;
/// Transforming a function may change the position of arguments. This
/// member records the mapping from each argument's old position to its new
/// position. Argument positions are zero-indexed. If the transformation
/// from F to F' made the first argument of F into the third argument of F',
/// then ArgumentIndexMapping[0] will equal 2.
std::vector<unsigned> ArgumentIndexMapping;
};
/// Given function attributes from a call site for the original function,
/// return function attributes appropriate for a call to the transformed
/// function.
AttributeList TransformFunctionAttributes(
const TransformedFunction& TransformedFunction,
LLVMContext& Ctx, AttributeList CallSiteAttrs) {
// Construct a vector of AttributeSet for each function argument.
std::vector<llvm::AttributeSet> ArgumentAttributes(
TransformedFunction.TransformedType->getNumParams());
// Copy attributes from the parameter of the original function to the
// transformed version. 'ArgumentIndexMapping' holds the mapping from
// old argument position to new.
for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
i < ie; ++i) {
unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
}
// Copy annotations on varargs arguments.
for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
}
return AttributeList::get(
Ctx,
CallSiteAttrs.getFnAttributes(),
CallSiteAttrs.getRetAttributes(),
llvm::makeArrayRef(ArgumentAttributes));
}
class DataFlowSanitizer : public ModulePass {
friend struct DFSanFunction;
friend class DFSanVisitor;
enum {
ShadowWidth = 16
};
/// Which ABI should be used for instrumented functions?
enum InstrumentedABI {
/// Argument and return value labels are passed through additional
/// arguments and by modifying the return type.
IA_Args,
/// Argument and return value labels are passed through TLS variables
/// __dfsan_arg_tls and __dfsan_retval_tls.
IA_TLS
};
/// How should calls to uninstrumented functions be handled?
enum WrapperKind {
/// This function is present in an uninstrumented form but we don't know
/// how it should be handled. Print a warning and call the function anyway.
/// Don't label the return value.
WK_Warning,
/// This function does not write to (user-accessible) memory, and its return
/// value is unlabelled.
WK_Discard,
/// This function does not write to (user-accessible) memory, and the label
/// of its return value is the union of the label of its arguments.
WK_Functional,
/// Instead of calling the function, a custom wrapper __dfsw_F is called,
/// where F is the name of the function. This function may wrap the
/// original function or provide its own implementation. This is similar to
/// the IA_Args ABI, except that IA_Args uses a struct return type to
/// pass the return value shadow in a register, while WK_Custom uses an
/// extra pointer argument to return the shadow. This allows the wrapped
/// form of the function type to be expressed in C.
WK_Custom
};
Module *Mod;
LLVMContext *Ctx;
IntegerType *ShadowTy;
PointerType *ShadowPtrTy;
IntegerType *IntptrTy;
ConstantInt *ZeroShadow;
ConstantInt *ShadowPtrMask;
ConstantInt *ShadowPtrMul;
Constant *ArgTLS;
Constant *RetvalTLS;
void *(*GetArgTLSPtr)();
void *(*GetRetvalTLSPtr)();
FunctionType *GetArgTLSTy;
FunctionType *GetRetvalTLSTy;
Constant *GetArgTLS;
Constant *GetRetvalTLS;
Constant *ExternalShadowMask;
FunctionType *DFSanUnionFnTy;
FunctionType *DFSanUnionLoadFnTy;
FunctionType *DFSanUnimplementedFnTy;
FunctionType *DFSanSetLabelFnTy;
FunctionType *DFSanNonzeroLabelFnTy;
FunctionType *DFSanVarargWrapperFnTy;
FunctionCallee DFSanUnionFn;
FunctionCallee DFSanCheckedUnionFn;
FunctionCallee DFSanUnionLoadFn;
FunctionCallee DFSanUnimplementedFn;
FunctionCallee DFSanSetLabelFn;
FunctionCallee DFSanNonzeroLabelFn;
FunctionCallee DFSanVarargWrapperFn;
MDNode *ColdCallWeights;
DFSanABIList ABIList;
DenseMap<Value *, Function *> UnwrappedFnMap;
AttrBuilder ReadOnlyNoneAttrs;
bool DFSanRuntimeShadowMask = false;
Value *getShadowAddress(Value *Addr, Instruction *Pos);
bool isInstrumented(const Function *F);
bool isInstrumented(const GlobalAlias *GA);
FunctionType *getArgsFunctionType(FunctionType *T);
FunctionType *getTrampolineFunctionType(FunctionType *T);
TransformedFunction getCustomFunctionType(FunctionType *T);
InstrumentedABI getInstrumentedABI();
WrapperKind getWrapperKind(Function *F);
void addGlobalNamePrefix(GlobalValue *GV);
Function *buildWrapperFunction(Function *F, StringRef NewFName,
GlobalValue::LinkageTypes NewFLink,
FunctionType *NewFT);
Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
public:
static char ID;
DataFlowSanitizer(
const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
bool doInitialization(Module &M) override;
bool runOnModule(Module &M) override;
};
struct DFSanFunction {
DataFlowSanitizer &DFS;
Function *F;
DominatorTree DT;
DataFlowSanitizer::InstrumentedABI IA;
bool IsNativeABI;
Value *ArgTLSPtr = nullptr;
Value *RetvalTLSPtr = nullptr;
AllocaInst *LabelReturnAlloca = nullptr;
DenseMap<Value *, Value *> ValShadowMap;
DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
DenseSet<Instruction *> SkipInsts;
std::vector<Value *> NonZeroChecks;
bool AvoidNewBlocks;
struct CachedCombinedShadow {
BasicBlock *Block;
Value *Shadow;
};
DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
CachedCombinedShadows;
DenseMap<Value *, std::set<Value *>> ShadowElements;
DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
: DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
DT.recalculate(*F);
// FIXME: Need to track down the register allocator issue which causes poor
// performance in pathological cases with large numbers of basic blocks.
AvoidNewBlocks = F->size() > 1000;
}
Value *getArgTLSPtr();
Value *getArgTLS(unsigned Index, Instruction *Pos);
Value *getRetvalTLS();
Value *getShadow(Value *V);
void setShadow(Instruction *I, Value *Shadow);
Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Value *combineOperandShadows(Instruction *Inst);
Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
Instruction *Pos);
void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
Instruction *Pos);
};
class DFSanVisitor : public InstVisitor<DFSanVisitor> {
public:
DFSanFunction &DFSF;
DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
const DataLayout &getDataLayout() const {
return DFSF.F->getParent()->getDataLayout();
}
void visitOperandShadowInst(Instruction &I);
void visitUnaryOperator(UnaryOperator &UO);
void visitBinaryOperator(BinaryOperator &BO);
void visitCastInst(CastInst &CI);
void visitCmpInst(CmpInst &CI);
void visitGetElementPtrInst(GetElementPtrInst &GEPI);
void visitLoadInst(LoadInst &LI);
void visitStoreInst(StoreInst &SI);
void visitReturnInst(ReturnInst &RI);
void visitCallSite(CallSite CS);
void visitPHINode(PHINode &PN);
void visitExtractElementInst(ExtractElementInst &I);
void visitInsertElementInst(InsertElementInst &I);
void visitShuffleVectorInst(ShuffleVectorInst &I);
void visitExtractValueInst(ExtractValueInst &I);
void visitInsertValueInst(InsertValueInst &I);
void visitAllocaInst(AllocaInst &I);
void visitSelectInst(SelectInst &I);
void visitMemSetInst(MemSetInst &I);
void visitMemTransferInst(MemTransferInst &I);
};
} // end anonymous namespace
char DataFlowSanitizer::ID;
INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
"DataFlowSanitizer: dynamic data flow analysis.", false, false)
ModulePass *
llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
void *(*getArgTLS)(),
void *(*getRetValTLS)()) {
return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
}
DataFlowSanitizer::DataFlowSanitizer(
const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
void *(*getRetValTLS)())
: ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
ClABIListFiles.end());
ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
}
FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
ArgTypes.append(T->getNumParams(), ShadowTy);
if (T->isVarArg())
ArgTypes.push_back(ShadowPtrTy);
Type *RetType = T->getReturnType();
if (!RetType->isVoidTy())
RetType = StructType::get(RetType, ShadowTy);
return FunctionType::get(RetType, ArgTypes, T->isVarArg());
}
FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
assert(!T->isVarArg());
SmallVector<Type *, 4> ArgTypes;
ArgTypes.push_back(T->getPointerTo());
ArgTypes.append(T->param_begin(), T->param_end());
ArgTypes.append(T->getNumParams(), ShadowTy);
Type *RetType = T->getReturnType();
if (!RetType->isVoidTy())
ArgTypes.push_back(ShadowPtrTy);
return FunctionType::get(T->getReturnType(), ArgTypes, false);
}
TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
SmallVector<Type *, 4> ArgTypes;
// Some parameters of the custom function being constructed are
// parameters of T. Record the mapping from parameters of T to
// parameters of the custom function, so that parameter attributes
// at call sites can be updated.
std::vector<unsigned> ArgumentIndexMapping;
for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
Type* param_type = T->getParamType(i);
FunctionType *FT;
if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
cast<PointerType>(param_type)->getElementType()))) {
ArgumentIndexMapping.push_back(ArgTypes.size());
ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
} else {
ArgumentIndexMapping.push_back(ArgTypes.size());
ArgTypes.push_back(param_type);
}
}
for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
ArgTypes.push_back(ShadowTy);
if (T->isVarArg())
ArgTypes.push_back(ShadowPtrTy);
Type *RetType = T->getReturnType();
if (!RetType->isVoidTy())
ArgTypes.push_back(ShadowPtrTy);
return TransformedFunction(
T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
ArgumentIndexMapping);
}
bool DataFlowSanitizer::doInitialization(Module &M) {
Triple TargetTriple(M.getTargetTriple());
bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
bool IsMIPS64 = TargetTriple.isMIPS64();
bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
TargetTriple.getArch() == Triple::aarch64_be;
const DataLayout &DL = M.getDataLayout();
Mod = &M;
Ctx = &M.getContext();
ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
ShadowPtrTy = PointerType::getUnqual(ShadowTy);
IntptrTy = DL.getIntPtrType(*Ctx);
ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
if (IsX86_64)
ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
else if (IsMIPS64)
ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
// AArch64 supports multiple VMAs and the shadow mask is set at runtime.
else if (IsAArch64)
DFSanRuntimeShadowMask = true;
else
report_fatal_error("unsupported triple");
Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
DFSanUnionFnTy =
FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
DFSanUnionLoadFnTy =
FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
DFSanUnimplementedFnTy = FunctionType::get(
Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
DFSanSetLabelArgs, /*isVarArg=*/false);
DFSanNonzeroLabelFnTy = FunctionType::get(
Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
DFSanVarargWrapperFnTy = FunctionType::get(
Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
if (GetArgTLSPtr) {
Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
ArgTLS = nullptr;
GetArgTLSTy = FunctionType::get(PointerType::getUnqual(ArgTLSTy), false);
GetArgTLS = ConstantExpr::getIntToPtr(
ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
PointerType::getUnqual(GetArgTLSTy));
}
if (GetRetvalTLSPtr) {
RetvalTLS = nullptr;
GetRetvalTLSTy = FunctionType::get(PointerType::getUnqual(ShadowTy), false);
GetRetvalTLS = ConstantExpr::getIntToPtr(
ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
PointerType::getUnqual(GetRetvalTLSTy));
}
ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
return true;
}
bool DataFlowSanitizer::isInstrumented(const Function *F) {
return !ABIList.isIn(*F, "uninstrumented");
}
bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
return !ABIList.isIn(*GA, "uninstrumented");
}
DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
return ClArgsABI ? IA_Args : IA_TLS;
}
DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
if (ABIList.isIn(*F, "functional"))
return WK_Functional;
if (ABIList.isIn(*F, "discard"))
return WK_Discard;
if (ABIList.isIn(*F, "custom"))
return WK_Custom;
return WK_Warning;
}
void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
std::string GVName = GV->getName(), Prefix = "dfs$";
GV->setName(Prefix + GVName);
// Try to change the name of the function in module inline asm. We only do
// this for specific asm directives, currently only ".symver", to try to avoid
// corrupting asm which happens to contain the symbol name as a substring.
// Note that the substitution for .symver assumes that the versioned symbol
// also has an instrumented name.
std::string Asm = GV->getParent()->getModuleInlineAsm();
std::string SearchStr = ".symver " + GVName + ",";
size_t Pos = Asm.find(SearchStr);
if (Pos != std::string::npos) {
Asm.replace(Pos, SearchStr.size(),
".symver " + Prefix + GVName + "," + Prefix);
GV->getParent()->setModuleInlineAsm(Asm);
}
}
Function *
DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
GlobalValue::LinkageTypes NewFLink,
FunctionType *NewFT) {
FunctionType *FT = F->getFunctionType();
Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
NewFName, F->getParent());
NewF->copyAttributesFrom(F);
NewF->removeAttributes(
AttributeList::ReturnIndex,
AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
if (F->isVarArg()) {
NewF->removeAttributes(AttributeList::FunctionIndex,
AttrBuilder().addAttribute("split-stack"));
CallInst::Create(DFSanVarargWrapperFn,
IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
BB);
new UnreachableInst(*Ctx, BB);
} else {
std::vector<Value *> Args;
unsigned n = FT->getNumParams();
for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
Args.push_back(&*ai);
CallInst *CI = CallInst::Create(F, Args, "", BB);
if (FT->getReturnType()->isVoidTy())
ReturnInst::Create(*Ctx, BB);
else
ReturnInst::Create(*Ctx, CI, BB);
}
return NewF;
}
Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
StringRef FName) {
FunctionType *FTT = getTrampolineFunctionType(FT);
FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
Function *F = dyn_cast<Function>(C.getCallee());
if (F && F->isDeclaration()) {
F->setLinkage(GlobalValue::LinkOnceODRLinkage);
BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
std::vector<Value *> Args;
Function::arg_iterator AI = F->arg_begin(); ++AI;
for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
Args.push_back(&*AI);
CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
ReturnInst *RI;
if (FT->getReturnType()->isVoidTy())
RI = ReturnInst::Create(*Ctx, BB);
else
RI = ReturnInst::Create(*Ctx, CI, BB);
DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
DFSanVisitor(DFSF).visitCallInst(*CI);
if (!FT->getReturnType()->isVoidTy())
new StoreInst(DFSF.getShadow(RI->getReturnValue()),
&*std::prev(F->arg_end()), RI);
}
return cast<Constant>(C.getCallee());
}
bool DataFlowSanitizer::runOnModule(Module &M) {
if (ABIList.isIn(M, "skip"))
return false;
if (!GetArgTLSPtr) {
Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
}
if (!GetRetvalTLSPtr) {
RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
}
ExternalShadowMask =
Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
{
AttributeList AL;
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::NoUnwind);
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::ReadNone);
AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
Attribute::ZExt);
AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
DFSanUnionFn =
Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
}
{
AttributeList AL;
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::NoUnwind);
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::ReadNone);
AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
Attribute::ZExt);
AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
DFSanCheckedUnionFn =
Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
}
{
AttributeList AL;
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::NoUnwind);
AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
Attribute::ReadOnly);
AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
Attribute::ZExt);
DFSanUnionLoadFn =
Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
}
DFSanUnimplementedFn =
Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
{
AttributeList AL;
AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
DFSanSetLabelFn =
Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
}
DFSanNonzeroLabelFn =
Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
DFSanVarargWrapperFnTy);
std::vector<Function *> FnsToInstrument;
SmallPtrSet<Function *, 2> FnsWithNativeABI;
for (Function &i : M) {
if (!i.isIntrinsic() &&
&i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
&i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
&i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
&i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
&i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
&i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
&i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
FnsToInstrument.push_back(&i);
}
// Give function aliases prefixes when necessary, and build wrappers where the
// instrumentedness is inconsistent.
for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
GlobalAlias *GA = &*i;
++i;
// Don't stop on weak. We assume people aren't playing games with the
// instrumentedness of overridden weak aliases.
if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
if (GAInst && FInst) {
addGlobalNamePrefix(GA);
} else if (GAInst != FInst) {
// Non-instrumented alias of an instrumented function, or vice versa.
// Replace the alias with a native-ABI wrapper of the aliasee. The pass
// below will take care of instrumenting it.
Function *NewF =
buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
NewF->takeName(GA);
GA->eraseFromParent();
FnsToInstrument.push_back(NewF);
}
}
}
ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
.addAttribute(Attribute::ReadNone);
// First, change the ABI of every function in the module. ABI-listed
// functions keep their original ABI and get a wrapper function.
for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
e = FnsToInstrument.end();
i != e; ++i) {
Function &F = **i;
FunctionType *FT = F.getFunctionType();
bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
FT->getReturnType()->isVoidTy());
if (isInstrumented(&F)) {
// Instrumented functions get a 'dfs$' prefix. This allows us to more
// easily identify cases of mismatching ABIs.
if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
FunctionType *NewFT = getArgsFunctionType(FT);
Function *NewF = Function::Create(NewFT, F.getLinkage(),
F.getAddressSpace(), "", &M);
NewF->copyAttributesFrom(&F);
NewF->removeAttributes(
AttributeList::ReturnIndex,
AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
for (Function::arg_iterator FArg = F.arg_begin(),
NewFArg = NewF->arg_begin(),
FArgEnd = F.arg_end();
FArg != FArgEnd; ++FArg, ++NewFArg) {
FArg->replaceAllUsesWith(&*NewFArg);
}
NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
UI != UE;) {
BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
++UI;
if (BA) {
BA->replaceAllUsesWith(
BlockAddress::get(NewF, BA->getBasicBlock()));
delete BA;
}
}
F.replaceAllUsesWith(
ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
NewF->takeName(&F);
F.eraseFromParent();
*i = NewF;
addGlobalNamePrefix(NewF);
} else {
addGlobalNamePrefix(&F);
}
} else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
// Build a wrapper function for F. The wrapper simply calls F, and is
// added to FnsToInstrument so that any instrumentation according to its
// WrapperKind is done in the second pass below.
FunctionType *NewFT = getInstrumentedABI() == IA_Args
? getArgsFunctionType(FT)
: FT;
// If the function being wrapped has local linkage, then preserve the
// function's linkage in the wrapper function.
GlobalValue::LinkageTypes wrapperLinkage =
F.hasLocalLinkage()
? F.getLinkage()
: GlobalValue::LinkOnceODRLinkage;
Function *NewF = buildWrapperFunction(
&F, std::string("dfsw$") + std::string(F.getName()),
wrapperLinkage, NewFT);
if (getInstrumentedABI() == IA_TLS)
NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Value *WrappedFnCst =
ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
F.replaceAllUsesWith(WrappedFnCst);
UnwrappedFnMap[WrappedFnCst] = &F;
*i = NewF;
if (!F.isDeclaration()) {
// This function is probably defining an interposition of an
// uninstrumented function and hence needs to keep the original ABI.
// But any functions it may call need to use the instrumented ABI, so
// we instrument it in a mode which preserves the original ABI.
FnsWithNativeABI.insert(&F);
// This code needs to rebuild the iterators, as they may be invalidated
// by the push_back, taking care that the new range does not include
// any functions added by this code.
size_t N = i - FnsToInstrument.begin(),
Count = e - FnsToInstrument.begin();
FnsToInstrument.push_back(&F);
i = FnsToInstrument.begin() + N;
e = FnsToInstrument.begin() + Count;
}
// Hopefully, nobody will try to indirectly call a vararg
// function... yet.
} else if (FT->isVarArg()) {
UnwrappedFnMap[&F] = &F;
*i = nullptr;
}
}
for (Function *i : FnsToInstrument) {
if (!i || i->isDeclaration())
continue;
removeUnreachableBlocks(*i);
DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
// DFSanVisitor may create new basic blocks, which confuses df_iterator.
// Build a copy of the list before iterating over it.
SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
for (BasicBlock *i : BBList) {
Instruction *Inst = &i->front();
while (true) {
// DFSanVisitor may split the current basic block, changing the current
// instruction's next pointer and moving the next instruction to the
// tail block from which we should continue.
Instruction *Next = Inst->getNextNode();
// DFSanVisitor may delete Inst, so keep track of whether it was a
// terminator.
bool IsTerminator = Inst->isTerminator();
if (!DFSF.SkipInsts.count(Inst))
DFSanVisitor(DFSF).visit(Inst);
if (IsTerminator)
break;
Inst = Next;
}
}
// We will not necessarily be able to compute the shadow for every phi node
// until we have visited every block. Therefore, the code that handles phi
// nodes adds them to the PHIFixups list so that they can be properly
// handled here.
for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
i = DFSF.PHIFixups.begin(),
e = DFSF.PHIFixups.end();
i != e; ++i) {
for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
++val) {
i->second->setIncomingValue(
val, DFSF.getShadow(i->first->getIncomingValue(val)));
}
}
// -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
// places (i.e. instructions in basic blocks we haven't even begun visiting
// yet). To make our life easier, do this work in a pass after the main
// instrumentation.
if (ClDebugNonzeroLabels) {
for (Value *V : DFSF.NonZeroChecks) {
Instruction *Pos;
if (Instruction *I = dyn_cast<Instruction>(V))
Pos = I->getNextNode();
else
Pos = &DFSF.F->getEntryBlock().front();
while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
Pos = Pos->getNextNode();
IRBuilder<> IRB(Pos);
Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
IRBuilder<> ThenIRB(BI);
ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
}
}
}
return false;
}
Value *DFSanFunction::getArgTLSPtr() {
if (ArgTLSPtr)
return ArgTLSPtr;
if (DFS.ArgTLS)
return ArgTLSPtr = DFS.ArgTLS;
IRBuilder<> IRB(&F->getEntryBlock().front());
return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLSTy, DFS.GetArgTLS, {});
}
Value *DFSanFunction::getRetvalTLS() {
if (RetvalTLSPtr)
return RetvalTLSPtr;
if (DFS.RetvalTLS)
return RetvalTLSPtr = DFS.RetvalTLS;
IRBuilder<> IRB(&F->getEntryBlock().front());
return RetvalTLSPtr =
IRB.CreateCall(DFS.GetRetvalTLSTy, DFS.GetRetvalTLS, {});
}
Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
IRBuilder<> IRB(Pos);
return IRB.CreateConstGEP2_64(ArrayType::get(DFS.ShadowTy, 64),
getArgTLSPtr(), 0, Idx);
}
Value *DFSanFunction::getShadow(Value *V) {
if (!isa<Argument>(V) && !isa<Instruction>(V))
return DFS.ZeroShadow;
Value *&Shadow = ValShadowMap[V];
if (!Shadow) {
if (Argument *A = dyn_cast<Argument>(V)) {
if (IsNativeABI)
return DFS.ZeroShadow;
switch (IA) {
case DataFlowSanitizer::IA_TLS: {
Value *ArgTLSPtr = getArgTLSPtr();
Instruction *ArgTLSPos =
DFS.ArgTLS ? &*F->getEntryBlock().begin()
: cast<Instruction>(ArgTLSPtr)->getNextNode();
IRBuilder<> IRB(ArgTLSPos);
Shadow =
IRB.CreateLoad(DFS.ShadowTy, getArgTLS(A->getArgNo(), ArgTLSPos));
break;
}
case DataFlowSanitizer::IA_Args: {
unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Function::arg_iterator i = F->arg_begin();
while (ArgIdx--)
++i;
Shadow = &*i;
assert(Shadow->getType() == DFS.ShadowTy);
break;
}
}
NonZeroChecks.push_back(Shadow);
} else {
Shadow = DFS.ZeroShadow;
}
}
return Shadow;
}
void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
assert(!ValShadowMap.count(I));
assert(Shadow->getType() == DFS.ShadowTy);
ValShadowMap[I] = Shadow;
}
Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
assert(Addr != RetvalTLS && "Reinstrumenting?");
IRBuilder<> IRB(Pos);
Value *ShadowPtrMaskValue;
if (DFSanRuntimeShadowMask)
ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
else
ShadowPtrMaskValue = ShadowPtrMask;
return IRB.CreateIntToPtr(
IRB.CreateMul(
IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
ShadowPtrMul),
ShadowPtrTy);
}
// Generates IR to compute the union of the two given shadows, inserting it
// before Pos. Returns the computed union Value.
Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
if (V1 == DFS.ZeroShadow)
return V2;
if (V2 == DFS.ZeroShadow)
return V1;
if (V1 == V2)
return V1;
auto V1Elems = ShadowElements.find(V1);
auto V2Elems = ShadowElements.find(V2);
if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
V2Elems->second.begin(), V2Elems->second.end())) {
return V1;
} else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
V1Elems->second.begin(), V1Elems->second.end())) {
return V2;
}
} else if (V1Elems != ShadowElements.end()) {
if (V1Elems->second.count(V2))
return V1;
} else if (V2Elems != ShadowElements.end()) {
if (V2Elems->second.count(V1))
return V2;
}
auto Key = std::make_pair(V1, V2);
if (V1 > V2)
std::swap(Key.first, Key.second);
CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
return CCS.Shadow;
IRBuilder<> IRB(Pos);
if (AvoidNewBlocks) {
CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Call->addParamAttr(0, Attribute::ZExt);
Call->addParamAttr(1, Attribute::ZExt);
CCS.Block = Pos->getParent();
CCS.Shadow = Call;
} else {
BasicBlock *Head = Pos->getParent();
Value *Ne = IRB.CreateICmpNE(V1, V2);
BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
IRBuilder<> ThenIRB(BI);
CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Call->addParamAttr(0, Attribute::ZExt);
Call->addParamAttr(1, Attribute::ZExt);
BasicBlock *Tail = BI->getSuccessor(0);
PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Phi->addIncoming(Call, Call->getParent());
Phi->addIncoming(V1, Head);
CCS.Block = Tail;
CCS.Shadow = Phi;
}
std::set<Value *> UnionElems;
if (V1Elems != ShadowElements.end()) {
UnionElems = V1Elems->second;
} else {
UnionElems.insert(V1);
}
if (V2Elems != ShadowElements.end()) {
UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
} else {
UnionElems.insert(V2);
}
ShadowElements[CCS.Shadow] = std::move(UnionElems);
return CCS.Shadow;
}
// A convenience function which folds the shadows of each of the operands
// of the provided instruction Inst, inserting the IR before Inst. Returns
// the computed union Value.
Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
if (Inst->getNumOperands() == 0)
return DFS.ZeroShadow;
Value *Shadow = getShadow(Inst->getOperand(0));
for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
}
return Shadow;
}
void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
Value *CombinedShadow = DFSF.combineOperandShadows(&I);
DFSF.setShadow(&I, CombinedShadow);
}
// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
// Addr has alignment Align, and take the union of each of those shadows.
Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
Instruction *Pos) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
const auto i = AllocaShadowMap.find(AI);
if (i != AllocaShadowMap.end()) {
IRBuilder<> IRB(Pos);
return IRB.CreateLoad(DFS.ShadowTy, i->second);
}
}
uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
SmallVector<const Value *, 2> Objs;
GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
bool AllConstants = true;
for (const Value *Obj : Objs) {
if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
continue;
if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
continue;
AllConstants = false;
break;
}
if (AllConstants)
return DFS.ZeroShadow;
Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
switch (Size) {
case 0:
return DFS.ZeroShadow;
case 1: {
LoadInst *LI = new LoadInst(DFS.ShadowTy, ShadowAddr, "", Pos);
LI->setAlignment(MaybeAlign(ShadowAlign));
return LI;
}
case 2: {
IRBuilder<> IRB(Pos);
Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
ConstantInt::get(DFS.IntptrTy, 1));
return combineShadows(
IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr, ShadowAlign),
IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr1, ShadowAlign), Pos);
}
}
if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
// Fast path for the common case where each byte has identical shadow: load
// shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
// shadow is non-equal.
BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
IRBuilder<> FallbackIRB(FallbackBB);
CallInst *FallbackCall = FallbackIRB.CreateCall(
DFS.DFSanUnionLoadFn,
{ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
// Compare each of the shadows stored in the loaded 64 bits to each other,
// by computing (WideShadow rotl ShadowWidth) == WideShadow.
IRBuilder<> IRB(Pos);
Value *WideAddr =
IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
Value *WideShadow =
IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
BasicBlock *Head = Pos->getParent();
BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
if (DomTreeNode *OldNode = DT.getNode(Head)) {
std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
for (auto Child : Children)
DT.changeImmediateDominator(Child, NewNode);
}
// In the following code LastBr will refer to the previous basic block's
// conditional branch instruction, whose true successor is fixed up to point
// to the next block during the loop below or to the tail after the final
// iteration.
BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
ReplaceInstWithInst(Head->getTerminator(), LastBr);
DT.addNewBlock(FallbackBB, Head);
for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
Ofs += 64 / DFS.ShadowWidth) {
BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
DT.addNewBlock(NextBB, LastBr->getParent());
IRBuilder<> NextIRB(NextBB);
WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
ConstantInt::get(DFS.IntptrTy, 1));
Value *NextWideShadow = NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(),
WideAddr, ShadowAlign);
ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
LastBr->setSuccessor(0, NextBB);
LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
}
LastBr->setSuccessor(0, Tail);
FallbackIRB.CreateBr(Tail);
PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Shadow->addIncoming(FallbackCall, FallbackBB);
Shadow->addIncoming(TruncShadow, LastBr->getParent());
return Shadow;
}
IRBuilder<> IRB(Pos);
CallInst *FallbackCall = IRB.CreateCall(
DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
return FallbackCall;
}
void DFSanVisitor::visitLoadInst(LoadInst &LI) {
auto &DL = LI.getModule()->getDataLayout();
uint64_t Size = DL.getTypeStoreSize(LI.getType());
if (Size == 0) {
DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
return;
}
uint64_t Align;
if (ClPreserveAlignment) {
Align = LI.getAlignment();
if (Align == 0)
Align = DL.getABITypeAlignment(LI.getType());
} else {
Align = 1;
}
IRBuilder<> IRB(&LI);
Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
if (ClCombinePointerLabelsOnLoad) {
Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
}
if (Shadow != DFSF.DFS.ZeroShadow)
DFSF.NonZeroChecks.push_back(Shadow);
DFSF.setShadow(&LI, Shadow);
}
void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
Value *Shadow, Instruction *Pos) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
const auto i = AllocaShadowMap.find(AI);
if (i != AllocaShadowMap.end()) {
IRBuilder<> IRB(Pos);
IRB.CreateStore(Shadow, i->second);
return;
}
}
uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
IRBuilder<> IRB(Pos);
Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
if (Shadow == DFS.ZeroShadow) {
IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
Value *ExtShadowAddr =
IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
return;
}
const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
uint64_t Offset = 0;
if (Size >= ShadowVecSize) {
VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
Value *ShadowVec = UndefValue::get(ShadowVecTy);
for (unsigned i = 0; i != ShadowVecSize; ++i) {
ShadowVec = IRB.CreateInsertElement(
ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
}
Value *ShadowVecAddr =
IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
do {
Value *CurShadowVecAddr =
IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
Size -= ShadowVecSize;
++Offset;
} while (Size >= ShadowVecSize);
Offset *= ShadowVecSize;
}
while (Size > 0) {
Value *CurShadowAddr =
IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
--Size;
++Offset;
}
}
void DFSanVisitor::visitStoreInst(StoreInst &SI) {
auto &DL = SI.getModule()->getDataLayout();
uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
if (Size == 0)
return;
uint64_t Align;
if (ClPreserveAlignment) {
Align = SI.getAlignment();
if (Align == 0)
Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
} else {
Align = 1;
}
Value* Shadow = DFSF.getShadow(SI.getValueOperand());
if (ClCombinePointerLabelsOnStore) {
Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
}
DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
}
void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
visitOperandShadowInst(UO);
}
void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
visitOperandShadowInst(BO);
}
void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
visitOperandShadowInst(GEPI);
}
void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
visitOperandShadowInst(I);
}
void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
visitOperandShadowInst(I);
}
void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
visitOperandShadowInst(I);
}
void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
visitOperandShadowInst(I);
}
void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
visitOperandShadowInst(I);
}
void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
bool AllLoadsStores = true;
for (User *U : I.users()) {
if (isa<LoadInst>(U))
continue;
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (SI->getPointerOperand() == &I)
continue;
}
AllLoadsStores = false;
break;
}
if (AllLoadsStores) {
IRBuilder<> IRB(&I);
DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
}
DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
}
void DFSanVisitor::visitSelectInst(SelectInst &I) {
Value *CondShadow = DFSF.getShadow(I.getCondition());
Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
if (isa<VectorType>(I.getCondition()->getType())) {
DFSF.setShadow(
&I,
DFSF.combineShadows(
CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
} else {
Value *ShadowSel;
if (TrueShadow == FalseShadow) {
ShadowSel = TrueShadow;
} else {
ShadowSel =
SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
}
DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
}
}
void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
IRBuilder<> IRB(&I);
Value *ValShadow = DFSF.getShadow(I.getValue());
IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
{ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
*DFSF.DFS.Ctx)),
IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
}
void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
IRBuilder<> IRB(&I);
Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
Value *LenShadow = IRB.CreateMul(
I.getLength(),
ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
auto *MTI = cast<MemTransferInst>(
IRB.CreateCall(I.getFunctionType(), I.getCalledValue(),
{DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
if (ClPreserveAlignment) {
MTI->setDestAlignment(I.getDestAlignment() * (DFSF.DFS.ShadowWidth / 8));
MTI->setSourceAlignment(I.getSourceAlignment() * (DFSF.DFS.ShadowWidth / 8));
} else {
MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
MTI->setSourceAlignment(DFSF.DFS.ShadowWidth / 8);
}
}
void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
if (!DFSF.IsNativeABI && RI.getReturnValue()) {
switch (DFSF.IA) {
case DataFlowSanitizer::IA_TLS: {
Value *S = DFSF.getShadow(RI.getReturnValue());
IRBuilder<> IRB(&RI);
IRB.CreateStore(S, DFSF.getRetvalTLS());
break;
}
case DataFlowSanitizer::IA_Args: {
IRBuilder<> IRB(&RI);
Type *RT = DFSF.F->getFunctionType()->getReturnType();
Value *InsVal =
IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
Value *InsShadow =
IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
RI.setOperand(0, InsShadow);
break;
}
}
}
}
void DFSanVisitor::visitCallSite(CallSite CS) {
Function *F = CS.getCalledFunction();
if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
visitOperandShadowInst(*CS.getInstruction());
return;
}
// Calls to this function are synthesized in wrappers, and we shouldn't
// instrument them.
if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
return;
IRBuilder<> IRB(CS.getInstruction());
DenseMap<Value *, Function *>::iterator i =
DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Function *F = i->second;
switch (DFSF.DFS.getWrapperKind(F)) {
case DataFlowSanitizer::WK_Warning:
CS.setCalledFunction(F);
IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
IRB.CreateGlobalStringPtr(F->getName()));
DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
return;
case DataFlowSanitizer::WK_Discard:
CS.setCalledFunction(F);
DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
return;
case DataFlowSanitizer::WK_Functional:
CS.setCalledFunction(F);
visitOperandShadowInst(*CS.getInstruction());
return;
case DataFlowSanitizer::WK_Custom:
// Don't try to handle invokes of custom functions, it's too complicated.
// Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
// wrapper.
if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
FunctionType *FT = F->getFunctionType();
TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
std::string CustomFName = "__dfsw_";
CustomFName += F->getName();
FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
CustomFName, CustomFn.TransformedType);
if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
CustomFn->copyAttributesFrom(F);
// Custom functions returning non-void will write to the return label.
if (!FT->getReturnType()->isVoidTy()) {
CustomFn->removeAttributes(AttributeList::FunctionIndex,
DFSF.DFS.ReadOnlyNoneAttrs);
}
}
std::vector<Value *> Args;
CallSite::arg_iterator i = CS.arg_begin();
for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Type *T = (*i)->getType();
FunctionType *ParamFT;
if (isa<PointerType>(T) &&
(ParamFT = dyn_cast<FunctionType>(
cast<PointerType>(T)->getElementType()))) {
std::string TName = "dfst";
TName += utostr(FT->getNumParams() - n);
TName += "$";
TName += F->getName();
Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
Args.push_back(T);
Args.push_back(
IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
} else {
Args.push_back(*i);
}
}
i = CS.arg_begin();
const unsigned ShadowArgStart = Args.size();
for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Args.push_back(DFSF.getShadow(*i));
if (FT->isVarArg()) {
auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
CS.arg_size() - FT->getNumParams());
auto *LabelVAAlloca = new AllocaInst(
LabelVATy, getDataLayout().getAllocaAddrSpace(),
"labelva", &DFSF.F->getEntryBlock().front());
for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
}
Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
}
if (!FT->getReturnType()->isVoidTy()) {
if (!DFSF.LabelReturnAlloca) {
DFSF.LabelReturnAlloca =
new AllocaInst(DFSF.DFS.ShadowTy,
getDataLayout().getAllocaAddrSpace(),
"labelreturn", &DFSF.F->getEntryBlock().front());
}
Args.push_back(DFSF.LabelReturnAlloca);
}
for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
Args.push_back(*i);
CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
CustomCI->setCallingConv(CI->getCallingConv());
CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
CI->getContext(), CI->getAttributes()));
// Update the parameter attributes of the custom call instruction to
// zero extend the shadow parameters. This is required for targets
// which consider ShadowTy an illegal type.
for (unsigned n = 0; n < FT->getNumParams(); n++) {
const unsigned ArgNo = ShadowArgStart + n;
if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
}
if (!FT->getReturnType()->isVoidTy()) {
LoadInst *LabelLoad =
IRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.LabelReturnAlloca);
DFSF.setShadow(CustomCI, LabelLoad);
}
CI->replaceAllUsesWith(CustomCI);
CI->eraseFromParent();
return;
}
break;
}
}
FunctionType *FT = cast<FunctionType>(
CS.getCalledValue()->getType()->getPointerElementType());
if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
DFSF.getArgTLS(i, CS.getInstruction()));
}
}
Instruction *Next = nullptr;
if (!CS.getType()->isVoidTy()) {
if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
if (II->getNormalDest()->getSinglePredecessor()) {
Next = &II->getNormalDest()->front();
} else {
BasicBlock *NewBB =
SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Next = &NewBB->front();
}
} else {
assert(CS->getIterator() != CS->getParent()->end());
Next = CS->getNextNode();
}
if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
IRBuilder<> NextIRB(Next);
LoadInst *LI = NextIRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.getRetvalTLS());
DFSF.SkipInsts.insert(LI);
DFSF.setShadow(CS.getInstruction(), LI);
DFSF.NonZeroChecks.push_back(LI);
}
}
// Do all instrumentation for IA_Args down here to defer tampering with the
// CFG in a way that SplitEdge may be able to detect.
if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Value *Func =
IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
std::vector<Value *> Args;
CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Args.push_back(*i);
i = CS.arg_begin();
for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Args.push_back(DFSF.getShadow(*i));
if (FT->isVarArg()) {
unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
AllocaInst *VarArgShadow =
new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
"", &DFSF.F->getEntryBlock().front());
Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
for (unsigned n = 0; i != e; ++i, ++n) {
IRB.CreateStore(
DFSF.getShadow(*i),
IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Args.push_back(*i);
}
}
CallSite NewCS;
if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
NewCS = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
II->getUnwindDest(), Args);
} else {
NewCS = IRB.CreateCall(NewFT, Func, Args);
}
NewCS.setCallingConv(CS.getCallingConv());
NewCS.setAttributes(CS.getAttributes().removeAttributes(
*DFSF.DFS.Ctx, AttributeList::ReturnIndex,
AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
if (Next) {
ExtractValueInst *ExVal =
ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
DFSF.SkipInsts.insert(ExVal);
ExtractValueInst *ExShadow =
ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
DFSF.SkipInsts.insert(ExShadow);
DFSF.setShadow(ExVal, ExShadow);
DFSF.NonZeroChecks.push_back(ExShadow);
CS.getInstruction()->replaceAllUsesWith(ExVal);
}
CS.getInstruction()->eraseFromParent();
}
}
void DFSanVisitor::visitPHINode(PHINode &PN) {
PHINode *ShadowPN =
PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
// Give the shadow phi node valid predecessors to fool SplitEdge into working.
Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
++i) {
ShadowPN->addIncoming(UndefShadow, *i);
}
DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
DFSF.setShadow(&PN, ShadowPN);
}
| {'content_hash': '15366d3e680ac36e04accf5bfeee05d2', 'timestamp': '', 'source': 'github', 'line_count': 1778, 'max_line_length': 81, 'avg_line_length': 37.91169853768279, 'alnum_prop': 0.6581512305843606, 'repo_name': 'GPUOpen-Drivers/llvm', 'id': 'c0353cba0b2fd566261e4533d6839ca2716e36b5', 'size': '67407', 'binary': False, 'copies': '7', 'ref': 'refs/heads/amd-vulkan-dev', 'path': 'lib/Transforms/Instrumentation/DataFlowSanitizer.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '53726601'}, {'name': 'Batchfile', 'bytes': '9235'}, {'name': 'C', 'bytes': '848003'}, {'name': 'C++', 'bytes': '85310923'}, {'name': 'CMake', 'bytes': '530158'}, {'name': 'CSS', 'bytes': '12605'}, {'name': 'Dockerfile', 'bytes': '5884'}, {'name': 'Go', 'bytes': '149213'}, {'name': 'HTML', 'bytes': '37873'}, {'name': 'LLVM', 'bytes': '135880251'}, {'name': 'Logos', 'bytes': '28'}, {'name': 'OCaml', 'bytes': '305839'}, {'name': 'Objective-C', 'bytes': '10226'}, {'name': 'Perl', 'bytes': '25574'}, {'name': 'Python', 'bytes': '993907'}, {'name': 'Roff', 'bytes': '39'}, {'name': 'Shell', 'bytes': '97425'}, {'name': 'Swift', 'bytes': '271'}, {'name': 'Vim script', 'bytes': '17482'}]} |
package signkeys
import (
"crypto/elliptic"
"crypto/rand"
"fmt"
"testing"
"github.com/agl/ed25519"
"github.com/ronperry/cryptoedge/eccutil"
)
func TestKeyGen(t *testing.T) {
pubkey, privkey, _ := ed25519.GenerateKey(rand.Reader)
gen := New(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
gen.PrivateKey = privkey
gen.PublicKey = pubkey
key, err := gen.GenKey()
if err != nil {
t.Fatalf("Key generation failed: %s", err)
}
if !key.PublicKey.Verify(pubkey) {
t.Error("Verification failed")
}
m, err := key.PublicKey.Marshal()
if err != nil {
t.Fatalf("Key marshal failed: %s", err)
}
pk, err := new(PublicKey).Unmarshal(m)
if err != nil {
t.Fatalf("Unmarshal failed: %s", err)
}
if pk.KeyID != key.PublicKey.KeyID {
t.Error("KeyID wrong")
}
if pk.Expire != key.PublicKey.Expire {
t.Error("Expire wrong")
}
if pk.Usage != key.PublicKey.Usage {
t.Error("Usage wrong")
}
if pk.Signature != key.PublicKey.Signature {
t.Error("Signature wrong")
}
if fmt.Sprintf("%d", pk.PublicKey.X) != fmt.Sprintf("%d", key.PublicKey.PublicKey.X) {
t.Error("PublicKey.X wrong")
}
if fmt.Sprintf("%d", pk.PublicKey.Y) != fmt.Sprintf("%d", key.PublicKey.PublicKey.Y) {
t.Error("PublicKey.Y wrong")
}
}
| {'content_hash': '1f7a394d178e4da649347ff80a315901', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 87, 'avg_line_length': 24.15686274509804, 'alnum_prop': 0.6623376623376623, 'repo_name': 'JonathanLogan/mute', 'id': 'b1ceb6886b5b5b2a4090c219b54e7d8a9d40dfe7', 'size': '1384', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'serviceguard/common/signkeys/keys_test.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '343'}, {'name': 'Go', 'bytes': '896986'}, {'name': 'HTML', 'bytes': '4283'}, {'name': 'JavaScript', 'bytes': '4533'}, {'name': 'Makefile', 'bytes': '190'}, {'name': 'Shell', 'bytes': '2490'}]} |
package com.microsoft.azure.management.compute.v2020_06_01;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* Specifies information about the gallery Application Definition that you want
* to update.
*/
@JsonFlatten
public class GalleryApplicationUpdate extends UpdateResourceDefinition {
/**
* The description of this gallery Application Definition resource. This
* property is updatable.
*/
@JsonProperty(value = "properties.description")
private String description;
/**
* The Eula agreement for the gallery Application Definition.
*/
@JsonProperty(value = "properties.eula")
private String eula;
/**
* The privacy statement uri.
*/
@JsonProperty(value = "properties.privacyStatementUri")
private String privacyStatementUri;
/**
* The release note uri.
*/
@JsonProperty(value = "properties.releaseNoteUri")
private String releaseNoteUri;
/**
* The end of life date of the gallery Application Definition. This
* property can be used for decommissioning purposes. This property is
* updatable.
*/
@JsonProperty(value = "properties.endOfLifeDate")
private DateTime endOfLifeDate;
/**
* This property allows you to specify the supported type of the OS that
* application is built for. <br><br> Possible values are:
* <br><br> **Windows** <br><br> **Linux**.
* Possible values include: 'Windows', 'Linux'.
*/
@JsonProperty(value = "properties.supportedOSType", required = true)
private OperatingSystemTypes supportedOSType;
/**
* Get the description of this gallery Application Definition resource. This property is updatable.
*
* @return the description value
*/
public String description() {
return this.description;
}
/**
* Set the description of this gallery Application Definition resource. This property is updatable.
*
* @param description the description value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withDescription(String description) {
this.description = description;
return this;
}
/**
* Get the Eula agreement for the gallery Application Definition.
*
* @return the eula value
*/
public String eula() {
return this.eula;
}
/**
* Set the Eula agreement for the gallery Application Definition.
*
* @param eula the eula value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withEula(String eula) {
this.eula = eula;
return this;
}
/**
* Get the privacy statement uri.
*
* @return the privacyStatementUri value
*/
public String privacyStatementUri() {
return this.privacyStatementUri;
}
/**
* Set the privacy statement uri.
*
* @param privacyStatementUri the privacyStatementUri value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withPrivacyStatementUri(String privacyStatementUri) {
this.privacyStatementUri = privacyStatementUri;
return this;
}
/**
* Get the release note uri.
*
* @return the releaseNoteUri value
*/
public String releaseNoteUri() {
return this.releaseNoteUri;
}
/**
* Set the release note uri.
*
* @param releaseNoteUri the releaseNoteUri value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withReleaseNoteUri(String releaseNoteUri) {
this.releaseNoteUri = releaseNoteUri;
return this;
}
/**
* Get the end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This property is updatable.
*
* @return the endOfLifeDate value
*/
public DateTime endOfLifeDate() {
return this.endOfLifeDate;
}
/**
* Set the end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This property is updatable.
*
* @param endOfLifeDate the endOfLifeDate value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withEndOfLifeDate(DateTime endOfLifeDate) {
this.endOfLifeDate = endOfLifeDate;
return this;
}
/**
* Get this property allows you to specify the supported type of the OS that application is built for. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux**. Possible values include: 'Windows', 'Linux'.
*
* @return the supportedOSType value
*/
public OperatingSystemTypes supportedOSType() {
return this.supportedOSType;
}
/**
* Set this property allows you to specify the supported type of the OS that application is built for. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux**. Possible values include: 'Windows', 'Linux'.
*
* @param supportedOSType the supportedOSType value to set
* @return the GalleryApplicationUpdate object itself.
*/
public GalleryApplicationUpdate withSupportedOSType(OperatingSystemTypes supportedOSType) {
this.supportedOSType = supportedOSType;
return this;
}
}
| {'content_hash': '72b0d7e51251503c2ec5a2314b62f41c', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 258, 'avg_line_length': 31.88135593220339, 'alnum_prop': 0.6726918305865675, 'repo_name': 'selvasingh/azure-sdk-for-java', 'id': '4b387b25646d17e7565b04cb1daec069eb74bc3f', 'size': '5873', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdk/compute/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/compute/v2020_06_01/GalleryApplicationUpdate.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '29891970'}, {'name': 'JavaScript', 'bytes': '6198'}, {'name': 'PowerShell', 'bytes': '160'}, {'name': 'Shell', 'bytes': '609'}]} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_17a.html">Class Test_AbaRouteValidator_17a</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_35779_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a.html?line=16717#src-16717" >testAbaNumberCheck_35779_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:46:08
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_35779_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=11171#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {'content_hash': 'dfab743aa7fbc100c119ff7db5f5b689', 'timestamp': '', 'source': 'github', 'line_count': 209, 'max_line_length': 297, 'avg_line_length': 43.942583732057415, 'alnum_prop': 0.5099085365853658, 'repo_name': 'dcarda/aba.route.validator', 'id': 'e5c941b01a536d8858b31ff1305ea95efa5bdca7', 'size': '9184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a_testAbaNumberCheck_35779_good_8mb.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]} |
using namespace swift;
using namespace ast_scope;
namespace swift {
namespace ast_scope {
#pragma mark ScopeCreator
class ScopeCreator final : public ASTAllocated<ScopeCreator> {
friend class ASTSourceFileScope;
/// For allocating scopes.
ASTContext &ctx;
public:
ASTSourceFileScope *const sourceFileScope;
ASTContext &getASTContext() const { return ctx; }
ScopeCreator(SourceFile *SF)
: ctx(SF->getASTContext()),
sourceFileScope(new (ctx) ASTSourceFileScope(SF, this)) {}
ScopeCreator(const ScopeCreator &) = delete; // ensure no copies
ScopeCreator(const ScopeCreator &&) = delete; // ensure no moves
public:
/// For each of searching, call this unless the insertion point is needed
void addToScopeTree(ASTNode n, ASTScopeImpl *parent) {
(void)addToScopeTreeAndReturnInsertionPoint(n, parent, None);
}
/// Return new insertion point.
/// For ease of searching, don't call unless insertion point is needed
///
/// \param endLoc The end location for any "scopes until the end" that
/// we introduce here, such as PatternEntryDeclScope and GuardStmtScope
ASTScopeImpl *
addToScopeTreeAndReturnInsertionPoint(ASTNode, ASTScopeImpl *parent,
Optional<SourceLoc> endLoc);
template <typename Scope, typename... Args>
ASTScopeImpl *constructExpandAndInsert(ASTScopeImpl *parent, Args... args) {
auto *child = new (ctx) Scope(args...);
parent->addChild(child, ctx);
if (auto *ip = child->insertionPointForDeferredExpansion().getPtrOrNull())
return ip;
ASTScopeImpl *insertionPoint = child->expandAndBeCurrent(*this);
return insertionPoint;
}
public:
template <typename Scope, typename PortionClass, typename... Args>
ASTScopeImpl *constructWithPortionExpandAndInsert(ASTScopeImpl *parent,
Args... args) {
const Portion *portion = new (ctx) PortionClass();
return constructExpandAndInsert<Scope>(parent, portion, args...);
}
void addExprToScopeTree(Expr *expr, ASTScopeImpl *parent) {
// Use the ASTWalker to find buried captures and closures
ASTScopeAssert(expr,
"If looking for closures, must have an expression to search.");
/// AST walker that finds top-level closures in an expression.
class ClosureFinder : public ASTWalker {
ScopeCreator &scopeCreator;
ASTScopeImpl *parent;
public:
ClosureFinder(ScopeCreator &scopeCreator, ASTScopeImpl *parent)
: scopeCreator(scopeCreator), parent(parent) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (auto *closure = dyn_cast<ClosureExpr>(E)) {
scopeCreator
.constructExpandAndInsert<ClosureParametersScope>(
parent, closure);
return {false, E};
}
if (auto *capture = dyn_cast<CaptureListExpr>(E)) {
scopeCreator
.constructExpandAndInsert<CaptureListScope>(
parent, capture);
return {false, E};
}
return {true, E};
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
if (isa<BraceStmt>(S)) { // closures hidden in here
return {true, S};
}
return {false, S};
}
std::pair<bool, Pattern *> walkToPatternPre(Pattern *P) override {
return {false, P};
}
bool walkToDeclPre(Decl *D) override { return false; }
bool walkToTypeReprPre(TypeRepr *T) override { return false; }
bool walkToParameterListPre(ParameterList *PL) override { return false; }
};
expr->walk(ClosureFinder(*this, parent));
}
public:
/// Create the matryoshka nested generic param scopes (if any)
/// that are subscopes of the receiver. Return
/// the furthest descendant.
/// Last GenericParamsScope includes the where clause
ASTScopeImpl *addNestedGenericParamScopesToTree(Decl *parameterizedDecl,
GenericParamList *generics,
ASTScopeImpl *parent) {
if (!generics)
return parent;
auto *s = parent;
for (unsigned i : indices(generics->getParams()))
s = constructExpandAndInsert<GenericParamScope>(
s, parameterizedDecl, generics, i);
return s;
}
void
addChildrenForParsedAccessors(AbstractStorageDecl *asd,
ASTScopeImpl *parent);
void addChildrenForKnownAttributes(ValueDecl *decl,
ASTScopeImpl *parent);
/// Add PatternEntryDeclScopes for each pattern binding entry.
///
/// Returns the new insertion point.
///
/// \param endLoc Must be valid iff the pattern binding is in a local
/// scope, in which case this is the last source location where the
/// pattern bindings are going to be visible.
ASTScopeImpl *
addPatternBindingToScopeTree(PatternBindingDecl *patternBinding,
ASTScopeImpl *parent,
Optional<SourceLoc> endLoc);
SWIFT_DEBUG_DUMP { print(llvm::errs()); }
void print(raw_ostream &out) const {
out << "(swift::ASTSourceFileScope*) " << sourceFileScope << "\n";
}
};
} // ast_scope
} // namespace swift
#pragma mark Scope tree creation and extension
ASTScope::ASTScope(SourceFile *SF) : impl(createScopeTree(SF)) {}
void ASTScope::buildFullyExpandedTree() { impl->buildFullyExpandedTree(); }
void ASTScope::
buildEnoughOfTreeForTopLevelExpressionsButDontRequestGenericsOrExtendedNominals() {
impl->buildEnoughOfTreeForTopLevelExpressionsButDontRequestGenericsOrExtendedNominals();
}
void ASTScope::expandFunctionBody(AbstractFunctionDecl *AFD) {
// There is no source file associated with C++ decl contexts, so there will
// be no parent source file if AFD is a C++ function.
if (auto *const SF = AFD->getParentSourceFile())
SF->getScope().expandFunctionBodyImpl(AFD);
}
void ASTScope::expandFunctionBodyImpl(AbstractFunctionDecl *AFD) {
impl->expandFunctionBody(AFD);
}
ASTSourceFileScope *ASTScope::createScopeTree(SourceFile *SF) {
ScopeCreator *scopeCreator = new (SF->getASTContext()) ScopeCreator(SF);
return scopeCreator->sourceFileScope;
}
void ASTSourceFileScope::buildFullyExpandedTree() {
if (!getWasExpanded())
expandAndBeCurrent(*scopeCreator);
preOrderChildrenDo([&](ASTScopeImpl *s) {
if (!s->getWasExpanded())
s->expandAndBeCurrent(*scopeCreator);
});
}
void ASTSourceFileScope::
buildEnoughOfTreeForTopLevelExpressionsButDontRequestGenericsOrExtendedNominals() {
if (!getWasExpanded())
expandAndBeCurrent(*scopeCreator);
}
void ASTSourceFileScope::expandFunctionBody(AbstractFunctionDecl *AFD) {
if (!AFD)
return;
auto sr = AFD->getOriginalBodySourceRange();
if (sr.isInvalid())
return;
ASTScopeImpl *bodyScope = findInnermostEnclosingScope(sr.Start, nullptr);
if (!bodyScope->getWasExpanded())
bodyScope->expandAndBeCurrent(*scopeCreator);
}
ASTSourceFileScope::ASTSourceFileScope(SourceFile *SF,
ScopeCreator *scopeCreator)
: SF(SF), scopeCreator(scopeCreator) {}
#pragma mark NodeAdder
namespace swift {
namespace ast_scope {
class NodeAdder
: public ASTVisitor<NodeAdder, ASTScopeImpl *,
ASTScopeImpl *, ASTScopeImpl *,
void, void, void, ASTScopeImpl *, ScopeCreator &> {
Optional<SourceLoc> endLoc;
public:
explicit NodeAdder(Optional<SourceLoc> endLoc) : endLoc(endLoc) {}
#pragma mark ASTNodes that do not create scopes
#define VISIT_AND_IGNORE(What) \
ASTScopeImpl *visit##What(What *w, ASTScopeImpl *p, \
ScopeCreator &) { \
return p; \
}
VISIT_AND_IGNORE(ImportDecl)
VISIT_AND_IGNORE(EnumCaseDecl)
VISIT_AND_IGNORE(PrecedenceGroupDecl)
VISIT_AND_IGNORE(InfixOperatorDecl)
VISIT_AND_IGNORE(PrefixOperatorDecl)
VISIT_AND_IGNORE(PostfixOperatorDecl)
VISIT_AND_IGNORE(GenericTypeParamDecl)
VISIT_AND_IGNORE(AssociatedTypeDecl)
VISIT_AND_IGNORE(ModuleDecl)
VISIT_AND_IGNORE(ParamDecl)
VISIT_AND_IGNORE(PoundDiagnosticDecl)
VISIT_AND_IGNORE(MissingMemberDecl)
// Only members of the active clause are in scope, and those
// are visited separately.
VISIT_AND_IGNORE(IfConfigDecl)
// This declaration is handled from the PatternBindingDecl
VISIT_AND_IGNORE(VarDecl)
// These contain nothing to scope.
VISIT_AND_IGNORE(BreakStmt)
VISIT_AND_IGNORE(ContinueStmt)
VISIT_AND_IGNORE(FallthroughStmt)
VISIT_AND_IGNORE(FailStmt)
#undef VISIT_AND_IGNORE
#pragma mark simple creation ignoring deferred nodes
#define VISIT_AND_CREATE(What, ScopeClass) \
ASTScopeImpl *visit##What(What *w, ASTScopeImpl *p, \
ScopeCreator &scopeCreator) { \
return scopeCreator.constructExpandAndInsert<ScopeClass>(p, w); \
}
VISIT_AND_CREATE(SubscriptDecl, SubscriptDeclScope)
VISIT_AND_CREATE(IfStmt, IfStmtScope)
VISIT_AND_CREATE(WhileStmt, WhileStmtScope)
VISIT_AND_CREATE(RepeatWhileStmt, RepeatWhileScope)
VISIT_AND_CREATE(DoStmt, DoStmtScope)
VISIT_AND_CREATE(DoCatchStmt, DoCatchStmtScope)
VISIT_AND_CREATE(SwitchStmt, SwitchStmtScope)
VISIT_AND_CREATE(ForEachStmt, ForEachStmtScope)
VISIT_AND_CREATE(CaseStmt, CaseStmtScope)
VISIT_AND_CREATE(AbstractFunctionDecl, AbstractFunctionDeclScope)
#undef VISIT_AND_CREATE
#pragma mark 2D simple creation (ignoring deferred nodes)
#define VISIT_AND_CREATE_WHOLE_PORTION(What, WhatScope) \
ASTScopeImpl *visit##What(What *w, ASTScopeImpl *p, \
ScopeCreator &scopeCreator) { \
return scopeCreator.constructWithPortionExpandAndInsert< \
WhatScope, GenericTypeOrExtensionWholePortion>(p, w); \
}
VISIT_AND_CREATE_WHOLE_PORTION(ExtensionDecl, ExtensionScope)
VISIT_AND_CREATE_WHOLE_PORTION(StructDecl, NominalTypeScope)
VISIT_AND_CREATE_WHOLE_PORTION(ClassDecl, NominalTypeScope)
VISIT_AND_CREATE_WHOLE_PORTION(ProtocolDecl, NominalTypeScope)
VISIT_AND_CREATE_WHOLE_PORTION(EnumDecl, NominalTypeScope)
VISIT_AND_CREATE_WHOLE_PORTION(TypeAliasDecl, TypeAliasScope)
VISIT_AND_CREATE_WHOLE_PORTION(OpaqueTypeDecl, OpaqueTypeScope)
#undef VISIT_AND_CREATE_WHOLE_PORTION
// This declaration is handled from
// addChildrenForParsedAccessors
ASTScopeImpl *visitAccessorDecl(AccessorDecl *ad, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
return visitAbstractFunctionDecl(ad, p, scopeCreator);
}
#pragma mark simple creation with deferred nodes
// Each of the following creates a new scope, so that nodes which were parsed
// after them need to be placed in scopes BELOW them in the tree. So pass down
// the deferred nodes.
ASTScopeImpl *visitGuardStmt(GuardStmt *e, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
ASTScopeAssert(endLoc.hasValue(), "GuardStmt outside of a BraceStmt?");
return scopeCreator.constructExpandAndInsert<GuardStmtScope>(
p, e, *endLoc);
}
ASTScopeImpl *visitTopLevelCodeDecl(TopLevelCodeDecl *d,
ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
ASTScopeAssert(endLoc.hasValue(), "TopLevelCodeDecl in wrong place?");
return scopeCreator.constructExpandAndInsert<TopLevelCodeScope>(
p, d, *endLoc);
}
#pragma mark special-case creation
ASTScopeImpl *visitSourceFile(SourceFile *, ASTScopeImpl *, ScopeCreator &) {
ASTScope_unreachable("SourceFiles are orphans.");
}
ASTScopeImpl *visitYieldStmt(YieldStmt *ys, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
for (Expr *e : ys->getYields())
visitExpr(e, p, scopeCreator);
return p;
}
ASTScopeImpl *visitDeferStmt(DeferStmt *ds, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
visitFuncDecl(ds->getTempDecl(), p, scopeCreator);
return p;
}
ASTScopeImpl *visitBraceStmt(BraceStmt *bs, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
if (bs->empty())
return p;
SmallVector<ValueDecl *, 2> localFuncsAndTypes;
SmallVector<VarDecl *, 2> localVars;
// All types and functions are visible anywhere within a brace statement
// scope. When ordering matters (i.e. var decl) we will have split the brace
// statement into nested scopes.
for (auto braceElement : bs->getElements()) {
if (auto localBinding = braceElement.dyn_cast<Decl *>()) {
if (auto *vd = dyn_cast<ValueDecl>(localBinding)) {
if (isa<FuncDecl>(vd) || isa<TypeDecl>(vd)) {
localFuncsAndTypes.push_back(vd);
} else if (auto *var = dyn_cast<VarDecl>(localBinding)) {
localVars.push_back(var);
}
}
}
}
SourceLoc endLocForBraceStmt = bs->getEndLoc();
if (endLoc.hasValue())
endLocForBraceStmt = *endLoc;
ASTContext &ctx = scopeCreator.getASTContext();
return
scopeCreator.constructExpandAndInsert<BraceStmtScope>(
p, bs,
ctx.AllocateCopy(localFuncsAndTypes),
ctx.AllocateCopy(localVars),
endLocForBraceStmt);
}
ASTScopeImpl *
visitPatternBindingDecl(PatternBindingDecl *patternBinding,
ASTScopeImpl *parentScope,
ScopeCreator &scopeCreator) {
return scopeCreator.addPatternBindingToScopeTree(
patternBinding, parentScope, endLoc);
}
ASTScopeImpl *visitEnumElementDecl(EnumElementDecl *eed,
ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
scopeCreator.constructExpandAndInsert<EnumElementScope>(p, eed);
return p;
}
ASTScopeImpl *visitReturnStmt(ReturnStmt *rs, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
if (rs->hasResult())
visitExpr(rs->getResult(), p, scopeCreator);
return p;
}
ASTScopeImpl *visitThrowStmt(ThrowStmt *ts, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
visitExpr(ts->getSubExpr(), p, scopeCreator);
return p;
}
ASTScopeImpl *visitPoundAssertStmt(PoundAssertStmt *pas,
ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
visitExpr(pas->getCondition(), p, scopeCreator);
return p;
}
ASTScopeImpl *visitExpr(Expr *expr, ASTScopeImpl *p,
ScopeCreator &scopeCreator) {
if (expr)
scopeCreator.addExprToScopeTree(expr, p);
return p;
}
};
} // namespace ast_scope
} // namespace swift
// These definitions are way down here so it can call into
// NodeAdder
ASTScopeImpl *
ScopeCreator::addToScopeTreeAndReturnInsertionPoint(ASTNode n,
ASTScopeImpl *parent,
Optional<SourceLoc> endLoc) {
if (!n)
return parent;
// HACK: LLDB creates implicit pattern bindings that... contain user
// expressions. We need to actually honor lookups through those bindings
// in case they contain closures that bind additional variables in further
// scopes.
if (auto *d = n.dyn_cast<Decl *>())
if (d->isImplicit())
if (!isa<PatternBindingDecl>(d)
|| !cast<PatternBindingDecl>(d)->isDebuggerBinding())
return parent;
NodeAdder adder(endLoc);
if (auto *p = n.dyn_cast<Decl *>())
return adder.visit(p, parent, *this);
if (auto *p = n.dyn_cast<Expr *>())
return adder.visit(p, parent, *this);
auto *p = n.get<Stmt *>();
return adder.visit(p, parent, *this);
}
void ScopeCreator::addChildrenForParsedAccessors(
AbstractStorageDecl *asd, ASTScopeImpl *parent) {
asd->visitParsedAccessors([&](AccessorDecl *ad) {
assert(asd == ad->getStorage());
this->addToScopeTree(ad, parent);
});
}
void ScopeCreator::addChildrenForKnownAttributes(ValueDecl *decl,
ASTScopeImpl *parent) {
SmallVector<DeclAttribute *, 2> relevantAttrs;
for (auto *attr : decl->getAttrs()) {
if (attr->isImplicit())
continue;
if (isa<DifferentiableAttr>(attr))
relevantAttrs.push_back(attr);
if (isa<SpecializeAttr>(attr))
relevantAttrs.push_back(attr);
if (isa<CustomAttr>(attr))
relevantAttrs.push_back(attr);
}
// Decl::getAttrs() is a linked list with head insertion, so the
// attributes are in reverse source order.
std::reverse(relevantAttrs.begin(), relevantAttrs.end());
for (auto *attr : relevantAttrs) {
if (auto *diffAttr = dyn_cast<DifferentiableAttr>(attr)) {
constructExpandAndInsert<DifferentiableAttributeScope>(
parent, diffAttr, decl);
} else if (auto *specAttr = dyn_cast<SpecializeAttr>(attr)) {
if (auto *afd = dyn_cast<AbstractFunctionDecl>(decl)) {
constructExpandAndInsert<SpecializeAttributeScope>(
parent, specAttr, afd);
}
} else if (auto *customAttr = dyn_cast<CustomAttr>(attr)) {
if (auto *vd = dyn_cast<VarDecl>(decl)) {
constructExpandAndInsert<AttachedPropertyWrapperScope>(
parent, customAttr, vd);
}
}
}
}
ASTScopeImpl *
ScopeCreator::addPatternBindingToScopeTree(PatternBindingDecl *patternBinding,
ASTScopeImpl *parentScope,
Optional<SourceLoc> endLoc) {
if (auto *var = patternBinding->getSingleVar())
addChildrenForKnownAttributes(var, parentScope);
bool isLocalBinding = false;
for (auto i : range(patternBinding->getNumPatternEntries())) {
if (auto *varDecl = patternBinding->getAnchoringVarDecl(i)) {
isLocalBinding = varDecl->getDeclContext()->isLocalContext();
break;
}
}
auto *insertionPoint = parentScope;
for (auto i : range(patternBinding->getNumPatternEntries())) {
Optional<SourceLoc> endLocForBinding = None;
if (isLocalBinding) {
endLocForBinding = endLoc;
ASTScopeAssert(endLoc.hasValue() && endLoc->isValid(),
"PatternBindingDecl in local context outside of BraceStmt?");
}
insertionPoint =
constructExpandAndInsert<PatternEntryDeclScope>(
insertionPoint, patternBinding, i,
isLocalBinding, endLocForBinding);
ASTScopeAssert(isLocalBinding || insertionPoint == parentScope,
"Bindings at the top-level or members of types should "
"not change the insertion point");
}
return insertionPoint;
}
#pragma mark creation helpers
void ASTScopeImpl::addChild(ASTScopeImpl *child, ASTContext &ctx) {
ASTScopeAssert(!child->getParent(), "child should not already have parent");
child->parentAndWasExpanded.setPointer(this);
#ifndef NDEBUG
checkSourceRangeBeforeAddingChild(child, ctx);
#endif
// If this is the first time we've added children, notify the ASTContext
// that there's a SmallVector that needs to be cleaned up.
if (storedChildren.empty())
ctx.addDestructorCleanup(storedChildren);
storedChildren.push_back(child);
}
#pragma mark implementations of expansion
ASTScopeImpl *ASTScopeImpl::expandAndBeCurrent(ScopeCreator &scopeCreator) {
ASTScopeAssert(!getWasExpanded(),
"Cannot expand the same scope twice");
// Set the flag before we actually expand, to detect re-entrant calls
// via the above assertion.
setWasExpanded();
if (auto *s = scopeCreator.getASTContext().Stats)
++s->getFrontendCounters().NumASTScopeExpansions;
auto *insertionPoint = expandSpecifically(scopeCreator);
ASTScopeAssert(!insertionPointForDeferredExpansion() ||
insertionPointForDeferredExpansion().get() ==
insertionPoint,
"In order for lookups into lazily-expanded scopes to be "
"accurate before expansion, the insertion point before "
"expansion must be the same as after expansion.");
return insertionPoint;
}
// Do this whole bit so it's easy to see which type of scope is which
#define CREATES_NEW_INSERTION_POINT(Scope) \
ASTScopeImpl *Scope::expandSpecifically(ScopeCreator &scopeCreator) { \
return expandAScopeThatCreatesANewInsertionPoint(scopeCreator) \
.insertionPoint; \
}
#define NO_NEW_INSERTION_POINT(Scope) \
ASTScopeImpl *Scope::expandSpecifically(ScopeCreator &scopeCreator) { \
expandAScopeThatDoesNotCreateANewInsertionPoint(scopeCreator); \
return getParent().get(); \
}
// Return this in particular for GenericParamScope so body is scoped under it
#define NO_EXPANSION(Scope) \
ASTScopeImpl *Scope::expandSpecifically(ScopeCreator &) { return this; }
CREATES_NEW_INSERTION_POINT(ASTSourceFileScope)
CREATES_NEW_INSERTION_POINT(GuardStmtScope)
CREATES_NEW_INSERTION_POINT(PatternEntryDeclScope)
CREATES_NEW_INSERTION_POINT(GenericTypeOrExtensionScope)
CREATES_NEW_INSERTION_POINT(BraceStmtScope)
CREATES_NEW_INSERTION_POINT(TopLevelCodeScope)
CREATES_NEW_INSERTION_POINT(ConditionalClausePatternUseScope)
NO_NEW_INSERTION_POINT(FunctionBodyScope)
NO_NEW_INSERTION_POINT(AbstractFunctionDeclScope)
NO_NEW_INSERTION_POINT(AttachedPropertyWrapperScope)
NO_NEW_INSERTION_POINT(EnumElementScope)
NO_NEW_INSERTION_POINT(GuardStmtBodyScope)
NO_NEW_INSERTION_POINT(ParameterListScope)
NO_NEW_INSERTION_POINT(PatternEntryInitializerScope)
NO_NEW_INSERTION_POINT(CaptureListScope)
NO_NEW_INSERTION_POINT(CaseStmtScope)
NO_NEW_INSERTION_POINT(CaseLabelItemScope)
NO_NEW_INSERTION_POINT(CaseStmtBodyScope)
NO_NEW_INSERTION_POINT(ConditionalClauseInitializerScope)
NO_NEW_INSERTION_POINT(ClosureParametersScope)
NO_NEW_INSERTION_POINT(DefaultArgumentInitializerScope)
NO_NEW_INSERTION_POINT(DoStmtScope)
NO_NEW_INSERTION_POINT(DoCatchStmtScope)
NO_NEW_INSERTION_POINT(ForEachPatternScope)
NO_NEW_INSERTION_POINT(ForEachStmtScope)
NO_NEW_INSERTION_POINT(IfStmtScope)
NO_NEW_INSERTION_POINT(RepeatWhileScope)
NO_NEW_INSERTION_POINT(SubscriptDeclScope)
NO_NEW_INSERTION_POINT(SwitchStmtScope)
NO_NEW_INSERTION_POINT(WhileStmtScope)
NO_EXPANSION(GenericParamScope)
NO_EXPANSION(SpecializeAttributeScope)
NO_EXPANSION(DifferentiableAttributeScope)
#undef CREATES_NEW_INSERTION_POINT
#undef NO_NEW_INSERTION_POINT
AnnotatedInsertionPoint
ASTSourceFileScope::expandAScopeThatCreatesANewInsertionPoint(
ScopeCreator &scopeCreator) {
ASTScopeAssert(SF, "Must already have a SourceFile.");
SourceLoc endLoc = getSourceRangeOfThisASTNode().End;
ASTScopeImpl *insertionPoint = this;
for (auto *d : SF->getTopLevelDecls()) {
insertionPoint = scopeCreator.addToScopeTreeAndReturnInsertionPoint(
ASTNode(d), insertionPoint, endLoc);
}
return {insertionPoint, "Next time decls are added they go here."};
}
void
ParameterListScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
// Each initializer for a function parameter is its own, sibling, scope.
// Unlike generic parameters or pattern initializers, it cannot refer to a
// previous parameter.
for (ParamDecl *pd : params->getArray()) {
if (pd->hasDefaultExpr())
scopeCreator
.constructExpandAndInsert<DefaultArgumentInitializerScope>(
this, pd);
}
}
AnnotatedInsertionPoint
PatternEntryDeclScope::expandAScopeThatCreatesANewInsertionPoint(
ScopeCreator &scopeCreator) {
// Initializers come before VarDecls, e.g. PCMacro/didSet.swift 19
auto patternEntry = getPatternEntry();
// Create a child for the initializer, if present.
// Cannot trust the source range given in the ASTScopeImpl for the end of the
// initializer (because of InterpolatedLiteralStrings and EditorPlaceHolders),
// so compute it ourselves.
// Even if this predicate fails, there may be an initContext but
// we cannot make a scope for it, since no source range.
if (patternEntry.getOriginalInit()) {
ASTScopeAssert(
patternEntry.getOriginalInit()->getSourceRange().isValid(),
"pattern initializer has invalid source range");
ASTScopeAssert(
!getSourceManager().isBeforeInBuffer(
patternEntry.getOriginalInit()->getStartLoc(), decl->getStartLoc()),
"Original inits are always after the '='");
scopeCreator
.constructExpandAndInsert<PatternEntryInitializerScope>(
this, decl, patternEntryIndex);
}
// If this pattern binding entry was created by the debugger, it will always
// have a synthesized init that is created from user code. We special-case
// lookups into these scopes to look through the debugger's chicanery to the
// underlying user-defined scopes, if any.
if (patternEntry.isFromDebugger() && patternEntry.getInit()) {
ASTScopeAssert(
patternEntry.getInit()->getSourceRange().isValid(),
"pattern initializer has invalid source range");
ASTScopeAssert(
!getSourceManager().isBeforeInBuffer(
patternEntry.getInit()->getStartLoc(), decl->getStartLoc()),
"inits are always after the '='");
scopeCreator
.constructExpandAndInsert<PatternEntryInitializerScope>(
this, decl, patternEntryIndex);
}
// Add accessors for the variables in this pattern.
patternEntry.getPattern()->forEachVariable([&](VarDecl *var) {
scopeCreator.addChildrenForParsedAccessors(var, this);
});
// In local context, the PatternEntryDeclScope becomes the insertion point, so
// that all any bindings introduecd by the pattern are in scope for subsequent
// lookups.
if (isLocalBinding)
return {this, "All code that follows is inside this scope"};
return {getParent().get(), "Global and type members do not introduce scopes"};
}
void
PatternEntryInitializerScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
// Create a child for the initializer expression.
scopeCreator.addToScopeTree(ASTNode(initAsWrittenWhenCreated), this);
}
AnnotatedInsertionPoint
ConditionalClausePatternUseScope::expandAScopeThatCreatesANewInsertionPoint(
ScopeCreator &scopeCreator) {
auto *initializer = sec.getInitializer();
if (!isa<ErrorExpr>(initializer)) {
scopeCreator
.constructExpandAndInsert<ConditionalClauseInitializerScope>(
this, initializer);
}
return {this,
"Succeeding code must be in scope of conditional clause pattern bindings"};
}
void
ConditionalClauseInitializerScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(ASTNode(initializer), this);
}
void
GuardStmtBodyScope::expandAScopeThatDoesNotCreateANewInsertionPoint(ScopeCreator &
scopeCreator) {
scopeCreator.addToScopeTree(ASTNode(body), this);
}
AnnotatedInsertionPoint
GuardStmtScope::expandAScopeThatCreatesANewInsertionPoint(ScopeCreator &
scopeCreator) {
ASTScopeImpl *conditionLookupParent =
createNestedConditionalClauseScopes(scopeCreator, endLoc);
// Add a child for the 'guard' body, which always exits.
// The lookup parent is whole guard stmt scope, NOT the cond scopes
auto *body = stmt->getBody();
if (!body->empty()) {
scopeCreator
.constructExpandAndInsert<GuardStmtBodyScope>(
conditionLookupParent, this, stmt->getBody());
}
return {conditionLookupParent,
"Succeeding code must be in scope of guard variables"};
}
AnnotatedInsertionPoint
GenericTypeOrExtensionScope::expandAScopeThatCreatesANewInsertionPoint(
ScopeCreator & scopeCreator) {
return {portion->expandScope(this, scopeCreator),
"<X: Foo, Y: X> is legal, so nest these"};
}
AnnotatedInsertionPoint
BraceStmtScope::expandAScopeThatCreatesANewInsertionPoint(
ScopeCreator &scopeCreator) {
ASTScopeImpl *insertionPoint = this;
for (auto nd : stmt->getElements()) {
insertionPoint = scopeCreator.addToScopeTreeAndReturnInsertionPoint(
nd, insertionPoint, endLoc);
}
return {
insertionPoint,
"For top-level code decls, need the scope under, say a guard statment."};
}
AnnotatedInsertionPoint
TopLevelCodeScope::expandAScopeThatCreatesANewInsertionPoint(ScopeCreator &
scopeCreator) {
auto *body =
scopeCreator
.addToScopeTreeAndReturnInsertionPoint(decl->getBody(), this, endLoc);
return {body, "So next top level code scope and put its decls in its body "
"under a guard statement scope (etc) from the last top level "
"code scope"};
}
#pragma mark expandAScopeThatDoesNotCreateANewInsertionPoint
// Create child scopes for every declaration in a body.
void AbstractFunctionDeclScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addChildrenForKnownAttributes(decl, this);
// Create scopes for generic and ordinary parameters.
// For a subscript declaration, the generic and ordinary parameters are in an
// ancestor scope, so don't make them here.
ASTScopeImpl *leaf = this;
if (!isa<AccessorDecl>(decl)) {
leaf = scopeCreator.addNestedGenericParamScopesToTree(
decl, decl->getGenericParams(), leaf);
auto *params = decl->getParameters();
if (params->size() > 0) {
scopeCreator.constructExpandAndInsert<ParameterListScope>(
leaf, params, nullptr);
}
}
// Create scope for the body.
// We create body scopes when there is no body for source kit to complete
// erroneous code in bodies.
if (decl->getBodySourceRange().isValid()) {
scopeCreator.constructExpandAndInsert<FunctionBodyScope>(leaf, decl);
}
}
void EnumElementScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
if (auto *pl = decl->getParameterList())
scopeCreator.constructExpandAndInsert<ParameterListScope>(this, pl, nullptr);
// The invariant that the raw value expression can never introduce a new scope
// is checked in Parse. However, this guarantee is not future-proof. Compute
// and add the raw value expression anyways just to be defensive.
//
// FIXME: Re-enable this. It currently crashes for malformed enum cases.
// scopeCreator.addToScopeTree(decl->getStructuralRawValueExpr(), this);
}
void FunctionBodyScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
expandBody(scopeCreator);
}
void IfStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
auto *thenStmt = stmt->getThenStmt();
auto *elseStmt = stmt->getElseStmt();
SourceLoc endLoc = thenStmt->getEndLoc();
ASTScopeImpl *insertionPoint =
createNestedConditionalClauseScopes(scopeCreator, endLoc);
// The 'then' branch
scopeCreator.addToScopeTree(thenStmt, insertionPoint);
// Result builders can add an 'else' block consisting entirely of
// implicit expressions. In this case, the end location of the
// 'then' block is equal to the start location of the 'else'
// block, and the 'else' block source range is empty.
if (elseStmt &&
thenStmt->getEndLoc() == elseStmt->getStartLoc() &&
elseStmt->getStartLoc() == elseStmt->getEndLoc())
return;
// Add the 'else' branch, if needed.
scopeCreator.addToScopeTree(elseStmt, this);
}
void WhileStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
SourceLoc endLoc = stmt->getBody()->getEndLoc();
ASTScopeImpl *insertionPoint =
createNestedConditionalClauseScopes(scopeCreator, endLoc);
scopeCreator.addToScopeTree(stmt->getBody(), insertionPoint);
}
void RepeatWhileScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getBody(), this);
scopeCreator.addToScopeTree(stmt->getCond(), this);
}
void DoStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getBody(), this);
}
void DoCatchStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getBody(), this);
for (auto catchClause : stmt->getCatches())
scopeCreator.addToScopeTree(catchClause, this);
}
void SwitchStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getSubjectExpr(), this);
for (auto caseStmt : stmt->getCases()) {
ASTScopeAssert(
caseStmt->getSourceRange().isValid(),
"pattern initializer has invalid source range");
scopeCreator.constructExpandAndInsert<CaseStmtScope>(this, caseStmt);
}
}
void ForEachStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getSequence(), this);
// Add a child describing the scope of the pattern.
// In error cases such as:
// let v: C { for b : Int -> S((array: P { }
// the body is implicit and it would overlap the source range of the expr
// above.
if (!stmt->getBody()->isImplicit()) {
ASTScopeAssert(
stmt->getBody()->getSourceRange().isValid(),
"pattern initializer has invalid source range");
scopeCreator.constructExpandAndInsert<ForEachPatternScope>(this, stmt);
}
}
void ForEachPatternScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getWhere(), this);
scopeCreator.addToScopeTree(stmt->getBody(), this);
}
void CaseStmtScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
for (auto &item : stmt->getCaseLabelItems()) {
if (item.getGuardExpr()) {
scopeCreator.constructExpandAndInsert<CaseLabelItemScope>(this, item);
}
}
if (!stmt->getBody()->empty()) {
scopeCreator.constructExpandAndInsert<CaseStmtBodyScope>(this, stmt);
}
}
void CaseLabelItemScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(item.getGuardExpr(), this);
}
void CaseStmtBodyScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(stmt->getBody(), this);
}
void SubscriptDeclScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addChildrenForKnownAttributes(decl, this);
auto *leaf = scopeCreator.addNestedGenericParamScopesToTree(
decl, decl->getGenericParams(), this);
scopeCreator.constructExpandAndInsert<ParameterListScope>(
leaf, decl->getIndices(), decl->getAccessor(AccessorKind::Get));
scopeCreator.addChildrenForParsedAccessors(decl, leaf);
}
void CaptureListScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
auto *closureExpr = expr->getClosureBody();
scopeCreator
.constructExpandAndInsert<ClosureParametersScope>(this, closureExpr);
}
void ClosureParametersScope::expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(closureExpr->getBody(), this);
}
void DefaultArgumentInitializerScope::
expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
auto *initExpr = decl->getStructuralDefaultExpr();
ASTScopeAssert(initExpr,
"Default argument initializer must have an initializer.");
scopeCreator.addToScopeTree(initExpr, this);
}
void AttachedPropertyWrapperScope::
expandAScopeThatDoesNotCreateANewInsertionPoint(
ScopeCreator &scopeCreator) {
if (auto *expr = attr->getArg())
scopeCreator.addToScopeTree(expr, this);
}
#pragma mark expandScope
ASTScopeImpl *GenericTypeOrExtensionWholePortion::expandScope(
GenericTypeOrExtensionScope *scope, ScopeCreator &scopeCreator) const {
// Get now in case recursion emancipates scope
auto *const ip = scope->getParent().get();
auto *context = scope->getGenericContext();
auto *genericParams = (isa<TypeAliasDecl>(context)
? context->getParsedGenericParams()
: context->getGenericParams());
auto *deepestScope = scopeCreator.addNestedGenericParamScopesToTree(
scope->getDecl(), genericParams, scope);
if (context->getTrailingWhereClause())
scope->createTrailingWhereClauseScope(deepestScope, scopeCreator);
// Prevent circular request bugs caused by illegal input and
// doing lookups that getExtendedNominal in the midst of getExtendedNominal.
if (scope->shouldHaveABody() && !scope->doesDeclHaveABody())
return ip;
scope->createBodyScope(deepestScope, scopeCreator);
return ip;
}
ASTScopeImpl *
IterableTypeBodyPortion::expandScope(GenericTypeOrExtensionScope *scope,
ScopeCreator &scopeCreator) const {
// Get it now in case of recursion and this one gets emancipated
auto *const ip = scope->getParent().get();
scope->expandBody(scopeCreator);
return ip;
}
ASTScopeImpl *GenericTypeOrExtensionWherePortion::expandScope(
GenericTypeOrExtensionScope *scope, ScopeCreator &) const {
return scope->getParent().get();
}
#pragma mark createBodyScope
void ExtensionScope::createBodyScope(ASTScopeImpl *leaf,
ScopeCreator &scopeCreator) {
scopeCreator.constructWithPortionExpandAndInsert<ExtensionScope,
IterableTypeBodyPortion>(
leaf, decl);
}
void NominalTypeScope::createBodyScope(ASTScopeImpl *leaf,
ScopeCreator &scopeCreator) {
scopeCreator.constructWithPortionExpandAndInsert<NominalTypeScope,
IterableTypeBodyPortion>(
leaf, decl);
}
#pragma mark createTrailingWhereClauseScope
ASTScopeImpl *GenericTypeOrExtensionScope::createTrailingWhereClauseScope(
ASTScopeImpl *parent, ScopeCreator &scopeCreator) {
return parent;
}
ASTScopeImpl *
ExtensionScope::createTrailingWhereClauseScope(ASTScopeImpl *parent,
ScopeCreator &scopeCreator) {
return scopeCreator.constructWithPortionExpandAndInsert<
ExtensionScope, GenericTypeOrExtensionWherePortion>(parent, decl);
}
ASTScopeImpl *
NominalTypeScope::createTrailingWhereClauseScope(ASTScopeImpl *parent,
ScopeCreator &scopeCreator) {
return scopeCreator.constructWithPortionExpandAndInsert<
NominalTypeScope, GenericTypeOrExtensionWherePortion>(parent, decl);
}
ASTScopeImpl *
TypeAliasScope::createTrailingWhereClauseScope(ASTScopeImpl *parent,
ScopeCreator &scopeCreator) {
return scopeCreator.constructWithPortionExpandAndInsert<
TypeAliasScope, GenericTypeOrExtensionWherePortion>(parent, decl);
}
#pragma mark misc
ASTScopeImpl *LabeledConditionalStmtScope::createNestedConditionalClauseScopes(
ScopeCreator &scopeCreator, SourceLoc endLoc) {
auto *stmt = getLabeledConditionalStmt();
ASTScopeImpl *insertionPoint = this;
for (auto &sec : stmt->getCond()) {
switch (sec.getKind()) {
case StmtConditionElement::CK_Availability:
break;
case StmtConditionElement::CK_Boolean:
scopeCreator.addToScopeTree(sec.getBoolean(), insertionPoint);
break;
case StmtConditionElement::CK_PatternBinding:
insertionPoint =
scopeCreator.constructExpandAndInsert<
ConditionalClausePatternUseScope>(
insertionPoint, sec, endLoc);
break;
}
}
return insertionPoint;
}
AbstractPatternEntryScope::AbstractPatternEntryScope(
PatternBindingDecl *declBeingScoped, unsigned entryIndex)
: decl(declBeingScoped), patternEntryIndex(entryIndex) {
ASTScopeAssert(entryIndex < declBeingScoped->getPatternList().size(),
"out of bounds");
}
#pragma mark - expandBody
void FunctionBodyScope::expandBody(ScopeCreator &scopeCreator) {
scopeCreator.addToScopeTree(decl->getBody(), this);
}
void GenericTypeOrExtensionScope::expandBody(ScopeCreator &) {}
void IterableTypeScope::expandBody(ScopeCreator &scopeCreator) {
for (auto *d : getIterableDeclContext().get()->getMembers())
scopeCreator.addToScopeTree(ASTNode(d), this);
}
#pragma mark getScopeCreator
ScopeCreator &ASTScopeImpl::getScopeCreator() {
return getParent().get()->getScopeCreator();
}
ScopeCreator &ASTSourceFileScope::getScopeCreator() { return *scopeCreator; }
#pragma mark currency
NullablePtr<ASTScopeImpl> ASTScopeImpl::insertionPointForDeferredExpansion() {
return nullptr;
}
NullablePtr<ASTScopeImpl>
FunctionBodyScope::insertionPointForDeferredExpansion() {
return getParent().get();
}
NullablePtr<ASTScopeImpl>
IterableTypeScope::insertionPointForDeferredExpansion() {
return portion->insertionPointForDeferredExpansion(this);
}
NullablePtr<ASTScopeImpl>
GenericTypeOrExtensionWholePortion::insertionPointForDeferredExpansion(
IterableTypeScope *s) const {
return s->getParent().get();
}
NullablePtr<ASTScopeImpl>
GenericTypeOrExtensionWherePortion::insertionPointForDeferredExpansion(
IterableTypeScope *) const {
return nullptr;
}
NullablePtr<ASTScopeImpl>
IterableTypeBodyPortion::insertionPointForDeferredExpansion(
IterableTypeScope *s) const {
return s->getParent().get();
}
#pragma mark verification
void ast_scope::simple_display(llvm::raw_ostream &out,
const ScopeCreator *scopeCreator) {
scopeCreator->print(out);
}
| {'content_hash': 'daa2f5c7ece57292bbcfdcf9652c712d', 'timestamp': '', 'source': 'github', 'line_count': 1174, 'max_line_length': 90, 'avg_line_length': 36.16354344122657, 'alnum_prop': 0.6962973431317129, 'repo_name': 'hooman/swift', 'id': 'b7b78abdd0daf78a83504b467e7409041c10c0c3', 'size': '43817', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'lib/AST/ASTScopeCreation.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2144'}, {'name': 'Batchfile', 'bytes': '34'}, {'name': 'C', 'bytes': '71921'}, {'name': 'C++', 'bytes': '24871779'}, {'name': 'CMake', 'bytes': '371873'}, {'name': 'D', 'bytes': '1107'}, {'name': 'DTrace', 'bytes': '2438'}, {'name': 'Emacs Lisp', 'bytes': '56890'}, {'name': 'LLVM', 'bytes': '59756'}, {'name': 'Makefile', 'bytes': '1841'}, {'name': 'Objective-C', 'bytes': '295313'}, {'name': 'Objective-C++', 'bytes': '205449'}, {'name': 'Perl', 'bytes': '2211'}, {'name': 'Python', 'bytes': '851559'}, {'name': 'Ruby', 'bytes': '2091'}, {'name': 'Shell', 'bytes': '193166'}, {'name': 'Swift', 'bytes': '20324899'}, {'name': 'Vim script', 'bytes': '13962'}]} |
package com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link DuplicateMapKeys} check.
*
* @author [email protected] (Sumit Bhagwani)
*/
@RunWith(JUnit4.class)
public class DuplicateMapKeysTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(DuplicateMapKeys.class, getClass());
@Test
public void testPositiveCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import static java.util.Map.entry;",
"import java.util.Map;",
"class A {",
" public static void test() {",
" // BUG: Diagnostic contains: Foo",
" Map<String, String> map = Map.ofEntries(",
" entry(\"Foo\", \"Bar\"),",
" entry(\"Ping\", \"Pong\"),",
" entry(\"Kit\", \"Kat\"),",
" entry(\"Foo\", \"Bar\"));",
" }",
"}")
.doTest();
}
@Test
public void testNegativeCase() {
compilationHelper
.addSourceLines(
"a/A.java",
"package a;",
"import static java.util.Map.entry;",
"import java.util.Map;",
"class A {",
" public static void test() {",
" Map<String, String> map = Map.ofEntries(",
" entry(\"Foo\", \"Bar\"),",
" entry(\"Ping\", \"Pong\"),",
" entry(\"Kit\", \"Kat\"),",
" entry(\"Food\", \"Bar\"));",
" }",
"}")
.doTest();
}
}
| {'content_hash': '05b2ed28f30900bbef99a92624fafad3', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 76, 'avg_line_length': 28.508196721311474, 'alnum_prop': 0.4997124784358827, 'repo_name': 'google/error-prone', 'id': 'd80f0314f8af623f10b352f79e51d922e1653e65', 'size': '2346', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/test/java/com/google/errorprone/bugpatterns/DuplicateMapKeysTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '9329704'}, {'name': 'Mustache', 'bytes': '1939'}, {'name': 'Shell', 'bytes': '1915'}, {'name': 'Starlark', 'bytes': '959'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'ac29eccbef50121e070ac6162532de18', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '890468cab0d0f08b4d540da42231631c2502e2d4', 'size': '194', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cissus/Cissus juttae/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
/* See LICENSE for licensing information */
/**
* \file crypto_dh_openssl.c
* \brief Implement Tor's Z_p diffie-hellman stuff for OpenSSL.
**/
#include "lib/crypt_ops/compat_openssl.h"
#include "lib/crypt_ops/crypto_dh.h"
#include "lib/crypt_ops/crypto_digest.h"
#include "lib/crypt_ops/crypto_hkdf.h"
#include "lib/crypt_ops/crypto_util.h"
#include "lib/log/log.h"
#include "lib/log/util_bug.h"
DISABLE_GCC_WARNING("-Wredundant-decls")
#include <openssl/dh.h>
ENABLE_GCC_WARNING("-Wredundant-decls")
#include <openssl/bn.h>
#include <string.h>
#ifndef ENABLE_NSS
static int tor_check_dh_key(int severity, const BIGNUM *bn);
/** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
* while we're waiting for the second.*/
struct crypto_dh_t {
DH *dh; /**< The openssl DH object */
};
#endif /* !defined(ENABLE_NSS) */
static DH *new_openssl_dh_from_params(BIGNUM *p, BIGNUM *g);
/** Shared P parameter for our circuit-crypto DH key exchanges. */
static BIGNUM *dh_param_p = NULL;
/** Shared P parameter for our TLS DH key exchanges. */
static BIGNUM *dh_param_p_tls = NULL;
/** Shared G parameter for our DH key exchanges. */
static BIGNUM *dh_param_g = NULL;
/* This function is disabled unless we change the DH parameters. */
#if 0
/** Validate a given set of Diffie-Hellman parameters. This is moderately
* computationally expensive (milliseconds), so should only be called when
* the DH parameters change. Returns 0 on success, * -1 on failure.
*/
static int
crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
{
DH *dh = NULL;
int ret = -1;
/* Copy into a temporary DH object, just so that DH_check() can be called. */
if (!(dh = DH_new()))
goto out;
#ifdef OPENSSL_1_1_API
BIGNUM *dh_p, *dh_g;
if (!(dh_p = BN_dup(p)))
goto out;
if (!(dh_g = BN_dup(g)))
goto out;
if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
goto out;
#else /* !defined(OPENSSL_1_1_API) */
if (!(dh->p = BN_dup(p)))
goto out;
if (!(dh->g = BN_dup(g)))
goto out;
#endif /* defined(OPENSSL_1_1_API) */
/* Perform the validation. */
int codes = 0;
if (!DH_check(dh, &codes))
goto out;
if (BN_is_word(g, DH_GENERATOR_2)) {
/* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
*
* OpenSSL checks the prime is congruent to 11 when g = 2; while the
* IETF's primes are congruent to 23 when g = 2.
*/
BN_ULONG residue = BN_mod_word(p, 24);
if (residue == 11 || residue == 23)
codes &= ~DH_NOT_SUITABLE_GENERATOR;
}
if (codes != 0) /* Specifics on why the params suck is irrelevant. */
goto out;
/* Things are probably not evil. */
ret = 0;
out:
if (dh)
DH_free(dh);
return ret;
}
#endif /* 0 */
/**
* Helper: convert <b>hex</b> to a bignum, and return it. Assert that the
* operation was successful.
*/
static BIGNUM *
bignum_from_hex(const char *hex)
{
BIGNUM *result = BN_new();
tor_assert(result);
int r = BN_hex2bn(&result, hex);
tor_assert(r);
tor_assert(result);
return result;
}
/** Set the global Diffie-Hellman generator, used for both TLS and internal
* DH stuff.
*/
static void
crypto_set_dh_generator(void)
{
BIGNUM *generator;
int r;
if (dh_param_g)
return;
generator = BN_new();
tor_assert(generator);
r = BN_set_word(generator, DH_GENERATOR);
tor_assert(r);
dh_param_g = generator;
}
/** Initialize our DH parameters. Idempotent. */
void
crypto_dh_init_openssl(void)
{
if (dh_param_p && dh_param_g && dh_param_p_tls)
return;
tor_assert(dh_param_g == NULL);
tor_assert(dh_param_p == NULL);
tor_assert(dh_param_p_tls == NULL);
crypto_set_dh_generator();
dh_param_p = bignum_from_hex(OAKLEY_PRIME_2);
dh_param_p_tls = bignum_from_hex(TLS_DH_PRIME);
/* Checks below are disabled unless we change the hardcoded DH parameters. */
#if 0
tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
#endif
}
/** Number of bits to use when choosing the x or y value in a Diffie-Hellman
* handshake. Since we exponentiate by this value, choosing a smaller one
* lets our handhake go faster.
*/
#define DH_PRIVATE_KEY_BITS 320
/** Used by tortls.c: Get the DH* for use with TLS.
*/
DH *
crypto_dh_new_openssl_tls(void)
{
return new_openssl_dh_from_params(dh_param_p_tls, dh_param_g);
}
#ifndef ENABLE_NSS
/** Allocate and return a new DH object for a key exchange. Returns NULL on
* failure.
*/
crypto_dh_t *
crypto_dh_new(int dh_type)
{
crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
dh_type == DH_TYPE_REND);
if (!dh_param_p)
crypto_dh_init();
BIGNUM *dh_p = NULL;
if (dh_type == DH_TYPE_TLS) {
dh_p = dh_param_p_tls;
} else {
dh_p = dh_param_p;
}
res->dh = new_openssl_dh_from_params(dh_p, dh_param_g);
if (res->dh == NULL)
tor_free(res); // sets res to NULL.
return res;
}
#endif /* !defined(ENABLE_NSS) */
/** Create and return a new openssl DH from a given prime and generator. */
static DH *
new_openssl_dh_from_params(BIGNUM *p, BIGNUM *g)
{
DH *res_dh;
if (!(res_dh = DH_new()))
goto err;
BIGNUM *dh_p = NULL, *dh_g = NULL;
dh_p = BN_dup(p);
if (!dh_p)
goto err;
dh_g = BN_dup(g);
if (!dh_g) {
BN_free(dh_p);
goto err;
}
#ifdef OPENSSL_1_1_API
if (!DH_set0_pqg(res_dh, dh_p, NULL, dh_g)) {
goto err;
}
if (!DH_set_length(res_dh, DH_PRIVATE_KEY_BITS))
goto err;
#else /* !defined(OPENSSL_1_1_API) */
res_dh->p = dh_p;
res_dh->g = dh_g;
res_dh->length = DH_PRIVATE_KEY_BITS;
#endif /* defined(OPENSSL_1_1_API) */
return res_dh;
/* LCOV_EXCL_START
* This error condition is only reached when an allocation fails */
err:
crypto_openssl_log_errors(LOG_WARN, "creating DH object");
if (res_dh) DH_free(res_dh); /* frees p and g too */
return NULL;
/* LCOV_EXCL_STOP */
}
#ifndef ENABLE_NSS
/** Return a copy of <b>dh</b>, sharing its internal state. */
crypto_dh_t *
crypto_dh_dup(const crypto_dh_t *dh)
{
crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
tor_assert(dh);
tor_assert(dh->dh);
dh_new->dh = dh->dh;
DH_up_ref(dh->dh);
return dh_new;
}
/** Return the length of the DH key in <b>dh</b>, in bytes.
*/
int
crypto_dh_get_bytes(crypto_dh_t *dh)
{
tor_assert(dh);
return DH_size(dh->dh);
}
/** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
* success, -1 on failure.
*/
int
crypto_dh_generate_public(crypto_dh_t *dh)
{
#ifndef OPENSSL_1_1_API
again:
#endif
if (!DH_generate_key(dh->dh)) {
/* LCOV_EXCL_START
* To test this we would need some way to tell openssl to break DH. */
crypto_openssl_log_errors(LOG_WARN, "generating DH key");
return -1;
/* LCOV_EXCL_STOP */
}
#ifdef OPENSSL_1_1_API
/* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
* recreating the DH object. I have no idea what sort of aliasing madness
* can occur here, so do the check, and just bail on failure.
*/
const BIGNUM *pub_key, *priv_key;
DH_get0_key(dh->dh, &pub_key, &priv_key);
if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
"the-universe chances really do happen. Treating as a failure.");
return -1;
}
#else /* !defined(OPENSSL_1_1_API) */
if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
/* LCOV_EXCL_START
* If this happens, then openssl's DH implementation is busted. */
log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
"the-universe chances really do happen. Trying again.");
/* Free and clear the keys, so OpenSSL will actually try again. */
BN_clear_free(dh->dh->pub_key);
BN_clear_free(dh->dh->priv_key);
dh->dh->pub_key = dh->dh->priv_key = NULL;
goto again;
/* LCOV_EXCL_STOP */
}
#endif /* defined(OPENSSL_1_1_API) */
return 0;
}
/** Generate g^x as necessary, and write the g^x for the key exchange
* as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
* success, -1 on failure. <b>pubkey_len</b> must be \>= DH1024_KEY_LEN.
*/
int
crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
{
int bytes;
tor_assert(dh);
const BIGNUM *dh_pub;
#ifdef OPENSSL_1_1_API
const BIGNUM *dh_priv;
DH_get0_key(dh->dh, &dh_pub, &dh_priv);
#else
dh_pub = dh->dh->pub_key;
#endif /* defined(OPENSSL_1_1_API) */
if (!dh_pub) {
if (crypto_dh_generate_public(dh)<0)
return -1;
else {
#ifdef OPENSSL_1_1_API
DH_get0_key(dh->dh, &dh_pub, &dh_priv);
#else
dh_pub = dh->dh->pub_key;
#endif
}
}
tor_assert(dh_pub);
bytes = BN_num_bytes(dh_pub);
tor_assert(bytes >= 0);
if (pubkey_len < (size_t)bytes) {
log_warn(LD_CRYPTO,
"Weird! pubkey_len (%d) was smaller than DH1024_KEY_LEN (%d)",
(int) pubkey_len, bytes);
return -1;
}
memset(pubkey, 0, pubkey_len);
BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
return 0;
}
/** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
* okay (in the subgroup [2,p-2]), or -1 if it's bad.
* See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
*/
static int
tor_check_dh_key(int severity, const BIGNUM *bn)
{
BIGNUM *x;
char *s;
tor_assert(bn);
x = BN_new();
tor_assert(x);
if (BUG(!dh_param_p))
crypto_dh_init(); //LCOV_EXCL_LINE we already checked whether we did this.
BN_set_word(x, 1);
if (BN_cmp(bn,x)<=0) {
log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
goto err;
}
BN_copy(x,dh_param_p);
BN_sub_word(x, 1);
if (BN_cmp(bn,x)>=0) {
log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
goto err;
}
BN_clear_free(x);
return 0;
err:
BN_clear_free(x);
s = BN_bn2hex(bn);
log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
OPENSSL_free(s);
return -1;
}
/** Given a DH key exchange object, and our peer's value of g^y (as a
* <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
* g^xy as a big-endian integer in <b>secret_out</b>.
* Return the number of bytes generated on success,
* or -1 on failure.
*
* This function MUST validate that g^y is actually in the group.
*/
ssize_t
crypto_dh_handshake(int severity, crypto_dh_t *dh,
const char *pubkey, size_t pubkey_len,
unsigned char *secret_out, size_t secret_bytes_out)
{
BIGNUM *pubkey_bn = NULL;
size_t secret_len=0;
int result=0;
tor_assert(dh);
tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
tor_assert(pubkey_len < INT_MAX);
if (BUG(crypto_dh_get_bytes(dh) > (int)secret_bytes_out)) {
goto error;
}
if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
(int)pubkey_len, NULL)))
goto error;
if (tor_check_dh_key(severity, pubkey_bn)<0) {
/* Check for invalid public keys. */
log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
goto error;
}
result = DH_compute_key(secret_out, pubkey_bn, dh->dh);
if (result < 0) {
log_warn(LD_CRYPTO,"DH_compute_key() failed.");
goto error;
}
secret_len = result;
goto done;
error:
result = -1;
done:
crypto_openssl_log_errors(LOG_WARN, "completing DH handshake");
if (pubkey_bn)
BN_clear_free(pubkey_bn);
if (result < 0)
return result;
else
return secret_len;
}
/** Free a DH key exchange object.
*/
void
crypto_dh_free_(crypto_dh_t *dh)
{
if (!dh)
return;
tor_assert(dh->dh);
DH_free(dh->dh);
tor_free(dh);
}
#endif /* !defined(ENABLE_NSS) */
void
crypto_dh_free_all_openssl(void)
{
if (dh_param_p)
BN_clear_free(dh_param_p);
if (dh_param_p_tls)
BN_clear_free(dh_param_p_tls);
if (dh_param_g)
BN_clear_free(dh_param_g);
dh_param_p = dh_param_p_tls = dh_param_g = NULL;
}
| {'content_hash': 'cea9553027d88389f206da1b6713b757', 'timestamp': '', 'source': 'github', 'line_count': 474, 'max_line_length': 79, 'avg_line_length': 25.314345991561183, 'alnum_prop': 0.6284690390865906, 'repo_name': 'zcoinofficial/zcoin', 'id': 'c5f72715968a66458749c657cd383ac0ef4d0056', 'size': '12197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/tor/src/lib/crypt_ops/crypto_dh_openssl.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '977651'}, {'name': 'C', 'bytes': '23449469'}, {'name': 'C++', 'bytes': '11590916'}, {'name': 'CMake', 'bytes': '96751'}, {'name': 'CSS', 'bytes': '42324'}, {'name': 'Dockerfile', 'bytes': '3182'}, {'name': 'Gnuplot', 'bytes': '940'}, {'name': 'HTML', 'bytes': '55527'}, {'name': 'Java', 'bytes': '30290'}, {'name': 'Lua', 'bytes': '3321'}, {'name': 'M4', 'bytes': '354106'}, {'name': 'Makefile', 'bytes': '176315'}, {'name': 'NASL', 'bytes': '177'}, {'name': 'Objective-C++', 'bytes': '6795'}, {'name': 'PHP', 'bytes': '4871'}, {'name': 'POV-Ray SDL', 'bytes': '1480'}, {'name': 'Perl', 'bytes': '18265'}, {'name': 'Python', 'bytes': '1731667'}, {'name': 'QMake', 'bytes': '1352'}, {'name': 'Roff', 'bytes': '2388'}, {'name': 'Ruby', 'bytes': '3216'}, {'name': 'Rust', 'bytes': '119897'}, {'name': 'Sage', 'bytes': '30192'}, {'name': 'Shell', 'bytes': '314196'}, {'name': 'SmPL', 'bytes': '5488'}, {'name': 'SourcePawn', 'bytes': '12001'}, {'name': 'q', 'bytes': '5584'}]} |
import * as React from 'react'
import * as ligands from '../ligands'
import * as proteins from '../proteins'
import { Layout } from '../components/Layout'
import { MolCanvas } from '../containers/MolCanvas'
import { LigandGLModel } from '../ligands/components/LigandGLModel'
import { LigandList } from '../ligands/containers/LigandList'
import { ProteinGLModel } from '../proteins/components/ProteinGLModel'
import { ProteinList } from '../proteins/containers/ProteinList'
export interface IStateProps {
ligands: ligands.ILigand[]
proteins: proteins.IProtein[]
pocketRadius: number
}
export interface IDispatchProps {
fetchLigands(): void
fetchProteins(): void
pageLoaded(): void
}
export type IProps = IStateProps & IDispatchProps
export class LigandsAndProteinsViewer extends React.Component<IProps, {}> {
public componentDidMount() {
this.props.fetchLigands()
this.props.fetchProteins()
this.props.pageLoaded()
}
public render() {
const title = 'Ligands and proteins viewer'
const sidebar = [
<LigandList key="ligands" ligands={this.props.ligands} />,
<ProteinList
key="proteins"
proteins={this.props.proteins}
pocketRadius={this.props.pocketRadius}
/>
]
const ligands = this.props.ligands.map(ligand => (
<LigandGLModel key={ligand.id} {...ligand} />
))
const proteins = this.props.proteins.map(protein => (
<ProteinGLModel
key={protein.id}
{...protein}
pocketRadius={this.props.pocketRadius}
hetColor="#FF8C00"
/>
))
const main = (
<MolCanvas id="canvas">
{ligands}
{proteins}
</MolCanvas>
)
return <Layout title={title} sidebar={sidebar} main={main} />
}
}
| {'content_hash': '4f0d99c9fc9c6d3fe7c65f2294d445c5', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 75, 'avg_line_length': 27.96825396825397, 'alnum_prop': 0.6623155505107832, 'repo_name': '3D-e-Chem/molviewer-tsx', 'id': 'c45832620cbe7826474bb1c3aa825813bc32e28e', 'size': '1762', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/components/LigandsAndProteinsViewer.tsx', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9185'}, {'name': 'HTML', 'bytes': '1159'}, {'name': 'JavaScript', 'bytes': '49555'}, {'name': 'Shell', 'bytes': '390'}, {'name': 'TypeScript', 'bytes': '198849'}]} |
package com.joker.picshowview.animation;
import android.view.animation.Interpolator;
/**
* Created by Joker on 2017/11/13.
* 实现弹性动画的类
*/
public class SpringScaleInterpolator implements Interpolator{
//弹性因数
private float factor;
public SpringScaleInterpolator (float factor){
this.factor=factor;
}
@Override
public float getInterpolation(float input) {
return (float)(Math.pow(2,-10 * input)*Math.sin((input-factor/4)*(2*Math.PI)/factor)+1);
}
}
| {'content_hash': '9d1b3d6deac5008aef47c5d48bf75e76', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 96, 'avg_line_length': 22.59090909090909, 'alnum_prop': 0.6901408450704225, 'repo_name': 'mengdegit/PicShowView', 'id': '2028cc0711f6f1ffb64e765c4fc9cb2d0e9f9b27', 'size': '521', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/joker/picshowview/animation/SpringScaleInterpolator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '349'}, {'name': 'Java', 'bytes': '131701'}]} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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
// OWNER 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.
package com.google.protobuf;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
/**
* An implementation of {@link LazyStringList} that wraps an ArrayList. Each
* element is either a ByteString or a String. It caches the last one requested
* which is most likely the one needed next. This minimizes memory usage while
* satisfying the most common use cases.
* <p>
* <strong>Note that this implementation is not synchronized.</strong> If
* multiple threads access an <tt>ArrayList</tt> instance concurrently, and at
* least one of the threads modifies the list structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation that
* adds or deletes one or more elements, or explicitly resizes the backing
* array; merely setting the value of an element is not a structural
* modification.) This is typically accomplished by synchronizing on some object
* that naturally encapsulates the list.
* <p>
* If the implementation is accessed via concurrent reads, this is thread safe.
* Conversions are done in a thread safe manner. It's possible that the
* conversion may happen more than once if two threads attempt to access the
* same element and the modifications were not visible to each other, but this
* will not result in any corruption of the list or change in behavior other
* than performance.
*
* @author [email protected] (Jon Perlow)
*/
public class LazyStringArrayList extends AbstractList<String> implements
LazyStringList, RandomAccess {
public final static LazyStringList EMPTY = new UnmodifiableLazyStringList(
new LazyStringArrayList());
private final List<Object> list;
public LazyStringArrayList() {
list = new ArrayList<Object>();
}
public LazyStringArrayList(LazyStringList from) {
list = new ArrayList<Object>(from.size());
addAll(from);
}
public LazyStringArrayList(List<String> from) {
list = new ArrayList<Object>(from);
}
@Override
public String get(int index) {
Object o = list.get(index);
if (o instanceof String) {
return (String) o;
} else {
ByteString bs = (ByteString) o;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
list.set(index, s);
}
return s;
}
}
@Override
public int size() {
return list.size();
}
@Override
public String set(int index, String s) {
Object o = list.set(index, s);
return asString(o);
}
@Override
public void add(int index, String element) {
list.add(index, element);
modCount++;
}
@Override
public boolean addAll(Collection<? extends String> c) {
// The default implementation of AbstractCollection.addAll(Collection)
// delegates to add(Object). This implementation instead delegates to
// addAll(int, Collection), which makes a special case for Collections
// which are instances of LazyStringList.
return addAll(size(), c);
}
@Override
public boolean addAll(int index, Collection<? extends String> c) {
// When copying from another LazyStringList, directly copy the
// underlying
// elements rather than forcing each element to be decoded to a String.
Collection<?> collection = c instanceof LazyStringList ? ((LazyStringList) c)
.getUnderlyingElements() : c;
boolean ret = list.addAll(index, collection);
modCount++;
return ret;
}
@Override
public String remove(int index) {
Object o = list.remove(index);
modCount++;
return asString(o);
}
public void clear() {
list.clear();
modCount++;
}
// @Override
public void add(ByteString element) {
list.add(element);
modCount++;
}
// @Override
public ByteString getByteString(int index) {
Object o = list.get(index);
if (o instanceof String) {
ByteString b = ByteString.copyFromUtf8((String) o);
list.set(index, b);
return b;
} else {
return (ByteString) o;
}
}
private String asString(Object o) {
if (o instanceof String) {
return (String) o;
} else {
return ((ByteString) o).toStringUtf8();
}
}
public List<?> getUnderlyingElements() {
return Collections.unmodifiableList(list);
}
}
| {'content_hash': '7dfa2271492feb980c5d0f2ad7247de3', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 80, 'avg_line_length': 32.44692737430167, 'alnum_prop': 0.7332988980716253, 'repo_name': 'adetalhouet/Profiler', 'id': '7a5630d5050531e945af203e00d51d3b0619cae1', 'size': '5808', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/google/protobuf/LazyStringArrayList.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '1030'}, {'name': 'C', 'bytes': '4070'}, {'name': 'C++', 'bytes': '3441192'}, {'name': 'Java', 'bytes': '735298'}, {'name': 'Makefile', 'bytes': '4120'}, {'name': 'Protocol Buffer', 'bytes': '369162'}, {'name': 'Shell', 'bytes': '5835'}]} |
package org.testobject.kernel.imaging.segmentation;
import org.testobject.commons.math.algebra.Size;
/**
*
* @author enijkamp
*
*/
public interface BooleanRaster
{
/**
* returns rectangle describing valid ranges for (x, y)
*/
Size.Int getSize();
/**
* Returns pixel value.
*
* @param x x-position of the pixel. Queries outside of bounding box should return background color (FALSE).
* @param y y-position of the pixel. Queries outside of bounding box should return background color (FALSE).
*
* @return pixel color (true is foreground, false is background).
*/
boolean get(int x, int y);
/**
* Sets pixel value. Its illegal to set a pixel outside of bounding box to anything but background.
*
* @param x
* @param y
* @param what
*/
void set(int x, int y, boolean what);
}
| {'content_hash': '067251b9a53f214104089d5cce873f9b', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 112, 'avg_line_length': 24.47222222222222, 'alnum_prop': 0.6367763904653803, 'repo_name': 'testobject/visual-scripting', 'id': 'f311723dbac4a134764e980cbb2b469643cc723a', 'size': '881', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'org.testobject.commons/imaging/src/main/java/org/testobject/kernel/imaging/segmentation/BooleanRaster.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2473156'}]} |
<?php
namespace Rezzza\Jobflow;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Make Job creation easier, better, stronger
*
* @author Timothée Barray <[email protected]>
*/
class JobBuilder extends JobConfig
{
/**
* @var array
*/
protected $children = array();
/**
* @var array
*/
protected $unresolvedChildren = array();
/**
* @param string $name
* @param JobFactory $jobFactory
*/
public function __construct($name, JobFactory $jobFactory, EventDispatcherInterface $dispatcher, array $initOptions = array(), array $execOptions = array())
{
parent::__construct($name, $dispatcher, $initOptions, $execOptions);
$this->setJobFactory($jobFactory);
}
/**
* Add sub job to a job
*
* @param string $child Name of the child
* @param string $type The JobTypeInterface or the alias of the job type registered as a service
* @param array $execOptions
* @param array $initOptions
*
* @return JobBuilder
*/
public function add($child, $type, array $execOptions = array(), array $initOptions = array())
{
if (!is_string($child) && !is_int($child)) {
throw new \InvalidArgumentException(sprintf('child name should be string or, integer'));
}
if (null !== $type && !is_string($type) && !$type instanceof JobTypeinterface) {
throw new \InvalidArgumentException('type should be string or JobTypeinterface');
}
$this->children[$child] = null; // to keep order
$this->unresolvedChildren[$child] = array(
'type' => $type,
'init_options' => $initOptions,
'exec_options' => $execOptions
);
return $this;
}
/**
* @param string $name
*/
public function has($name)
{
return isset($this->unresolvedChildren[$name])
|| isset($this->children[$name]);
}
/**
* Create new JobBuilder
*
* @param string $name
* @param mixed $type The JobTypeInterface or the alias of the job type registered as a service
*
* @return JobBuilder
*/
public function create($name, $type = null, array $initOptions = array(), array $execOptions = array())
{
if (null === $type) {
$type = 'job';
}
return $this->getJobFactory()->createNamedBuilder($name, $type, $initOptions, $execOptions);
}
/**
* Create the job with all children configure
*
* @return Job
*/
public function getJob()
{
$this->resolveChildren();
$job = new Job($this->getJobConfig());
foreach ($this->children as $child) {
$job->add($child->getJob());
}
return $job;
}
public function hasUnresolvedChildren()
{
return count($this->unresolvedChildren) > 0;
}
/**
* For each child added, we create a new JobBuilder around it to make fully configurable each sub job
*/
protected function resolveChildren()
{
foreach ($this->unresolvedChildren as $name => $info) {
$this->children[$name] = $this->create($name, $info['type'], $info['init_options'], $info['exec_options']);
}
$this->unresolvedChildren = array();
}
} | {'content_hash': '8ba12e172dec845d40951541cce67f1d', 'timestamp': '', 'source': 'github', 'line_count': 124, 'max_line_length': 160, 'avg_line_length': 27.008064516129032, 'alnum_prop': 0.5810689758136757, 'repo_name': 'rezzza/jobflow', 'id': '0ab4bcd89d96132eb8b1efa730b4c9b6fc9a863d', 'size': '3350', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Rezzza/Jobflow/JobBuilder.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '205583'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'c428bc3d4ec3be9a20f17ad4375827b5', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'a132825c48ef558a857abcdee0842427ad0d4fb0', 'size': '182', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Cornales/Hydrangeaceae/Philadelphus/Philadelphus angustifolius/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
class Server:
def __init__(self, id=-1, host="", url="", app_id=None):
self.id = id
self.host = host
self.url = url
self.app_id=app_id
def to_dict(self):
return self.__dict__
@staticmethod
def from_dict(server_dict):
if server_dict and "id" in server_dict and "host" in server_dict and "url" in server_dict:
return Server(server_dict["id"], server_dict["host"], server_dict["url"])
return None | {'content_hash': '6fda08968148e89b48ced5e6acd47275', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 98, 'avg_line_length': 32.46666666666667, 'alnum_prop': 0.5585215605749486, 'repo_name': 'maximx1/checktheplug', 'id': '64078e6a353685c716ef73f764143626ce895526', 'size': '487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'checktheplug/models/Server.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1352'}, {'name': 'Perl', 'bytes': '124'}, {'name': 'Python', 'bytes': '25878'}, {'name': 'Smarty', 'bytes': '13314'}]} |
namespace BohFoundation.Domain.Dtos.Email
{
public class SendEmailDtoWithSubjectBodyAndSender : SendEmailWithSubjectAndBodyDto
{
public string SendersFullName { get; set; }
public string SendersEmail { get; set; }
}
} | {'content_hash': 'f421a41d4bb7b2a0f8a9012b9c9ef1f9', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 86, 'avg_line_length': 30.75, 'alnum_prop': 0.7195121951219512, 'repo_name': 'Sobieck00/BOH-Bulldog-Scholarship-Application-Management', 'id': '19d66ae416383620d82b15a2d8769fb62deac8d1', 'size': '248', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BohFoundation.Domain/Dtos/Email/SendEmailDtoWithSubjectBodyAndSender.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '114'}, {'name': 'C#', 'bytes': '962582'}, {'name': 'CSS', 'bytes': '164646'}, {'name': 'JavaScript', 'bytes': '390553'}, {'name': 'Shell', 'bytes': '97'}, {'name': 'TypeScript', 'bytes': '1017223'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Prodr. 1:456. 1824
#### Original name
null
### Remarks
null | {'content_hash': '7f3ac1413fcba3c06ed849701a9111a6', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 11.384615384615385, 'alnum_prop': 0.6891891891891891, 'repo_name': 'mdoering/backbone', 'id': '50f2c8eccc7e43947786a8c25e2bcb977f9bd087', 'size': '197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Thespesia/Thespesia grandiflora/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">import_history_listing.import_history_listing_data_source</item>
<item name="deps" xsi:type="string">import_history_listing.import_history_listing_data_source</item>
</item>
<item name="spinner" xsi:type="string">log_columns</item>
</argument>
<dataSource name="import_history_listing_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
<argument name="name" xsi:type="string">import_history_listing_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">id</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
<item name="update_url" xsi:type="url" path="mui/index/render"/>
<item name="storageConfig" xsi:type="array">
<item name="indexField" xsi:type="string">id</item>
</item>
</item>
</argument>
</argument>
</dataSource>
<listingToolbar name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="sticky" xsi:type="boolean">true</item>
</item>
</argument>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls"/>
<exportButton name="export_button"/>
<filterSearch name="fulltext"/>
<filters name="listing_filters">
<filterSelect name="import_name">
<argument name="optionsProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Jh\Import\ListingFilter\ImportName</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="provider" xsi:type="string">import_history_listing.import_history_listing.listing_top.listing_filters</item>
<item name="dataScope" xsi:type="string">import_name</item>
<item name="caption" xsi:type="string" translate="true">Select...</item>
<item name="label" xsi:type="string" translate="true">Import Name</item>
</item>
</argument>
</filterSelect>
</filters>
<massaction name="listing_massaction">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
</item>
</argument>
</massaction>
<paging name="listing_paging"/>
</listingToolbar>
<columns name="log_columns" class="Magento\Ui\Component\Listing\Columns">
<selectionsColumn name="ids">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">id</item>
<item name="sortOrder" xsi:type="number">10</item>
</item>
</argument>
</selectionsColumn>
<column name="id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">textRange</item>
<item name="sorting" xsi:type="string">asc</item>
<item name="label" xsi:type="string" translate="true">ID</item>
<item name="sortOrder" xsi:type="number">20</item>
</item>
</argument>
</column>
<column name="import_name">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Import Name</item>
<item name="sortOrder" xsi:type="number">30</item>
</item>
</argument>
</column>
<column name="started" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="dataType" xsi:type="string">date</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="label" xsi:type="string" translate="true">Started At</item>
<item name="sortOrder" xsi:type="number">40</item>
</item>
</argument>
</column>
<column name="finished" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="dataType" xsi:type="string">date</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="label" xsi:type="string" translate="true">Finished At</item>
<item name="sortOrder" xsi:type="number">50</item>
</item>
</argument>
</column>
<column name="elapsed" class="Jh\Import\Ui\Component\Listing\Column\Elapsed">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Time Elapsed</item>
</item>
</argument>
</column>
<column name="memory_usage" class="Jh\Import\Ui\Component\Listing\Column\Memory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Memory Usage</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Jh\Import\Ui\Component\Listing\Column\ImportHistoryActions">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">id</item>
<item name="label" xsi:type="string" translate="true">Actions</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing> | {'content_hash': 'eed8751f5ada6e5ab9a562ba692383f0', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 150, 'avg_line_length': 50.68531468531469, 'alnum_prop': 0.5521523178807947, 'repo_name': 'WeareJH/m2-module-import', 'id': 'ce01b176243a9c886df7dabb7aba7ff48042490f', 'size': '7248', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/view/adminhtml/ui_component/import_history_listing.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8939'}, {'name': 'PHP', 'bytes': '211272'}]} |
from .base import *
from .user import *
from .shift import *
| {'content_hash': '26bac715a1449348754f68ee9028077e', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 20, 'avg_line_length': 20.333333333333332, 'alnum_prop': 0.7049180327868853, 'repo_name': 'swappr-tanda-team/swappr', 'id': 'edad22713166cf60aa10f287d9d3fd4787cd531f', 'size': '61', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'swappr/models/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '707'}, {'name': 'HTML', 'bytes': '14732'}, {'name': 'Makefile', 'bytes': '1723'}, {'name': 'Python', 'bytes': '18405'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '904961c9abb50614d740dadf06081800', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '01f517d014599942a4b96336b9c51bba80a0692e', 'size': '174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Loranthus/Loranthus caloreas/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Euphrasia kerneri Wettst.
### Remarks
null | {'content_hash': 'be37fbc86823c0d77445af69c752ba22', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 11.307692307692308, 'alnum_prop': 0.7278911564625851, 'repo_name': 'mdoering/backbone', 'id': 'b4f4a1d9b73c05b63217b005830c3cd1cd508f47', 'size': '230', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Euphrasia/Euphrasia officinalis/Euphrasia officinalis kerneri/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package org.apache.pulsar.functions.runtime;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.converters.StringConverter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.Empty;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.functions.instance.InstanceConfig;
import org.apache.pulsar.functions.proto.Function.FunctionDetails;
import org.apache.pulsar.functions.proto.InstanceCommunication;
import org.apache.pulsar.functions.proto.InstanceControlGrpc;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* A function container implemented using java thread.
*/
@Slf4j
public class JavaInstanceMain {
@Parameter(names = "--function_classname", description = "Function Class Name\n", required = true)
protected String className;
@Parameter(
names = "--jar",
description = "Path to Jar\n",
listConverter = StringConverter.class)
protected String jarFile;
@Parameter(names = "--name", description = "Function Name\n", required = true)
protected String functionName;
@Parameter(names = "--tenant", description = "Tenant Name\n", required = true)
protected String tenant;
@Parameter(names = "--namespace", description = "Namespace Name\n", required = true)
protected String namespace;
@Parameter(names = "--output_topic", description = "Output Topic Name\n")
protected String outputTopicName;
@Parameter(names = "--custom_serde_input_topics", description = "Input Topics that need custom deserialization\n", required = false)
protected String customSerdeInputTopics;
@Parameter(names = "--custom_serde_classnames", description = "Input SerDe\n", required = false)
protected String customSerdeClassnames;
@Parameter(names = "--input_topics", description = "Input Topics\n", required = false)
protected String defaultSerdeInputTopics;
@Parameter(names = "--output_serde_classname", description = "Output SerDe\n")
protected String outputSerdeClassName;
@Parameter(names = "--log_topic", description = "Log Topic")
protected String logTopic;
@Parameter(names = "--processing_guarantees", description = "Processing Guarantees\n", required = true)
protected FunctionDetails.ProcessingGuarantees processingGuarantees;
@Parameter(names = "--instance_id", description = "Instance Id\n", required = true)
protected String instanceId;
@Parameter(names = "--function_id", description = "Function Id\n", required = true)
protected String functionId;
@Parameter(names = "--function_version", description = "Function Version\n", required = true)
protected String functionVersion;
@Parameter(names = "--pulsar_serviceurl", description = "Pulsar Service Url\n", required = true)
protected String pulsarServiceUrl;
@Parameter(names = "--state_storage_serviceurl", description = "State Storage Service Url\n", required= false)
protected String stateStorageServiceUrl;
@Parameter(names = "--port", description = "Port to listen on\n", required = true)
protected int port;
@Parameter(names = "--max_buffered_tuples", description = "Maximum number of tuples to buffer\n", required = true)
protected int maxBufferedTuples;
@Parameter(names = "--user_config", description = "UserConfig\n")
protected String userConfig;
@Parameter(names = "--auto_ack", description = "Enable Auto Acking?\n")
protected String autoAck = "true";
@Parameter(names = "--subscription_type", description = "What subscription type to use")
protected FunctionDetails.SubscriptionType subscriptionType;
private Server server;
public JavaInstanceMain() { }
public void start() throws Exception {
InstanceConfig instanceConfig = new InstanceConfig();
instanceConfig.setFunctionId(functionId);
instanceConfig.setFunctionVersion(functionVersion);
instanceConfig.setInstanceId(instanceId);
instanceConfig.setMaxBufferedTuples(maxBufferedTuples);
FunctionDetails.Builder functionDetailsBuilder = FunctionDetails.newBuilder();
functionDetailsBuilder.setTenant(tenant);
functionDetailsBuilder.setNamespace(namespace);
functionDetailsBuilder.setName(functionName);
functionDetailsBuilder.setClassName(className);
if (defaultSerdeInputTopics != null) {
String[] inputTopics = defaultSerdeInputTopics.split(",");
for (String inputTopic : inputTopics) {
functionDetailsBuilder.addInputs(inputTopic);
}
}
if (customSerdeInputTopics != null && customSerdeClassnames != null) {
String[] inputTopics = customSerdeInputTopics.split(",");
String[] inputSerdeClassNames = customSerdeClassnames.split(",");
if (inputTopics.length != inputSerdeClassNames.length) {
throw new RuntimeException("Error specifying inputs");
}
for (int i = 0; i < inputTopics.length; ++i) {
functionDetailsBuilder.putCustomSerdeInputs(inputTopics[i], inputSerdeClassNames[i]);
}
}
if (outputSerdeClassName != null) {
functionDetailsBuilder.setOutputSerdeClassName(outputSerdeClassName);
}
if (outputTopicName != null) {
functionDetailsBuilder.setOutput(outputTopicName);
}
if (logTopic != null) {
functionDetailsBuilder.setLogTopic(logTopic);
}
functionDetailsBuilder.setProcessingGuarantees(processingGuarantees);
if (autoAck.equals("true")) {
functionDetailsBuilder.setAutoAck(true);
} else {
functionDetailsBuilder.setAutoAck(false);
}
functionDetailsBuilder.setSubscriptionType(subscriptionType);
if (userConfig != null && !userConfig.isEmpty()) {
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> userConfigMap = new Gson().fromJson(userConfig, type);
functionDetailsBuilder.putAllUserConfig(userConfigMap);
}
FunctionDetails functionDetails = functionDetailsBuilder.build();
instanceConfig.setFunctionDetails(functionDetails);
ThreadRuntimeFactory containerFactory = new ThreadRuntimeFactory(
"LocalRunnerThreadGroup",
pulsarServiceUrl,
stateStorageServiceUrl);
RuntimeSpawner runtimeSpawner = new RuntimeSpawner(
instanceConfig,
jarFile,
containerFactory,
null);
server = ServerBuilder.forPort(port)
.addService(new InstanceControlImpl(runtimeSpawner))
.build()
.start();
log.info("JaveInstance Server started, listening on " + port);
java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
try {
server.shutdown();
runtimeSpawner.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
});
log.info("Starting runtimeSpawner");
runtimeSpawner.start();
runtimeSpawner.join();
log.info("RuntimeSpawner quit, shutting down JavaInstance");
server.shutdown();
}
public static void main(String[] args) throws Exception {
JavaInstanceMain javaInstanceMain = new JavaInstanceMain();
JCommander jcommander = new JCommander(javaInstanceMain);
jcommander.setProgramName("JavaInstanceMain");
// parse args by JCommander
jcommander.parse(args);
javaInstanceMain.start();
}
static class InstanceControlImpl extends InstanceControlGrpc.InstanceControlImplBase {
private RuntimeSpawner runtimeSpawner;
public InstanceControlImpl(RuntimeSpawner runtimeSpawner) {
this.runtimeSpawner = runtimeSpawner;
}
@Override
public void getFunctionStatus(Empty request, StreamObserver<InstanceCommunication.FunctionStatus> responseObserver) {
try {
InstanceCommunication.FunctionStatus response = runtimeSpawner.getFunctionStatus().get();
responseObserver.onNext(response);
responseObserver.onCompleted();
} catch (Exception e) {
log.error("Exception in JavaInstance doing getFunctionStatus", e);
throw new RuntimeException(e);
}
}
@Override
public void getAndResetMetrics(com.google.protobuf.Empty request,
io.grpc.stub.StreamObserver<org.apache.pulsar.functions.proto.InstanceCommunication.MetricsData> responseObserver) {
Runtime runtime = runtimeSpawner.getRuntime();
if (runtime != null) {
try {
InstanceCommunication.MetricsData metrics = runtime.getAndResetMetrics().get();
responseObserver.onNext(metrics);
responseObserver.onCompleted();
} catch (InterruptedException | ExecutionException e) {
log.error("Exception in JavaInstance doing getAndResetMetrics", e);
throw new RuntimeException(e);
}
}
}
}
}
| {'content_hash': '69830cd90abf3ed35231e180a02d65ba', 'timestamp': '', 'source': 'github', 'line_count': 229, 'max_line_length': 155, 'avg_line_length': 42.585152838427945, 'alnum_prop': 0.6625307629204266, 'repo_name': 'saandrews/pulsar', 'id': '88f1ac76ee76fbfabe46aff17b5cdfa2b811fd28', 'size': '10560', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pulsar-functions/runtime/src/main/java/org/apache/pulsar/functions/runtime/JavaInstanceMain.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '78182'}, {'name': 'C++', 'bytes': '981922'}, {'name': 'CMake', 'bytes': '20054'}, {'name': 'CSS', 'bytes': '29213'}, {'name': 'Groovy', 'bytes': '20837'}, {'name': 'HCL', 'bytes': '11887'}, {'name': 'HTML', 'bytes': '100124'}, {'name': 'Java', 'bytes': '8940550'}, {'name': 'JavaScript', 'bytes': '3803'}, {'name': 'Makefile', 'bytes': '2350'}, {'name': 'Python', 'bytes': '236967'}, {'name': 'Ruby', 'bytes': '7728'}, {'name': 'Shell', 'bytes': '95564'}]} |
var simpleCoinSelector = function(target, inputs) {
var sorted = inputs.sort(function(a, b) {
return b.confirmations - a.confirmations;
});
var selected = [];
var total = 0;
inputs.forEach(function(input) {
console.log('processing', input);
if (total >= target) return;
selected.push(input);
total += input.value;
});
return [selected, total - target];
};
export { simpleCoinSelector };
| {'content_hash': '0c91cf2852533ad2fbeb2795e651291c', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 51, 'avg_line_length': 22.36842105263158, 'alnum_prop': 0.6470588235294118, 'repo_name': 'goshakkk/meklebar', 'id': '38daf0f08acf2403724a32d8eb20dc7689921fee', 'size': '425', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/coin_selector.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '433'}, {'name': 'JavaScript', 'bytes': '209745'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rollover Images</title>
<link href="../_css/site.css" rel="stylesheet">
<style>
#gallery {
float: left;
width: 90px;
margin-right: 30px;
margin-left: 10px;
border-right: white 1px dotted;
}
#gallery img {
display: inline-block;
margin: 0 0 10px 0;
border: 1px solid rgb(0,0,0);
}
#photo {
margin-left: 150px;
position: relative;
}
#photo img {
position: absolute;
}
</style>
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
$('#gallery img').each(function(i) {
var imgFile = $(this).attr('src');
var preloadImage = new Image();
var imgExt = /(\.\w{3,4}$)/;
preloadImage.src = imgFile.replace(imgExt,'_h$1');
$(this).hover(
function() {
$(this).attr('src', preloadImage.src);
},
function () {
var currentSource=$(this).attr('src');
$(this).attr('src', imgFile);
}); // end hover
}); // end each
//insert new programming below this line
}); // end ready
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>
Missing<br>
Manual</i></p>
</div>
<div class="content">
<div class="main">
<h1>Slideshow</h1>
<div id="gallery"> <a href="../_images/large/slide1.jpg"><img src="../_images/small/slide1.jpg" width="70" height="70" alt="golf balls"></a> <a href="../_images/large/slide2.jpg"><img src="../_images/small/slide2.jpg" width="70" height="70" alt="rock wall"></a> <a href="../_images/large/slide3.jpg"><img src="../_images/small/slide3.jpg" width="70" height="70" alt="old course"></a> <a href="../_images/large/slide4.jpg"><img src="../_images/small/slide4.jpg" width="70" height="70" alt="tees"></a> <a href="../_images/large/slide5.jpg"><img src="../_images/small/slide5.jpg" width="70" height="70" alt="tree"></a> <a href="../_images/large/slide6.jpg"><img src="../_images/small/slide6.jpg" width="70" height="70" alt="ocean course"></a></div>
<div id="photo"></div>
</div>
</div>
<div class="footer">
<p>JavaScript & jQuery: The Missing Manual, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
</div>
</div>
</body>
</html>
| {'content_hash': '2809e2ddfb40cc8b24177386a0d7fcd2', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 748, 'avg_line_length': 30.986301369863014, 'alnum_prop': 0.6251105216622458, 'repo_name': 'LukeMichaels/learning-js', 'id': '08eb9c3ba9ab1ae89cfb5c44d6d42a2ac41a016b', 'size': '2262', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'missing-manual/chapter07/gallery.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '37159'}, {'name': 'JavaScript', 'bytes': '66691'}, {'name': 'PHP', 'bytes': '4712'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="/CMPUT391F/Sources/js/jquery-1.9.1.min.js" defer></script>
<script type="text/javascript" src="/CMPUT391F/Sources/js/jquery.cookie.min.js" defer></script>
<script type="text/javascript" src="/CMPUT391F/Sources/js/jquery-ui.min.js" defer></script>
<script type="text/javascript" src="/CMPUT391F/Sources/js/buildHeader.js" defer></script>
<script type="text/javascript" src="/CMPUT391F/Sources/uploadify/jquery.uploadify.min.js" defer></script>
<script type="text/javascript" src="/CMPUT391F/Sources/js/upload.js" defer></script>
<link rel="stylesheet" type="text/css" href="/CMPUT391F/Sources/css/main.css">
<link rel="stylesheet" type="text/css" href="/CMPUT391F/Sources/css/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="/CMPUT391F/Sources/css/jquery-ui.theme.css">
<link rel="stylesheet" type="text/css" href="/CMPUT391F/Sources/uploadify/uploadify.css">
<title>LUX Image Hosting</title>
</head>
<body>
<div class="section hcenter" style="display:none">
<h1><center>Upload Images</center></h1>
<form id="upload-form" name="upload-image" enctype="multipart/form-data" >
<table>
<tbody>
<tr>
<td>Select Image:</td>
<td>
<input id="upload-here" name="Filedata" type="file" accept=".jpg, .gif">
<div class="Filedata validation"></div>
</td>
</tr>
<tr>
<td>Permission:</td>
<td>
<div class="radio-horizontal"><input type="radio" name="permitted" value="2" checked> Private</div>
<div class="radio-horizontal"><input type="radio" name="permitted" value="1"> Public</div>
<div class="radio-horizontal" style='margin-right:3px;'><input type="radio" name="permitted" value="group" disabled> Group</div>
<div class="permission-validation" style="vertical-align: top"></div>
</td>
</tr>
<tr class="collapsible group-selector">
<td >Select Group:</td>
<td >
<select name="groupid">
</select>
</td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" maxlength="128"></td>
</tr>
<tr>
<td>Date Taken:</td>
<td><input id="date-taken" type="text" name="date" placeholder="mm/dd/yyyy"> <div class="date validation"></div></td>
</tr>
<tr>
<td>Location Taken:</td>
<td><input type="text" name="location" maxlength="128"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea name="description" maxlength="2048" rows="15"></textarea></td>
</tr>
</tbody>
</table>
<input class="hcenter" type="submit" name="submit-button" value="Upload">
</form>
<br>
<div id="upload-results" class="hcenter"></div>
</div>
</body>
</html>
| {'content_hash': 'c67a15d4482e36a2cda7aa73033d2a24', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 135, 'avg_line_length': 40.851351351351354, 'alnum_prop': 0.5851802844856103, 'repo_name': 'ulviibrahimov/CMPUT391F', 'id': '90e9e623f763ab01ee1683b7cd04d9fb403ece32', 'size': '3023', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'upload.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '41346'}, {'name': 'Java', 'bytes': '318022'}, {'name': 'JavaScript', 'bytes': '108505'}, {'name': 'Makefile', 'bytes': '61'}, {'name': 'Shell', 'bytes': '1634'}]} |
[](https://travis-ci.org/yifeic/FluxCocoa)
[](http://cocoadocs.org/docsets/FluxCocoa)
[](http://cocoadocs.org/docsets/FluxCocoa)
[](http://cocoadocs.org/docsets/FluxCocoa)
## Usage
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Requirements
## Installation
FluxCocoa is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
pod "FluxCocoa"
## Author
yifeic, [email protected]
## License
FluxCocoa is available under the MIT license. See the LICENSE file for more info.
| {'content_hash': '2b4c9c2c4d278a10bd3c2ccac685810b', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 116, 'avg_line_length': 34.38461538461539, 'alnum_prop': 0.7539149888143176, 'repo_name': 'yifeic/FluxCocoa', 'id': '0434db22eed7e5791916f7d83519c0a894594313', 'size': '907', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '6133'}, {'name': 'Ruby', 'bytes': '1516'}]} |
package com.dexitcompany.libgdxutils.ui;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import lombok.Getter;
public abstract class UIComponent
{
private @Getter WidgetGroup container;
public UIComponent()
{
container = new WidgetGroup()
{
@Override
public void act(float delta)
{
super.act(delta);
update(delta);
}
};
}
protected final void addChild(Actor actor)
{
container.addActor(actor);
container.pack();
}
protected final void addChild(UIComponent component)
{
container.addActor(component.getContainer());
container.pack();
}
protected void update(float deltaTime)
{
}
public void setPositon(float x, float y)
{
container.setPosition(x, y);
}
public float getWidth()
{
return container.getWidth();
}
public float getHeight()
{
return container.getHeight();
}
public float getX()
{
return container.getX();
}
public float getY()
{
return container.getY();
}
protected final void rotate(float angle)
{
container.addAction(Actions.rotateBy(angle));
}
public abstract void resize(float width, float height);
}
| {'content_hash': '929b9786f01439ab3b96deecea069062', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 59, 'avg_line_length': 19.60810810810811, 'alnum_prop': 0.5982081323225362, 'repo_name': 'DEXIT33/LibGDX-Utils', 'id': '5e0ffdbb9c75d60259cbf49d7b9541067a184e87', 'size': '1451', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/dexitcompany/libgdxutils/ui/UIComponent.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '28309'}]} |
import { Vector3 } from 'three'
// import { randInteger } from '.'
import { ParticleType } from '../emun/ParticleType'
import Environment from './environment'
import { getBoundary } from './boundary'
interface Options {
type: ParticleType
speedy: boolean
}
const boundary = getBoundary()
const randInteger = (max: number) => {
return Math.floor(Math.random() * Math.floor(max))
}
export default function placeParticle(
env: Environment,
options: Options,
): void {
const size = boundary.getBoundarySize()
const radius = 1
const position = new Vector3(
randInteger(size - radius),
randInteger(size - radius),
randInteger(size - radius),
)
let velocity = new Vector3()
if (options.speedy) {
velocity = new Vector3(randInteger(6), randInteger(6), randInteger(6))
}
switch (options.type) {
case ParticleType.NEUTRON: {
env.addParticle(position, velocity, 0, 1, 1)
break
}
case ParticleType.PROTON: {
env.addParticle(position, velocity, 1, 1, 1)
break
}
case ParticleType.ELECTRON: {
env.addParticle(position, velocity, -1, 1, 1)
break
}
case ParticleType.RANDOM: {
const chance = Math.random()
if (chance > 0.66) {
env.addParticle(position, velocity, 0, 1, 1)
} else if (chance > 0.33) {
env.addParticle(position, velocity, -1, 1, 1)
} else {
env.addParticle(position, velocity, 1, 1, 1)
}
break
}
default: {
break
}
}
}
| {'content_hash': '06beb23e019fedfc03aee22c5bbc2b7b', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 72, 'avg_line_length': 22.822580645161292, 'alnum_prop': 0.669964664310954, 'repo_name': 'kochie/particle-sim-v2', 'id': 'ee8123bfe8a9bc2fa779763fa2b0a7c498bbde58', 'size': '1415', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/rendering/gui.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '670'}, {'name': 'JavaScript', 'bytes': '42888'}, {'name': 'TypeScript', 'bytes': '57612'}]} |
"""Mypy static type checker plugin for Pytest"""
import json
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Dict, List, Optional, TextIO
import attr
from filelock import FileLock # type: ignore
import mypy.api
import pytest # type: ignore
PYTEST_MAJOR_VERSION = int(pytest.__version__.partition(".")[0])
mypy_argv = []
nodeid_name = "mypy"
def default_file_error_formatter(item, results, errors):
"""Create a string to be displayed when mypy finds errors in a file."""
return "\n".join(errors)
file_error_formatter = default_file_error_formatter
def pytest_addoption(parser):
"""Add options for enabling and running mypy."""
group = parser.getgroup("mypy")
group.addoption("--mypy", action="store_true", help="run mypy on .py files")
group.addoption(
"--mypy-ignore-missing-imports",
action="store_true",
help="suppresses error messages about imports that cannot be resolved",
)
group.addoption(
"--mypy-config-file",
action="store",
type=str,
help="adds custom mypy config file",
)
XDIST_WORKERINPUT_ATTRIBUTE_NAMES = (
"workerinput",
# xdist < 2.0.0:
"slaveinput",
)
def _get_xdist_workerinput(config_node):
workerinput = None
for attr_name in XDIST_WORKERINPUT_ATTRIBUTE_NAMES:
workerinput = getattr(config_node, attr_name, None)
if workerinput is not None:
break
return workerinput
def _is_master(config):
"""
True if the code running the given pytest.config object is running in
an xdist master node or not running xdist at all.
"""
return _get_xdist_workerinput(config) is None
def pytest_configure(config):
"""
Initialize the path used to cache mypy results,
register a custom marker for MypyItems,
and configure the plugin based on the CLI.
"""
if _is_master(config):
# Get the path to a temporary file and delete it.
# The first MypyItem to run will see the file does not exist,
# and it will run and parse mypy results to create it.
# Subsequent MypyItems will see the file exists,
# and they will read the parsed results.
with NamedTemporaryFile(delete=True) as tmp_f:
config._mypy_results_path = tmp_f.name
# If xdist is enabled, then the results path should be exposed to
# the workers so that they know where to read parsed results from.
if config.pluginmanager.getplugin("xdist"):
class _MypyXdistPlugin:
def pytest_configure_node(self, node): # xdist hook
"""Pass config._mypy_results_path to workers."""
_get_xdist_workerinput(node)[
"_mypy_results_path"
] = node.config._mypy_results_path
config.pluginmanager.register(_MypyXdistPlugin())
config.addinivalue_line(
"markers",
f"{MypyItem.MARKER}: mark tests to be checked by mypy.",
)
if config.getoption("--mypy-ignore-missing-imports"):
mypy_argv.append("--ignore-missing-imports")
mypy_config_file = config.getoption("--mypy-config-file")
if mypy_config_file:
mypy_argv.append(f"--config-file={mypy_config_file}")
def pytest_collect_file(file_path, parent):
"""Create a MypyFileItem for every file mypy should run on."""
if file_path.suffix in {".py", ".pyi"} and any(
[
parent.config.option.mypy,
parent.config.option.mypy_config_file,
parent.config.option.mypy_ignore_missing_imports,
],
):
# Do not create MypyFile instance for a .py file if a
# .pyi file with the same name already exists;
# pytest will complain about duplicate modules otherwise
if file_path.suffix == ".pyi" or not file_path.with_suffix(".pyi").is_file():
return MypyFile.from_parent(parent=parent, path=file_path)
return None
if PYTEST_MAJOR_VERSION < 7: # pragma: no cover
_pytest_collect_file = pytest_collect_file
def pytest_collect_file(path, parent): # type: ignore
try:
# https://docs.pytest.org/en/7.0.x/deprecations.html#py-path-local-arguments-for-hooks-replaced-with-pathlib-path
return _pytest_collect_file(Path(str(path)), parent)
except TypeError:
# https://docs.pytest.org/en/7.0.x/deprecations.html#fspath-argument-for-node-constructors-replaced-with-pathlib-path
return MypyFile.from_parent(parent=parent, fspath=path)
class MypyFile(pytest.File):
"""A File that Mypy will run on."""
@classmethod
def from_parent(cls, *args, **kwargs):
"""Override from_parent for compatibility."""
# pytest.File.from_parent did not exist before pytest 5.4.
return getattr(super(), "from_parent", cls)(*args, **kwargs)
def collect(self):
"""Create a MypyFileItem for the File."""
yield MypyFileItem.from_parent(parent=self, name=nodeid_name)
# Since mypy might check files that were not collected,
# pytest could pass even though mypy failed!
# To prevent that, add an explicit check for the mypy exit status.
if not any(isinstance(item, MypyStatusItem) for item in self.session.items):
yield MypyStatusItem.from_parent(
parent=self,
name=nodeid_name + "-status",
)
class MypyItem(pytest.Item):
"""A Mypy-related test Item."""
MARKER = "mypy"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_marker(self.MARKER)
def collect(self):
"""
Partially work around https://github.com/pytest-dev/pytest/issues/8016
for pytest < 6.0 with --looponfail.
"""
yield self
@classmethod
def from_parent(cls, *args, **kwargs):
"""Override from_parent for compatibility."""
# pytest.Item.from_parent did not exist before pytest 5.4.
return getattr(super(), "from_parent", cls)(*args, **kwargs)
def repr_failure(self, excinfo):
"""
Unwrap mypy errors so we get a clean error message without the
full exception repr.
"""
if excinfo.errisinstance(MypyError):
return excinfo.value.args[0]
return super().repr_failure(excinfo)
class MypyFileItem(MypyItem):
"""A check for Mypy errors in a File."""
def runtest(self):
"""Raise an exception if mypy found errors for this item."""
results = MypyResults.from_session(self.session)
abspath = os.path.abspath(str(self.fspath))
errors = results.abspath_errors.get(abspath)
if errors:
raise MypyError(file_error_formatter(self, results, errors))
def reportinfo(self):
"""Produce a heading for the test report."""
return (
self.fspath,
None,
self.config.invocation_dir.bestrelpath(self.fspath),
)
class MypyStatusItem(MypyItem):
"""A check for a non-zero mypy exit status."""
def runtest(self):
"""Raise a MypyError if mypy exited with a non-zero status."""
results = MypyResults.from_session(self.session)
if results.status:
raise MypyError(f"mypy exited with status {results.status}.")
@attr.s(frozen=True, kw_only=True)
class MypyResults:
"""Parsed results from Mypy."""
_abspath_errors_type = Dict[str, List[str]]
opts = attr.ib(type=List[str])
stdout = attr.ib(type=str)
stderr = attr.ib(type=str)
status = attr.ib(type=int)
abspath_errors = attr.ib(type=_abspath_errors_type)
unmatched_stdout = attr.ib(type=str)
def dump(self, results_f: TextIO) -> None:
"""Cache results in a format that can be parsed by load()."""
return json.dump(vars(self), results_f)
@classmethod
def load(cls, results_f: TextIO) -> "MypyResults":
"""Get results cached by dump()."""
return cls(**json.load(results_f))
@classmethod
def from_mypy(
cls,
items: List[MypyFileItem],
*,
opts: Optional[List[str]] = None,
) -> "MypyResults":
"""Generate results from mypy."""
if opts is None:
opts = mypy_argv[:]
abspath_errors = {
os.path.abspath(str(item.fspath)): [] for item in items
} # type: MypyResults._abspath_errors_type
stdout, stderr, status = mypy.api.run(opts + list(abspath_errors))
unmatched_lines = []
for line in stdout.split("\n"):
if not line:
continue
path, _, error = line.partition(":")
abspath = os.path.abspath(path)
try:
abspath_errors[abspath].append(error)
except KeyError:
unmatched_lines.append(line)
return cls(
opts=opts,
stdout=stdout,
stderr=stderr,
status=status,
abspath_errors=abspath_errors,
unmatched_stdout="\n".join(unmatched_lines),
)
@classmethod
def from_session(cls, session) -> "MypyResults":
"""Load (or generate) cached mypy results for a pytest session."""
results_path = (
session.config._mypy_results_path
if _is_master(session.config)
else _get_xdist_workerinput(session.config)["_mypy_results_path"]
)
with FileLock(results_path + ".lock"):
try:
with open(results_path, mode="r") as results_f:
results = cls.load(results_f)
except FileNotFoundError:
results = cls.from_mypy(
[item for item in session.items if isinstance(item, MypyFileItem)],
)
with open(results_path, mode="w") as results_f:
results.dump(results_f)
return results
class MypyError(Exception):
"""
An error caught by mypy, e.g a type checker violation
or a syntax error.
"""
def pytest_terminal_summary(terminalreporter, config):
"""Report stderr and unrecognized lines from stdout."""
try:
with open(config._mypy_results_path, mode="r") as results_f:
results = MypyResults.load(results_f)
except FileNotFoundError:
# No MypyItems executed.
return
if results.unmatched_stdout or results.stderr:
terminalreporter.section("mypy")
if results.unmatched_stdout:
color = {"red": True} if results.status else {"green": True}
terminalreporter.write_line(results.unmatched_stdout, **color)
if results.stderr:
terminalreporter.write_line(results.stderr, yellow=True)
os.remove(config._mypy_results_path)
| {'content_hash': 'eab0f2584df28b94b8a584d457b199d5', 'timestamp': '', 'source': 'github', 'line_count': 330, 'max_line_length': 129, 'avg_line_length': 32.942424242424245, 'alnum_prop': 0.614570876644283, 'repo_name': 'dbader/pytest-mypy', 'id': 'd067925288cf4c0f4015b8c674631ef850b1d3b4', 'size': '10871', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/pytest_mypy.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '28811'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '05ae29c3a7e16882fce094cf0a4dc319', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'e970185d3ebda8c5a847e7f4f1bd41b813a4706e', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Crepis/Crepis atrabarba/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
class PropertyFileConfigurationTest: public CppUnit::TestCase
{
public:
PropertyFileConfigurationTest(const std::string& name);
~PropertyFileConfigurationTest();
void testLoad();
void testSave();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // PropertyFileConfigurationTest_INCLUDED
| {'content_hash': '3b0856aa5dc6353ee941184f806a283f', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 61, 'avg_line_length': 17.473684210526315, 'alnum_prop': 0.7620481927710844, 'repo_name': 'nocnokneo/MITK', 'id': 'cfce0edc5cb8fc3b475cd3afbf50aa868b6ebb72', 'size': '2048', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Utilities/Poco/Util/testsuite/src/PropertyFileConfigurationTest.h', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '5991982'}, {'name': 'C++', 'bytes': '29934042'}, {'name': 'CSS', 'bytes': '52056'}, {'name': 'IDL', 'bytes': '5583'}, {'name': 'Java', 'bytes': '350330'}, {'name': 'JavaScript', 'bytes': '287054'}, {'name': 'Objective-C', 'bytes': '606620'}, {'name': 'Perl', 'bytes': '982'}, {'name': 'Python', 'bytes': '7545'}, {'name': 'Shell', 'bytes': '5438'}, {'name': 'TeX', 'bytes': '1204'}, {'name': 'XSLT', 'bytes': '30684'}]} |
version: 1.2.0
title: Mnesia
---
Mnesia is a heavy duty real-time distributed database management system.
{% include toc.html %}
## Overview
Mnesia is a Database Management System (DBMS) that ships with the Erlang Runtime System which we can use naturally with Elixir.
The Mnesia *relational and object hybrid data model* is what makes it suitable for developing distributed applications of any scale.
## When to use
When to use a particular piece of technology is often a confusing pursuit.
If you can answer 'yes' to any of the following questions, then this is a good indication to use Mnesia over ETS or DETS.
- Do I need to roll back transactions?
- Do I need an easy to use syntax for reading and writing data?
- Should I store data across multiple nodes, rather than one?
- Do I need a choice where to store information (RAM or disk)?
## Schema
As Mnesia is part of the Erlang core, rather than Elixir, we have to access it with the colon syntax (See Lesson: [Erlang Interoperability](../../advanced/erlang/)):
```elixir
iex> :mnesia.create_schema([node()])
# or if you prefer the Elixir feel...
iex> alias :mnesia, as: Mnesia
iex> Mnesia.create_schema([node()])
```
For this lesson, we will take the latter approach when working with the Mnesia API.
`Mnesia.create_schema/1` initializes a new empty schema and passes in a Node List.
In this case, we are passing in the node associated with our IEx session.
## Nodes
Once we run the `Mnesia.create_schema([node()])` command via IEx, you should see a folder called **Mnesia.nonode@nohost** or similar in your present working directory.
You may be wondering what the **nonode@nohost** means as we haven't come across this before.
Let's have a look.
```shell
$ iex --help
Usage: iex [options] [.exs file] [data]
-v Prints version
-e "command" Evaluates the given command (*)
-r "file" Requires the given files/patterns (*)
-S "script" Finds and executes the given script
-pr "file" Requires the given files/patterns in parallel (*)
-pa "path" Prepends the given path to Erlang code path (*)
-pz "path" Appends the given path to Erlang code path (*)
--app "app" Start the given app and its dependencies (*)
--erl "switches" Switches to be passed down to Erlang (*)
--name "name" Makes and assigns a name to the distributed node
--sname "name" Makes and assigns a short name to the distributed node
--cookie "cookie" Sets a cookie for this distributed node
--hidden Makes a hidden node
--werl Uses Erlang's Windows shell GUI (Windows only)
--detached Starts the Erlang VM detached from console
--remsh "name" Connects to a node using a remote shell
--dot-iex "path" Overrides default .iex.exs file and uses path instead;
path can be empty, then no file will be loaded
** Options marked with (*) can be given more than once
** Options given after the .exs file or -- are passed down to the executed code
** Options can be passed to the VM using ELIXIR_ERL_OPTIONS or --erl
```
When we pass in the `--help` option to IEx from the command line we are presented with all the possible options.
We can see that there is a `--name` and `--sname` options for assigning information to nodes.
A node is just a running Erlang Virtual Machine which handles it's own communications, garbage collection, processing scheduling, memory and more.
The node is being named as **nonode@nohost** simply by default.
```shell
$ iex --name [email protected]
Erlang/OTP {{ site.erlang.OTP }} [erts-{{ site.erlang.erts }}] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir ({{ site.elixir.version }}) - press Ctrl+C to exit (type h() ENTER for help)
iex([email protected])> Node.self
:"[email protected]"
```
As we can now see, the node we are running is an atom called `:"[email protected]"`.
If we run `Mnesia.create_schema([node()])` again, we will see that it created another folder called **[email protected]**.
The purpose of this is quite simple.
Nodes in Erlang are used to connect to other nodes to share (distribute) information and resources.
This doesn't have to be restricted to the same machine and can communicate via LAN, the internet etc.
## Starting Mnesia
Now we have the background basics out of the way and set up the database, we are now in a position to start the Mnesia DBMS with the `Mnesia.start/0` command.
```elixir
iex> alias :mnesia, as: Mnesia
iex> Mnesia.create_schema([node()])
:ok
iex> Mnesia.start()
:ok
```
The function `Mnesia.start/0` is asynchronous.
It starts the initialization of the existing tables and returns the `:ok` atom.
In case we need to perform some actions on an existing table right after starting Mnesia, we need to call the `Mnesia.wait_for_tables/2` function.
It will suspend the caller until the tables are initialized.
See the example in the section [Data initialization and migration](#data-initialization-and-migration).
It is worth keeping in mind when running a distributed system with two or more participating nodes, the function `Mnesia.start/1` must be executed on all participating nodes.
## Creating Tables
The function `Mnesia.create_table/2` is used to create tables within our database.
Below we create a table called `Person` and then pass a keyword list defining the table schema.
```elixir
iex> Mnesia.create_table(Person, [attributes: [:id, :name, :job]])
{:atomic, :ok}
```
We define the columns using the atoms `:id`, `:name`, and `:job`.
The first atom (in this case `:id`) is the primary key.
At least one additional attribute is required.
When we execute `Mnesia.create_table/2`, it will return either one of the following responses:
- `{:atomic, :ok}` if the function executes successfully
- `{:aborted, Reason}` if the function failed
In particular, if the table already exists, the reason will be of the form `{:already_exists, table}` so if we try to create this table a second time, we will get:
```elixir
iex> Mnesia.create_table(Person, [attributes: [:id, :name, :job]])
{:aborted, {:already_exists, Person}}
```
## The Dirty Way
First of all we will look at the dirty way of reading and writing to a Mnesia table.
This should generally be avoided as success is not guaranteed, but it should help us learn and become comfortable working with Mnesia.
Let's add some entries to our **Person** table.
```elixir
iex> Mnesia.dirty_write({Person, 1, "Seymour Skinner", "Principal"})
:ok
iex> Mnesia.dirty_write({Person, 2, "Homer Simpson", "Safety Inspector"})
:ok
iex> Mnesia.dirty_write({Person, 3, "Moe Szyslak", "Bartender"})
:ok
```
...and to retrieve the entries we can use `Mnesia.dirty_read/1`:
```elixir
iex> Mnesia.dirty_read({Person, 1})
[{Person, 1, "Seymour Skinner", "Principal"}]
iex> Mnesia.dirty_read({Person, 2})
[{Person, 2, "Homer Simpson", "Safety Inspector"}]
iex> Mnesia.dirty_read({Person, 3})
[{Person, 3, "Moe Szyslak", "Bartender"}]
iex> Mnesia.dirty_read({Person, 4})
[]
```
If we try to query a record that doesn't exist Mnesia will respond with an empty list.
## Transactions
Traditionally we use **transactions** to encapsulate our reads and writes to our database.
Transactions are an important part of designing fault-tolerant, highly distributed systems.
An Mnesia *transaction is a mechanism by which a series of database operations can be executed as one functional block*.
First we create an anonymous function, in this case `data_to_write` and then pass it onto `Mnesia.transaction`.
```elixir
iex> data_to_write = fn ->
...> Mnesia.write({Person, 4, "Marge Simpson", "home maker"})
...> Mnesia.write({Person, 5, "Hans Moleman", "unknown"})
...> Mnesia.write({Person, 6, "Monty Burns", "Businessman"})
...> Mnesia.write({Person, 7, "Waylon Smithers", "Executive assistant"})
...> end
#Function<20.54118792/0 in :erl_eval.expr/5>
iex> Mnesia.transaction(data_to_write)
{:atomic, :ok}
```
Based on this transaction message, we can safely assume that we have written the data to our `Person` table.
Let's use a transaction to read from the database now to make sure.
We will use `Mnesia.read/1` to read from the database, but again from within an anonymous function.
```elixir
iex> data_to_read = fn ->
...> Mnesia.read({Person, 6})
...> end
#Function<20.54118792/0 in :erl_eval.expr/5>
iex> Mnesia.transaction(data_to_read)
{:atomic, [{Person, 6, "Monty Burns", "Businessman"}]}
```
Note that if you want to update data, you just need to call `Mnesia.write/1` with the same key as an existing record.
Therefore, to update the record for Hans, you can do:
```elixir
iex> Mnesia.transaction(
...> fn ->
...> Mnesia.write({Person, 5, "Hans Moleman", "Ex-Mayor"})
...> end
...> )
```
## Using indices
Mnesia support indices on non-key columns and data can then be queried against those indices.
So we can add an index against the `:job` column of the `Person` table:
```elixir
iex> Mnesia.add_table_index(Person, :job)
{:atomic, :ok}
```
The result is similar to the one returned by `Mnesia.create_table/2`:
- `{:atomic, :ok}` if the function executes successfully
- `{:aborted, Reason}` if the function failed
In particular, if the index already exists, the reason will be of the form `{:already_exists, table, attribute_index}` so if we try to add this index a second time, we will get:
```elixir
iex> Mnesia.add_table_index(Person, :job)
{:aborted, {:already_exists, Person, 4}}
```
Once the index is successfully created, we can read against it and retrieve a list of all principals:
```elixir
iex> Mnesia.transaction(
...> fn ->
...> Mnesia.index_read(Person, "Principal", :job)
...> end
...> )
{:atomic, [{Person, 1, "Seymour Skinner", "Principal"}]}
```
## Match and select
Mnesia supports complex queries to retrieve data from a table in the form of matching and ad-hoc select functions.
The `Mnesia.match_object/1` function returns all records that match the given pattern.
If any of the columns in the table have indices, it can make use of them to make the query more efficient.
Use the special atom `:_` to identify columns that don't participate in the match.
```elixir
iex> Mnesia.transaction(
...> fn ->
...> Mnesia.match_object({Person, :_, "Marge Simpson", :_})
...> end
...> )
{:atomic, [{Person, 4, "Marge Simpson", "home maker"}]}
```
The `Mnesia.select/2` function allows you to specify a custom query using any operator or function in the Elixir language (or Erlang for that matter).
Let's look at an example to select all records that have a key that is greater than 3:
```elixir
iex> Mnesia.transaction(
...> fn ->
...> {% raw %}Mnesia.select(Person, [{{Person, :"$1", :"$2", :"$3"}, [{:>, :"$1", 3}], [:"$$"]}]){% endraw %}
...> end
...> )
{:atomic, [[7, "Waylon Smithers", "Executive assistant"], [4, "Marge Simpson", "home maker"], [6, "Monty Burns", "Businessman"], [5, "Hans Moleman", "unknown"]]}
```
Let's unpack this.
The first attribute is the table, `Person`, the second attribute is a triple of the form `{match, [guard], [result]}`:
- `match` is the same as what you'd pass to the `Mnesia.match_object/1` function; however, note the special atoms `:"$n"` that specify positional parameters that are used by the remainder of the query
- the `guard` list is a list of tuples that specifies what guard functions to apply, in this case the `:>` (greater than) built in function with the first positional parameter `:"$1"` and the constant `3` as attributes
- the `result` list is the list of fields that are returned by the query, in the form of positional parameters of the special atom `:"$$"` to reference all fields so you could use `[:"$1", :"$2"]` to return the first two fields or `[:"$$"]` to return all fields
For more details, see [the Erlang Mnesia documentation for select/2](http://erlang.org/doc/man/mnesia.html#select-2).
## Data initialization and migration
With every software solution, there will come a time when you need to upgrade the software and migrate the data stored in your database.
For example, we may want to add an `:age` column to our `Person` table in v2 of our app.
We can't create the `Person` table once it's been created but we can transform it.
For this we need to know when to transform, which we can do when creating the table.
To do this, we can use the `Mnesia.table_info/2` function to retrieve the current structure of the table and the `Mnesia.transform_table/3` function to transform it to the new structure.
The code below does this by implementing the following logic:
* Create the table with the v2 attributes: `[:id, :name, :job, :age]`
* Handle the creation result:
* `{:atomic, :ok}`: initialize the table by creating indices on `:job` and `:age`
* `{:aborted, {:already_exists, Person}}`: check what the attributes are in the current table and act accordingly:
* if it's the v1 list (`[:id, :name, :job]`), transform the table giving everybody an age of 21 and add a new index on `:age`
* if it's the v2 list, do nothing, we're good
* if it's something else, bail out
If we are performing any actions on the existing tables right after starting Mnesia with `Mnesia.start/0`, those tables may not be initialized and accessible.
In that case, we should use the [`Mnesia.wait_for_tables/2`](http://erlang.org/doc/man/mnesia.html#wait_for_tables-2) function.
It will suspend the current process until the tables are initialized or until the timeout is reached.
The `Mnesia.transform_table/3` function takes as attributes the name of the table, a function that transforms a record from the old to the new format and the list of new attributes.
```elixir
case Mnesia.create_table(Person, [attributes: [:id, :name, :job, :age]]) do
{:atomic, :ok} ->
Mnesia.add_table_index(Person, :job)
Mnesia.add_table_index(Person, :age)
{:aborted, {:already_exists, Person}} ->
case Mnesia.table_info(Person, :attributes) do
[:id, :name, :job] ->
Mnesia.wait_for_tables([Person], 5000)
Mnesia.transform_table(
Person,
fn ({Person, id, name, job}) ->
{Person, id, name, job, 21}
end,
[:id, :name, :job, :age]
)
Mnesia.add_table_index(Person, :age)
[:id, :name, :job, :age] ->
:ok
other ->
{:error, other}
end
end
```
| {'content_hash': 'aea5e4c86d48535c5b8486e85017a52c', 'timestamp': '', 'source': 'github', 'line_count': 340, 'max_line_length': 261, 'avg_line_length': 42.57941176470588, 'alnum_prop': 0.7060164398701388, 'repo_name': 'nscyclone/elixir-school', 'id': 'cc1e60c8368feb935f9f7e9b166ea6a111de97da', 'size': '14482', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'en/lessons/specifics/mnesia.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '75023'}, {'name': 'HTML', 'bytes': '33698'}, {'name': 'JavaScript', 'bytes': '26015'}, {'name': 'Ruby', 'bytes': '15552'}, {'name': 'Shell', 'bytes': '25'}]} |
import six
from zope.interface import implementer, Interface
from foolscap.util import ensure_tuple_str
from foolscap.tokens import Violation, BananaError, SIZE_LIMIT, \
STRING, LIST, INT, NEG, LONGINT, LONGNEG, VOCAB, FLOAT, OPEN, \
tokenNames
everythingTaster = {
# he likes everything
STRING: None,
LIST: None,
INT: None,
NEG: None,
LONGINT: SIZE_LIMIT, # this limits numbers to about 2**8000, probably ok
LONGNEG: SIZE_LIMIT,
VOCAB: None,
FLOAT: None,
OPEN: None,
}
openTaster = {
OPEN: None,
}
nothingTaster = {}
class IConstraint(Interface):
pass
class IRemoteMethodConstraint(IConstraint):
def getPositionalArgConstraint(argnum):
"""Return the constraint for posargs[argnum]. This is called on
inbound methods when receiving positional arguments. This returns a
tuple of (accept, constraint), where accept=False means the argument
should be rejected immediately, regardless of what type it might be."""
def getKeywordArgConstraint(argname, num_posargs=0, previous_kwargs=[]):
"""Return the constraint for kwargs[argname]. The other arguments are
used to handle mixed positional and keyword arguments. Returns a
tuple of (accept, constraint)."""
def checkAllArgs(args, kwargs, inbound):
"""Submit all argument values for checking. When inbound=True, this
is called after the arguments have been deserialized, but before the
method is invoked. When inbound=False, this is called just inside
callRemote(), as soon as the target object (and hence the remote
method constraint) is located.
This should either raise Violation or return None."""
pass
def getResponseConstraint():
"""Return an IConstraint-providing object to enforce the response
constraint. This is called on outbound method calls so that when the
response starts to come back, we can start enforcing the appropriate
constraint right away."""
def checkResults(results, inbound):
"""Inspect the results of invoking a method call. inbound=False is
used on the side that hosts the Referenceable, just after the target
method has provided a value. inbound=True is used on the
RemoteReference side, just after it has finished deserializing the
response.
This should either raise Violation or return None."""
@implementer(IConstraint)
class Constraint(object):
"""
Each __schema__ attribute is turned into an instance of this class, and
is eventually given to the unserializer (the 'Unslicer') to enforce as
the tokens are arriving off the wire.
"""
taster = everythingTaster
"""the Taster is a dict that specifies which basic token types are
accepted. The keys are typebytes like INT and STRING, while the
values are size limits: the body portion of the token must not be
longer than LIMIT bytes.
"""
strictTaster = False
"""If strictTaster is True, taste violations are raised as BananaErrors
(indicating a protocol error) rather than a mere Violation.
"""
opentypes = None
"""opentypes is a list of currently acceptable OPEN token types. None
indicates that all types are accepted. An empty list indicates that no
OPEN tokens are accepted. These are native strings.
"""
name = None
"""Used to describe the Constraint in a Violation error message"""
def checkToken(self, typebyte, size):
"""Check the token type. Raise an exception if it is not accepted
right now, or if the body-length limit is exceeded."""
limit = self.taster.get(typebyte, "not in list")
if limit == "not in list":
if self.strictTaster:
raise BananaError("invalid token type: %s" %
tokenNames[typebyte])
else:
raise Violation("%s token rejected by %s" %
(tokenNames[typebyte], self.name))
if limit and size > limit:
raise Violation("%s token too large: %d>%d" %
(tokenNames[typebyte], size, limit))
def setNumberTaster(self, maxValue):
self.taster = {INT: None,
NEG: None,
LONGINT: None, # TODO
LONGNEG: None,
FLOAT: None,
}
def checkOpentype(self, opentype):
"""Check the OPEN type (the tuple of Index Tokens). Raise an
exception if it is not accepted.
"""
if self.opentypes == None:
return
opentype = ensure_tuple_str(opentype)
# shared references are always accepted. checkOpentype() is a defense
# against resource-exhaustion attacks, and references don't consume
# any more resources than any other token. For inbound method
# arguments, the CallUnslicer will perform a final check on all
# arguments (after these shared references have been resolved), and
# that will get to verify that they have resolved to the correct
# type.
#if opentype == ReferenceSlicer.opentype:
if opentype == ('reference',):
return
for o in self.opentypes:
if len(o) == len(opentype):
if o == opentype:
return
if len(o) > len(opentype):
# we might have a partial match: they haven't flunked yet
if opentype == o[:len(opentype)]:
return # still in the running
raise Violation("unacceptable OPEN type: %s not in my list %s" %
(opentype, self.opentypes))
def checkObject(self, obj, inbound):
"""Validate an existing object. Usually objects are validated as
their tokens come off the wire, but pre-existing objects may be
added to containers if a REFERENCE token arrives which points to
them. The older objects were were validated as they arrived (by a
different schema), but now they must be re-validated by the new
schema.
A more naive form of validation would just accept the entire object
tree into memory and then run checkObject() on the result. This
validation is too late: it is vulnerable to both DoS and
made-you-run-code attacks.
If inbound=True, this object is arriving over the wire. If
inbound=False, this is being called to validate an existing object
before it is sent over the wire. This is done as a courtesy to the
remote end, and to improve debuggability.
Most constraints can use the same checker for both inbound and
outbound objects.
"""
# this default form passes everything
return
COUNTERBYTES = 64 # max size of opencount
def OPENBYTES(self, dummy):
# an OPEN,type,CLOSE sequence could consume:
# 64 (header)
# 1 (OPEN)
# 64 (header)
# 1 (STRING)
# 1000 (value)
# or
# 64 (header)
# 1 (VOCAB)
# 64 (header)
# 1 (CLOSE)
# for a total of 65+1065+65 = 1195
return self.COUNTERBYTES+1 + 64+1+1000 + self.COUNTERBYTES+1
class OpenerConstraint(Constraint):
taster = openTaster
class Any(Constraint):
pass # accept everything
# constraints which describe individual banana tokens
class ByteStringConstraint(Constraint):
opentypes = [] # redundant, as taster doesn't accept OPEN
name = "ByteStringConstraint"
def __init__(self, maxLength=None, minLength=0):
self.maxLength = maxLength
self.minLength = minLength
self.taster = {STRING: self.maxLength,
VOCAB: None}
def checkObject(self, obj, inbound):
if not isinstance(obj, six.binary_type):
raise Violation("'%r' is not a bytestring" % (obj,))
if self.maxLength != None and len(obj) > self.maxLength:
raise Violation("string too long (%d > %d)" %
(len(obj), self.maxLength))
if len(obj) < self.minLength:
raise Violation("string too short (%d < %d)" %
(len(obj), self.minLength))
class IntegerConstraint(Constraint):
opentypes = [] # redundant
# taster set in __init__
name = "IntegerConstraint"
def __init__(self, maxBytes=-1):
# -1 means s_int32_t: INT/NEG instead of INT/NEG/LONGINT/LONGNEG
# None means unlimited
assert maxBytes == -1 or maxBytes == None or maxBytes >= 4
self.maxBytes = maxBytes
self.taster = {INT: None, NEG: None}
if maxBytes != -1:
self.taster[LONGINT] = maxBytes
self.taster[LONGNEG] = maxBytes
def checkObject(self, obj, inbound):
if not isinstance(obj, six.integer_types):
raise Violation("'%r' is not a number" % (obj,))
if self.maxBytes == -1:
if obj >= 2**31 or obj < -2**31:
raise Violation("number too large")
elif self.maxBytes != None:
if abs(obj) >= 2**(8*self.maxBytes):
raise Violation("number too large")
class NumberConstraint(IntegerConstraint):
"""I accept floats, ints, and longs."""
name = "NumberConstraint"
def __init__(self, maxBytes=1024):
assert maxBytes != -1 # not valid here
IntegerConstraint.__init__(self, maxBytes)
self.taster[FLOAT] = None
def checkObject(self, obj, inbound):
if isinstance(obj, float):
return
IntegerConstraint.checkObject(self, obj, inbound)
#TODO
class Shared(Constraint):
name = "Shared"
def __init__(self, constraint, refLimit=None):
self.constraint = IConstraint(constraint)
self.refLimit = refLimit
#TODO: might be better implemented with a .optional flag
class Optional(Constraint):
name = "Optional"
def __init__(self, constraint, default):
self.constraint = IConstraint(constraint)
self.default = default
| {'content_hash': '8ba252950d7f5a6a7f717767c187af25', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 79, 'avg_line_length': 37.549815498154985, 'alnum_prop': 0.6241155660377359, 'repo_name': 'warner/foolscap', 'id': 'd484465de919818e16d83fce3c8b4b5ae590a18a', 'size': '10430', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/foolscap/constraint.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '1254'}, {'name': 'Python', 'bytes': '1233676'}, {'name': 'Roff', 'bytes': '214037'}]} |
title: Overlay networking
description: Configure Calico to use IP in IP or VXLAN overlay networking so the underlying network doesn’t need to understand pod addresses.
---
### Big picture
Enable inter workload communication across networks that are not aware of workload IPs.
### Value
In general, we recommend running Calico without network overlay/encapsulation. This gives you the highest performance and simplest network; the packet that leaves your workload is the packet that goes on the wire.
However, selectively using overlays/encapsulation can be useful when running on top of an underlying network that cannot easily be made aware of workload IPs. A common example is if you are using Calico networking in AWS across multiple VPCs/subnets. In this case, Calico can selectively encapsulate only the traffic that is routed between the VPCs/subnets, and run without encapsulation within each VPC/subnet. You might also decide to run your entire Calico network with encapsulation as an overlay network -- as a quick way to get started without setting up BGP peering or other routing information in your underlying network.
### Features
This how-to guide uses the following features:
**IPPool** resource with:
- ipipMode field (IP in IP encapsulation)
- vxlanMode field (VXLAN encapsulation)
### Concepts
#### Routing workload IP addresses
Networks become aware of workload IP addresses through layer 3 routing techniques like static routes or BGP route distribution, or layer 2 address learning. As such, they can route unencapsulated traffic to the right host for the endpoint that is the ultimate destination. However, not all networks are able to route workload IP addresses. For example, public cloud environments where you don’t own the hardware, AWS across VPC subnet boundaries, and other scenarios where you cannot peer Calico over BGP to the underlay, or easily configure static routes. This is why Calico supports encapsulation, so you can send traffic between workloads without requiring the underlying network to be aware of workload IP addresses.
#### Encapsulation types
Calico supports two types of encapsulation: VXLAN and IP in IP. VXLAN is supported in some environments where IP in IP is not (for example, Azure). VXLAN has a slightly higher per-packet overhead because the header is larger, but unless you are running very network intensive workloads the difference is not something you would typically notice. The other small difference between the two types of encapsulation is that Calico's VXLAN implementation does not use BGP, whereas Calico's IP in IP implementation uses BGP between Calico nodes.
#### Cross-subnet
Encapsulation of workload traffic is typically required only when traffic crosses a router that is unable to route workload IP addresses on its own. Calico can perform encapsulation on: all traffic, no traffic, or only on traffic that crosses a subnet boundary.
### How to
You can configure each IP pool with different encapsulation configurations. However, you cannot mix encapsulation types within an IP pool.
- [Configure IP in IP encapsulation for only cross-subnet traffic](#configure-ip-in-ip-encapsulation-for-only-cross-subnet-traffic)
- [Configure IP in IP encapsulation for all inter workload traffic](#configure-ip-in-ip-encapsulation-for-all-inter-workload-traffic)
- [Configure VXLAN encapsulation for only cross-subnet traffic](#configure-vxlan-encapsulation-for-only-cross-subnet-traffic)
- [Configure VXLAN encapsulation for all inter workload traffic](#configure-vxlan-encapsulation-for-all-inter-workload-traffic)
#### IPv4/6 address support
IP in IP and VXLAN support only IPv4 addresses.
#### Best practice
Calico has an option to selectively encapsulate only traffic that crosses subnet boundaries. We recommend using the **cross-subnet** option with IP in IP or VXLAN to minimize encapsulation overhead. Cross-subnet mode provides better performance in AWS multi-AZ deployments, Azure VNETs, and on networks where routers are used to connect pools of nodes with L2 connectivity.
Be aware that switching encapsulation modes can cause disruption to in-progress connections. Plan accordingly.
#### Configure IP in IP encapsulation for only cross-subnet traffic
IP in IP encapsulation can be performed selectively, and only for traffic crossing subnet boundaries.
To enable this feature, set `ipipMode` to `CrossSubnet`.
```yaml
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
name: ippool-ipip-cross-subnet-1
spec:
cidr: 192.168.0.0/16
ipipMode: CrossSubnet
natOutgoing: true
```
#### Configure IP in IP encapsulation for all inter workload traffic
With `ipipMode` set to `Always`, Calico routes traffic using IP in IP for all traffic originating from a Calico enabled-host, to all Calico networked containers and VMs within the IP pool.
```yaml
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
name: ippool-ipip-1
spec:
cidr: 192.168.0.0/16
ipipMode: Always
natOutgoing: true
```
#### Configure VXLAN encapsulation for only cross subnet traffic
VXLAN encapsulation can be performed selectively, and only for traffic crossing subnet boundaries.
To enable this feature, set `vxlanMode` to `CrossSubnet`.
```yaml
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
name: ippool-vxlan-cross-subnet-1
spec:
cidr: 192.168.0.0/16
vxlanMode: CrossSubnet
natOutgoing: true
```
#### Configure VXLAN encapsulation for all inter workload traffic
With `vxlanMode` set to `Always`, Calico routes traffic using VXLAN for all traffic originating from a Calico enabled host, to all Calico networked containers and VMs within the IP pool.
```yaml
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
name: ippool-vxlan-1
spec:
cidr: 192.168.0.0/16
vxlanMode: Always
natOutgoing: true
```
If you use only VXLAN pools, BGP networking is not required. You can disable BGP to reduce the moving parts in your cluster by [Customizing the manifests]({{ site.baseurl }}/getting-started/kubernetes/installation/config-options). Set the `calico_backend` setting to `vxlan`, and disable the BGP readiness check.
### Above and beyond
For details on IP pool resource options, see [IP pool]({{ site.baseurl }}/reference/resources/ippool).
| {'content_hash': '4fa8d80e915bef8d75a823b4591defd3', 'timestamp': '', 'source': 'github', 'line_count': 124, 'max_line_length': 720, 'avg_line_length': 50.596774193548384, 'alnum_prop': 0.7919987248963979, 'repo_name': 'bcreane/calico', 'id': '16d6f733dbc1c56bcf633dd8047bf6cd310887b2', 'size': '6282', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'networking/vxlan-ipip.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10694'}, {'name': 'Dockerfile', 'bytes': '4393'}, {'name': 'Go', 'bytes': '7861'}, {'name': 'HTML', 'bytes': '28363'}, {'name': 'JavaScript', 'bytes': '6641'}, {'name': 'Makefile', 'bytes': '23224'}, {'name': 'Python', 'bytes': '9167'}, {'name': 'Ruby', 'bytes': '206260'}, {'name': 'Shell', 'bytes': '35202'}, {'name': 'Smarty', 'bytes': '3471'}]} |
/**
* This will only work with PhoneGap/Cordova greater or equal 2.1.0 !
* @see https://issues.apache.org/jira/browse/CB-1380
*/
Ext.application({
name: 'Loading from local FileSystem Demo',
views: [
'Ext.ux.panel.PDF'
],
launch: function() {
// Local file
// For the right path, see http://stackoverflow.com/questions/4548561/filereader-returns-empty-result-for-file-from-the-bundle
var localFile = './../myApp.app/www/resources/tracemonkey.pdf';
var viewer = Ext.create('Ext.ux.panel.PDF', {
fullscreen: true,
layout: 'fit',
style: {
backgroundColor: '#333'
}
});
Ext.Viewport.add([
{
xtype: 'toolbar',
docked: 'top',
title: 'PDF Viewer'
},
viewer
]);
function gotFileSystem(fileSystem) {
fileSystem.root.getFile(localFile, null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(readDataUrl, fail);
}
function readDataUrl(file) {
// Read the local file into a Uint8Array.
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('Read as data URL');
var base64String = evt.target.result;
// replace data:application/pdf;base64,
base64String = base64String.substring(28);
var byteArray = Base64Binary.decodeArrayBuffer(base64String);
viewer.setData(byteArray);
};
// This uses PhoneGap/Cordova FileReader API
// @see http://docs.phonegap.com/en/2.0.0/cordova_file_file.md.html#FileReader
reader.readAsDataURL(file);
}
function fail(error) {
console.log('File Error:');
switch (error.code) {
case FileError.NOT_FOUND_ERR:
console.log('NOT_FOUND_ERR');
break;
case FileError.SECURITY_ERR:
console.log('SECURITY_ERR');
break;
case FileError.ABORT_ERR:
console.log('ABORT_ERR');
break;
case FileError.NOT_READABLE_ERR:
console.log('NOT_READABLE_ERR');
break;
case FileError.ENCODING_ERR:
console.log('ENCODING_ERR');
break;
case FileError.NO_MODIFICATION_ALLOWED_ERR:
console.log('NO_MODIFICATION_ALLOWED_ERR');
break;
case FileError.INVALID_STATE_ERR:
console.log('INVALID_STATE_ERR');
break;
case FileError.SYNSYNTAX_ERRTAX_ERR:
console.log('SYNSYNTAX_ERRTAX_ERR');
break;
case FileError.INVALID_MODIFICATION_ERR:
console.log('INVALID_MODIFICATION_ERR');
break;
case FileError.QUOTA_EXCEEDED_ERR:
console.log('QUOTA_EXCEEDED_ERR');
break;
case FileError.TYPE_MISMATCH_ERR:
console.log('TYPE_MISMATCH_ERR');
break;
case FileError.PATH_EXISTS_ERR:
console.log('PATH_EXISTS_ERR');
break;
}
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem, fail);
}
}); | {'content_hash': 'd788c206f7a6785d187589b8e57c1257', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 134, 'avg_line_length': 35.28846153846154, 'alnum_prop': 0.49591280653950953, 'repo_name': 'SunboX/st2_pdf_panel', 'id': '8d349d59e062c8bbc4f035d94366c0f144403ab6', 'size': '3670', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demo/LocalFileSystem/app.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1756865'}, {'name': 'JavaScript', 'bytes': '9528633'}]} |
from django.contrib import admin
from blog_app.models import Blog, Tag
# Register your models here.
class TextAreaAdmin(admin.ModelAdmin):
class Media:
js = (
'tinymce/tinymce.min.js',
'tinymce/textarea.js',
)
class BlogAdmin(TextAreaAdmin):
#As created and modified fields are automatically generated, they are not editable and thus, would not be displayed
# as a part of editable fields section.
fields = ['title', 'body', 'published', 'slug', 'tags']
date_hierarchy = 'published_on'
prepopulated_fields = { 'slug': ('title',)}
class TagAdmin(admin.ModelAdmin):
prepopulated_fields = { 'slug' : ('title',)}
admin.site.register(Blog, BlogAdmin)
admin.site.register(Tag, TagAdmin)
| {'content_hash': '21421ff4c0859a6fbb55229ace290ee7', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 119, 'avg_line_length': 32.73913043478261, 'alnum_prop': 0.6759628154050464, 'repo_name': 'varunsagi20/varunmehta.me', 'id': 'ce5fe94ae37496b38701e2c221cfc4d4a4cecf42', 'size': '753', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'blog_app/admin.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13479'}, {'name': 'JavaScript', 'bytes': '1328'}, {'name': 'Python', 'bytes': '18559'}]} |
import re
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth import logout
from django.urls import reverse
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request, 'user')
path = request.path_info.lstrip('/')
url_is_exempt = any(url.match(path) for url in EXEMPT_URLS)
if path == reverse('debate:logout').lstrip('/'):
logout(request)
if request.user.is_authenticated() and url_is_exempt:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated() or url_is_exempt:
return None
else:
return redirect(settings.LOGIN_URL)
| {'content_hash': '64fcc0de525bc02e005d7ad844d5c02f', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 74, 'avg_line_length': 31.38888888888889, 'alnum_prop': 0.6619469026548672, 'repo_name': 'steventimberman/masterDebater', 'id': '02721f0ad072e1100aaf563f8ce886a4b1a5e82a', 'size': '1130', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'debateIt/middleware.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '673'}, {'name': 'CSS', 'bytes': '83414'}, {'name': 'HTML', 'bytes': '696030'}, {'name': 'JavaScript', 'bytes': '176225'}, {'name': 'Makefile', 'bytes': '148'}, {'name': 'Python', 'bytes': '11809652'}, {'name': 'Shell', 'bytes': '3230'}]} |
package net.bolbat.gest.fs.common.filter;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.bolbat.utils.lang.StringUtils;
import net.bolbat.utils.lang.ToStringUtils;
/**
* Class for file filtering. Implements {@link FileFilter} interface. Use {@link File} extensions for file validation.
*
* @author rkapushchak
* @see FileFilter
*/
public class FileExtensionFilter implements FileFilter {
/**
* Generated SerialVersionUID.
*/
private static final long serialVersionUID = -3852697446108691307L;
/**
* Extension for dot character.
*/
public static final String DOT_CHARACTER = ".";
/**
* Default delimiter that separated extensions list {@link String}.
*/
public static final String CHARACTER_DELIMITER = ",";
/**
* Extensions list for file filtering.
*/
private final List<String> extensions;
/**
* Default constructor. Extensions parameter is {@link String} that contains extensions separated by comma or {@link String} array of extensions.
*/
public FileExtensionFilter(final Object... parameters) {
if (parameters != null && parameters.length > 0 && parameters[0] instanceof String && !StringUtils.isEmpty(String.class.cast(parameters[0]))) {
final Set<String> extensionSet = new HashSet<>(Arrays.asList(String.class.cast(parameters[0]).split(CHARACTER_DELIMITER)));
extensions = new ArrayList<>(extensionSet);
return;
}
if (parameters != null && parameters.length > 0 && parameters[0] instanceof String[]) {
extensions = Collections.emptyList();
extensions.addAll(new HashSet<>(Arrays.asList(String.class.cast(parameters[0]))));
return;
}
throw new FileFilterRuntimeException("parameters[" + ToStringUtils.toString(parameters) + "] argument is wrong.");
}
/**
* Filter {@link File} by extension. In case when {@link File} is {@code null} or {@link File} name is empty return {@code false}.
*
* @param file
* {@link File} which should be filtered, can be {@code null}
* @return {@code true} if file is valid.
*/
@Override
public boolean accept(final File file) {
if (file == null)
return false;
if (file.isDirectory())
return true;
if (!StringUtils.isEmpty(file.getName()))
return extensionMatch(file.getName());
return false;
}
/**
* Return {@code true} if text matches with valid extensions.
*
* @param text
* {@link String} under investigation text
* @return {@code true} if text match with extensions
*/
protected boolean extensionMatch(final String text) {
if (StringUtils.isEmpty(text))
throw new IllegalArgumentException("Empty matching parameter");
for (String extension : extensions) {
final String currExtension = extension.startsWith(DOT_CHARACTER) ? extension : DOT_CHARACTER + extension;
if (text.endsWith(currExtension))
return true;
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FileExtensionFilter that = (FileExtensionFilter) o;
if (extensions != null ? !extensions.equals(that.extensions) : that.extensions != null)
return false;
return true;
}
@Override
public int hashCode() {
return extensions != null ? extensions.hashCode() : 0;
}
}
| {'content_hash': '659a889c6ef4a5d90ad06ffccb733b10', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 146, 'avg_line_length': 27.715447154471544, 'alnum_prop': 0.6996186564975067, 'repo_name': 'Squadity/bb-gest', 'id': 'e770c00fed24ad52dd116dda72059d07b5ea01b4', 'size': '3409', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fs/common/src/net/bolbat/gest/fs/common/filter/FileExtensionFilter.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '485610'}]} |
// Copyright 2012 Google Inc. All Rights Reserved
//
// 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.
//
// Author: [email protected] (Tomasz Kaftal)
//
// File containing several examples of operation benchmarks.
#include "supersonic/benchmark/examples/common_utils.h"
#include "supersonic/cursor/core/merge_union_all.h"
#include "supersonic/supersonic.h"
#include "supersonic/testing/block_builder.h"
#include "supersonic/utils/file_util.h"
#include "supersonic/utils/container_literal.h"
#include "supersonic/utils/random.h"
#include <gflags/gflags.h>
DEFINE_string(output_directory, "", "Directory to which the output files will"
" be written.");
namespace supersonic {
namespace {
using util::gtl::Container;
const size_t kInputRowCount = 1000000;
const size_t kGroupNum = 50;
Operation* CreateGroup() {
MTRandom random(0);
BlockBuilder<STRING, INT32> builder;
for (int i = 0; i < kInputRowCount; ++i) {
builder.AddRow(StringPrintf("test_string_%ld", i % kGroupNum),
random.Rand32());
}
scoped_ptr<Operation> group(GroupAggregate(
ProjectAttributeAt(0),
(new AggregationSpecification)->AddAggregation(MAX, "col1", "col1_maxes"),
NULL,
new Table(builder.Build())));
return group.release();
}
Operation* CreateCompute() {
MTRandom random(0);
BlockBuilder<INT32, INT64, DOUBLE> builder;
for (int i = 0; i < kInputRowCount; ++i) {
builder.AddRow(random.Rand32(), random.Rand64(), random.RandDouble());
}
return Compute(Multiply(AttributeAt(0),
Plus(Sin(AttributeAt(2)),
Exp(AttributeAt(1)))),
new Table(builder.Build()));
}
SortOrder* CreateExampleSortOrder() {
return (new SortOrder)
->add(ProjectAttributeAt(0), ASCENDING)
->add(ProjectAttributeAt(1), DESCENDING);
}
Operation* CreateSort(size_t input_row_count) {
MTRandom random(0);
BlockBuilder<INT32, STRING> builder;
for (int i = 0; i < input_row_count; ++i) {
builder.AddRow(random.Rand32(), StringPrintf("test_string_%d", i));
}
return Sort(
CreateExampleSortOrder(),
NULL,
std::numeric_limits<size_t>::max(),
new Table(builder.Build()));
}
Operation* CreateMergeUnion() {
return MergeUnionAll(CreateExampleSortOrder(),
Container(CreateSort(kInputRowCount),
CreateSort(2 * kInputRowCount)));
}
Operation* CreateHashJoin() {
scoped_ptr<Operation> lhs(CreateSort(kInputRowCount));
scoped_ptr<Operation> rhs(CreateGroup());
scoped_ptr<CompoundMultiSourceProjector> projector(
new CompoundMultiSourceProjector());
projector->add(0, ProjectAllAttributes("L."));
projector->add(1, ProjectAllAttributes("R."));
return new HashJoinOperation(LEFT_OUTER,
ProjectAttributeAt(1),
ProjectAttributeAt(0),
projector.release(),
UNIQUE,
lhs.release(),
rhs.release());
}
Operation* SimpleTreeExample() {
MTRandom random(0);
// col0, col1 , col2 , col3, col4
// name, salary, intern, age , boss_name
BlockBuilder<STRING, INT32, BOOL, INT32, STRING> builder;
for (int i = 0; i < kInputRowCount; ++i) {
builder.AddRow(StringPrintf("Name%d", i),
(random.Rand16() % 80) * 100,
random.Rand16() % 1000 == 0 && i > kGroupNum,
(random.Rand16() % 60) + 20,
StringPrintf("Name%ld", i % kGroupNum));
}
scoped_ptr<Operation> named_columns(
Project(ProjectRename(
Container("name", "salary", "intern", "age", "boss_name"),
ProjectAllAttributes()),
new Table(builder.Build())));
scoped_ptr<Operation> filter1(Filter(NamedAttribute("intern"),
ProjectAllAttributes(),
named_columns.release()));
scoped_ptr<Operation> compute(
Compute((new CompoundExpression)
->Add(NamedAttribute("name"))
->Add(NamedAttribute("intern"))
->Add(NamedAttribute("boss_name"))
->AddAs("ratio", Divide(NamedAttribute("salary"),
NamedAttribute("age"))),
filter1.release()));
scoped_ptr<Operation> group(GroupAggregate(
ProjectNamedAttribute("boss_name"),
(new AggregationSpecification)->AddAggregation(MAX, "ratio", "max_ratio"),
NULL,
compute.release()));
// Let every fourth pass.
scoped_ptr<Operation> filter2(Filter(
Equal(ConstInt32(0), Modulus(Sequence(), ConstInt32(4))),
ProjectAllAttributes(),
new Table(builder.Build())));
scoped_ptr<CompoundMultiSourceProjector> projector(
new CompoundMultiSourceProjector());
projector->add(0, ProjectAllAttributes("L."));
projector->add(1, ProjectAllAttributes("R."));
return new HashJoinOperation(INNER,
ProjectAttributeAt(0),
ProjectNamedAttribute("boss_name"),
projector.release(),
UNIQUE,
filter2.release(),
group.release());
}
typedef vector<Operation*>::iterator operation_iterator;
void Run() {
vector<Operation*> operations(Container(
CreateGroup(),
CreateSort(kInputRowCount),
CreateCompute(),
CreateMergeUnion(),
CreateHashJoin(),
SimpleTreeExample()));
GraphVisualisationOptions options(DOT_FILE);
for (int i = 0; i < operations.size(); ++i) {
options.file_name = File::JoinPath(
FLAGS_output_directory, StrCat("benchmark_", i, ".dot"));
// Automatically disposes of the operations after having drawn DOT graphs.
BenchmarkOperation(
operations[i],
"Operation Benchmark",
options,
/* 16KB (optimised for cache size) */ 16 * Cursor::kDefaultRowCount,
/* log result? */ false);
}
}
} // namespace
} // namespace supersonic
int main(int argc, char *argv[]) {
supersonic::SupersonicInit(&argc, &argv);
supersonic::Run();
}
| {'content_hash': '1dc56ffd73dbc5b5bea49fb0b357f0b9', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 80, 'avg_line_length': 32.81642512077295, 'alnum_prop': 0.6129839540703665, 'repo_name': 'oza/supersonic', 'id': 'ad21e9f1471cf68d2e5784970fe829f5afe8d638', 'size': '6793', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'supersonic/benchmark/examples/operation_example.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
title: "Happy beard in plaid"
excerpt: "PaperFaces portrait of @kessler drawn with Paper for iOS on an iPad."
image:
path: &image /assets/images/paperfaces-kessler-twitter.jpg
feature: *image
thumbnail: /assets/images/paperfaces-kessler-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS, beard]
---
PaperFaces portrait of [@kessler](https://twitter.com/kessler).
{% include_cached boilerplate/paperfaces.md %}
{% youtube g6r-pZY3Awc %}
| {'content_hash': 'a0bef09aba50d91e420fb722f369e04c', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 79, 'avg_line_length': 32.2, 'alnum_prop': 0.7494824016563147, 'repo_name': 'mmistakes/made-mistakes-jekyll', 'id': '2c82c7f7eb932c2c808c6c6f9b28341d69936f5c', 'size': '487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/_posts/paperfaces/2012-09-27-kessler-portrait.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '80926'}, {'name': 'HTML', 'bytes': '69057'}, {'name': 'JavaScript', 'bytes': '30944'}, {'name': 'Liquid', 'bytes': '1095'}, {'name': 'Ruby', 'bytes': '12856'}]} |
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
# Images
Each container in a pod has its own image. Currently, the only type of image supported is a [Docker Image](https://docs.docker.com/userguide/dockerimages/).
You create your Docker image and push it to a registry before referring to it in a Kubernetes pod.
The `image` property of a container supports the same syntax as the `docker` command does, including private registries and tags.
**Table of Contents**
<!-- BEGIN MUNGE: GENERATED_TOC -->
- [Images](#images)
- [Updating Images](#updating-images)
- [Using a Private Registry](#using-a-private-registry)
- [Using Google Container Registry](#using-google-container-registry)
- [Configuring Nodes to Authenticate to a Private Repository](#configuring-nodes-to-authenticate-to-a-private-repository)
- [Pre-pulling Images](#pre-pulling-images)
- [Specifying ImagePullSecrets on a Pod](#specifying-imagepullsecrets-on-a-pod)
- [Use Cases](#use-cases)
<!-- END MUNGE: GENERATED_TOC -->
## Updating Images
The default pull policy is `IfNotPresent` which causes the Kubelet to not
pull an image if it already exists. If you would like to always force a pull
you must set a pull image policy of `Always` or specify a `:latest` tag on
your image.
## Using a Private Registry
Private registries may require keys to read images from them.
Credentials can be provided in several ways:
- Using Google Container Registry
- Per-cluster
- automatically configured on Google Compute Engine or Google Container Engine
- all pods can read the project's private registry
- Configuring Nodes to Authenticate to a Private Registry
- all pods can read any configured private registries
- requires node configuration by cluster administrator
- Pre-pulling Images
- all pods can use any images cached on a node
- requires root access to all nodes to setup
- Specifying ImagePullSecrets on a Pod
- only pods which provide own keys can access the private registry
Each option is described in more detail below.
### Using Google Container Registry
Kubernetes has native support for the [Google Container
Registry (GCR)](https://cloud.google.com/tools/container-registry/), when running on Google Compute
Engine (GCE). If you are running your cluster on GCE or Google Container Engine (GKE), simply
use the full image name (e.g. gcr.io/my_project/image:tag).
All pods in a cluster will have read access to images in this registry.
The kubelet will authenticate to GCR using the instance's
Google service account. The service account on the instance
will have a `https://www.googleapis.com/auth/devstorage.read_only`,
so it can pull from the project's GCR, but not push.
### Configuring Nodes to Authenticate to a Private Repository
**Note:** if you are running on Google Container Engine (GKE), there will already be a `.dockercfg` on each node
with credentials for Google Container Registry. You cannot use this approach.
**Note:** this approach is suitable if you can control node configuration. It
will not work reliably on GCE, and any other cloud provider that does automatic
node replacement.
Docker stores keys for private registries in the `$HOME/.dockercfg` file. If you put this
in the `$HOME` of `root` on a kubelet, then docker will use it.
Here are the recommended steps to configuring your nodes to use a private registry. In this
example, run these on your desktop/laptop:
1. run `docker login [server]` for each set of credentials you want to use.
1. view `$HOME/.dockercfg` in an editor to ensure it contains just the credentials you want to use.
1. get a list of your nodes
- for example: `nodes=$(kubectl get nodes -o template --template='{{range.items}}{{.metadata.name}} {{end}}')`
1. copy your local `.dockercfg` to the home directory of root on each node.
- for example: `for n in $nodes; do scp ~/.dockercfg root@$n:/root/.dockercfg; done`
Verify by creating a pod that uses a private image, e.g.:
```yaml
$ cat <<EOF > /tmp/private-image-test-1.yaml
apiVersion: v1
kind: Pod
metadata:
name: private-image-test-1
spec:
containers:
- name: uses-private-image
image: $PRIVATE_IMAGE_NAME
imagePullPolicy: Always
command: [ "echo", "SUCCESS" ]
EOF
$ kubectl create -f /tmp/private-image-test-1.yaml
pods/private-image-test-1
$
```
If everything is working, then, after a few moments, you should see:
```console
$ kubectl logs private-image-test-1
SUCCESS
```
If it failed, then you will see:
```console
$ kubectl describe pods/private-image-test-1 | grep "Failed"
Fri, 26 Jun 2015 15:36:13 -0700 Fri, 26 Jun 2015 15:39:13 -0700 19 {kubelet node-i2hq} spec.containers{uses-private-image} failed Failed to pull image "user/privaterepo:v1": Error: image user/privaterepo:v1 not found
```
You must ensure all nodes in the cluster have the same `.dockercfg`. Otherwise, pods will run on
some nodes and fail to run on others. For example, if you use node autoscaling, then each instance
template needs to include the `.dockercfg` or mount a drive that contains it.
All pods will have read access to images in any private registry once private
registry keys are added to the `.dockercfg`.
**This was tested with a private docker repository as of 26 June with Kubernetes version v0.19.3.
It should also work for a private registry such as quay.io, but that has not been tested.**
### Pre-pulling Images
**Note:** if you are running on Google Container Engine (GKE), there will already be a `.dockercfg` on each node
with credentials for Google Container Registry. You cannot use this approach.
**Note:** this approach is suitable if you can control node configuration. It
will not work reliably on GCE, and any other cloud provider that does automatic
node replacement.
Be default, the kubelet will try to pull each image from the specified registry.
However, if the `imagePullPolicy` property of the container is set to `IfNotPresent` or `Never`,
then a local image is used (preferentially or exclusively, respectively).
If you want to rely on pre-pulled images as a substitute for registry authentication,
you must ensure all nodes in the cluster have the same pre-pulled images.
This can be used to preload certain images for speed or as an alternative to authenticating to a private registry.
All pods will have read access to any pre-pulled images.
### Specifying ImagePullSecrets on a Pod
**Note:** This approach is currently the recommended approach for GKE, GCE, and any cloud-providers
where node creation is automated.
Kubernetes supports specifying registry keys on a pod.
First, create a `.dockercfg`, such as running `docker login <registry.domain>`.
Then put the resulting `.dockercfg` file into a [secret resource](secrets.md). For example:
```console
$ docker login
Username: janedoe
Password: ●●●●●●●●●●●
Email: [email protected]
WARNING: login credentials saved in /Users/jdoe/.dockercfg.
Login Succeeded
$ echo $(cat ~/.dockercfg)
{ "https://index.docker.io/v1/": { "auth": "ZmFrZXBhc3N3b3JkMTIK", "email": "[email protected]" } }
$ cat ~/.dockercfg | base64
eyAiaHR0cHM6Ly9pbmRleC5kb2NrZXIuaW8vdjEvIjogeyAiYXV0aCI6ICJabUZyWlhCaGMzTjNiM0prTVRJSyIsICJlbWFpbCI6ICJqZG9lQGV4YW1wbGUuY29tIiB9IH0K
$ cat > /tmp/image-pull-secret.yaml <<EOF
apiVersion: v1
kind: Secret
metadata:
name: myregistrykey
data:
.dockercfg: eyAiaHR0cHM6Ly9pbmRleC5kb2NrZXIuaW8vdjEvIjogeyAiYXV0aCI6ICJabUZyWlhCaGMzTjNiM0prTVRJSyIsICJlbWFpbCI6ICJqZG9lQGV4YW1wbGUuY29tIiB9IH0K
type: kubernetes.io/dockercfg
EOF
$ kubectl create -f /tmp/image-pull-secret.yaml
secrets/myregistrykey
$
```
If you get the error message `error: no objects passed to create`, it may mean the base64 encoded string is invalid.
If you get an error message like `Secret "myregistrykey" is invalid: data[.dockercfg]: invalid value ...` it means
the data was successfully un-base64 encoded, but could not be parsed as a dockercfg file.
This process only needs to be done one time (per namespace).
Now, you can create pods which reference that secret by adding an `imagePullSecrets`
section to a pod definition.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: foo
spec:
containers:
- name: foo
image: janedoe/awesomeapp:v1
imagePullSecrets:
- name: myregistrykey
```
This needs to be done for each pod that is using a private registry.
However, setting of this field can be automated by setting the imagePullSecrets
in a [serviceAccount](service-accounts.md) resource.
Currently, all pods will potentially have read access to any images which were
pulled using imagePullSecrets. That is, imagePullSecrets does *NOT* protect your
images from being seen by other users in the cluster. Our intent
is to fix that.
You can use this in conjunction with a per-node `.dockerfile`. The credentials
will be merged. This approach will work on Google Container Engine (GKE).
### Use Cases
There are a number of solutions for configuring private registries. Here are some
common use cases and suggested solutions.
1. Cluster running only non-proprietary (e.g open-source) images. No need to hide images.
- Use public images on the Docker hub.
- no configuration required
- on GCE/GKE, a local mirror is automatically used for improved speed and availability
1. Cluster running some proprietary images which should be hidden to those outside the company, but
visible to all cluster users.
- Use a hosted private [Docker registry](https://docs.docker.com/registry/)
- may be hosted on the [Docker Hub](https://hub.docker.com/account/signup/), or elsewhere.
- manually configure .dockercfg on each node as described above
- Or, run an internal private registry behind your firewall with open read access.
- no Kubernetes configuration required
- Or, when on GCE/GKE, use the project's Google Container Registry.
- will work better with cluster autoscaling than manual node configuration
- Or, on a cluster where changing the node configuration is inconvenient, use `imagePullSecrets`.
1. Cluster with a proprietary images, a few of which require stricter access control
- Move sensitive data into a "Secret" resource, instead of packaging it in an image.
- DO NOT use imagePullSecrets for this use case yet.
1. A multi-tenant cluster where each tenant needs own private registry
- NOT supported yet.
<!-- BEGIN MUNGE: IS_VERSIONED -->
<!-- TAG IS_VERSIONED -->
<!-- END MUNGE: IS_VERSIONED -->
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[]()
<!-- END MUNGE: GENERATED_ANALYTICS -->
| {'content_hash': '66ecad702cb5ce9b739c1b78a0c330c7', 'timestamp': '', 'source': 'github', 'line_count': 262, 'max_line_length': 219, 'avg_line_length': 41.00763358778626, 'alnum_prop': 0.753723008190618, 'repo_name': 'linsun/kubernetes11', 'id': '5653fc5ec6b69a75cfd482639189973921706be7', 'size': '10766', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/user-guide/images.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '11613740'}, {'name': 'HTML', 'bytes': '1193991'}, {'name': 'Makefile', 'bytes': '18496'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'Python', 'bytes': '67433'}, {'name': 'SaltStack', 'bytes': '35576'}, {'name': 'Shell', 'bytes': '939971'}]} |
Argument unpacking does not work with string keys (forward compatibility for named args)
--FILE--
<?php
set_error_handler(function($errno, $errstr) {
var_dump($errstr);
});
var_dump(...[1, 2, "foo" => 3, 4]);
var_dump(...new ArrayIterator([1, 2, "foo" => 3, 4]));
?>
--EXPECTF--
string(36) "Cannot unpack array with string keys"
int(1)
int(2)
string(42) "Cannot unpack Traversable with string keys"
int(1)
int(2)
| {'content_hash': '2cf826c65d8e80b19d5deb07b56f486c', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 88, 'avg_line_length': 22.105263157894736, 'alnum_prop': 0.6642857142857143, 'repo_name': 'lunaczp/learning', 'id': '443a8829413dd599561b395b94be0933ce65e89b', 'size': '429', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'language/c/testPhpSrc/php-5.6.17/Zend/tests/arg_unpack/string_keys.phpt', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '4526'}, {'name': 'Assembly', 'bytes': '14500403'}, {'name': 'Awk', 'bytes': '21252'}, {'name': 'Batchfile', 'bytes': '2526'}, {'name': 'C', 'bytes': '381839655'}, {'name': 'C++', 'bytes': '10162228'}, {'name': 'CMake', 'bytes': '68196'}, {'name': 'CSS', 'bytes': '3943'}, {'name': 'D', 'bytes': '1022'}, {'name': 'DTrace', 'bytes': '4528'}, {'name': 'Fortran', 'bytes': '1834'}, {'name': 'GAP', 'bytes': '4344'}, {'name': 'GDB', 'bytes': '31864'}, {'name': 'Gnuplot', 'bytes': '148'}, {'name': 'Go', 'bytes': '732'}, {'name': 'HTML', 'bytes': '86756'}, {'name': 'Java', 'bytes': '8286'}, {'name': 'JavaScript', 'bytes': '238365'}, {'name': 'Lex', 'bytes': '121233'}, {'name': 'Limbo', 'bytes': '1609'}, {'name': 'Lua', 'bytes': '96'}, {'name': 'M4', 'bytes': '483288'}, {'name': 'Makefile', 'bytes': '1915601'}, {'name': 'Nix', 'bytes': '180099'}, {'name': 'Objective-C', 'bytes': '1742504'}, {'name': 'OpenEdge ABL', 'bytes': '4238'}, {'name': 'PHP', 'bytes': '27984629'}, {'name': 'Pascal', 'bytes': '74868'}, {'name': 'Perl', 'bytes': '317465'}, {'name': 'Perl 6', 'bytes': '6916'}, {'name': 'Python', 'bytes': '21547'}, {'name': 'R', 'bytes': '1112'}, {'name': 'Roff', 'bytes': '435717'}, {'name': 'Scilab', 'bytes': '22980'}, {'name': 'Shell', 'bytes': '468206'}, {'name': 'UnrealScript', 'bytes': '20840'}, {'name': 'Vue', 'bytes': '563'}, {'name': 'XSLT', 'bytes': '7946'}, {'name': 'Yacc', 'bytes': '172805'}, {'name': 'sed', 'bytes': '2073'}]} |
from ..Module import Module
from ..TagData import TagData
class finance(Module):
opmap = {
'infData': 'descend',
'balance': 'set',
}
def __init__(self, xmlns):
Module.__init__(self, xmlns)
self.name = 'finance'
### RESPONSE parsing
### REQUEST rendering
def render_info(self, request, data):
return self.render_default(request, data)
def render_default(self, request, data):
command = self.render_command_with_fields(request, 'info', [
])
| {'content_hash': 'bee1db772019ed3edd7480938915e7ba', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 68, 'avg_line_length': 22.73913043478261, 'alnum_prop': 0.5965583173996176, 'repo_name': 'hiqdev/reppy', 'id': 'd5883d91402e86f5ef8d990ac771c3394852b5b1', 'size': '523', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'heppy/modules/finance.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '36339'}]} |
require 'rails_helper'
RSpec.describe Bar do
before(:all) do
AppCollaborators::Loader.load 'test'
RoleLoader.load_all
end
it "responds" do
expect(bar.respond_to?(:reinstate_relationship_invitation)).to be_truthy
end
context "after bar has invited foo to be a friend" do
before(:each) do
bar_invite_foo_as_friend
use_first_relationship_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'pending'" do
expect(@relationship_invitation.status).to eq('pending')
end
it "bar is NOT foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_falsey
end
it "foo is NOT bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_falsey
end
context "after foo accepts bar's friend invitation" do
before(:each) do
accept_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'accepted'" do
expect(@relationship_invitation.status).to eq('accepted')
end
it "bar is foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_truthy
end
it "foo is bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_truthy
end
context "after bar cancels the friend invitation" do
before(:each) do
cancel_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'cancelled_accepted'" do
expect(@relationship_invitation.status).to eq('cancelled_accepted')
end
it "bar is NOT foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_falsey
end
it "foo is NOT bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_falsey
end
context "when bar reinstates the friend invitation" do
it "relationships_count changes by 2" do
expect{reinstate_invitation}.to change{relationships_count}.by(2)
end
it "has_as_count changes by 2" do
expect{reinstate_invitation}.to change{has_as_count}.by(2)
end
end
context "after bar reinstates the friend invitation" do
before(:each) do
reinstate_invitation
reload_relationship_invitation
end
it "the relationship request has a status of 'accepted'" do
expect(@relationship_invitation.status).to eq('accepted')
end
it "bar is foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_truthy
end
it "foo is bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_truthy
end
end
end
end
context "after foo declines bar's friend invitation" do
before(:each) do
decline_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'declined'" do
expect(@relationship_invitation.status).to eq('declined')
end
it "bar is NOT foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_falsey
end
it "foo is NOT bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_falsey
end
context "after bar cancels the friend invitation" do
before(:each) do
cancel_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'cancelled_declined'" do
expect(@relationship_invitation.status).to eq('cancelled_declined')
end
it "bar is NOT foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_falsey
end
it "foo is NOT bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_falsey
end
context "when bar reinstates the friend invitation" do
it "relationships_count changes by 0" do
expect{reinstate_invitation}.to change{relationships_count}.by(0)
end
it "has_as_count changes by 0" do
expect{reinstate_invitation}.to change{has_as_count}.by(0)
end
end
context "after bar reinstates the friend invitation" do
before(:each) do
reinstate_invitation
reload_relationship_invitation
end
it "the relationship_invitation has a status of 'declined'" do
expect(@relationship_invitation.status).to eq('declined')
end
it "bar is NOT foo's friend" do
expect(bar.relates_to_foo?(foo, as: 'friend')).to be_falsey
end
it "foo is NOT bar's friend" do
expect(foo.relates_to_bar?(bar, as: 'friend')).to be_falsey
end
end
end
end
end
end
def use_first_relationship_invitation
@relationship_invitation = foo.received_relationship_invitations.first
end
def use_second_relationship_invitation
@relationship_invitation = foo.received_relationship_invitations.last
end
def relationship_invitations_count
ActsAsRelatingTo::RelationshipInvitation.count
end
def relationships_count
relationships.count
end
def relationships
ActsAsRelatingTo::Relationship.all
end
def has_as_count
ActsAsHaving::HasA.count
end
def bar_invite_foo_as_friend
bar.invite_person_to_relationship(foo, as: 'friend')
end
def reinstate_invitation
bar.reinstate_relationship_invitation(id: @relationship_invitation.id)
end
def cancel_invitation
bar.cancel_relationship_invitation(id: @relationship_invitation.id)
end
def decline_invitation
foo.decline_relationship_invitation(id: @relationship_invitation.id)
end
def accept_invitation
foo.accept_relationship_invitation(id: @relationship_invitation.id)
end
def reload_relationship_invitation
@relationship_invitation.reload
end
def foo() @foo ||= create_foo end
def create_foo
Foo.create
end
def bar() @bar ||= create_bar end
def create_bar
Bar.create
end | {'content_hash': 'e91aafcd9c5e302abbbed8f7e317448c', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 80, 'avg_line_length': 31.564102564102566, 'alnum_prop': 0.6437043054427295, 'repo_name': 'josephvilla/acts_as_relating_to', 'id': '569cae405517c1aa5bf127044db5dca63fa8f096', 'size': '6155', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/dummy/spec/models/bar/reinstate_relationship_invitation_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1500'}, {'name': 'HTML', 'bytes': '5799'}, {'name': 'JavaScript', 'bytes': '1339'}, {'name': 'Ruby', 'bytes': '197063'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.