max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,002 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#pragma once
namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace UI { namespace Xaml
{
class AnimatedControlAsyncAction : public RuntimeClass<
AsyncBase<IAsyncActionCompletedHandler, ::Microsoft::WRL::Details::Nil, SingleResult, AsyncOptions<PropagateDelegateError>>, IAsyncAction>,
private LifespanTracker<AnimatedControlAsyncAction>
{
InspectableClass(InterfaceName_Windows_Foundation_IAsyncAction, BaseTrust);
ComPtr<IDispatchedHandler> m_dispatchedHandler;
public:
AnimatedControlAsyncAction(IDispatchedHandler* callback)
: m_dispatchedHandler(callback)
{
Start();
}
struct InvocationResult
{
HRESULT ActionResult;
HRESULT CompletedHandlerResult;
};
InvocationResult InvokeAndFireCompletion()
{
InvocationResult result{ S_OK, S_OK };
//
// Only actually invoke the handler if we're in a non-terminal
// state (eg we haven't been canceled already).
//
if (!IsTerminalState())
result.ActionResult = m_dispatchedHandler->Invoke();
//
// Even though the CanvasControl will handle device lost,
// the completed handler should still be notified there
// was an error and that the async handler wasn't actually
// called.
//
if (FAILED(result.ActionResult))
{
TryTransitionToError(result.ActionResult);
}
//
// FireCompletion is a method inherited from AsyncBase
// that transitions the action into a completed state.
//
// Errors from it are expected to be handled by the calling
// CanvasAnimatedControl.
//
// In particular, CanvasAnimatedControl should re-thow
// device lost so that the device can be re-created.
//
// Non-device-lost errors should result in the cancellation of
// subsequent async actions.
//
result.CompletedHandlerResult = FireCompletion();
return result;
}
void CancelAndFireCompletion()
{
(void)Cancel();
(void)FireCompletion();
}
IFACEMETHODIMP put_Completed(IAsyncActionCompletedHandler* value) override
{
return PutOnComplete(value);
}
IFACEMETHODIMP get_Completed(IAsyncActionCompletedHandler** value) override
{
return GetOnComplete(value);
}
IFACEMETHODIMP GetResults() override
{
return CheckValidStateForResultsCall();
}
protected:
virtual HRESULT OnStart() override
{
return S_OK;
}
virtual void OnClose() override
{
}
virtual void OnCancel() override
{
}
};
}}}}}}
| 1,419 |
9,425 | """
Test utility methods that the idem module and state share
"""
from contextlib import contextmanager
import salt.utils.idem as idem
import salt.utils.path
from tests.support.case import TestCase
from tests.support.unit import skipIf
HAS_IDEM = not salt.utils.path.which("idem")
@skipIf(not idem.HAS_POP[0], str(idem.HAS_POP[1]))
@contextmanager
class TestIdem(TestCase):
@classmethod
def setUpClass(cls):
cls.hub = idem.hub()
def test_loop(self):
assert hasattr(self.hub.pop, "Loop")
def test_subs(self):
for sub in ("acct", "config", "idem", "exec", "states"):
with self.subTest(sub=sub):
assert hasattr(self.hub, sub)
@skipIf(not HAS_IDEM, "idem is not installed")
def test_idem_ex(self):
assert hasattr(self.hub.idem, "ex")
@skipIf(not HAS_IDEM, "idem is not installed")
def test_idem_state_apply(self):
assert hasattr(self.hub.idem.state, "apply")
@skipIf(not HAS_IDEM, "idem is not installed")
def test_idem_exec(self):
# self.hub.exec.test.ping() causes a pylint error because of "exec" in the namespace
assert getattr(self.hub, "exec").test.ping()
@skipIf(not HAS_IDEM, "idem is not installed")
def test_idem_state(self):
ret = self.hub.states.test.succeed_without_changes({}, "test_state")
assert ret["result"] is True
def test_config(self):
assert self.hub.OPT.acct
assert self.hub.OPT.idem
| 608 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.subversion.api;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.SwingUtilities;
import org.netbeans.modules.subversion.FileInformation;
import org.netbeans.modules.subversion.FileStatusCache;
import org.netbeans.modules.subversion.RepositoryFile;
import org.netbeans.modules.subversion.SvnFileNode;
import org.netbeans.modules.subversion.SvnModuleConfig;
import org.netbeans.modules.subversion.client.SvnClient;
import org.netbeans.modules.subversion.client.SvnClientExceptionHandler;
import org.netbeans.modules.subversion.client.SvnClientFactory;
import org.netbeans.modules.subversion.client.SvnProgressSupport;
import org.netbeans.modules.versioning.hooks.SvnHook;
import org.netbeans.modules.subversion.ui.browser.Browser;
import org.netbeans.modules.subversion.ui.checkout.CheckoutAction;
import org.netbeans.modules.subversion.ui.commit.CommitAction;
import org.netbeans.modules.subversion.ui.commit.CommitOptions;
import org.netbeans.modules.subversion.ui.repository.RepositoryConnection;
import org.netbeans.modules.subversion.util.SvnUtils;
import org.netbeans.modules.versioning.util.VCSBugtrackingAccessor;
import org.openide.util.Lookup;
import org.openide.util.NbPreferences;
import org.openide.util.RequestProcessor;
import org.tigris.subversion.svnclientadapter.ISVNInfo;
import org.tigris.subversion.svnclientadapter.SVNClientException;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
/**
*
* @author <NAME>
*/
public class Subversion {
private static final String WORKINGDIR_KEY_PREFIX = "working.dir."; //NOI18N
private static final String RELATIVE_PATH_ROOT = "/"; //NOI18N
public static final String CLIENT_UNAVAILABLE_ERROR_MESSAGE = "SVN client unavailable"; //NOI18N
/**
* Displays a dialog for selection of one or more Subversion repository
* folders.
*
* @param dialogTitle title of the dialog
* @param repositoryUrl URL of the Subversion repository to browse
* @return relative paths of the selected folders,
* or {@code null} if the user cancelled the selection
* @throws java.net.MalformedURLException if the given URL is invalid
* @throws IOException some error, e.g. unavailable client
*/
public static String[] selectRepositoryFolders(String dialogTitle,
String repositoryUrl)
throws MalformedURLException, IOException {
return selectRepositoryFolders(dialogTitle, repositoryUrl, null, null);
}
/**
* Displays a dialog for selection of one or more Subversion repository
* folders.
*
* @param dialogTitle title of the dialog
* @param repositoryUrl URL of the Subversion repository to browse
* @param username username for access to the given repository
* @param password password for access to the given repository
* @return relative paths of the selected folders,
* or {@code null} if the user cancelled the selection
* @throws java.net.MalformedURLException if the given URL is invalid
* @throws IOException some error, e.g. unavailable client
*/
public static String[] selectRepositoryFolders(String dialogTitle,
String repositoryUrl,
String username,
char[] password)
throws MalformedURLException, IOException {
if (!isClientAvailable(true)) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.WARNING, "Subversion client is unavailable");
throw new IOException(CLIENT_UNAVAILABLE_ERROR_MESSAGE);
}
RepositoryConnection conn = new RepositoryConnection(repositoryUrl);
SVNUrl svnUrl = conn.getSvnUrl();
SVNRevision svnRevision = conn.getSvnRevision();
RepositoryFile repositoryFile = new RepositoryFile(svnUrl, svnRevision);
Browser browser = new Browser(dialogTitle,
Browser.BROWSER_SHOW_FILES | Browser.BROWSER_FOLDERS_SELECTION_ONLY,
repositoryFile,
null, //files to select
(username != null) ? username : "", //NOI18N
username != null ? password : null,
null, //node actions
Browser.BROWSER_HELP_ID_CHECKOUT); //PENDING - is this help ID correct?
RepositoryFile[] selectedFiles = browser.getRepositoryFiles();
if ((selectedFiles == null) || (selectedFiles.length == 0)) {
return null;
}
String[] relativePaths = makeRelativePaths(repositoryFile, selectedFiles);
return relativePaths;
}
/**
* Checks out a given folder from a given Subversion repository. The method blocks
* until the whole chcekout is done. Do not call in AWT.
*
* @param repositoryUrl URL of the Subversion repository
* @param relativePaths relative paths denoting folder the folder in the
* repository that is to be checked-out; to specify
* that the whole repository folder should be
* checked-out, use use a sing arrya containig one empty string
* @param localFolder local folder to store the checked-out files to
* @param scanForNewProjects scans the created working copy for netbenas projects
* and presents a dialog to open them eventually
*/
public static void checkoutRepositoryFolder(String repositoryUrl,
String[] relativePaths,
File localFolder,
boolean scanForNewProjects)
throws MalformedURLException, IOException {
assert !SwingUtilities.isEventDispatchThread() : "Accessing remote repository. Do not call in awt!";
checkoutRepositoryFolder(repositoryUrl,
relativePaths,
localFolder,
null,
null,
false,
scanForNewProjects);
}
/**
* Checks out a given folder from a given Subversion repository. The method blocks
* until the whole chcekout is done. Do not call in AWT.
*
* @param repositoryUrl URL of the Subversion repository
* @param relativePaths relative paths denoting folder the folder in the
* repository that is to be checked-out; to specify
* that the whole repository folder should be
* checked-out, use use a sing arrya containig one empty string
* @param localFolder local folder to store the checked-out files to
* @param atLocalFolderLevel if true the contents from the remote url with be
* checked out into the given local folder, otherwise a new folder with the remote
* folders name will be created in the local folder
* @param scanForNewProjects scans the created working copy for netbenas projects
* and presents a dialog to open them eventually
* @throws IOException when an error occurrs
*/
public static void checkoutRepositoryFolder(String repositoryUrl,
String[] relativePaths,
File localFolder,
boolean atLocalFolderLevel,
boolean scanForNewProjects)
throws MalformedURLException, IOException {
assert !SwingUtilities.isEventDispatchThread() : "Accessing remote repository. Do not call in awt!";
checkoutRepositoryFolder(repositoryUrl,
relativePaths,
localFolder,
null,
null,
scanForNewProjects);
}
/**
* Checks out a given folder from a given Subversion repository. The method blocks
* until the whole chcekout is done. Do not call in AWT.
*
* @param repositoryUrl URL of the Subversion repository
* @param relativePaths relative paths denoting folder the folder in the
* repository that is to be checked-out; to specify
* that the whole repository folder should be
* checked-out, use a string array containig one empty string
* @param localFolder local folder to store the checked-out files to
* @param username username for access to the given repository
* @param password password for access to the given repository
* @param scanForNewProjects scans the created working copy for netbenas projects
* and presents a dialog to open them eventually
* @throws IOException when an error occurrs
*/
public static void checkoutRepositoryFolder(String repositoryUrl,
String[] repoRelativePaths,
File localFolder,
String username,
String password,
boolean scanForNewProjects) throws MalformedURLException, IOException {
checkoutRepositoryFolder(
repositoryUrl,
repoRelativePaths,
localFolder,
username,
password,
false,
scanForNewProjects);
}
/**
* Checks out a given folder from a given Subversion repository. The method blocks
* until the whole chcekout is done. Do not call in AWT.
*
* @param repositoryUrl URL of the Subversion repository
* @param relativePaths relative paths denoting folder the folder in the
* repository that is to be checked-out; to specify
* that the whole repository folder should be
* checked-out, use a string array containig one empty string
* @param localFolder local folder to store the checked-out files to
* @param username username for access to the given repository
* @param password <PASSWORD> access to the given repository
* @param atLocalFolderLevel if true the contents from the remote url with be
* checked out into the given local folder, otherwise a new folder with the remote
* folders name will be created in the local folder
* @param scanForNewProjects scans the created working copy for netbenas projects
* and presents a dialog to open them eventually
* @throws IOException when an error occurrs
*/
public static void checkoutRepositoryFolder(String repositoryUrl,
String[] repoRelativePaths,
File localFolder,
String username,
String password,
boolean atLocalFolderLevel,
boolean scanForNewProjects)
throws MalformedURLException, IOException {
assert !SwingUtilities.isEventDispatchThread() : "Accessing remote repository. Do not call in awt!";
if (!isClientAvailable(true)) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.WARNING, "Subversion client is unavailable");
throw new IOException(CLIENT_UNAVAILABLE_ERROR_MESSAGE);
}
RepositoryConnection conn = new RepositoryConnection(repositoryUrl);
SVNUrl svnUrl = conn.getSvnUrl();
SVNRevision svnRevision = conn.getSvnRevision();
SvnClient client = getClient(svnUrl, username, password);
RepositoryFile[] repositoryFiles;
if(repoRelativePaths.length == 0 || (repoRelativePaths.length == 1 && repoRelativePaths[0].trim().equals(""))) {
repositoryFiles = new RepositoryFile[1];
repositoryFiles[0] = new RepositoryFile(svnUrl, ".", svnRevision);
} else {
repositoryFiles = new RepositoryFile[repoRelativePaths.length];
for (int i = 0; i < repoRelativePaths.length; i++) {
String repoRelativePath = repoRelativePaths[i];
repoRelativePath = polishRelativePath(repoRelativePath);
repositoryFiles[i] = new RepositoryFile(svnUrl, repoRelativePath, svnRevision);
}
}
boolean notVersionedYet = localFolder.exists() && !SvnUtils.isManaged(localFolder);
CheckoutAction.performCheckout(
svnUrl,
client,
repositoryFiles,
localFolder,
atLocalFolderLevel,
false, // false -> do export
scanForNewProjects).waitFinished();
try {
storeWorkingDir(new URL(repositoryUrl), localFolder.toURI().toURL());
} catch (Exception e) {
Logger.getLogger(Subversion.class.getName()).log(Level.FINE, "Cannot store subversion workdir preferences", e);
}
if(notVersionedYet) {
getSubversion().versionedFilesChanged();
SvnUtils.refreshParents(localFolder);
getSubversion().getStatusCache().refreshRecursively(localFolder);
}
VCSBugtrackingAccessor bugtrackingSupport = Lookup.getDefault().lookup(VCSBugtrackingAccessor.class);
if(bugtrackingSupport != null) {
bugtrackingSupport.setFirmAssociations(new File[]{localFolder}, repositoryUrl);
}
}
/**
* Creates a new remote folder with the given url. Missing parents also wil be created.
*
* @param url
* @param user
* @param password
* @param message
* @throws java.net.MalformedURLException
* @throws IOException when an error occurrs
*/
public static void mkdir(String url, String user, String password, String message) throws MalformedURLException, IOException {
assert !SwingUtilities.isEventDispatchThread() : "Accessing remote repository. Do not call in awt!";
if (!isClientAvailable(true)) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.WARNING, "Subversion client is unavailable");
throw new IOException(CLIENT_UNAVAILABLE_ERROR_MESSAGE);
}
SVNUrl svnUrl = new SVNUrl(url);
SvnClient client = getClient(svnUrl, user, password);
try {
client.mkdir(svnUrl, true, message);
} catch (SVNClientException ex) {
SvnClientExceptionHandler.notifyException(ex, false, true);
throw new IOException(ex.getMessage());
}
}
/**
* Adds a remote url for the combos used in Checkout and Import wizard
*
* @param url
* @throws java.net.MalformedURLException
*/
public static void addRecentUrl(String url) throws MalformedURLException {
new SVNUrl(url); // check url format
RepositoryConnection rc = new RepositoryConnection(url);
SvnModuleConfig.getDefault().insertRecentUrl(rc);
}
/**
* Commits all local chages under the given root
*
* @param root
* @param message
* @throws IOException when an error occurrs
*/
public static void commit(final File[] roots, final String user, final String password, final String message) throws IOException {
if (!isClientAvailable(true)) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.WARNING, "Subversion client is unavailable");
throw new IOException(CLIENT_UNAVAILABLE_ERROR_MESSAGE);
}
FileStatusCache cache = getSubversion().getStatusCache();
File[] files = cache.listFiles(roots, FileInformation.STATUS_LOCAL_CHANGE);
if (files.length == 0) {
return;
}
SvnFileNode[] nodes = new SvnFileNode[files.length];
for (int i = 0; i < files.length; i++) {
nodes[i] = new SvnFileNode(files[i]);
}
CommitOptions[] commitOptions = SvnUtils.createDefaultCommitOptions(nodes, false);
final Map<SvnFileNode, CommitOptions> commitFiles = new HashMap<SvnFileNode, CommitOptions>(nodes.length);
for (int i = 0; i < nodes.length; i++) {
commitFiles.put(nodes[i], commitOptions[i]);
}
try {
final SVNUrl repositoryUrl = SvnUtils.getRepositoryRootUrl(roots[0]);
RequestProcessor rp = getSubversion().getRequestProcessor(repositoryUrl);
SvnProgressSupport support = new SvnProgressSupport() {
@Override
public void perform() {
SvnClient client;
try {
client = getSubversion().getClient(repositoryUrl, user, password.toCharArray(), this);
} catch (SVNClientException ex) {
SvnClientExceptionHandler.notifyException(ex, true, true); // should not hapen
return;
}
CommitAction.performCommit(client, message, commitFiles, roots, this, false, Collections.<SvnHook>emptyList() );
}
};
support.start(rp, repositoryUrl, org.openide.util.NbBundle.getMessage(CommitAction.class, "LBL_Commit_Progress")).waitFinished(); // NOI18N
} catch (SVNClientException ex) {
SvnClientExceptionHandler.notifyException(ex, true, true);
}
}
/**
* Tries to resolve the given URL and determine if the URL represents a subversion repository
* Should not be called inside AWT, this might access network.
* @param url repository URL
* @return true if:
* <ul>
* <li>protocol is svn</li>
* <li>protocol is svn+</li>
* <li>svn client is available and invoked 'svn info' returns valid data</li>
* </ul>
* Note that this may not be 100% successful for private projects requiring authentication.
*/
public static boolean isRepository (final String url) {
boolean retval = false;
if (!isClientAvailable(false)) {
// isClientAvailable(false) -> do not show errorDialog at this point.
// The tested url may be from another vcs and we don't want to open a
// dialog with an error just becasue svn is not installed.
return false;
}
RepositoryConnection conn = new RepositoryConnection(url);
SVNUrl svnUrl = null;
try {
svnUrl = new SVNUrl(conn.getSvnUrl().toString()); // this is double check filters file://
} catch (MalformedURLException ex) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.FINE, "Invalid svn url " + url, ex);
}
if (svnUrl != null) {
String protocol = svnUrl.getProtocol();
if ("svn".equals(protocol) || protocol.startsWith("svn+")) {
// svn protocol belongs to subversion module
retval = true;
} else {
SvnClient client = null;
try {
// DO NOT HANDLE ANY EXCEPTIONS
client = getSubversion().getClient(svnUrl, conn.getUsername(), conn.getPassword(), 0);
} catch (SVNClientException ex) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.INFO, "Cannot create client for url: " + url, ex);
}
if (client != null) {
try {
ISVNInfo info = client.getInfo(svnUrl);
if (info != null) {
// repository url is valid
retval = true;
}
} catch (SVNClientException ex) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.FINE, "Invalid url: " + url, ex);
}
}
}
}
return retval;
}
/**
* Opens standard checkout wizard
* @param url repository url to checkout
* @throws java.net.MalformedURLException in case the url is invalid
* @throws IOException when an error occurrs
*/
public static void openCheckoutWizard (final String url) throws MalformedURLException, IOException {
openCheckoutWizard(url, false);
}
/**
* Opens standard checkout wizard
* @param url repository url to checkout
* @param waitFinished if true, blocks and waits for the task to finish
* @throws java.net.MalformedURLException in case the url is invalid
* @throws IOException when an error occurrs
*/
public static File openCheckoutWizard (final String url, boolean waitFinished) throws MalformedURLException, IOException {
addRecentUrl(url);
if (!isClientAvailable(true)) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.INFO, "Subversion client is unavailable");
throw new IOException(CLIENT_UNAVAILABLE_ERROR_MESSAGE);
}
return CheckoutAction.performCheckout(waitFinished);
}
/**
* Checks if the svn client is available.
*
* @param showErrorDialog - if true and client not available an error dialog
* is show and the user gets the option to download the bundled svn
* client from the UC or to correctly setup the commandline client.
* Note that an UC download might cause a NetBeans restart.
*
* @return if client available, otherwise false
*/
public static boolean isClientAvailable(boolean showErrorDialog) {
if(!showErrorDialog) {
return isClientAvailable();
} else {
if(getSubversion().checkClientAvailable()) {
return true;
}
// the client wasn't available, but it could be the user has
// setup e.g. a correct path to the cli client -> check again!
return isClientAvailable();
}
}
/**
* Checks if client is available
* @return true if client available, otherwise false
*/
private static boolean isClientAvailable() {
try {
SvnClientFactory.checkClientAvailable();
} catch (SVNClientException ex) {
org.netbeans.modules.subversion.Subversion.LOG.log(Level.INFO, "svn client not available");
return false;
}
return true;
}
private static org.netbeans.modules.subversion.Subversion getSubversion() {
return org.netbeans.modules.subversion.Subversion.getInstance();
}
private static String[] makeRelativePaths(RepositoryFile repositoryFile,
RepositoryFile[] selectedFiles) {
String[] result = new String[selectedFiles.length];
String[] repoPathSegments = repositoryFile.getPathSegments();
for (int i = 0; i < selectedFiles.length; i++) {
RepositoryFile selectedFile = selectedFiles[i];
result[i] = makeRelativePath(repoPathSegments, selectedFile.getPathSegments());
}
return result;
}
private static String makeRelativePath(String[] repoPathSegments,
String[] selectedPathSegments) {
assert isPrefixOf(repoPathSegments, selectedPathSegments);
int delta = selectedPathSegments.length - repoPathSegments.length;
if (delta == 0) {
return "/"; //root of the repository selected //NOI18N
}
if (delta == 1) {
return selectedPathSegments[selectedPathSegments.length - 1];
}
StringBuilder buf = new StringBuilder(120);
int startIndex = repoPathSegments.length;
int endIndex = selectedPathSegments.length;
buf.append(selectedPathSegments[startIndex++]);
for (int i = startIndex; i < endIndex; i++) {
buf.append('/');
buf.append(selectedPathSegments[i]);
}
return buf.toString();
}
private static boolean isPrefixOf(String[] prefix, String[] path) {
if (prefix.length > path.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (!path[i].equals(prefix[i])) {
return false;
}
}
return true;
}
/**
* Stores working directory for specified remote root
* into NetBeans preferences.
* These are later used in kenai.ui module
*/
private static void storeWorkingDir(URL remoteUrl, URL localFolder) {
Preferences prf = NbPreferences.forModule(Subversion.class);
prf.put(WORKINGDIR_KEY_PREFIX + remoteUrl, localFolder.toString());
}
private static String polishRelativePath(String path) {
if (path.length() == 0) {
throw new IllegalArgumentException("empty path"); //NOI18N
}
path = removeDuplicateSlashes(path);
if (path.equals("/")) { //NOI18N
return RELATIVE_PATH_ROOT;
}
if (path.charAt(0) == '/') {
path = path.substring(1);
}
if (path.charAt(path.length() - 1) == '/') {
path = path.substring(0, path.length() - 1);
}
return path;
}
private static boolean isRootRelativePath(String relativePath) {
return relativePath.equals(RELATIVE_PATH_ROOT);
}
private static String removeDuplicateSlashes(String str) {
int len = str.length();
StringBuilder buf = null;
boolean lastWasSlash = false;
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == '/') {
if (lastWasSlash) {
if (buf == null) {
buf = new StringBuilder(len);
buf.append(str, 0, i); //up to the first slash in a row
}
continue;
}
lastWasSlash = true;
} else {
lastWasSlash = false;
}
if (buf != null) {
buf.append(c);
}
}
return (buf != null) ? buf.toString() : str;
}
private static SvnClient getClient(SVNUrl url, String username, String password) {
try {
if(username != null) {
password = password != null ? password : ""; // NOI18N
return getSubversion().getClient(url, username, password.toCharArray());
} else {
return getSubversion().getClient(url);
}
} catch (SVNClientException ex) {
SvnClientExceptionHandler.notifyException(ex, false, true);
}
return null;
}
}
| 12,749 |
1,241 | // Copyright (c) 2020-2021 Dr. <NAME> and <NAME>
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#include <iomanip>
#include <iostream>
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/json.hpp>
#include <tao/pegtl/contrib/parse_tree.hpp>
#include <tao/pegtl/contrib/parse_tree_to_dot.hpp>
#include "json_errors.hpp"
namespace pegtl = TAO_PEGTL_NAMESPACE;
namespace example
{
using grammar = pegtl::seq< pegtl::json::text, pegtl::eof >;
template< typename Rule >
using selector = pegtl::parse_tree::selector<
Rule,
pegtl::parse_tree::remove_content::on<
pegtl::json::null,
pegtl::json::true_,
pegtl::json::false_,
pegtl::json::array,
pegtl::json::object,
pegtl::json::member >,
pegtl::parse_tree::store_content::on<
pegtl::json::number,
pegtl::json::string,
pegtl::json::key > >;
} // namespace example
int main( int argc, char** argv ) // NOLINT(bugprone-exception-escape)
{
if( argc != 2 ) {
std::cerr << "Usage: " << argv[ 0 ] << " JSON\n"
<< "Generate a 'dot' file from the JSON text.\n\n"
<< "Example: " << argv[ 0 ] << " '{\"foo\":[42,null]}' | dot -Tpng -o parse_tree.png\n";
return 1;
}
pegtl::argv_input in( argv, 1 );
#if defined( __cpp_exceptions )
try {
const auto root = pegtl::parse_tree::parse< example::grammar, example::selector, pegtl::nothing, example::control >( in );
pegtl::parse_tree::print_dot( std::cout, *root );
}
catch( const pegtl::parse_error& e ) {
const auto p = e.positions().front();
std::cerr << e.what() << std::endl
<< in.line_at( p ) << std::endl
<< std::setw( p.column ) << '^' << std::endl;
return 1;
}
#else
if( const auto root = pegtl::parse_tree::parse< example::grammar, example::selector, pegtl::nothing, example::control >( in ) ) {
pegtl::parse_tree::print_dot( std::cout, *root );
}
else {
std::cerr << "error occurred" << std::endl;
return 1;
}
#endif
return 0;
}
| 984 |
2,921 | {
"name": "Throne",
"type": "ERC20",
"symbol": "THN",
"decimals": 18,
"website": "https://www.thr.one",
"description": "Throne has developed an exciting and disruptive blockchain technology that will transform our relationship to content and empower content creators like never before.",
"explorer": "https://etherscan.io/token/<KEY>",
"status": "active",
"id": "0x2E95Cea14dd384429EB3c4331B776c4CFBB6FCD9"
} | 167 |
1,338 | <reponame>Kirishikesan/haiku<gh_stars>1000+
#ifndef CPPUNITUI_TEXT_TESTRUNNER_H
#define CPPUNITUI_TEXT_TESTRUNNER_H
#include <cppunit/Portability.h>
#include <string>
#include <vector>
namespace CppUnit {
class Outputter;
class Test;
class TestSuite;
class TextOutputter;
class TestResult;
class TestResultCollector;
namespace TextUi
{
/*!
* \brief A text mode test runner.
* \ingroup WritingTestResult
* \ingroup ExecutingTest
*
* The test runner manage the life cycle of the added tests.
*
* The test runner can run only one of the added tests or all the tests.
*
* TestRunner prints out a trace as the tests are executed followed by a
* summary at the end. The trace and summary print are optional.
*
* Here is an example of use:
*
* \code
* CppUnit::TextUi::TestRunner runner;
* runner.addTest( ExampleTestCase::suite() );
* runner.run( "", true ); // Run all tests and wait
* \endcode
*
* The trace is printed using a TextTestProgressListener. The summary is printed
* using a TextOutputter.
*
* You can specify an alternate Outputter at construction
* or later with setOutputter().
*
* After construction, you can register additional TestListener to eventManager(),
* for a custom progress trace, for example.
*
* \code
* CppUnit::TextUi::TestRunner runner;
* runner.addTest( ExampleTestCase::suite() );
* runner.setOutputter( CppUnit::CompilerOutputter::defaultOutputter(
* &runner.result(),
* cerr ) );
* MyCustomProgressTestListener progress;
* runner.eventManager().addListener( &progress );
* runner.run( "", true ); // Run all tests and wait
* \endcode
*
* \see CompilerOutputter, XmlOutputter, TextOutputter.
*/
class CPPUNIT_API TestRunner
{
public:
TestRunner( Outputter *outputter =NULL );
virtual ~TestRunner();
bool run( string testName ="",
bool doWait = false,
bool doPrintResult = true,
bool doPrintProgress = true );
void addTest( Test *test );
void setOutputter( Outputter *outputter );
TestResultCollector &result() const;
TestResult &eventManager() const;
protected:
virtual bool runTest( Test *test,
bool doPrintProgress );
virtual bool runTestByName( string testName,
bool printProgress );
virtual void wait( bool doWait );
virtual void printResult( bool doPrintResult );
virtual Test *findTestByName( string name ) const;
TestSuite *m_suite;
TestResultCollector *m_result;
TestResult *m_eventManager;
Outputter *m_outputter;
};
} // namespace TextUi
} // namespace CppUnit
#endif // CPPUNITUI_TEXT_TESTRUNNER_H
| 928 |
778 | #ifndef AMGCL_MPI_DIRECT_SOLVER_PASTIX_HPP
#define AMGCL_MPI_DIRECT_SOLVER_PASTIX_HPP
/*
The MIT License
Copyright (c) 2012-2020 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
\file amgcl/mpi/direct_solver/pastix.hpp
\author <NAME> <<EMAIL>>
\brief Wrapper for PaStiX distributed sparse solver.
See http://pastix.gforge.inria.fr
*/
#ifdef _OPENMP
# include <omp.h>
#endif
#include <type_traits>
#include <amgcl/util.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/mpi/util.hpp>
#include <amgcl/mpi/direct_solver/solver_base.hpp>
extern "C" {
#include <pastix.h>
}
namespace amgcl {
namespace mpi {
namespace direct {
/// Provides distributed direct solver interface for pastix solver.
/**
* \sa http://pastix.gforge.<EMAIL>, \cite Henon2002
*/
template <typename value_type, bool Distrib=false>
class pastix : public solver_base< value_type, pastix<value_type, Distrib> > {
public:
static_assert(
std::is_same<value_type, float >::value ||
std::is_same<value_type, double>::value,
"Unsupported value type for pastix solver"
);
typedef backend::crs<value_type> build_matrix;
struct params {
int max_rows_per_process;
params()
: max_rows_per_process(50000)
{}
#ifndef AMGCL_NO_BOOST
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_VALUE(p, max_rows_per_process)
{
check_params(p, {"max_rows_per_process"});
}
void get(boost::property_tree::ptree &p, const std::string &path) const {
AMGCL_PARAMS_EXPORT_VALUE(p, path, max_rows_per_process);
}
#endif
};
/// Constructor.
template <class Matrix>
pastix(communicator comm, const Matrix &A,
const params &prm = params()) : prm(prm), pastix_data(0)
{
static_cast<Base*>(this)->init(comm, A);
}
static size_t coarse_enough() {
return 10000;
}
int comm_size(int n) const {
return Distrib ? (n + prm.max_rows_per_process - 1) / prm.max_rows_per_process : 1;
}
void init(communicator C, const build_matrix &A) {
comm = C;
nrows = A.nrows;
ptr.assign(A.ptr, A.ptr + A.nrows + 1);
col.assign(A.col, A.col + A.nnz);
val.assign(A.val, A.val + A.nnz);
row.resize(nrows);
perm.resize(nrows);
if (!Distrib) inv_perm.resize(nrows);
std::vector<int> domain = comm.exclusive_sum(nrows);
// PaStiX needs 1-based matrices:
for(pastix_int_t &p : ptr) ++p;
for(pastix_int_t &c : col) ++c;
for(int i = 0, j = domain[comm.rank]; i < nrows; ++i)
row[i] = ++j;
// Initialize parameters with default values:
iparm[IPARM_MODIFY_PARAMETER] = API_NO;
call_pastix(API_TASK_INIT, API_TASK_INIT);
// Factorize the matrix.
#ifdef NDEBUG
iparm[IPARM_VERBOSE ] = API_VERBOSE_NOT;
#else
iparm[IPARM_VERBOSE ] = API_VERBOSE_YES;
#endif
iparm[IPARM_RHS_MAKING ] = API_RHS_B;
iparm[IPARM_SYM ] = API_SYM_NO;
iparm[IPARM_FACTORIZATION ] = API_FACT_LU;
iparm[IPARM_TRANSPOSE_SOLVE] = API_YES;
#ifdef _OPENMP
iparm[IPARM_THREAD_NBR] = omp_get_max_threads();
#endif
call_pastix(API_TASK_ORDERING, API_TASK_NUMFACT);
}
/// Cleans up internal PaStiX data.
~pastix() {
if(pastix_data) call_pastix(API_TASK_CLEAN, API_TASK_CLEAN);
}
/// Solves the problem for the given right-hand side.
/**
* \param rhs The right-hand side.
* \param x The solution.
*/
template <class Vec1, class Vec2>
void solve(const Vec1 &rhs, Vec2 &x) const {
for(int i = 0; i < nrows; ++i) x[i] = rhs[i];
call_pastix(API_TASK_SOLVE, API_TASK_SOLVE, &x[0]);
}
private:
typedef solver_base< value_type, pastix<value_type, Distrib> > Base;
params prm;
amgcl::mpi::communicator comm;
int nrows;
// Pastix internal data.
mutable pastix_data_t *pastix_data;
// Pastix parameters
mutable pastix_int_t iparm[IPARM_SIZE];
mutable double dparm[DPARM_SIZE];
std::vector<pastix_int_t> ptr;
std::vector<pastix_int_t> col;
std::vector<value_type> val;
// Local to global mapping
std::vector<pastix_int_t> row;
// Permutation array
std::vector<pastix_int_t> perm;
std::vector<pastix_int_t> inv_perm;
void call_pastix(int beg, int end, value_type *x = NULL) const {
iparm[IPARM_START_TASK] = beg;
iparm[IPARM_END_TASK ] = end;
call_pastix(x);
}
void call_pastix(double *x) const {
if (Distrib) {
d_dpastix(&pastix_data, comm, nrows,
const_cast<pastix_int_t*>(&ptr[0]),
const_cast<pastix_int_t*>(&col[0]),
const_cast<double* >(&val[0]),
const_cast<pastix_int_t*>(&row[0]),
const_cast<pastix_int_t*>(&perm[0]),
NULL, x, 1, iparm, dparm
);
} else {
d_pastix(&pastix_data, comm, nrows,
const_cast<pastix_int_t*>(&ptr[0]),
const_cast<pastix_int_t*>(&col[0]),
const_cast<double* >(&val[0]),
const_cast<pastix_int_t*>(&perm[0]),
const_cast<pastix_int_t*>(&inv_perm[0]),
x, 1, iparm, dparm
);
}
}
void call_pastix(float *x) const {
if (Distrib) {
s_dpastix(&pastix_data, comm, nrows,
const_cast<pastix_int_t*>(&ptr[0]),
const_cast<pastix_int_t*>(&col[0]),
const_cast<float* >(&val[0]),
const_cast<pastix_int_t*>(&row[0]),
const_cast<pastix_int_t*>(&perm[0]),
NULL, x, 1, iparm, dparm
);
} else {
s_pastix(&pastix_data, comm, nrows,
const_cast<pastix_int_t*>(&ptr[0]),
const_cast<pastix_int_t*>(&col[0]),
const_cast<float* >(&val[0]),
const_cast<pastix_int_t*>(&perm[0]),
const_cast<pastix_int_t*>(&inv_perm[0]),
x, 1, iparm, dparm
);
}
}
};
} // namespace direct
} // namespace mpi
} // namespace amgcl
#endif
| 4,271 |
9,136 | <filename>examples/OpenCL/CommonOpenCL/GpuDemoInternalData.h
#ifndef GPU_DEMO_INTERNAL_DATA_H
#define GPU_DEMO_INTERNAL_DATA_H
#include "Bullet3OpenCL/Initialize/b3OpenCLInclude.h"
struct GpuDemoInternalData
{
cl_platform_id m_platformId;
cl_context m_clContext;
cl_device_id m_clDevice;
cl_command_queue m_clQueue;
bool m_clInitialized;
char* m_clDeviceName;
GpuDemoInternalData()
: m_platformId(0),
m_clContext(0),
m_clDevice(0),
m_clQueue(0),
m_clInitialized(false),
m_clDeviceName(0)
{
}
};
#endif
| 240 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/sandbox_status_service.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "sandbox/policy/linux/sandbox_linux.h"
namespace content {
// static
void SandboxStatusService::MakeSelfOwnedReceiver(
mojo::PendingReceiver<mojom::SandboxStatusService> receiver) {
mojo::MakeSelfOwnedReceiver(std::make_unique<SandboxStatusService>(),
std::move(receiver));
}
SandboxStatusService::SandboxStatusService() = default;
SandboxStatusService::~SandboxStatusService() = default;
void SandboxStatusService::GetSandboxStatus(GetSandboxStatusCallback callback) {
std::move(callback).Run(
sandbox::policy::SandboxLinux::GetInstance()->GetStatus());
}
} // namespace content
| 304 |
343 | <reponame>talatkuyuk/blessed-android
package com.welie.blessed;
import static android.bluetooth.le.ScanSettings.SCAN_MODE_BALANCED;
import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_LATENCY;
import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_POWER;
/**
* This class represents the possible scan modes
*/
public enum ScanMode {
/**
* A special Bluetooth LE scan mode. Applications using this scan mode will passively listen for
* other scan results without starting BLE scans themselves.
*/
OPPORTUNISTIC(-1),
/**
* Perform Bluetooth LE scan in balanced power mode. Scan results are returned at a rate that
* provides a good trade-off between scan frequency and power consumption.
*/
BALANCED(SCAN_MODE_BALANCED),
/**
* Scan using highest duty cycle. It's recommended to only use this mode when the application is
* running in the foreground.
*/
LOW_LATENCY(SCAN_MODE_LOW_LATENCY),
/**
* Perform Bluetooth LE scan in low power mode. This is the default scan mode as it consumes the
* least power. This mode is enforced if the scanning application is not in foreground.
*/
LOW_POWER(SCAN_MODE_LOW_POWER);
ScanMode(final int value) {
this.value = value;
}
public final int value;
}
| 446 |
1,886 | <gh_stars>1000+
typedef struct _typeobject {
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
/* Methods to implement standard operations */
destructor tp_dealloc;
Py_ssize_t tp_vectorcall_offset;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
or tp_reserved (Python 3) */
reprfunc tp_repr;
/* Method suites for standard classes */
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
/* More standard operations (here for binary compatibility) */
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;
/* Flags to define presence of optional/expanded features */
unsigned long tp_flags;
const char *tp_doc; /* Documentation string */
/* call function for all accessible objects */
traverseproc tp_traverse;
/* delete references to contained objects */
inquiry tp_clear;
/* rich comparisons */
richcmpfunc tp_richcompare;
/* weak reference enabler */
Py_ssize_t tp_weaklistoffset;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
/* Type attribute cache version tag. Added in version 2.6 */
unsigned int tp_version_tag;
destructor tp_finalize;
} PyTypeObject;
| 895 |
1,007 | # -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Nov 12, 2014
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
from __future__ import print_function
from collections import namedtuple
import logging
import os
import shutil
import socket
import struct
import sys
from tarfile import TarFile
import threading
from time import time
import unittest
from numpy.random import randint
import pygit2
from six import BytesIO
from tornado import gen
from tornado.httpclient import HTTPClient, HTTPRequest, HTTPError
from tornado.ioloop import IOLoop
from veles import __root__
from veles.config import root
from veles.forge.forge_server import ForgeServer
while True:
PORT = 8067 + randint(-1000, 1000)
probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if probe.connect_ex(('127.0.0.1', PORT)):
probe.close()
break
ForgeServerArgs = namedtuple(
"ForgeServerArgs", ("root", "port", "smtp_host", "smtp_port", "smtp_user",
"smtp_password", "email_sender", "verbose"))
class FakeSMTP(object):
@gen.coroutine
def sendmail(self, sender, addr, msg):
self.sender = sender
self.addr = addr
self.msg = msg
@gen.coroutine
def quit(self):
pass
class TestForgeServer(unittest.TestCase):
ioloop_thread = None
server = None
fake_smtp = FakeSMTP()
@classmethod
def setUpClass(cls):
cls.ioloop_thread = threading.Thread(
target=IOLoop.instance().start)
base = os.path.join(__root__, "veles/tests/forge")
for name in ("First", "Second"):
path = os.path.join(base, os.path.join(name, ".git"))
if os.path.exists(path):
shutil.rmtree(path)
with TarFile.open(
os.path.join(base, "%s.git.tar.gz" % name)) as tar:
tar.extractall(os.path.join(base, name))
sys.stderr = sys.stdout
cls.server = ForgeServer(ForgeServerArgs(
base, PORT, "smtp_host", 25, "user", "password", "from", True))
cls.server.smtp = TestForgeServer.smtp.__get__(cls.server)
cls.server.run(loop=False)
cls.ioloop_thread.start()
def setUp(self):
self.client = HTTPClient()
self.base = os.path.join(__root__, "veles/tests/forge")
@classmethod
def tearDownClass(cls):
IOLoop.instance().stop()
cls.ioloop_thread.join()
@gen.coroutine
def smtp(self):
return TestForgeServer.fake_smtp
def test_list(self):
response = self.client.fetch(
"http://localhost:%d/service?query=list" % PORT)
self.assertEqual(
response.body,
b'[["First", "First test model", "<NAME>", "master",'
b' "2014-11-17 11:02:24"],["Second", "Second test model", '
b'"<NAME>", "1.0.0", "2014-11-17 11:00:46"]]')
def test_details(self):
response = self.client.fetch(
"http://localhost:%d/service?query=details&name=Second" % PORT)
self.assertEqual(
response.body,
b'{"date": "2014-11-17 11:00:46", "description": "Second test '
b'model LOOONG textz", "name": "Second", "version": "1.0.0"}')
def _test_fetch_case(self, query, files):
response = self.client.fetch(
"http://localhost:%d/fetch?%s" % (PORT, query))
with TarFile.open(fileobj=BytesIO(response.body)) as tar:
self.assertEqual(set(tar.getnames()), files)
def test_fetch(self):
files = {'manifest.json', 'workflow.py', 'workflow_config.py'}
self._test_fetch_case("name=First", files)
self._test_fetch_case("name=First&version=master", files)
files = {'manifest.json', 'second.py', 'config.py'}
self._test_fetch_case("name=Second&version=1.0.0", files)
def _compose_upload(self, file):
name = os.path.splitext(os.path.splitext(file)[0])[0]
mfn = os.path.join(self.base, name + "_" + root.common.forge.manifest)
tarfn = os.path.join(self.base, file)
body = bytearray(4 + os.path.getsize(mfn) + os.path.getsize(tarfn))
body[:4] = struct.pack('!I', os.path.getsize(mfn))
with open(mfn, 'rb') as fin:
body[4:4 + os.path.getsize(mfn)] = fin.read()
with open(tarfn, 'rb') as fin:
body[4 + os.path.getsize(mfn):] = fin.read()
logging.debug("Will send %d (incl. metadata: 4 + %d) bytes",
len(body), os.path.getsize(mfn))
return bytes(body)
def test_upload(self):
src_path = os.path.join(self.base, "Second")
bak_path = os.path.join(self.base, "Second.bak")
shutil.copytree(src_path, bak_path)
TestForgeServer.server.tokens[
TestForgeServer.server.scramble("secret")] = "<EMAIL>"
try:
try:
self.client.fetch(HTTPRequest(
method='POST',
url="http://localhost:%d/upload?token=n" % PORT,
body=self._compose_upload("second_bad.tar.gz")))
self.fail("HTTPError was not thrown")
except HTTPError as e:
self.assertEqual(e.response.code, 403)
try:
self.client.fetch(HTTPRequest(
method='POST', url="http://localhost:%d/upload?token=%s" %
(PORT, "secret"),
body=self._compose_upload("second_bad.tar.gz")))
self.fail("HTTPError was not thrown")
except HTTPError as e:
self.assertGreaterEqual(
e.response.body.find(b'No new changes'), 0)
response = self.client.fetch(HTTPRequest(
method='POST', url="http://localhost:%d/upload?token=%s" % (
PORT, "secret"),
body=self._compose_upload("second_good.tar.gz")))
self.assertEqual(response.reason, 'OK')
rep = pygit2.Repository(os.path.join(self.base, "Second"))
self.assertEqual("2.0.0", rep.head.get_object().message)
self.assertEqual(
2, len([c for c in rep.walk(rep.head.target,
pygit2.GIT_SORT_TOPOLOGICAL)]))
self.assertIsNotNone(rep.lookup_reference("refs/tags/2.0.0"))
finally:
shutil.rmtree(src_path)
shutil.move(bak_path, src_path)
def test_upload_new(self):
TestForgeServer.server.tokens[
TestForgeServer.server.scramble("secret")] = "<EMAIL>"
try:
response = self.client.fetch(HTTPRequest(
method='POST', url="http://localhost:%d/upload?token=%s" % (
PORT, "secret"),
body=self._compose_upload("First2.tar.gz")))
self.assertEqual(response.reason, 'OK')
rep = pygit2.Repository(os.path.join(self.base, "First2"))
self.assertEqual("master", rep.head.get_object().message)
self.assertEqual(
1, len([c for c in rep.walk(
rep.head.target, pygit2.GIT_SORT_TOPOLOGICAL)]))
finally:
rpath = os.path.join(self.base, "First2")
if os.path.exists(rpath):
shutil.rmtree(rpath)
def test_delete(self):
dirname = os.path.join(self.base, "Second")
shutil.copytree(dirname, dirname + ".bak")
deldir = os.path.join(self.base, ForgeServer.DELETED_DIR)
TestForgeServer.server.tokens[
TestForgeServer.server.scramble("secret")] = "<EMAIL>"
try:
response = self.client.fetch(
"http://localhost:%d/service?query=delete&name=Second&"
"token=secret" % PORT)
self.assertEqual(response.body, b'OK')
self.assertFalse(os.path.exists(dirname))
self.assertTrue(os.path.exists(deldir))
backup_file = list(os.walk(deldir))[0][2][0]
with TarFile.open(os.path.join(deldir, backup_file)) as tar:
tar.extractall(deldir)
orig_files = set(list(os.walk(dirname + ".bak"))[0][2])
extr_files = set(list(os.walk(deldir))[0][2])
self.assertEqual(extr_files.difference(orig_files), {backup_file})
finally:
if os.path.exists(dirname):
shutil.rmtree(dirname)
shutil.copytree(dirname + ".bak", dirname)
shutil.rmtree(dirname + ".bak")
if os.path.exists(deldir):
shutil.rmtree(deldir)
TestForgeServer.server._build_db()
def test_register_bad(self):
self.assertRaises(
HTTPError, self.client.fetch,
"http://localhost:%d/service?query=register&"
"email=bademail.com" % PORT)
self.assertRaises(
HTTPError, self.client.fetch,
"http://localhost:%d/service?query=register&"
"email=bad=<EMAIL>" % PORT)
self.assertRaises(
HTTPError, self.client.fetch,
"http://localhost:%d/service?query=register&"
"email=" % PORT)
def do_register(self):
TestForgeServer.server._tokens = {}
TestForgeServer.server._tokens_timestamp = time()
TestForgeServer.server._emails = {}
response = self.client.fetch(
"http://localhost:%d/service?query=register&"
"email=<EMAIL>" % PORT)
self.assertTrue(
b"The confirmation email has been sent to <EMAIL>"
in response.body)
pos = self.fake_smtp.msg.find("token=") + len("token=")
token = self.fake_smtp.msg[pos:pos+36]
response = self.client.fetch(
"http://localhost:%d/service?query=confirm&"
"token=%s" % (PORT, token))
self.assertTrue(
("Registered, your token is %s" % token).encode("utf-8")
in response.body)
TestForgeServer.server._emails = {
"<EMAIL>": self.server.scramble(token)}
return token
def test_register_unregister(self):
token = self.do_register()
response = self.client.fetch(
"http://localhost:%d/service?query=unregister&"
"email=<EMAIL>" % PORT)
self.assertTrue(
b"The confirmation email has been sent to <EMAIL>"
in response.body)
response = self.client.fetch(
"http://localhost:%d/service?query=unconfirm&"
"token=%s" % (PORT, self.server.scramble(token)))
self.assertTrue(b"Successfully unregistered" in response.body)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
unittest.main()
| 5,584 |