From 1cb758875701fbb631efe86df9132eabb4357e69 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 6 Oct 2014 19:10:32 +0200 Subject: [PATCH 01/26] EA-61137 - IOE: PsiJavaParserFacadeImpl.createExpressionFromText --- .../codeInsight/javadoc/JavaDocInfoGenerator.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 18dbccb258c5..3c9e76151e1d 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -639,13 +639,15 @@ public class JavaDocInfoGenerator { String text = o.toString(); PsiType type = variable.getType(); if (type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { - text = "\"" + StringUtil.escapeLineBreak(StringUtil.shortenPathWithEllipsis(text, 120)) + "\""; + text = "\"" + StringUtil.escapeStringCharacters(StringUtil.shortenPathWithEllipsis(text, 120)) + "\""; + } + else if (type.equalsToText("char")) { + text = "'" + text + "'"; } - else if (type.equalsToText("char")) text = "'" + text + "'"; try { return instance.getElementFactory().createExpressionFromText(text, variable); } catch (IncorrectOperationException ex) { - LOG.error(text, ex); + LOG.info("type:" + type.getCanonicalText() + "; text: " + text, ex); } } } From 6456f0b335c1a053cbc5883ba55fffff765abbbd Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 6 Oct 2014 19:14:24 +0200 Subject: [PATCH 02/26] EA-61050 - NPE: JavaSafeDeleteProcessor.findConflicts --- .../refactoring/safeDelete/JavaSafeDeleteProcessor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java index 807700bc52ae..f236f79473a8 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java @@ -223,7 +223,7 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { if (element instanceof PsiMethod) { final PsiClass containingClass = ((PsiMethod)element).getContainingClass(); - if (!containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + if (containingClass != null && !containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) { final PsiMethod[] superMethods = ((PsiMethod) element).findSuperMethods(); for (PsiMethod superMethod : superMethods) { if (isInside(superMethod, allElementsToDelete)) continue; From 018c907d85f4151f8575836b231b3298eeb3f61e Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 6 Oct 2014 19:17:23 +0200 Subject: [PATCH 03/26] exclude classes without correct VM name from tests run EA-61053 - NPE: LaunchSuite$ClassesAndMethodsSuite.initContentBuffer --- .../testng/configuration/SearchingForTestsTask.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java index ccc820a83817..32a9734c7562 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java @@ -207,14 +207,17 @@ public class SearchingForTestsTask extends Task.Backgroundable { } } } - map.put(ApplicationManager.getApplication().runReadAction( + final String className = ApplicationManager.getApplication().runReadAction( new Computable() { @Nullable public String compute() { return ClassUtil.getJVMClassName(entry.getKey()); } } - ), methods); + ); + if (className != null) { + map.put(className, methods); + } } // We have groups we wish to limit to. Collection groupNames = null; From a50ffc0bdacb159dc873529f73a0cca0b0d0f288 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Tue, 7 Oct 2014 10:03:25 +0200 Subject: [PATCH 04/26] dispose in tests (cherry picked from commit 2b3a211bd553fc0a2e71cc0cb91063e87dca9311) --- .../codeInspection/SingleInspectionProfilePanelTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/SingleInspectionProfilePanelTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/SingleInspectionProfilePanelTest.java index 255358b1bb84..3d750352f383 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/SingleInspectionProfilePanelTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/SingleInspectionProfilePanelTest.java @@ -55,6 +55,7 @@ public class SingleInspectionProfilePanelTest extends LightIdeaTestCase { assertEquals(1, InspectionProfileTest.countInitializedTools(model)); assertEquals("foo", getInspection(profile).myAdditionalJavadocTags); + panel.disposeUI(); } public void testModifyInstantiatedTool() throws Exception { @@ -82,6 +83,7 @@ public class SingleInspectionProfilePanelTest extends LightIdeaTestCase { assertEquals(1, InspectionProfileTest.countInitializedTools(model)); assertEquals("bar", getInspection(profile).myAdditionalJavadocTags); + panel.disposeUI(); } public void testDoNotChangeSettingsOnCancel() throws Exception { From 94dcb7c2fc8929a02c9a8307085812c92e55f8e8 Mon Sep 17 00:00:00 2001 From: Alexander Doroshko Date: Tue, 7 Oct 2014 15:11:42 +0400 Subject: [PATCH 05/26] excludedGeneratedRoot.png icon --- .../icons/src/modules/excludedGeneratedRoot.png | Bin 0 -> 319 bytes .../src/modules/excludedGeneratedRoot@2x.png | Bin 0 -> 622 bytes .../src/modules/excludedGeneratedRoot@2x_dark.png | Bin 0 -> 620 bytes .../src/modules/excludedGeneratedRoot_dark.png | Bin 0 -> 326 bytes .../util/src/com/intellij/icons/AllIcons.java | 1 + 5 files changed, 1 insertion(+) create mode 100644 platform/icons/src/modules/excludedGeneratedRoot.png create mode 100644 platform/icons/src/modules/excludedGeneratedRoot@2x.png create mode 100644 platform/icons/src/modules/excludedGeneratedRoot@2x_dark.png create mode 100644 platform/icons/src/modules/excludedGeneratedRoot_dark.png diff --git a/platform/icons/src/modules/excludedGeneratedRoot.png b/platform/icons/src/modules/excludedGeneratedRoot.png new file mode 100644 index 0000000000000000000000000000000000000000..bd49906d7f07b97ad4deefe86a405b34d9fb4ffa GIT binary patch literal 319 zcmV-F0l@x=P)TJ?R#GEST`{o+OaU&_b`p|G=AP554rLus@Pb;znG}kIlhQO(Yx5#z_VK#Mo9m6tQ$|yHfHtP5o$lwH!T1y;?ry*XM=#;7JNkD!u~e=4IHo51v(-95waSf7NAgriBU0%?MP2GVlx(fhTR4#;d)nmTjk7;o}&)9=x4i literal 0 HcmV?d00001 diff --git a/platform/icons/src/modules/excludedGeneratedRoot_dark.png b/platform/icons/src/modules/excludedGeneratedRoot_dark.png new file mode 100644 index 0000000000000000000000000000000000000000..f2a8ac7a150d8d1bb92e9cc345d4a097f6e99d73 GIT binary patch literal 326 zcmV-M0lEH(P)X zDiBKpF$)kc2I4oDyPF$<>WYaqU@8!|0&y%5gPfgmr82MRN>N%au?B!_{Q|^&K>PrR z7XtCW^QTU}1Jb6%7@!ZtFM#+V5QF@E^1}8ldoFC*upP)QA!I-;5cdP|bRa$p#J7R? z@%huI-e2l(Z^7mTWIXxO(ge^X34ZzwN?~tp|_|K*3nzUK5D#K?9N*h{d4MOL=Yt Y00}ptwvTDOegFUf07*qoM6N<$f Date: Tue, 7 Oct 2014 14:01:38 +0200 Subject: [PATCH 06/26] project: dependency validation scopes tuned --- .idea/scopes/util_rt_dependencies.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/scopes/util_rt_dependencies.xml b/.idea/scopes/util_rt_dependencies.xml index 0014b767c9fb..763451da8bff 100644 --- a/.idea/scopes/util_rt_dependencies.xml +++ b/.idea/scopes/util_rt_dependencies.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file From 07fe06ea7c4a4f1840ed43b985663b9a09b0eb9d Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Tue, 7 Oct 2014 16:08:11 +0400 Subject: [PATCH 07/26] IDEA-130874 diff: show "Revert dialog" if no line markers selected by caret --- .../openapi/vcs/ex/RollbackLineStatusAction.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java index 529da7371bf7..24ac8fd1c2a3 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java @@ -44,6 +44,11 @@ public class RollbackLineStatusAction extends DumbAwareAction { e.getPresentation().setEnabledAndVisible(false); return; } + if (!isSomeChangeSelected(editor, tracker)) { + e.getPresentation().setVisible(true); + e.getPresentation().setEnabled(false); + return; + } e.getPresentation().setEnabledAndVisible(true); } @@ -57,6 +62,14 @@ public class RollbackLineStatusAction extends DumbAwareAction { rollback(tracker, editor, null); } + protected static boolean isSomeChangeSelected(@NotNull Editor editor, @NotNull LineStatusTracker tracker) { + List carets = editor.getCaretModel().getAllCarets(); + if (carets.size() != 1) return true; + Caret caret = carets.get(0); + if (caret.hasSelection()) return true; + return tracker.getRangeForLine(caret.getLogicalPosition().line) != null; + } + protected static void rollback(@NotNull LineStatusTracker tracker, @Nullable Editor editor, @Nullable Range range) { assert editor != null || range != null; From 97fe81a034c6d94ef18cc8b6876406cda108687f Mon Sep 17 00:00:00 2001 From: Oleg Sukhodolsky Date: Tue, 7 Oct 2014 16:09:57 +0400 Subject: [PATCH 08/26] Do not push new event queue in test mode --- .../src/com/intellij/ide/IdeEventQueue.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 5ff4d4e7fcfb..a6221007427f 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -147,9 +147,12 @@ public class IdeEventQueue extends EventQueue { } private IdeEventQueue() { - EventQueue systemEventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); - assert !(systemEventQueue instanceof IdeEventQueue) : systemEventQueue; - systemEventQueue.push(this); + final Application application = ApplicationManager.getApplication(); + if (application == null || !application.isUnitTestMode()) { + EventQueue systemEventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); + assert !(systemEventQueue instanceof IdeEventQueue) : systemEventQueue; + systemEventQueue.push(this); + } addIdleTimeCounterRequest(); final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); From a8c28548f3f3fa35b6712835029277ceba5bf8c6 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 7 Oct 2014 12:16:01 +0200 Subject: [PATCH 09/26] app info as service --- .../openapi/application/ApplicationInfo.java | 3 +- .../application/impl/ApplicationInfoImpl.java | 48 ++++++++++++++++--- .../openapi/wm/impl/WindowManagerImpl.java | 7 +-- .../src/META-INF/PlatformExtensions.xml | 15 +++--- .../src/componentSets/Platform.xml | 5 -- 5 files changed, 55 insertions(+), 23 deletions(-) diff --git a/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java b/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java index 6f827dad20bf..576cdc097de8 100644 --- a/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java +++ b/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java @@ -15,6 +15,7 @@ */ package com.intellij.openapi.application; +import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.BuildNumber; import java.awt.*; @@ -52,7 +53,7 @@ public abstract class ApplicationInfo { } public static ApplicationInfo getInstance() { - return ApplicationManager.getApplication().getComponent(ApplicationInfo.class); + return ServiceManager.getService(ApplicationInfo.class); } public static boolean helpAvailable() { diff --git a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java index 13d580ef0834..186d387e1ac0 100644 --- a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java @@ -19,7 +19,7 @@ import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; -import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; @@ -40,7 +40,7 @@ import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; -public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExternalizable, ApplicationComponent { +public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExternalizable, NamedComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.application.impl.ApplicationInfoImpl"); private String myCodeName = null; @@ -175,14 +175,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern @NonNls private static final String CUSTOMIZE_IDE_WIZARD_STEPS = "customize-ide-wizard"; @NonNls private static final String STEPS_PROVIDER = "provider"; - public void initComponent() { } - - public void disposeComponent() { } - + @Override public Calendar getBuildDate() { return myBuildDate; } + @Override public Calendar getMajorReleaseBuildDate() { return myMajorReleaseBuildDate != null ? myMajorReleaseBuildDate : myBuildDate; } @@ -211,14 +209,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return getBuild().asString(); } + @Override public String getMajorVersion() { return myMajorVersion; } + @Override public String getMinorVersion() { return myMinorVersion; } + @Override public String getVersionName() { final String fullName = ApplicationNamesInfo.getInstance().getFullProductName(); if (myEAP && !StringUtil.isEmptyOrSpaces(myCodeName)) { @@ -227,6 +228,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return fullName; } + @Override @NonNls public String getHelpURL() { return "jar:file:///" + getHelpJarPath() + "!/" + myHelpRootName; @@ -247,14 +249,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return PathManager.getHomePath() + File.separator + "help" + File.separator + myHelpFileName; } + @Override public String getSplashImageUrl() { return mySplashImageUrl; } + @Override public Color getSplashTextColor() { return mySplashTextColor; } + @Override public String getAboutImageUrl() { return myAboutImageUrl; } @@ -279,10 +284,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myProgressTailIcon; } + @Override public String getIconUrl() { return myIconUrl; } + @Override public String getSmallIconUrl() { return mySmallIconUrl; } @@ -293,18 +300,22 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myBigIconUrl; } + @Override public String getOpaqueIconUrl() { return myOpaqueIconUrl; } + @Override public String getToolWindowIconUrl() { return myToolWindowIconUrl; } + @Override public String getWelcomeScreenCaptionUrl() { return myWelcomeScreenCaptionUrl; } + @Override public String getWelcomeScreenDeveloperSloganUrl() { return myWelcomeScreenDeveloperSloganUrl; } @@ -325,30 +336,37 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myEditorBackgroundImageUrl; } + @Override public String getPackageCode() { return myPackageCode; } + @Override public boolean isEAP() { return myEAP; } + @Override public UpdateUrls getUpdateUrls() { return myUpdateUrls; } + @Override public String getDocumentationUrl() { return myDocumentationUrl; } + @Override public String getSupportUrl() { return mySupportUrl; } + @Override public String getEAPFeedbackUrl() { return myEAPFeedbackUrl; } + @Override public String getReleaseFeedbackUrl() { return myReleaseFeedbackUrl; } @@ -358,18 +376,22 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myPluginManagerUrl; } + @Override public String getPluginsListUrl() { return myPluginsListUrl; } + @Override public String getPluginsDownloadUrl() { return myPluginsDownloadUrl; } + @Override public String getBuiltinPluginsUrl() { return myBuiltinPluginsUrl; } + @Override public String getWebHelpUrl() { return myWebHelpUrl; } @@ -384,14 +406,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myHasContextHelp; } + @Override public String getWhatsNewUrl() { return myWhatsNewUrl; } + @Override public String getWinKeymapUrl() { return myWinKeymapUrl; } + @Override public String getMacKeymapUrl() { return myMacKeymapUrl; } @@ -405,6 +430,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myAboutLinkColor; } + @Override public String getFullApplicationName() { @NonNls StringBuilder buffer = new StringBuilder(); buffer.append(getVersionName()); @@ -423,6 +449,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return buffer.toString(); } + @Override public boolean showLicenseeInfo() { return myShowLicensee; } @@ -478,6 +505,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return ourShadowInstance; } + @Override public void readExternal(Element parentNode) throws InvalidDataException { Element versionElement = parentNode.getChild(ELEMENT_VERSION); if (versionElement != null) { @@ -737,14 +765,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return new Color((int)rgb, rgb > 0xffffff); } + @Override public void writeExternal(Element element) throws WriteExternalException { throw new WriteExternalException(); } + @Override public List getPluginChooserPages() { return myPluginChooserPages; } + @Override @NotNull public String getComponentName() { return ApplicationNamesInfo.getComponentName(); @@ -761,10 +792,12 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern } } + @Override public String getCheckingUrl() { return myCheckingUrl; } + @Override public String getPatchesUrl() { return myPatchesUrl; } @@ -781,14 +814,17 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern myDependentPlugin = e.getAttributeValue("depends"); } + @Override public String getTitle() { return myTitle; } + @Override public String getCategory() { return myCategory; } + @Override public String getDependentPlugin() { return myDependentPlugin; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java index 9fd11531588f..17883b2493fe 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java @@ -116,7 +116,6 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom private Rectangle myFrameBounds; private int myFrameExtendedState; private final WindowAdapter myActivationListener; - private final ApplicationInfoEx myApplicationInfoEx; private final DataManager myDataManager; private final ActionManagerEx myActionManager; private final UISettings myUiSettings; @@ -125,11 +124,9 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom * invoked by reflection */ public WindowManagerImpl(DataManager dataManager, - ApplicationInfoEx applicationInfoEx, ActionManagerEx actionManager, UISettings uiSettings, MessageBus bus) { - myApplicationInfoEx = applicationInfoEx; myDataManager = dataManager; myActionManager = actionManager; myUiSettings = uiSettings; @@ -524,7 +521,7 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom } public void showFrame() { - final IdeFrameImpl frame = new IdeFrameImpl(myApplicationInfoEx, + final IdeFrameImpl frame = new IdeFrameImpl(ApplicationInfoEx.getInstanceEx(), myActionManager, myUiSettings, myDataManager, ApplicationManager.getApplication()); myProject2Frame.put(null, frame); @@ -595,7 +592,7 @@ public final class WindowManagerImpl extends WindowManagerEx implements NamedCom frame.setProject(project); } else { - frame = new IdeFrameImpl(myApplicationInfoEx, myActionManager, myUiSettings, + frame = new IdeFrameImpl(ApplicationInfoEx.getInstanceEx(), myActionManager, myUiSettings, myDataManager, ApplicationManager.getApplication()); final Rectangle bounds = ProjectFrameBounds.getInstance(project).getBounds(); diff --git a/platform/platform-resources/src/META-INF/PlatformExtensions.xml b/platform/platform-resources/src/META-INF/PlatformExtensions.xml index 3ed36ff0996b..0f1ea54bc37d 100644 --- a/platform/platform-resources/src/META-INF/PlatformExtensions.xml +++ b/platform/platform-resources/src/META-INF/PlatformExtensions.xml @@ -55,10 +55,10 @@ + serviceImplementation="com.intellij.openapi.fileEditor.impl.EditorEmptyTextPainter"/> + serviceImplementation="com.intellij.openapi.editor.impl.EditorCopyPasteHelperImpl"/> @@ -157,6 +157,8 @@ serviceImplementation="com.intellij.application.options.PathMacrosImpl"/> + @@ -208,7 +210,8 @@ serviceImplementation="com.intellij.openapi.project.impl.ProjectReloadStateImpl"/> - + - + @@ -270,8 +273,8 @@ - - + + diff --git a/platform/platform-resources/src/componentSets/Platform.xml b/platform/platform-resources/src/componentSets/Platform.xml index 7a3258fdfe1f..5f42fe651ff5 100644 --- a/platform/platform-resources/src/componentSets/Platform.xml +++ b/platform/platform-resources/src/componentSets/Platform.xml @@ -1,10 +1,5 @@ - - com.intellij.openapi.application.ApplicationInfo - com.intellij.openapi.application.impl.ApplicationInfoImpl - - com.intellij.openapi.project.ProjectManager com.intellij.openapi.project.impl.ProjectManagerImpl From b6359bdab5cdc819df9de5fdef4ecb483c400d37 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 7 Oct 2014 12:33:42 +0200 Subject: [PATCH 10/26] =?UTF-8?q?DefaultColorSchemesManager=20=E2=80=94=20?= =?UTF-8?q?avoid=20use=20WriteExternalException=20to=20cancel=20write?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../colors/ex/DefaultColorSchemesManager.java | 45 +++++++++---------- .../src/META-INF/PlatformExtensions.xml | 3 +- 2 files changed, 21 insertions(+), 27 deletions(-) diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/ex/DefaultColorSchemesManager.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/ex/DefaultColorSchemesManager.java index 81c14027ade6..53ac33ba72fc 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/ex/DefaultColorSchemesManager.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/ex/DefaultColorSchemesManager.java @@ -15,34 +15,25 @@ */ package com.intellij.openapi.editor.colors.ex; -import com.intellij.openapi.components.NamedComponent; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.components.*; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.impl.DefaultColorsScheme; import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.JDOMExternalizable; -import com.intellij.openapi.util.WriteExternalException; import org.jdom.Element; import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; -/** - * @author max - */ -public class DefaultColorSchemesManager implements JDOMExternalizable, NamedComponent { +@State( + name = "DefaultColorSchemesManager", + storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml") +) +public class DefaultColorSchemesManager implements PersistentStateComponent { private final List mySchemes; @NonNls private static final String SCHEME_ELEMENT = "scheme"; - @Override - @NotNull - public String getComponentName() { - return "DefaultColorSchemesManager"; - } - public DefaultColorSchemesManager() { mySchemes = new ArrayList(); } @@ -51,20 +42,24 @@ public class DefaultColorSchemesManager implements JDOMExternalizable, NamedComp return ServiceManager.getService(DefaultColorSchemesManager.class); } + @Nullable @Override - public void readExternal(Element element) throws InvalidDataException { - List schemes = element.getChildren(SCHEME_ELEMENT); - for (Object scheme : schemes) { - Element schemeElement = (Element)scheme; - DefaultColorsScheme newScheme = new DefaultColorsScheme(this); - newScheme.readExternal(schemeElement); - mySchemes.add(newScheme); - } + public Element getState() { + return null; } @Override - public void writeExternal(Element element) throws WriteExternalException { - throw new WriteExternalException(); + public void loadState(Element state) { + for (Element schemeElement : state.getChildren(SCHEME_ELEMENT)) { + DefaultColorsScheme newScheme = new DefaultColorsScheme(this); + try { + newScheme.readExternal(schemeElement); + } + catch (InvalidDataException e) { + throw new RuntimeException(e); + } + mySchemes.add(newScheme); + } } public DefaultColorsScheme[] getAllSchemes() { diff --git a/platform/platform-resources/src/META-INF/PlatformExtensions.xml b/platform/platform-resources/src/META-INF/PlatformExtensions.xml index 0f1ea54bc37d..588675bfb14e 100644 --- a/platform/platform-resources/src/META-INF/PlatformExtensions.xml +++ b/platform/platform-resources/src/META-INF/PlatformExtensions.xml @@ -139,8 +139,7 @@ - + Date: Tue, 7 Oct 2014 14:12:43 +0200 Subject: [PATCH 11/26] =?UTF-8?q?constant=20order=20of=20externalization?= =?UTF-8?q?=20sessions=20=E2=80=94=20simplify=20debug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/stores/StateStorageManagerImpl.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java index 434767be988b..e678dc6f7dc7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java @@ -15,7 +15,6 @@ */ package com.intellij.openapi.components.impl.stores; -import com.intellij.codeInspection.SmartHashMap; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; @@ -414,9 +413,13 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di @Override public SaveSession startSave(@NotNull ExternalizationSession externalizationSession) { StateStorageManagerExternalizationSession myExternalizationSession = (StateStorageManagerExternalizationSession)externalizationSession; + if (myExternalizationSession.mySessions.isEmpty()) { + return null; + } + List saveSessions = null; - for (StateStorage stateStorage : myExternalizationSession.mySessions.keySet()) { - SaveSession saveSession = stateStorage.startSave(myExternalizationSession.mySessions.get(stateStorage)); + for (Map.Entry entry : myExternalizationSession.mySessions.entrySet()) { + SaveSession saveSession = entry.getKey().startSave(entry.getValue()); if (saveSession != null) { if (saveSessions == null) { saveSessions = new SmartList(); @@ -448,7 +451,7 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di } private final class StateStorageManagerExternalizationSession implements ExternalizationSession { - final Map mySessions = new SmartHashMap(); + final Map mySessions = new LinkedHashMap(); @Override public void setState(@NotNull Storage[] storageSpecs, @NotNull Object component, @NotNull String componentName, @NotNull Object state) { From f3a12fdcecbede7987b767569ebfdb65f68368fb Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 7 Oct 2014 14:13:25 +0200 Subject: [PATCH 12/26] rename to XmlElementStorageSaveSession --- .../impl/stores/DefaultProjectStoreImpl.java | 4 +- .../impl/stores/FileBasedStorage.java | 16 ++++--- .../impl/stores/XmlElementStorage.java | 43 ++++++++++++++----- .../impl/XmlElementStorageTest.java | 4 +- 4 files changed, 48 insertions(+), 19 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java index 05d2bb7a4fde..3c1bf6f964ce 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java @@ -71,8 +71,8 @@ public class DefaultProjectStoreImpl extends ProjectStoreImpl { } @Override - protected MySaveSession createSaveSession(@NotNull StorageData storageData) { - return new MySaveSession(storageData) { + protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) { + return new XmlElementStorageSaveSession(storageData) { @Override protected void doSave(@Nullable Element element) { // we must set empty element instead of null as indicator - ProjectManager state is ready to save diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/FileBasedStorage.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/FileBasedStorage.java index 287ffb90841f..1b12e4db75d6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/FileBasedStorage.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/FileBasedStorage.java @@ -21,7 +21,6 @@ import com.intellij.notification.Notifications; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; -import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.FileUtil; @@ -43,8 +42,6 @@ import java.util.Collections; import java.util.Set; public class FileBasedStorage extends XmlElementStorage { - private static final Logger LOG = Logger.getInstance(FileBasedStorage.class); - private final String myFilePath; private final File myFile; private volatile VirtualFile myCachedVirtualFile; @@ -104,11 +101,11 @@ public class FileBasedStorage extends XmlElementStorage { } @Override - protected MySaveSession createSaveSession(@NotNull StorageData storageData) { + protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) { return new FileSaveSession(storageData); } - private class FileSaveSession extends MySaveSession { + private class FileSaveSession extends XmlElementStorageSaveSession { protected FileSaveSession(@NotNull StorageData storageData) { super(storageData); } @@ -134,6 +131,10 @@ public class FileBasedStorage extends XmlElementStorage { LOG.error(e); } + if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) { + LOG.debug("doSave " + getFilePath()); + } + if (content == null) { StorageUtil.deleteFile(myFile, this, getVirtualFile()); myCachedVirtualFile = null; @@ -306,4 +307,9 @@ public class FileBasedStorage extends XmlElementStorage { FileUtil.writeToFile(file, out.getInternalBuffer(), 0, out.size()); return file; } + + @Override + public String toString() { + return getFilePath(); + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java index 5263a1358d7b..6267af2dc4d3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java @@ -19,12 +19,10 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.CurrentUserHolder; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.JDOMUtil; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.WriteExternalException; +import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import gnu.trove.TObjectLongHashMap; import org.jdom.Document; @@ -40,7 +38,7 @@ import java.io.InputStream; import java.util.*; public abstract class XmlElementStorage implements StateStorage, Disposable { - private static final Logger LOG = Logger.getInstance(XmlElementStorage.class); + protected static final Logger LOG = Logger.getInstance(XmlElementStorage.class); private final static RoamingElementFilter DISABLED_ROAMING_ELEMENT_FILTER = new RoamingElementFilter(RoamingType.DISABLED); @@ -174,6 +172,9 @@ public abstract class XmlElementStorage implements StateStorage, Disposable { @Override @Nullable public final ExternalizationSession startExternalization() { + if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) { + LOG.debug("startExternalization: mySavingDisabled " + mySavingDisabled + " for " + toString()); + } return mySavingDisabled ? null : createSaveSession(getStorageData()); } @@ -181,21 +182,33 @@ public abstract class XmlElementStorage implements StateStorage, Disposable { @Override public SaveSession startSave(@NotNull ExternalizationSession externalizationSession) { if (mySavingDisabled) { + if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) { + LOG.debug("startSave: saving disabled for " + toString()); + } return null; } else { - MySaveSession session = (MySaveSession)externalizationSession; + XmlElementStorageSaveSession session = (XmlElementStorageSaveSession)externalizationSession; + if (LOG.isDebugEnabled() && myFileSpec.equals(StoragePathMacros.MODULE_FILE)) { + LOG.debug("startSave: session " + session.myCopiedStorageData + " for " + toString()); + } return session.myCopiedStorageData == null ? null : session; } } - protected abstract MySaveSession createSaveSession(@NotNull StorageData storageData); + protected abstract XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData); public void disableSaving() { + if (LOG.isDebugEnabled()) { + LOG.debug("Saving disabled for " + toString()); + } mySavingDisabled = true; } public void enableSaving() { + if (LOG.isDebugEnabled()) { + LOG.debug("Saving enabled for " + toString()); + } mySavingDisabled = false; } @@ -223,23 +236,29 @@ public abstract class XmlElementStorage implements StateStorage, Disposable { StorageData oldData = myLoadedData; StorageData newData = getStorageData(true); if (oldData == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("analyzeExternalChangesAndUpdateIfNeed: old data null, load new for " + toString()); + } result.addAll(newData.getComponentNames()); } else { Set changedComponentNames = oldData.getChangedComponentNames(newData, myPathMacroSubstitutor); - if (changedComponentNames != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("analyzeExternalChangesAndUpdateIfNeed: changedComponentNames + " + changedComponentNames + " for " + toString()); + } + if (!ContainerUtil.isEmpty(changedComponentNames)) { result.addAll(changedComponentNames); } } } - protected abstract class MySaveSession implements SaveSession, ExternalizationSession { + protected abstract class XmlElementStorageSaveSession implements SaveSession, ExternalizationSession { private final StorageData myOriginalStorageData; private StorageData myCopiedStorageData; private final Map myNewLiveStates = new THashMap(); - public MySaveSession(@NotNull StorageData storageData) { + public XmlElementStorageSaveSession(@NotNull StorageData storageData) { myOriginalStorageData = storageData; } @@ -247,6 +266,10 @@ public abstract class XmlElementStorage implements StateStorage, Disposable { public final void setState(@NotNull Object component, @NotNull String componentName, @NotNull Object state, @Nullable Storage storageSpec) { Element element; try { + //noinspection deprecation + if (LOG.isDebugEnabled() && state instanceof JDOMExternalizable && componentName.endsWith("ApplicationInfo")) { + return; + } element = DefaultStateSerializer.serializeState(state, storageSpec); } catch (WriteExternalException e) { diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/components/impl/XmlElementStorageTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/components/impl/XmlElementStorageTest.java index 1f2c31c6a207..bf2eaefa2340 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/components/impl/XmlElementStorageTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/components/impl/XmlElementStorageTest.java @@ -97,8 +97,8 @@ public class XmlElementStorageTest extends LightPlatformLangTestCase { } @Override - protected MySaveSession createSaveSession(@NotNull StorageData storageData) { - return new MySaveSession(storageData) { + protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) { + return new XmlElementStorageSaveSession(storageData) { @Override protected void doSave(@Nullable Element element) { mySavedElement = element == null ? null : element.clone(); From 72c0e4ac19e204263b7a2ec70cab740b06dc1826 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 7 Oct 2014 14:21:16 +0200 Subject: [PATCH 13/26] set old storage data to new on save --- .../openapi/components/impl/stores/XmlElementStorage.java | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java index 6267af2dc4d3..4112d0be6eb9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/XmlElementStorage.java @@ -300,6 +300,7 @@ public abstract class XmlElementStorage implements StateStorage, Disposable { try { doSave(getElement(myCopiedStorageData, isCollapsePathsOnSave(), myNewLiveStates)); + myLoadedData = myCopiedStorageData; } catch (IOException e) { throw new StateStorageException(e); From 46df798f26beb12172a77067ffdf5e19e2f75148 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Sun, 3 Aug 2014 19:22:36 +0400 Subject: [PATCH 14/26] [git] IDEA-124821 Don't make the auto-generated changelist default It is not needed: commit dialog can easily commit a non-default changelist. On the other hand, making the auto-changelist non-default will help to avoid such problems as IDEA-103094, when the changelist is not removed after cherry-pick for some reason and then is used as the default one. This also should help with IDEA-120133. --- .../git4idea/cherrypick/GitCherryPicker.java | 24 ++++--------- .../git4idea/cherry-pick-auto-commit.feature | 4 +-- .../cherry-pick-without-auto-commit.feature | 6 ++-- .../git4idea/GitCherryPickStepdefs.java | 36 ++++++++----------- 4 files changed, 24 insertions(+), 46 deletions(-) diff --git a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java index 2b18f07b6c1d..0730a1821f75 100644 --- a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java +++ b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java @@ -170,20 +170,13 @@ public class GitCherryPicker { CherryPickData data = updateChangeListManager(commit.getCommit()); boolean committed = showCommitDialogAndWaitForCommit(repository, commit, data.myChangeList, data.myCommitMessage); if (committed) { - removeChangeList(data); + myChangeListManager.removeChangeList(data.myChangeList); successfulCommits.add(commit); return true; } return false; } - private void removeChangeList(CherryPickData list) { - myChangeListManager.setDefaultChangeList(list.myPreviouslyDefaultChangeList); - if (!myChangeListManager.getDefaultChangeList().equals(list.myChangeList)) { - myChangeListManager.removeChangeList(list.myChangeList); - } - } - private void notifyConflictWarning(@NotNull GitRepository repository, @NotNull GitCommitWrapper commit, @NotNull List successfulCommits) { NotificationListener resolveLinkListener = new ResolveLinkListener(myProject, myGit, myPlatformFacade, repository.getRoot(), @@ -210,9 +203,8 @@ public class GitCherryPicker { final Collection paths = ChangesUtil.getPaths(commit.getChanges()); refreshChangedFiles(paths); final String commitMessage = createCommitMessage(commit); - LocalChangeList previouslyDefaultChangeList = myChangeListManager.getDefaultChangeList(); LocalChangeList changeList = createChangeListAfterUpdate(commit, paths, commitMessage); - return new CherryPickData(changeList, commitMessage, previouslyDefaultChangeList); + return new CherryPickData(changeList, commitMessage); } @NotNull @@ -378,14 +370,12 @@ public class GitCherryPicker { @NotNull private LocalChangeList createChangeList(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) { Collection changes = commit.getChanges(); + String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); + final LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit); if (!changes.isEmpty()) { - String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); - final LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit); myChangeListManager.moveChangesTo(changeList, changes.toArray(new Change[changes.size()])); - myChangeListManager.setDefaultChangeList(changeList); - return changeList; } - return myChangeListManager.getDefaultChangeList(); + return changeList; } @NotNull @@ -405,12 +395,10 @@ public class GitCherryPicker { private static class CherryPickData { private final LocalChangeList myChangeList; private final String myCommitMessage; - private final LocalChangeList myPreviouslyDefaultChangeList; - private CherryPickData(LocalChangeList list, String message, LocalChangeList previouslyDefaultChangeList) { + private CherryPickData(LocalChangeList list, String message) { myChangeList = list; myCommitMessage = message; - myPreviouslyDefaultChangeList = previouslyDefaultChangeList; } } diff --git a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature index 8433b6277347..ae5bdbfde0ce 100644 --- a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature +++ b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature @@ -82,7 +82,7 @@ Background: M conflict.txt "feature version" """ When I cherry-pick the commit bb6453c and don't resolve conflicts - Then active changelist is 'feature content (cherry picked from commit bb6453c)' + Then there is changelist 'feature content (cherry picked from commit bb6453c)' And warning notification is shown 'Cherry-picked with conflicts' """ bb6453c feature content @@ -137,7 +137,7 @@ Background: M conflict.txt "feature version" """ When I cherry-pick the commit bb6453c, resolve conflicts and don't commit - Then active changelist is 'feature content (cherry picked from commit bb6453c)' + Then there is changelist 'feature content (cherry picked from commit bb6453c)' And no notification is shown Scenario: Cherry-pick 2 commits diff --git a/plugins/git4idea/test-features/git4idea/cherry-pick-without-auto-commit.feature b/plugins/git4idea/test-features/git4idea/cherry-pick-without-auto-commit.feature index 715f9e268720..c3883a40c7f9 100644 --- a/plugins/git4idea/test-features/git4idea/cherry-pick-without-auto-commit.feature +++ b/plugins/git4idea/test-features/git4idea/cherry-pick-without-auto-commit.feature @@ -15,8 +15,6 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected Scenario: Simple cherry-pick When I cherry-pick the commit f5027a3 Then commit dialog should be shown - And active changelist is 'fix #1 (cherry picked from commit f5027a3)' - Scenario: Simple cherry-pick, agree to commit When I cherry-pick the commit f5027a3 and commit @@ -34,7 +32,7 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected Scenario: Simple cherry-pick, cancel commit When I cherry-pick the commit f5027a3 and don't commit Then nothing is committed - And active changelist is 'fix #1 (cherry picked from commit f5027a3)' + And there is changelist 'fix #1 (cherry picked from commit f5027a3)' And no notification is shown Scenario: Cherry-pick 2 commits @@ -67,7 +65,7 @@ Feature: Git Cherry-Pick When Auto-Commit is deselected (cherry picked from commit f5027a3) """ And working tree is dirty - And active changelist is 'fix #2 (cherry picked from commit abc1234)' + And there is changelist 'fix #2 (cherry picked from commit abc1234)' And warning notification is shown 'Cherry-pick cancelled' """ abc1234 fix #2 diff --git a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java index 553cf260e268..e43d5edbc037 100644 --- a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java +++ b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java @@ -15,10 +15,9 @@ */ package git4idea; -import com.google.common.base.Function; -import com.google.common.collect.Collections2; import com.intellij.mock.MockVirtualFile; import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePathImpl; @@ -40,6 +39,7 @@ import cucumber.annotation.en.When; import git4idea.cherrypick.GitCherryPicker; import git4idea.config.GitVersionSpecialty; import git4idea.test.MockVcsHelper; +import org.jetbrains.annotations.NotNull; import java.util.*; @@ -214,30 +214,22 @@ public class GitCherryPickStepdefs { assertTrue("Commit dialog was not shown", myVcsHelper.commitDialogWasShown()); } - @Then("^active changelist is '(.+)'$") - public void active_changelist_is(String name) throws Throwable { - assertActiveChangeList(virtualCommits.replaceVirtualHashes(name)); + @Then("^there is changelist '(.*)'$") + public void there_is_changelist(@NotNull final String name) throws Throwable { + List changeLists = myChangeListManager.getChangeListsCopy(); + assertTrue("Didn't find changelist with name '" + name + "' among :" + changeLists, + ContainerUtil.exists(changeLists, new Condition() { + @Override + public boolean value(LocalChangeList list) { + return list.getName().equals(virtualCommits.replaceVirtualHashes(name)); + } + })); } private static void assertOnlyDefaultChangelist() { String DEFAULT = MockChangeListManager.DEFAULT_CHANGE_LIST_NAME; - assertChangeLists(Collections.singleton(DEFAULT), DEFAULT); - } - - private static void assertChangeLists(Collection changeLists, String activeChangelist) { - List lists = myChangeListManager.getChangeLists(); - Collection listNames = Collections2.transform(lists, new Function() { - @Override - public String apply(LocalChangeList input) { - return input.getName(); - } - }); - assertEquals("Change lists are different", new ArrayList(changeLists), new ArrayList(listNames)); - assertActiveChangeList(activeChangelist); - } - - private static void assertActiveChangeList(String name) { - assertEquals("Wrong active changelist", name, myChangeListManager.getDefaultChangeList().getName()); + assertEquals("Only default change list is expected", 1, myChangeListManager.getChangeListsNumber()); + assertEquals("Default changelist is not active", DEFAULT, myChangeListManager.getDefaultChangeList().getName()); } private static void cherryPick(List virtualHashes) { From de1fc33d1d26422c77a5db252c02e67e54b91264 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Sun, 3 Aug 2014 20:07:40 +0400 Subject: [PATCH 15/26] [git tests] More correctly apply file modifications \n used to be escaped; modification used to append instead of overwrite. --- .../testSrc/com/intellij/openapi/vcs/Executor.java | 4 ++++ .../test-stepdefs/git4idea/CommitDetails.java | 11 ++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/Executor.java b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/Executor.java index 91ef3dd1716d..3a5613001ac8 100644 --- a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/Executor.java +++ b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/Executor.java @@ -119,6 +119,10 @@ public class Executor { } } + public static void overwrite(@NotNull String fileName, @NotNull String content) throws IOException { + overwrite(child(fileName), content); + } + public static void overwrite(@NotNull File file, @NotNull String content) throws IOException { FileUtil.writeToFile(file, content.getBytes(), false); } diff --git a/plugins/git4idea/test-stepdefs/git4idea/CommitDetails.java b/plugins/git4idea/test-stepdefs/git4idea/CommitDetails.java index bd2d22aad6ba..870c6d6c55a8 100644 --- a/plugins/git4idea/test-stepdefs/git4idea/CommitDetails.java +++ b/plugins/git4idea/test-stepdefs/git4idea/CommitDetails.java @@ -18,12 +18,13 @@ package git4idea; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.intellij.openapi.vcs.Executor.echo; +import static com.intellij.openapi.vcs.Executor.overwrite; import static com.intellij.openapi.vcs.Executor.touch; import static git4idea.GitCucumberWorld.virtualCommits; import static git4idea.test.GitExecutor.git; @@ -42,10 +43,10 @@ public class CommitDetails { private static class Change { - public void apply() { + public void apply() throws IOException { switch (myType) { case MODIFIED: - echo(myFile, myContent); + overwrite(myFile, myContent); break; case ADDED: touch(myFile, myContent); @@ -159,7 +160,7 @@ public class CommitDetails { int secondSpace = change.indexOf(' ', firstSpace + 1); return new Change(parseType(change.substring(0, firstSpace)), change.substring(firstSpace + 1, secondSpace), - change.substring(secondSpace + 1)); + StringUtil.unescapeStringCharacters(StringUtil.unquoteString(change.substring(secondSpace + 1)))); } private static Change.Type parseType(String type) { @@ -181,7 +182,7 @@ public class CommitDetails { /** * @return real commit details. */ - public CommitDetails apply() { + public CommitDetails apply() throws IOException { for (Change change : myChanges) { change.apply(); } From 0a3e3799feb4c3d7213e76585bf5b67f3f704ae6 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Tue, 5 Aug 2014 13:50:57 +0400 Subject: [PATCH 16/26] [git] IDEA-84771 don't propose to commit empty changelist on cherry-pick --- .../git4idea/cherrypick/GitCherryPicker.java | 93 +++++++++++++--- .../git4idea/cherry-pick-auto-commit.feature | 103 +++++++++--------- .../git4idea/GeneralStepdefs.java | 7 +- .../git4idea/GitCherryPickStepdefs.java | 68 +++++------- 4 files changed, 158 insertions(+), 113 deletions(-) diff --git a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java index 0730a1821f75..b5fe83c00c31 100644 --- a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java +++ b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java @@ -21,6 +21,7 @@ import com.intellij.notification.NotificationListener; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vcs.changes.*; @@ -42,11 +43,15 @@ import git4idea.merge.GitConflictResolver; import git4idea.repo.GitRepository; import git4idea.util.UntrackedFilesNotifier; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -80,18 +85,19 @@ public class GitCherryPicker { } public void cherryPick(@NotNull Map> commitsInRoots) { - List successfulCommits = new ArrayList(); + List successfulCommits = ContainerUtil.newArrayList(); + List alreadyPicked = ContainerUtil.newArrayList(); DvcsUtil.workingTreeChangeStarted(myProject); try { for (Map.Entry> entry : commitsInRoots.entrySet()) { GitRepository repository = entry.getKey(); - boolean result = cherryPick(repository, entry.getValue(), successfulCommits); + boolean result = cherryPick(repository, entry.getValue(), successfulCommits, alreadyPicked); repository.update(); if (!result) { return; } } - notifySuccess(successfulCommits); + notifyResult(successfulCommits, alreadyPicked); } finally { DvcsUtil.workingTreeChangeFinished(myProject); @@ -100,7 +106,7 @@ public class GitCherryPicker { // return true to continue with other roots, false to break execution private boolean cherryPick(@NotNull GitRepository repository, @NotNull List commits, - @NotNull List successfulCommits) { + @NotNull List successfulCommits, @NotNull List alreadyPicked) { for (VcsFullCommitDetails commit : commits) { GitSimpleEventDetector conflictDetector = new GitSimpleEventDetector(CHERRY_PICK_CONFLICT); GitSimpleEventDetector localChangesOverwrittenDetector = new GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK); @@ -115,7 +121,7 @@ public class GitCherryPicker { } else { boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper, - successfulCommits); + successfulCommits, alreadyPicked); if (!committed) { notifyCommitCancelled(commitWrapper, successfulCommits); return false; @@ -129,7 +135,7 @@ public class GitCherryPicker { if (mergeCompleted) { boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper, - successfulCommits); + successfulCommits, alreadyPicked); if (!committed) { notifyCommitCancelled(commitWrapper, successfulCommits); return false; @@ -156,6 +162,10 @@ public class GitCherryPicker { commitWrapper, successfulCommits); return false; } + else if (isNothingToCommitMessage(result)) { + alreadyPicked.add(commitWrapper); + return true; + } else { notifyError(result.getErrorOutputAsHtmlString(), commitWrapper, successfulCommits); return false; @@ -164,10 +174,23 @@ public class GitCherryPicker { return true; } + private static boolean isNothingToCommitMessage(@NotNull GitCommandResult result) { + if (!result.getErrorOutputAsJoinedString().isEmpty()) { + return false; + } + String stdout = result.getOutputAsJoinedString(); + return stdout.contains("nothing to commit") || stdout.contains("previous cherry-pick is now empty"); + } + private boolean updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(@NotNull GitRepository repository, @NotNull GitCommitWrapper commit, - @NotNull List successfulCommits) { + @NotNull List successfulCommits, + @NotNull List alreadyPicked) { CherryPickData data = updateChangeListManager(commit.getCommit()); + if (data == null) { + alreadyPicked.add(commit); + return true; + } boolean committed = showCommitDialogAndWaitForCommit(repository, commit, data.myChangeList, data.myCommitMessage); if (committed) { myChangeListManager.removeChangeList(data.myChangeList); @@ -199,15 +222,16 @@ public class GitCherryPicker { VcsNotifier.getInstance(myProject).notifyMinorWarning("Cherry-pick cancelled", description, null); } + @Nullable private CherryPickData updateChangeListManager(@NotNull final VcsFullCommitDetails commit) { final Collection paths = ChangesUtil.getPaths(commit.getChanges()); refreshChangedFiles(paths); final String commitMessage = createCommitMessage(commit); LocalChangeList changeList = createChangeListAfterUpdate(commit, paths, commitMessage); - return new CherryPickData(changeList, commitMessage); + return changeList == null ? null : new CherryPickData(changeList, commitMessage); } - @NotNull + @Nullable private LocalChangeList createChangeListAfterUpdate(@NotNull final VcsFullCommitDetails commit, @NotNull final Collection paths, @NotNull final String commitMessage) { final AtomicReference changeList = new AtomicReference(); @@ -338,9 +362,37 @@ public class GitCherryPicker { return description; } - private void notifySuccess(@NotNull List successfulCommits) { - String description = getCommitsDetails(successfulCommits); - VcsNotifier.getInstance(myProject).notifySuccess("Cherry-pick successful", description); + private void notifyResult(@NotNull List successfulCommits, @NotNull List alreadyPicked) { + if (alreadyPicked.isEmpty()) { + VcsNotifier.getInstance(myProject).notifySuccess("Cherry-pick successful", getCommitsDetails(successfulCommits)); + } + else if (!successfulCommits.isEmpty()) { + String title = String.format("Cherry-picked %d commits from %d", successfulCommits.size(), + successfulCommits.size() + alreadyPicked.size()); + String description = getCommitsDetails(successfulCommits) + "

" + formAlreadyPickedDescription(alreadyPicked, true); + VcsNotifier.getInstance(myProject).notifyImportantWarning(title, description); + } + else { + VcsNotifier.getInstance(myProject).notifyImportantWarning("Nothing to cherry-pick", + formAlreadyPickedDescription(alreadyPicked, false)); + } + } + + @NotNull + private static String formAlreadyPickedDescription(@NotNull List alreadyPicked, boolean but) { + + String hashes = StringUtil.join(alreadyPicked, new Function() { + @Override + public String fun(GitCommitWrapper commit) { + return commit.getCommit().getId().toShortString(); + } + }, ", "); + if (but) { + String wasnt = alreadyPicked.size() == 1 ? "wasn't" : "weren't"; + String it = alreadyPicked.size() == 1 ? "it" : "them"; + return String.format("%s %s picked, because all changes from %s have already been applied.", hashes, wasnt, it); + } + return String.format("All changes from %s have already been applied", hashes); } @NotNull @@ -365,9 +417,10 @@ public class GitCherryPicker { } })); VfsUtil.markDirtyAndRefresh(false, false, false, ArrayUtil.toObjectArray(virtualFiles, VirtualFile.class)); + VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(filePaths, null); } - @NotNull + @Nullable private LocalChangeList createChangeList(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) { Collection changes = commit.getChanges(); String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); @@ -375,7 +428,11 @@ public class GitCherryPicker { if (!changes.isEmpty()) { myChangeListManager.moveChangesTo(changeList, changes.toArray(new Change[changes.size()])); } - return changeList; + if (!changeList.getChanges().isEmpty()) { + return changeList; + } + myChangeListManager.removeChangeList(changeList); + return null; } @NotNull @@ -393,10 +450,10 @@ public class GitCherryPicker { } private static class CherryPickData { - private final LocalChangeList myChangeList; - private final String myCommitMessage; + @NotNull private final LocalChangeList myChangeList; + @NotNull private final String myCommitMessage; - private CherryPickData(LocalChangeList list, String message) { + private CherryPickData(@NotNull LocalChangeList list, @NotNull String message) { myChangeList = list; myCommitMessage = message; } diff --git a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature index ae5bdbfde0ce..1d85fd5022be 100644 --- a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature +++ b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature @@ -4,12 +4,11 @@ Background: Given enabled auto-commit in the settings Given new committed files file.txt, a.txt, conflict.txt with initial content Given branch feature - Given commit f5027a3 on branch feature """ fix #1 Author: John Bro - M file.txt "feature changes" + M file.txt "initial content\nfeature changes" """ Scenario: Simple cherry-pick @@ -220,53 +219,53 @@ Background: """ And merge dialog should be shown - #Scenario: Notify if changes have already been applied (IDEA-73548) - # Given commit eef9832 on branch master - # """ - # fix #1 manually incorporated - # M file.txt "feature changes" - # """ - # When I cherry-pick the commit f5027a3 - # Then the last commit is eef9832 - # And warning notification is shown 'Nothing to cherry-pick' - # """ - # All changes from f5027a3 fix #1 have already been applied - # """ - # - #Scenario: Cherry-pick 3 commits, second commit have already been applied (IDEA-73548) - # Given commit c123abc on branch feature - # """ - # fix #2 - # M file.txt "feature changes\nmore feature changes" - # """ - # Given commit d123abc on branch feature - # """ - # fix #3 - # M file.txt "feature changes\nmore feature changes\nmore feature changes" - # """ - # Given commit e123abc on branch feature - # """ - # fix for f2 - # M a.txt "feature changes" - # """ - # Given commit e098fed on branch master - # """ - # fix for f2 manually incorporated - # M a.txt "feature changes" - # """ - # When I cherry-pick commits c123abc, d123abc and e123abc - # Then `git log -2` should return - # """ - # fix #3 - # (cherry picked from commit c123abc) - # ----- - # fix #2 - # (cherry picked from commit f5027a3) - # """ - # And warning notification is shown 'Cherry-picked 2 commits' - # """ - # c123abc fix #2 - # d123abc fix #3 - #


- # Commit e123abc wasn't picked, because all changes from it have already been applied. - # """ + Scenario: Notify if changes have already been applied (IDEA-73548) + Given commit eef9832 on branch master + """ + fix #1 manually incorporated + M file.txt "feature changes" + """ + When I cherry-pick the commit f5027a3 + Then the last commit is eef9832 + And warning notification is shown 'Nothing to cherry-pick' + """ + All changes from f5027a3 fix #1 have already been applied + """ + + Scenario: Cherry-pick 3 commits, second commit have already been applied (IDEA-73548) + Given commit c123abc on branch feature + """ + fix #2 + M file.txt "feature changes\nmore feature changes" + """ + Given commit d123abc on branch feature + """ + fix #3 + M file.txt "feature changes\nmore feature changes\nmore feature changes" + """ + Given commit e123abc on branch feature + """ + fix for f2 + M a.txt "feature changes" + """ + Given commit e098fed on branch master + """ + fix for f2 manually incorporated + M a.txt "feature changes" + """ + When I cherry-pick commits c123abc, d123abc and e123abc + Then `git log -2` should return + """ + fix #3 + (cherry picked from commit c123abc) + ----- + fix #2 + (cherry picked from commit f5027a3) + """ + And warning notification is shown 'Cherry-picked 2 commits' + """ + c123abc fix #2 + d123abc fix #3 +
+ Commit e123abc wasn't picked, because all changes from it have already been applied. + """ diff --git a/plugins/git4idea/test-stepdefs/git4idea/GeneralStepdefs.java b/plugins/git4idea/test-stepdefs/git4idea/GeneralStepdefs.java index 5195f40abc23..f70f2417d5d3 100644 --- a/plugins/git4idea/test-stepdefs/git4idea/GeneralStepdefs.java +++ b/plugins/git4idea/test-stepdefs/git4idea/GeneralStepdefs.java @@ -70,14 +70,15 @@ public class GeneralStepdefs { notificationType.equals("error") ? NotificationType.ERROR : null; Notification actualNotification = lastNotification(); assertNotNull("Notification should be shown", actualNotification); - assertEquals("Notification type is incorrect", type, actualNotification.getType()); - assertEquals("Notification title is incorrect", title, actualNotification.getTitle()); + assertEquals("Notification type is incorrect in " + actualNotification, type, actualNotification.getType()); + assertEquals("Notification title is incorrect in" + actualNotification, title, actualNotification.getTitle()); assertNotificationContent(content, actualNotification.getContent()); } private static void assertNotificationContent(String expected, String actual) { expected = virtualCommits.replaceVirtualHashes(expected); - assertEquals("Notification content is incorrect", StringUtil.convertLineSeparators(expected), StringUtil.convertLineSeparators(adjustNotificationContent(actual))); + assertEquals("Notification content is incorrect", StringUtil.convertLineSeparators(expected), + StringUtil.convertLineSeparators(adjustNotificationContent(actual))); } private static String adjustNotificationContent(String content) { diff --git a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java index e43d5edbc037..6d5cc31c012e 100644 --- a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java +++ b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java @@ -15,33 +15,30 @@ */ package git4idea; -import com.intellij.mock.MockVirtualFile; -import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vcs.FilePathImpl; -import com.intellij.openapi.vcs.changes.Change; +import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.LocalChangeList; -import com.intellij.openapi.vcs.history.VcsRevisionNumber; -import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.vcs.MockChangeListManager; -import com.intellij.testFramework.vcs.MockContentRevision; +import com.intellij.util.ArrayUtil; +import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; -import com.intellij.vcs.log.Hash; import com.intellij.vcs.log.VcsFullCommitDetails; -import com.intellij.vcs.log.VcsLogObjectsFactory; -import com.intellij.vcs.log.impl.HashImpl; import cucumber.annotation.en.And; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; import git4idea.cherrypick.GitCherryPicker; import git4idea.config.GitVersionSpecialty; +import git4idea.history.GitHistoryUtils; import git4idea.test.MockVcsHelper; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import static com.intellij.openapi.vcs.Executor.echo; import static git4idea.GitCucumberWorld.*; @@ -63,7 +60,7 @@ public class GitCherryPickStepdefs { } @When("^I cherry-pick the commit (\\w+)$") - public void I_cherry_pick_the_commit(String hash) { + public void I_cherry_pick_the_commit(String hash) throws VcsException { cherryPick(hash); } @@ -232,36 +229,27 @@ public class GitCherryPickStepdefs { assertEquals("Default changelist is not active", DEFAULT, myChangeListManager.getDefaultChangeList().getName()); } - private static void cherryPick(List virtualHashes) { - List commits = ContainerUtil.newArrayList(); - for (String virtualHash : virtualHashes) { - commits.add(createMockCommit(virtualHash)); - } + private static void cherryPick(final List virtualHashes) throws VcsException { + List commits = loadDetails(ContainerUtil.map(virtualHashes, new Function() { + @Override + public String fun(String virtualHash) { + return virtualCommits.getRealCommit(virtualHash).getHash(); + } + }), myProjectDir); + new GitCherryPicker(myProject, myGit, myPlatformFacade, mySettings.isAutoCommitOnCherryPick()) - .cherryPick(Collections.singletonMap(myRepository, commits)); + .cherryPick(Collections.singletonMap(myRepository, commits)); } - private static void cherryPick(String... virtualHashes) { + private static List loadDetails(List hashes, @NotNull VirtualFile root) throws VcsException { + String noWalk = GitVersionSpecialty.NO_WALK_UNSORTED.existsIn(myVcs.getVersion()) ? "--no-walk=unsorted" : "--no-walk"; + List params = new ArrayList(); + params.add(noWalk); + params.addAll(hashes); + return new ArrayList(GitHistoryUtils.history(myProject, root, ArrayUtil.toStringArray(params))); + } + + private static void cherryPick(String... virtualHashes) throws VcsException { cherryPick(Arrays.asList(virtualHashes)); } - - private static VcsFullCommitDetails createMockCommit(String virtualHash) { - CommitDetails realCommit = virtualCommits.getRealCommit(virtualHash); - return mockCommit(realCommit.getHash(), realCommit.getMessage()); - } - - private static VcsFullCommitDetails mockCommit(String hash, String message) { - final List changes = new ArrayList(); - changes.add(new Change(null, new MockContentRevision(new FilePathImpl(new MockVirtualFile("name")), VcsRevisionNumber.NULL))); - return ServiceManager.getService(myProject, VcsLogObjectsFactory.class).createFullDetails( - HashImpl.build(hash), Collections.emptyList(), 0, NullVirtualFile.INSTANCE, message, "John Smith", "john@mail.com", message, - "John Smith", "john@mail.com", 0, new ThrowableComputable, Exception>() { - @Override - public Collection compute() throws Exception { - return changes; - } - } - ); - } - } \ No newline at end of file From 4dd17f75eb76b010113a15313362eaece8e0f4ee Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Mon, 6 Oct 2014 18:43:08 +0400 Subject: [PATCH 17/26] [git] IDEA-116748 Fix race condition issue in cherry-pick --- .../git4idea/cherrypick/GitCherryPicker.java | 70 ++++++++++++++++--- .../git4idea/cherry-pick-auto-commit.feature | 20 +++--- .../git4idea/GitCherryPickStepdefs.java | 5 ++ 3 files changed, 75 insertions(+), 20 deletions(-) diff --git a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java index b5fe83c00c31..48dbdb554321 100644 --- a/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java +++ b/plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java @@ -21,6 +21,7 @@ import com.intellij.notification.NotificationListener; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsNotifier; @@ -52,7 +53,9 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -240,7 +243,7 @@ public class GitCherryPicker { public void run() { myChangeListManager.invokeAfterUpdate(new Runnable() { public void run() { - changeList.set(createChangeList(commit, commitMessage)); + changeList.set(createChangeListIfThereAreChanges(commit, commitMessage)); } }, InvokeAfterUpdateMode.SYNCHRONOUS_NOT_CANCELLABLE, "Cherry-pick", new Consumer() { @@ -369,8 +372,8 @@ public class GitCherryPicker { else if (!successfulCommits.isEmpty()) { String title = String.format("Cherry-picked %d commits from %d", successfulCommits.size(), successfulCommits.size() + alreadyPicked.size()); - String description = getCommitsDetails(successfulCommits) + "

" + formAlreadyPickedDescription(alreadyPicked, true); - VcsNotifier.getInstance(myProject).notifyImportantWarning(title, description); + String description = getCommitsDetails(successfulCommits) + "


" + formAlreadyPickedDescription(alreadyPicked, true); + VcsNotifier.getInstance(myProject).notifySuccess(title, description); } else { VcsNotifier.getInstance(myProject).notifyImportantWarning("Nothing to cherry-pick", @@ -421,20 +424,67 @@ public class GitCherryPicker { } @Nullable - private LocalChangeList createChangeList(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) { - Collection changes = commit.getChanges(); - String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); - final LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit); - if (!changes.isEmpty()) { - myChangeListManager.moveChangesTo(changeList, changes.toArray(new Change[changes.size()])); + private LocalChangeList createChangeListIfThereAreChanges(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) { + Collection originalChanges = commit.getChanges(); + if (originalChanges.isEmpty()) { + LOG.info("Empty commit " + commit.getId()); + return null; } - if (!changeList.getChanges().isEmpty()) { + if (noChangesAfterCherryPick(originalChanges)) { + LOG.info("No changes after cherry-picking " + commit.getId()); + return null; + } + + String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); + LocalChangeList changeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit); + changeList = (LocalChangeList)moveChanges(originalChanges, changeList); + if (changeList != null && !changeList.getChanges().isEmpty()) { return changeList; } + LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges + + "\nAll changes: " + myChangeListManager.getAllChanges()); myChangeListManager.removeChangeList(changeList); return null; } + private boolean noChangesAfterCherryPick(@NotNull Collection originalChanges) { + final Collection allChanges = myChangeListManager.getAllChanges(); + return !ContainerUtil.exists(originalChanges, new Condition() { + @Override + public boolean value(Change change) { + return allChanges.contains(change); + } + }); + } + + @Nullable + private ChangeList moveChanges(@NotNull Collection originalChanges, @NotNull LocalChangeList targetChangeList) { + // 1. We have to listen to CLM changes, because moveChangesTo is asynchronous + // 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time. + final CountDownLatch moveChangesWaiter = new CountDownLatch(1); + final AtomicReference resultingChangeList = new AtomicReference(); + ChangeListAdapter listener = new ChangeListAdapter() { + @Override + public void changesMoved(Collection changes, ChangeList fromList, ChangeList toList) { + resultingChangeList.set(toList); + moveChangesWaiter.countDown(); + } + }; + try { + myChangeListManager.addChangeListListener(listener); + myChangeListManager.moveChangesTo(targetChangeList, originalChanges.toArray(new Change[originalChanges.size()])); + moveChangesWaiter.await(100, TimeUnit.SECONDS); + return resultingChangeList.get(); + } + catch (InterruptedException e) { + LOG.error(e); + return null; + } + finally { + myChangeListManager.removeChangeListListener(listener); + } + } + @NotNull private String createNameForChangeList(@NotNull String proposedName, int step) { for (LocalChangeList list : myChangeListManager.getChangeLists()) { diff --git a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature index 1d85fd5022be..16d0d8bae664 100644 --- a/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature +++ b/plugins/git4idea/test-features/git4idea/cherry-pick-auto-commit.feature @@ -223,49 +223,49 @@ Background: Given commit eef9832 on branch master """ fix #1 manually incorporated - M file.txt "feature changes" + M file.txt "initial content\nfeature changes" """ When I cherry-pick the commit f5027a3 Then the last commit is eef9832 And warning notification is shown 'Nothing to cherry-pick' """ - All changes from f5027a3 fix #1 have already been applied + All changes from f5027a3 have already been applied """ Scenario: Cherry-pick 3 commits, second commit have already been applied (IDEA-73548) Given commit c123abc on branch feature """ fix #2 - M file.txt "feature changes\nmore feature changes" + A newfile.txt "initial content" """ Given commit d123abc on branch feature """ fix #3 - M file.txt "feature changes\nmore feature changes\nmore feature changes" + M newfile.txt "initial content\nfeature changes" """ Given commit e123abc on branch feature """ fix for f2 - M a.txt "feature changes" + M a.txt "initial content\nfeature changes" """ Given commit e098fed on branch master """ fix for f2 manually incorporated - M a.txt "feature changes" + M a.txt "initial content\nfeature changes" """ When I cherry-pick commits c123abc, d123abc and e123abc Then `git log -2` should return """ fix #3 - (cherry picked from commit c123abc) + (cherry picked from commit d123abc) ----- fix #2 - (cherry picked from commit f5027a3) + (cherry picked from commit c123abc) """ - And warning notification is shown 'Cherry-picked 2 commits' + And success notification is shown 'Cherry-picked 2 commits from 3' """ c123abc fix #2 d123abc fix #3
- Commit e123abc wasn't picked, because all changes from it have already been applied. + e123abc wasn't picked, because all changes from it have already been applied. """ diff --git a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java index 6d5cc31c012e..7374ca4dbd78 100644 --- a/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java +++ b/plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java @@ -172,6 +172,11 @@ public class GitCherryPickStepdefs { expectedMessage = expectedMessage.replace("\n", "").replace(" ", ""); actualMessage = actualMessage.replace("\n", "").replace(" ", ""); } + else { + // replace just double \n between subject and body to avoid lengthy feature steps + expectedMessage = expectedMessage.replace("\n\n", "\n"); + actualMessage = actualMessage.replace("\n\n", "\n"); + } expectedMessage = virtualCommits.replaceVirtualHashes(expectedMessage); assertEquals("Commit doesn't match", expectedMessage, trimHash(actualMessage)); } From ac5ef9f5d8b4ebbc1a0bdde3e6f0a8e1427824c7 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Tue, 7 Oct 2014 16:51:55 +0400 Subject: [PATCH 18/26] [vcs] Deprecate VcsManagerPerModuleConfiguration Not actually used anywhere, the purpose is doubtful. --- .../openapi/vcs/impl/VcsManagerPerModuleConfiguration.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsManagerPerModuleConfiguration.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsManagerPerModuleConfiguration.java index 39c55e9b2bea..c97c8cef3968 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsManagerPerModuleConfiguration.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsManagerPerModuleConfiguration.java @@ -32,6 +32,10 @@ import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +/** + * @deprecated to remove in IDEA 15 + */ +@Deprecated @State( name = "VcsManagerConfiguration", storages = @Storage(file = StoragePathMacros.MODULE_FILE) From e865a0f93036c362f7915a361032e7c9192eab24 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Tue, 7 Oct 2014 16:57:01 +0400 Subject: [PATCH 19/26] [git] IDEA-130898 Make GitPushTagMode deserializable --- .../src/git4idea/push/GitPushTagMode.java | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/plugins/git4idea/src/git4idea/push/GitPushTagMode.java b/plugins/git4idea/src/git4idea/push/GitPushTagMode.java index 8e88d9973df1..6c28cc109f67 100644 --- a/plugins/git4idea/src/git4idea/push/GitPushTagMode.java +++ b/plugins/git4idea/src/git4idea/push/GitPushTagMode.java @@ -20,7 +20,7 @@ import org.jetbrains.annotations.NotNull; /** */ -public class GitPushTagMode implements VcsPushOptionValue { +public final class GitPushTagMode implements VcsPushOptionValue { public static GitPushTagMode ALL = new GitPushTagMode("All", "--tags"); public static GitPushTagMode FOLLOW = new GitPushTagMode("Current Branch", "--follow-tags"); @@ -28,7 +28,13 @@ public class GitPushTagMode implements VcsPushOptionValue { @NotNull private final String myTitle; @NotNull private final String myArgument; - public GitPushTagMode(@NotNull String title, @NotNull String argument) { + // for deserialization + @SuppressWarnings("UnusedDeclaration") + public GitPushTagMode() { + this(ALL.getTitle(), ALL.getArgument()); + } + + private GitPushTagMode(@NotNull String title, @NotNull String argument) { myTitle = title; myArgument = argument; } @@ -47,4 +53,24 @@ public class GitPushTagMode implements VcsPushOptionValue { public String getArgument() { return myArgument; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GitPushTagMode mode = (GitPushTagMode)o; + + if (!myArgument.equals(mode.myArgument)) return false; + if (!myTitle.equals(mode.myTitle)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = myTitle.hashCode(); + result = 31 * result + myArgument.hashCode(); + return result; + } } From 2c282d75de909b3e4350926361d66b46addfcf59 Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Sun, 5 Oct 2014 20:48:03 +0200 Subject: [PATCH 20/26] remove structural search short cut from keymap (IDEA-128003) --- platform/platform-resources/src/idea/Keymap_Default.xml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/platform/platform-resources/src/idea/Keymap_Default.xml b/platform/platform-resources/src/idea/Keymap_Default.xml index dcd417f0711c..405316ff8468 100644 --- a/platform/platform-resources/src/idea/Keymap_Default.xml +++ b/platform/platform-resources/src/idea/Keymap_Default.xml @@ -921,12 +921,8 @@ - - - - - - + + From 8afd9e85dd776c3dcb63926a882ce0b29e91bbbe Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Tue, 7 Oct 2014 14:59:30 +0200 Subject: [PATCH 21/26] use StringUtil.stripQuotesAroundValue() --- .../ig/bugs/NewStringBufferWithCharArgumentInspection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java index e73a4e37ee8b..4f8851ca6918 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java @@ -92,7 +92,7 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection { } final PsiExpression argument = arguments[0]; final String text = argument.getText(); - final String newArgument = '"' + StringUtil.escapeStringCharacters(text.substring(1, text.length() - 1)) + '"'; + final String newArgument = '"' + StringUtil.escapeStringCharacters(StringUtil.stripQuotesAroundValue(text)) + '"'; PsiReplacementUtil.replaceExpression(argument, newArgument); } } From d614d31b76a9ed180a8a621d36cdfc91938947e9 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 7 Oct 2014 17:14:39 +0400 Subject: [PATCH 22/26] reverted --- .../src/com/intellij/ide/IdeEventQueue.java | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index a6221007427f..ff023e1080ef 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -56,8 +56,10 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.*; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; /** * @author Vladimir Kondratyev @@ -131,7 +133,7 @@ public class IdeEventQueue extends EventQueue { private final Set myDispatchers = new LinkedHashSet(); private final Set myPostProcessors = new LinkedHashSet(); - private final Set myReady = new HashSet(); + private final Set myReady = ContainerUtil.newHashSet(); private boolean myKeyboardBusy; private boolean myDispatchingFocusEvent; @@ -147,12 +149,9 @@ public class IdeEventQueue extends EventQueue { } private IdeEventQueue() { - final Application application = ApplicationManager.getApplication(); - if (application == null || !application.isUnitTestMode()) { - EventQueue systemEventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); - assert !(systemEventQueue instanceof IdeEventQueue) : systemEventQueue; - systemEventQueue.push(this); - } + EventQueue systemEventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); + assert !(systemEventQueue instanceof IdeEventQueue) : systemEventQueue; + systemEventQueue.push(this); addIdleTimeCounterRequest(); final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); @@ -332,7 +331,7 @@ public class IdeEventQueue extends EventQueue { } private static class InertialMouseRouter { - private static int MOUSE_WHEEL_RESTART_THRESHOLD = 50; + private static final int MOUSE_WHEEL_RESTART_THRESHOLD = 50; private static Component wheelDestinationComponent = null; private static long lastMouseWheel = 0; @@ -559,7 +558,7 @@ public class IdeEventQueue extends EventQueue { } else if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; - if (myMouseEventDispatcher.patchClickCount(me) && me.getID() == MouseEvent.MOUSE_CLICKED) { + if (IdeMouseEventDispatcher.patchClickCount(me) && me.getID() == MouseEvent.MOUSE_CLICKED) { final MouseEvent toDispatch = new MouseEvent(me.getComponent(), me.getID(), System.currentTimeMillis(), me.getModifiers(), me.getX(), me.getY(), 1, me.isPopupTrigger(), me.getButton()); @@ -593,9 +592,8 @@ public class IdeEventQueue extends EventQueue { } public boolean wasRootRecentlyClicked(Component component) { - if (component == null || lastClickEvent == null || lastClickEvent.getComponent() == null) - return false; - return SwingUtilities.getRoot(lastClickEvent.getComponent()) == SwingUtilities.getRoot(component); + return component != null && lastClickEvent != null && lastClickEvent.getComponent() != null && + SwingUtilities.getRoot(lastClickEvent.getComponent()) == SwingUtilities.getRoot(component); } private static void fixStickyWindow(KeyboardFocusManager mgr, Window wnd, String resetMethod) { From 113022a95999aa76808aa09e3cb35ba80e4bb46d Mon Sep 17 00:00:00 2001 From: Andrey Vlasovskikh Date: Tue, 7 Oct 2014 17:22:23 +0400 Subject: [PATCH 23/26] Added snapshot of python-skeletons @ 031d9cc --- .gitignore | 1 - python/helpers/python-skeletons/AUTHORS.txt | 7 + python/helpers/python-skeletons/LICENSE.txt | 13 + python/helpers/python-skeletons/README.md | 237 ++ python/helpers/python-skeletons/StringIO.py | 126 + .../helpers/python-skeletons/__builtin__.py | 2507 +++++++++++++++++ .../python-skeletons/asyncio/__init__.py | 0 .../python-skeletons/asyncio/events.py | 12 + python/helpers/python-skeletons/behave.py | 60 + python/helpers/python-skeletons/builtins.py | 2046 ++++++++++++++ python/helpers/python-skeletons/cStringIO.py | 131 + .../helpers/python-skeletons/collections.py | 26 + python/helpers/python-skeletons/datetime.py | 625 ++++ python/helpers/python-skeletons/decimal.py | 82 + python/helpers/python-skeletons/functools.py | 16 + python/helpers/python-skeletons/io.py | 622 ++++ .../python-skeletons/lettuce/__init__.py | 2 + .../python-skeletons/lettuce/terrain.py | 68 + python/helpers/python-skeletons/math.py | 381 +++ .../multiprocessing/__init__.py | 280 ++ .../multiprocessing/managers.py | 76 + .../helpers/python-skeletons/nose/__init__.py | 5 + .../python-skeletons/nose/tools/__init__.py | 181 ++ .../python-skeletons/numpy/__init__.py | 10 + .../python-skeletons/numpy/core/__init__.py | 3 + .../python-skeletons/numpy/core/multiarray.py | 202 ++ .../helpers/python-skeletons/os/__init__.py | 1257 +++++++++ python/helpers/python-skeletons/os/path.py | 293 ++ python/helpers/python-skeletons/pathlib.py | 373 +++ python/helpers/python-skeletons/pickle.py | 81 + python/helpers/python-skeletons/re.py | 277 ++ python/helpers/python-skeletons/shutil.py | 99 + python/helpers/python-skeletons/sqlite3.py | 190 ++ python/helpers/python-skeletons/struct.py | 106 + python/helpers/python-skeletons/subprocess.py | 140 + 35 files changed, 10534 insertions(+), 1 deletion(-) create mode 100644 python/helpers/python-skeletons/AUTHORS.txt create mode 100644 python/helpers/python-skeletons/LICENSE.txt create mode 100644 python/helpers/python-skeletons/README.md create mode 100644 python/helpers/python-skeletons/StringIO.py create mode 100644 python/helpers/python-skeletons/__builtin__.py create mode 100644 python/helpers/python-skeletons/asyncio/__init__.py create mode 100644 python/helpers/python-skeletons/asyncio/events.py create mode 100644 python/helpers/python-skeletons/behave.py create mode 100644 python/helpers/python-skeletons/builtins.py create mode 100644 python/helpers/python-skeletons/cStringIO.py create mode 100644 python/helpers/python-skeletons/collections.py create mode 100644 python/helpers/python-skeletons/datetime.py create mode 100644 python/helpers/python-skeletons/decimal.py create mode 100644 python/helpers/python-skeletons/functools.py create mode 100644 python/helpers/python-skeletons/io.py create mode 100644 python/helpers/python-skeletons/lettuce/__init__.py create mode 100644 python/helpers/python-skeletons/lettuce/terrain.py create mode 100644 python/helpers/python-skeletons/math.py create mode 100644 python/helpers/python-skeletons/multiprocessing/__init__.py create mode 100644 python/helpers/python-skeletons/multiprocessing/managers.py create mode 100644 python/helpers/python-skeletons/nose/__init__.py create mode 100644 python/helpers/python-skeletons/nose/tools/__init__.py create mode 100644 python/helpers/python-skeletons/numpy/__init__.py create mode 100644 python/helpers/python-skeletons/numpy/core/__init__.py create mode 100644 python/helpers/python-skeletons/numpy/core/multiarray.py create mode 100644 python/helpers/python-skeletons/os/__init__.py create mode 100644 python/helpers/python-skeletons/os/path.py create mode 100644 python/helpers/python-skeletons/pathlib.py create mode 100644 python/helpers/python-skeletons/pickle.py create mode 100644 python/helpers/python-skeletons/re.py create mode 100644 python/helpers/python-skeletons/shutil.py create mode 100644 python/helpers/python-skeletons/sqlite3.py create mode 100644 python/helpers/python-skeletons/struct.py create mode 100644 python/helpers/python-skeletons/subprocess.py diff --git a/.gitignore b/.gitignore index 3fb1a17163fc..e380455105f0 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,5 @@ .idea/workspace.xml /out .DS_Store -/python/helpers/python-skeletons /test-system /test-config diff --git a/python/helpers/python-skeletons/AUTHORS.txt b/python/helpers/python-skeletons/AUTHORS.txt new file mode 100644 index 000000000000..58ecacda0fe9 --- /dev/null +++ b/python/helpers/python-skeletons/AUTHORS.txt @@ -0,0 +1,7 @@ +The current maintainer: + +* Andrey Vlasovskikh + +Contributors: + +TODO: The list of contributors diff --git a/python/helpers/python-skeletons/LICENSE.txt b/python/helpers/python-skeletons/LICENSE.txt new file mode 100644 index 000000000000..f80bfeb4e25a --- /dev/null +++ b/python/helpers/python-skeletons/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright 2013 The python-skeletons authors + +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. \ No newline at end of file diff --git a/python/helpers/python-skeletons/README.md b/python/helpers/python-skeletons/README.md new file mode 100644 index 000000000000..ac3af02c6823 --- /dev/null +++ b/python/helpers/python-skeletons/README.md @@ -0,0 +1,237 @@ +Python Skeletons +================ + +_This proposal is a draft._ + +Python skeletons are Python files that contain API definitions of existing +libraries extended for static analysis tools. + +Rationale +--------- + +Python is a dynamic language less suitable for static code analysis than static +languages like C or Java. Although Python static analysis tools can extract +some information from Python source code without executing it, this information +is often very shallow and incomplete. + +Dynamic features of Python are very useful for user code. But using these +features in APIs of third-party libraries and the standard library is not +always a good idea. Tools (and users, in fact) need clear definitions of APIs. +Often library API definitions are quite static and easy to grasp (defined +using `class`, `def`), but types of function parameters and return values +usually are not specified. Sometimes API definitions involve metaprogramming. + +As there is not enough information in API definition code of libraries, +developers of static analysis tools collect extended API data themselves and +store it in their own formats. For example, PyLint uses imperative AST +transformations of API modules in order to extend them with hard-coded data. +PyCharm extends APIs via its proprietary database of declarative type +annotations. The absence of a common extended API information format makes it +hard for developers and users of tools to collect and share data. + + +Proposal +-------- + +The proposal is to create a common database of extended API definitions as a +collection of Python files called skeletons. Static analysis tools already +understand Python code, so it should be easy to start extracting API +definitions from these Python skeleton files. Regular function and class +definitions can be extended with additional docstrings and decorators, e.g. for +providing types of function parameters and return values. Static analysis tools +may use a subset of information contained in skeleton files needed for their +operation. Using Python files instead of a custom API definition format will +also make it easier for users to populate the skeletons database. + +Declarative Python API definitions for static analysis tools cannot cover all +dynamic tricks used in real APIs of libraries: some of them still require +library-specific code analysis. Nevertheless the skeletons database is enough +for many libraries. + +The proposed [python-skeletons](https://github.com/JetBrains/python-skeletons) +repository is hosted on GitHub. + + +Conventions +----------- + +Skeletons should contain syntactically correct Python code, preferably compatible +with Python 2.6-3.3. + +Skeletons should respect [PEP-8](http://www.python.org/dev/peps/pep-0008/) and +[PEP-257](http://www.python.org/dev/peps/pep-0257/) style guides. + +If you need to reference the members of the original module of a skeleton, you +should import it explicitly. For example, in a skeleton for the `foo` module: + + import foo + + + class C(foo.B): + def bar(): + """Do bar and return Bar. + + :rtype: foo.Bar + """ + return foo.Bar() + +Modules can be referenced in docstring without explicit imports. + +The body of a function in a skeleton file should consist of a single `return` +statement that returns a simple value of the declared return type (e.g. `0` +for `int`, `False` for `bool`, `Foo()` for `Foo`). If the function returns +something non-trivial, its may consist of a `pass` statement. + + +### Types + +There is no standard notation for specifying types in Python code. We would +like this standard to emerge, see the related work below. + +The current understanding is that a standard for optional type annotations in +Python could use the syntax of function annotations in Python 3 and decorators +as a fallback in Python 2. The type system should be relatively simple, but it +has to include parametric (generic) types for collections and probably more. + +As a temporary solution, we propose a simple way of specifying types in +skeletons using Sphinx docstrings using the following notation: + + Foo # Class Foo visible in the current scope + x.y.Bar # Class Bar from x.y module + Foo | Bar # Foo or Bar + (Foo, Bar) # Tuple of Foo and Bar + list[Foo] # List of Foo elements + dict[Foo, Bar] # Dict from Foo to Bar + T # Generic type (T-Z are reserved for generics) + T <= Foo # Generic type with upper bound Foo + Foo[T] # Foo parameterized with T + (Foo, Bar) -> Baz # Function of Foo and Bar that returns Baz + +There are several shortcuts available: + + unknown # Unknown type + None # type(None) + string # Py2: str | unicode, Py3: str + bytestring # Py2: str | unicode, Py3: bytes + bytes # Py2: str, Py3: bytes + unicode # Py2: unicode, Py3: str + +The syntax is a subject to change. It is almost compatible to Python (except +function types), but its semantics differs from Python (no `|`, no implicitly +visible names, no generic types). So you cannot use these expressions in +Python 3 function annotations. + +If you want to create a parameterized class, you should define its parameters +in the mock return type of a constructor: + + class C(object): + """Some collection C that can contain values of T.""" + + def __init__(self, value): + """Initialize C. + + :type value: T + :rtype: C[T] + """ + pass + + def get(self): + """Return the contained value. + + :rtype: T + """ + pass + + +### Versioning + +The recommended way of checking the version of Python is: + + import sys + + + if sys.version_info >= (2, 7) and sys.version_info < (3,): + def from_27_until_30(): + pass + +A skeleton should document the most recently released version of a library. Use +deprecation warnings for functions that have been removed from the API. + +Skeletons for built-in symbols is an exception. There are two modules: +`__builtin__` for Python 2 and `builtins` for Python 3. + + +Related Work +------------ + +The JavaScript community is also interested in formalizing API definitions and +specifying types. They have come up with several JavaScript dialects that +support optional types: TypeScript, Dart. There is a JavaScript initiative +similar to the proposed Python skeletons called +[DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped). The idea is +to use TypeScript API stubs for various JavaScript libraries. + +There are many approaches to specifying types in Python, none of them is widely +adopted at the moment: + +* A series of old (2005) posts by GvR: + [1](http://www.artima.com/weblogs/viewpost.jsp?thread=85551), + [2](http://www.artima.com/weblogs/viewpost.jsp?thread=86641), + [3](http://www.artima.com/weblogs/viewpost.jsp?thread=87182) +* String-based [python-rightarrow](https://github.com/kennknowles/python-rightarrow) + library +* Expression-based [typeannotations](https://github.com/ceronman/typeannotations) + library for Python 3 +* [mypy](http://www.mypy-lang.org/) Python dialect +* [pytypes](https://github.com/pytypes/pytypes): Optional typing for Python proposal +* [Proposal: Use mypy syntax for function annotations](https://mail.python.org/pipermail/python-ideas/2014-August/028618.html) by GvR + +See also the notes on function annotations in +[PEP-8](http://www.python.org/dev/peps/pep-0008/). + + +PyCharm / IntelliJ +------------------ + +PyCharm 3 and the Python plugin 3.x for IntelliJ can extract the following +information from the skeletons: + +* Parameters of functions and methods +* Return types and parameter types of functions and methods +* Types of assignment targets +* Extra module members +* Extra class members +* TODO + +PyCharm 3 comes with a snapshot of the Python skeletons repository (Python +plugin 3.0.1 for IntelliJ still doesn't include this repository). You +**should not** modify it, because it will be updated with the PyCharm / Python +plugin for IntelliJ installation. If you want to change the skeletons, clone +the skeletons GitHub repository into your PyCharm/IntelliJ config directory: + + cd + git clone https://github.com/JetBrains/python-skeletons.git + +where `` is: + +* PyCharm + * Mac OS X: `~/Library/Preferences/PyCharmXX` + * Linux: `~/.PyCharmXX/config` + * Windows: `\.PyCharmXX\config` +* IntelliJ + * Mac OS X: `~/Library/Preferences/IntelliJIdeaXX` + * Linux: `~/.IntelliJIdeaXX/config` + * Windows: `\.IntelliJIdeaXX\config` + +Please send your PyCharm/IntelliJ-related bug reports and feature requests to +[PyCharm issue tracker](http://youtrack.jetbrains.com/issues/PY). + + +Feedback +-------- + +If you want to contribute, send your pull requests to the Python skeletons +repository on GitHub. Please make sure, that you follow the conventions above. + +Use [code-quality](http://mail.python.org/mailman/listinfo/code-quality) +mailing list to discuss Python skeletons. diff --git a/python/helpers/python-skeletons/StringIO.py b/python/helpers/python-skeletons/StringIO.py new file mode 100644 index 000000000000..6d38add1df6a --- /dev/null +++ b/python/helpers/python-skeletons/StringIO.py @@ -0,0 +1,126 @@ +"""Skeleton for 'StringIO' stdlib module.""" + + +import StringIO as _StringIO + + +class StringIO(object): + """Reads and writes a string buffer (also known as memory files).""" + + def __init__(self, buffer=None): + """When a StringIO object is created, it can be initialized to an existing + string by passing the string to the constructor. + + :type buffer: T <= bytes | unicode + :rtype: _StringIO.StringIO[T] + """ + self.closed = False + + def getvalue(self): + """Retrieve the entire contents of the "file" at any time before the + StringIO object's close() method is called. + + :rtype: T + """ + pass + + def close(self): + """Free the memory buffer. + + :rtype: None + """ + pass + + def flush(self): + """Flush the internal buffer. + + :rtype: None + """ + pass + + def isatty(self): + """Return True if the file is connected to a tty(-like) device, + else False. + + :rtype: bool + """ + return False + + def __iter__(self): + """Return an iterator over lines. + + :rtype: _StringIO.StringIO[T] + """ + return self + + def next(self): + """Returns the next input line. + + :rtype: T + """ + pass + + def read(self, size=-1): + """Read at most size bytes or characters from the buffer. + + :type size: numbers.Integral + :rtype: T + """ + pass + + def readline(self, size=-1): + """Read one entire line from the buffer. + + :type size: numbers.Integral + :rtype: T + """ + pass + + def readlines(self, sizehint=-1): + """Read until EOF using readline() and return a list containing the + lines thus read. + + :type sizehint: numbers.Integral + :rtype: list[T] + """ + pass + + def seek(self, offset, whence=0): + """Set the buffer's current position, like stdio's fseek(). + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def tell(self): + """Return the buffer's current position, like stdio's ftell(). + + :rtype: int + """ + pass + + def truncate(self, size=-1): + """Truncate the buffer's size. + + :type size: numbers.Integral + :rtype: None + """ + pass + + def write(self, str): + """"Write bytes or a string to the buffer. + + :type str: T + :rtype: None + """ + pass + + def writelines(self, sequence): + """Write a sequence of bytes or strings to the buffer. + + :type sequence: collections.Iterable[T] + :rtype: None + """ + pass diff --git a/python/helpers/python-skeletons/__builtin__.py b/python/helpers/python-skeletons/__builtin__.py new file mode 100644 index 000000000000..0324085cad3d --- /dev/null +++ b/python/helpers/python-skeletons/__builtin__.py @@ -0,0 +1,2507 @@ +"""Skeletons for Python 2 built-in symbols.""" + + +from __future__ import unicode_literals +import sys + + +def abs(number): + """Return the absolute value of the argument. + + :type number: T + :rtype: T | unknown + """ + return number + + +def all(iterable): + """Return True if bool(x) is True for all values x in the iterable. + + :type iterable: collections.Iterable + :rtype: bool + """ + return False + + +def any(iterable): + """Return True if bool(x) is True for any x in the iterable. + + :type iterable: collections.Iterable + :rtype: bool + """ + return False + + +def bin(number): + """Return the binary representation of an integer or long integer. + + :type number: numbers.Number + :rtype: bytes + """ + return b'' + + +def callable(object): + """Return whether the object is callable (i.e., some kind of function). + Note that classes are callable, as are instances with a __call__() method. + + :rtype: bool + """ + return False + + +def chr(i): + """Return a string of one character with ordinal i; 0 <= i < 256. + + :type i: numbers.Integral + :rtype: bytes + """ + return b'' + + +def cmp(x, y): + """Return negative if xy. + + :rtype: int + """ + return 0 + + +def dir(object=None): + """If called without an argument, return the names in the current scope. + Else, return an alphabetized list of names comprising (some of) the + attributes of the given object, and of attributes reachable from it. + + :rtype: list[string] + """ + return [] + + +def divmod(x, y): + """Return the tuple ((x-x%y)/y, x%y). + + :type x: numbers.Number + :type y: numbers.Number + :rtype: (int | long | float | unknown, int | long | float | unknown) + """ + return 0, 0 + + +def filter(function_or_none, sequence): + """Return those items of sequence for which function(item) is true. If + function is None, return the items that are true. If sequence is a tuple + or string, return the same type, else return a list. + + :type function_or_none: collections.Callable | None + :type sequence: T <= list[V] | collections.Iterable[V] | bytes | unicode + :rtype: T + """ + return sequence + + +def getattr(object, name, default=None): + """Get a named attribute from an object; getattr(x, 'y') is equivalent to + x.y. When a default argument is given, it is returned when the attribute + doesn't exist; without it, an exception is raised in that case. + + :type name: string + """ + pass + + +def globals(): + """Return the dictionary containing the current scope's global variables. + + :rtype: dict[string, unknown] + """ + return {} + + +def hasattr(object, name): + """Return whether the object has an attribute with the given name. + + :type name: string + :rtype: bool + """ + return False + + +def hash(object): + """Return a hash value for the object. + + :rtype: int + """ + return 0 + + +def hex(number): + """Return the hexadecimal representation of an integer or long integer. + + :type number: numbers.Integral + :rtype: bytes + """ + return b'' + + +def id(object): + """Return the identity of an object. + + :rtype: int + """ + return 0 + + +def isinstance(object, class_or_type_or_tuple): + """Return whether an object is an instance of a class or of a subclass + thereof. + + :rtype: bool + """ + return False + + +def issubclass(C, B): + """Return whether class C is a subclass (i.e., a derived class) of class B. + + :rtype: bool + """ + return False + + +def iter(o, sentinel=None): + """Get an iterator from an object. In the first form, the argument must + supply its own iterator, or be a sequence. In the second form, the callable + is called until it returns the sentinel. + + :type o: collections.Iterable[T] | (() -> object) + :type sentinel: object | None + :rtype: collections.Iterator[T] + """ + return [] + + +def len(object): + """Return the number of items of a sequence or mapping. + + :type object: collections.Sized + :rtype: int + """ + return 0 + + +def locals(): + """Update and return a dictionary containing the current scope's local + variables. + + :rtype: dict[string, unknown] + """ + return {} + + +def map(function, sequence, *sequence_1): + """Return a list of the results of applying the function to the items of + the argument sequence(s). + + :type function: ((T) -> V) | None + :type sequence: collections.Iterable[T] + :rtype: list[V] | bytes | unicode + """ + pass + + +def next(iterator, default=None): + """Return the next item from the iterator. + + :type iterator: collections.Iterator[T] + :rtype: T + """ + pass + + +def oct(number): + """Return the octal representation of an integer or long integer. + + :type number: numbers.Integral + :rtype: bytes + """ + return b'' + + +def open(name, mode='r', buffering=-1, encoding=None, errors=None, newline=None, + closefd=None, opener=None): + """Open a file, returns a file object. + + :type name: string + :type mode: string + :type buffering: numbers.Integral + :type encoding: string | None + :type errors: string | None + :rtype: file + """ + return file() + + +def ord(c): + """Return the integer ordinal of a one-character string. + + :type c: string + :rtype: int + """ + return 0 + + +def pow(x, y, z=None): + """With two arguments, equivalent to x**y. With three arguments, + equivalent to (x**y) % z, but may be more efficient (e.g. for longs). + + :type x: numbers.Number + :type y: numbers.Number + :type z: numbers.Number | None + :rtype: int | long | float | complex + """ + return 0 + + +def range(start, stop=None, step=None): + """Return a list containing an arithmetic progression of integers. + + :type start: numbers.Integral + :type stop: numbers.Integral | None + :type step: numbers.Integral | None + :rtype: list[int] + """ + return [] + + +def reduce(function, sequence, initial=None): + """Apply a function of two arguments cumulatively to the items of a + sequence, from left to right, so as to reduce the sequence to a single + value. + + :type function: collections.Callable + :type sequence: collections.Iterable + :type initial: T + :rtype: T | unknown + """ + return initial + + +def repr(object): + """ + Return the canonical string representation of the object. + + :rtype: bytes + """ + return b'' + + +def round(number, ndigits=None): + """Round a number to a given precision in decimal digits (default 0 digits). + + :type number: object + :type ndigits: numbers.Integral | None + :rtype: float + """ + return 0.0 + + +class slice(object): + def __init__(self, start, stop=None, step=None): + """Create a slice object. This is used for extended slicing (e.g. + a[0:10:2]). + + :type start: numbers.Integral + :type stop: numbers.Integral | None + :type step: numbers.Integral | None + """ + pass + + +def unichr(i): + """Return the Unicode string of one character whose Unicode code is the + integer i. + + :type i: numbers.Integral + :rtype: unicode + """ + return '' + + +def vars(object=None): + """Without arguments, equivalent to locals(). With an argument, equivalent + to object.__dict__. + + :rtype: dict[string, unknown] + """ + return {} + + +def zip(*iterables): + """This function returns a list of tuples, where the i-th tuple contains + the i-th element from each of the argument sequences or iterables. + + :rtype: list[tuple] + """ + return [] + + +class object: + """ The most base type.""" + + @staticmethod + def __new__(cls, *more): + """Create a new object. + + :type cls: T + :rtype: T + """ + pass + + +class type(object): + """Type of object.""" + + def __instancecheck__(cls, instance): + """Return true if instance should be considered a (direct or indirect) + instance of class. + """ + return False + + def __subclasscheck__(cls, subclass): + """Return true if subclass should be considered a (direct or indirect) + subclass of class. + """ + return False + + +class enumerate(object): + """enumerate object.""" + + def __init__(self, iterable, start=0): + """Create an enumerate object. + + :type iterable: collections.Iterable[T] + :type start: numbers.Integral + :rtype: enumerate[int, T] + """ + pass + + def next(self): + """Return the next value, or raise StopIteration. + + :rtype: (int, T) + """ + pass + + def __iter__(self): + """x.__iter__() <==> iter(x). + + :rtype: enumerate[int, T] + """ + return self + + +class xrange(object): + """xrange object.""" + + def __init__(self, start, stop=None, step=None): + """Create an xrange object. + + :type start: numbers.Integral + :type stop: numbers.Integral | None + :type step: numbers.Integral | None + :rtype: xrange[int] + """ + pass + + +class int(object): + """Integer numeric type.""" + + def __init__(self, x=None, base=10): + """Convert a number or string x to an integer, or return 0 if no + arguments are given. + + :type x: object + :type base: numbers.Integral + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __pow__(self, y, modulo=None): + """x to the power y. + + :type y: numbers.Number + :type modulo: numbers.Integral | None + :rtype: int + """ + return 0 + + def __lshift__(self, n): + """x shifted left by n bits. + + :type n: numbers.Integral + :rtype: int + """ + return 0 + + def __rshift__(self, n): + """x shifted right by n bits. + + :type n: numbers.Integral + :rtype: int + """ + return 0 + + def __and__(self, y): + """Bitwise and of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __or__(self, y): + """Bitwise or of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __xor__(self, y): + """Bitwise exclusive or of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rlshift__(self, y): + """y shifted left by x bits. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rrshift__(self, y): + """y shifted right by n bits. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rand__(self, y): + """Bitwise and of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __ror__(self, y): + """Bitwise or of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rxor__(self, y): + """Bitwise exclusive or of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __pos__(self): + """x unchanged. + + :rtype: int + """ + return 0 + + def __neg__(self): + """x negated. + + :rtype: int + """ + return 0 + + def __invert__(self): + """The bits of x inverted. + + :rtype: int + """ + return 0 + + +class long(object): + """Long integer numeric type.""" + + def __init__(self, x=None, base=10): + """Convert a number or string x to a long integer, or return 0 if + no arguments are given. + + :type x: object + :type base: numbers.Integral + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __pow__(self, y, modulo=None): + """x to the power y. + + :type y: numbers.Number + :type modulo: numbers.Integral | None + :rtype: long + """ + return 0 + + def __lshift__(self, n): + """x shifted left by n bits. + + :type n: numbers.Integral + :rtype: long + """ + return 0 + + def __rshift__(self, n): + """x shifted right by n bits. + + :type n: numbers.Integral + :rtype: long + """ + return 0 + + def __and__(self, y): + """Bitwise and of x and y. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __or__(self, y): + """Bitwise or of x and y. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __xor__(self, y): + """Bitwise exclusive or of x and y. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rlshift__(self, y): + """y shifted left by x bits. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __rrshift__(self, y): + """y shifted right by n bits. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __rand__(self, y): + """Bitwise and of y and x. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __ror__(self, y): + """Bitwise or of y and x. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __rxor__(self, y): + """Bitwise exclusive or of y and x. + + :type y: numbers.Integral + :rtype: long + """ + return 0 + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: long + """ + return 0 + + def __pos__(self): + """x unchanged. + + :rtype: long + """ + return 0 + + def __neg__(self): + """x negated. + + :rtype: long + """ + return 0 + + def __invert__(self): + """The bits of x inverted. + + :rtype: long + """ + return 0 + + +class float(object): + """Floating point numeric type.""" + + def __init__(self, x=None): + """Convert a string or a number to floating point. + + :type x: object + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __pow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __pos__(self): + """x unchanged. + + :rtype: float + """ + return 0.0 + + def __neg__(self): + """x negated. + + :rtype: float + """ + return 0.0 + + +class complex(object): + """Complex numeric type.""" + + def __init__(self, real=None, imag=None): + """Create a complex number with the value real + imag*j or convert a + string or number to a complex number. + + :type real: object + :type imag: object + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __pow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __pos__(self): + """x unchanged. + + :rtype: complex + """ + return 0j + + def __neg__(self): + """x negated. + + :rtype: complex + """ + return 0j + + +class str(basestring): + """String object.""" + + def __init__(self, object=''): + """Construct an immutable string. + + :type object: object + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: string + :rtype: string + """ + return b'' + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: str + """ + return b'' + + def __mod__(self, y): + """x % y. + + :rtype: string + """ + return b'' + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: str + """ + return b'' + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: str + """ + return b'' + + def __iter__(self): + """Iterator over bytes. + + :rtype: collections.Iterator[str] + """ + return [] + + def capitalize(self): + """Return a copy of the string with its first character capitalized + and the rest lowercased. + + :rtype: str + """ + return b'' + + def center(self, width, fillchar=' '): + """Return centered in a string of length width. + + :type width: numbers.Integral + :type fillchar: str + :rtype: str + """ + return b'' + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of substring + sub in the range [start, end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: int + """ + return 0 + + def decode(self, encoding='utf-8', errors='strict'): + """Return a string decoded from the given bytes. + + :type encoding: string + :type errors: string + :rtype: unicode + """ + return '' + + def encode(self, encoding='utf-8', errors='strict'): + """Return an encoded version of the string as a bytes object. + + :type encoding: string + :type errors: string + :rtype: str + """ + return b'' + + def endswith(self, suffix, start=None, end=None): + """Return True if the string ends with the specified suffix, + otherwise return False. + + :type suffix: string | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def find(self, sub, start=None, end=None): + """Return the lowest index in the string where substring sub is + found, such that sub is contained in the slice s[start:end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def index(self, sub, start=None, end=None): + """Like find(), but raise ValueError when the substring is not + found. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def isalnum(self): + """Return true if all characters in the string are alphanumeric and + there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isalpha(self): + """Return true if all characters in the string are alphabetic and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isdigit(self): + """Return true if all characters in the string are digits and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def islower(self): + """Return true if all cased characters in the string are lowercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def isspace(self): + """Return true if there are only whitespace characters in the + string and there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def istitle(self): + """Return true if the string is a titlecased string and there is at + least one character, for example uppercase characters may only + follow uncased characters and lowercase characters only cased ones. + + :rtype: bool + """ + return False + + def isupper(self): + """Return true if all cased characters in the string are uppercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def join(self, iterable): + """Return a string which is the concatenation of the strings in the + iterable. + + :type iterable: collections.Iterable[string] + :rtype: string + """ + return '' + + def ljust(self, width, fillchar=' '): + """Return the string left justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: str + :rtype: str + """ + return b'' + + def lower(self): + """Return a copy of the string with all the cased characters + converted to lowercase. + + :rtype: str + """ + return b'' + + def lstrip(self, chars=None): + """Return a copy of the string with leading characters removed. + + :type chars: string | None + :rtype: str + """ + return b'' + + def partition(self, sep): + """Split the string at the first occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: string + :rtype: (str, str, str) + """ + return b'', b'', b'' + + def replace(self, old, new, count=-1): + """Return a copy of the string with all occurrences of substring + old replaced by new. + + :type old: string + :type new: string + :type count: numbers.Integral + :rtype: string + """ + return '' + + def rfind(self, sub, start=None, end=None): + """Return the highest index in the string where substring sub is + found, such that sub is contained within s[start:end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rindex(self, sub, start=None, end=None): + """Like rfind(), but raise ValueError when the substring is not + found. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rjust(self, width, fillchar=' '): + """Return the string right justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: string + :rtype: string + """ + return '' + + def rpartition(self, sep): + """Split the string at the last occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: string + :rtype: (str, str, str) + """ + return b'', b'', b'' + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: string | None + :type maxsplit: numbers.Integral + :rtype: list[str] + """ + return [] + + def rstrip(self, chars=None): + """Return a copy of the string with trailing characters removed. + + :type chars: string | None + :rtype: str + """ + return b'' + + def split(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: string | None + :type maxsplit: numbers.Integral + :rtype: list[str] + """ + return [] + + def splitlines(self, keepends=False): + """Return a list of the lines in the string, breaking at line + boundaries. + + :type keepends: bool + :rtype: list[str] + """ + return [] + + def startswith(self, prefix, start=None, end=None): + """Return True if string starts with the prefix, otherwise return + False. + + :type prefix: string | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def strip(self, chars=None): + """Return a copy of the string with the leading and trailing + characters removed. + + :type chars: string | None + :rtype: str + """ + return b'' + + def swapcase(self): + """Return a copy of the string with uppercase characters converted + to lowercase and vice versa. + + :rtype: str + """ + return b'' + + def title(self): + """Return a titlecased version of the string where words start with + an uppercase character and the remaining characters are lowercase. + + :rtype: str + """ + return b'' + + def upper(self): + """Return a copy of the string with all the cased characters + converted to uppercase. + + :rtype: str + """ + return b'' + + def zfill(self, width): + """Return the numeric string left filled with zeros in a string of + length width. + + :type width: numbers.Integral + :rtype: str + """ + return b'' + + +class unicode(basestring): + """Unicode string object.""" + + def __init__(self, object='', encoding='utf-8', errors='strict'): + """Construct an immutable Unicode string. + + :type object: object + :type encoding: string + :type errors: string + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: string + :rtype: unicode + """ + return '' + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: unicode + """ + return '' + + def __mod__(self, y): + """x % y. + + :rtype: unicode + """ + return '' + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: unicode + """ + return '' + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: unicode + """ + return '' + + def __iter__(self): + """Iterator over bytes. + + :rtype: collections.Iterator[unicode] + """ + return [] + + def capitalize(self): + """Return a copy of the string with its first character capitalized + and the rest lowercased. + + :rtype: unicode + """ + return '' + + def center(self, width, fillchar=' '): + """Return centered in a string of length width. + + :type width: numbers.Integral + :type fillchar: string + :rtype: unicode + """ + return '' + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of substring + sub in the range [start, end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: int + """ + return 0 + + def decode(self, encoding='utf-8', errors='strict'): + """Return a string decoded from the given bytes. + + :type encoding: string + :type errors: string + :rtype: unicode + """ + return '' + + def encode(self, encoding='utf-8', errors='strict'): + """Return an encoded version of the string as a bytes object. + + :type encoding: string + :type errors: string + :rtype: bytes + """ + return b'' + + def endswith(self, suffix, start=None, end=None): + """Return True if the string ends with the specified suffix, + otherwise return False. + + :type suffix: string | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def find(self, sub, start=None, end=None): + """Return the lowest index in the string where substring sub is + found, such that sub is contained in the slice s[start:end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def index(self, sub, start=None, end=None): + """Like find(), but raise ValueError when the substring is not + found. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def isalnum(self): + """Return true if all characters in the string are alphanumeric and + there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isalpha(self): + """Return true if all characters in the string are alphabetic and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isdigit(self): + """Return true if all characters in the string are digits and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def islower(self): + """Return true if all cased characters in the string are lowercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def isspace(self): + """Return true if there are only whitespace characters in the + string and there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def istitle(self): + """Return true if the string is a titlecased string and there is at + least one character, for example uppercase characters may only + follow uncased characters and lowercase characters only cased ones. + + :rtype: bool + """ + return False + + def isupper(self): + """Return true if all cased characters in the string are uppercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def join(self, iterable): + """Return a string which is the concatenation of the strings in the + iterable. + + :type iterable: collections.Iterable[string] + :rtype: unicode + """ + return '' + + def ljust(self, width, fillchar=' '): + """Return the string left justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: string + :rtype: unicode + """ + return '' + + def lower(self): + """Return a copy of the string with all the cased characters + converted to lowercase. + + :rtype: unicode + """ + return '' + + def lstrip(self, chars=None): + """Return a copy of the string with leading characters removed. + + :type chars: string | None + :rtype: unicode + """ + return '' + + def partition(self, sep): + """Split the string at the first occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: string + :rtype: (unicode, unicode, unicode) + """ + return '', '', '' + + def replace(self, old, new, count=-1): + """Return a copy of the string with all occurrences of substring + old replaced by new. + + :type old: string + :type new: string + :type count: numbers.Integral + :rtype: unicode + """ + return '' + + def rfind(self, sub, start=None, end=None): + """Return the highest index in the string where substring sub is + found, such that sub is contained within s[start:end]. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rindex(self, sub, start=None, end=None): + """Like rfind(), but raise ValueError when the substring is not + found. + + :type sub: string + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rjust(self, width, fillchar=' '): + """Return the string right justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: string + :rtype: unicode + """ + return '' + + def rpartition(self, sep): + """Split the string at the last occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: string + :rtype: (unicode, unicode, unicode) + """ + return '', '', '' + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: string | None + :type maxsplit: numbers.Integral + :rtype: list[unicode] + """ + return [] + + def rstrip(self, chars=None): + """Return a copy of the string with trailing characters removed. + + :type chars: string | None + :rtype: unicode + """ + return '' + + def split(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: string | None + :type maxsplit: numbers.Integral + :rtype: list[unicode] + """ + return [] + + def splitlines(self, keepends=False): + """Return a list of the lines in the string, breaking at line + boundaries. + + :type keepends: bool + :rtype: list[unicode] + """ + return [] + + def startswith(self, prefix, start=None, end=None): + """Return True if string starts with the prefix, otherwise return + False. + + :type prefix: string | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def strip(self, chars=None): + """Return a copy of the string with the leading and trailing + characters removed. + + :type chars: string | None + :rtype: unicode + """ + return '' + + def swapcase(self): + """Return a copy of the string with uppercase characters converted + to lowercase and vice versa. + + :rtype: unicode + """ + return '' + + def title(self): + """Return a titlecased version of the string where words start with + an uppercase character and the remaining characters are lowercase. + + :rtype: unicode + """ + return '' + + def upper(self): + """Return a copy of the string with all the cased characters + converted to uppercase. + + :rtype: unicode + """ + return '' + + def zfill(self, width): + """Return the numeric string left filled with zeros in a string of + length width. + + :type width: numbers.Integral + :rtype: unicode + """ + return '' + + +class list(object): + """List object.""" + + def __init__(self, iterable=None): + """Create a list object. + + :type iterable: collections.Iterable[T] + :rtype: list[T] + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: list[T] + :rtype: list[T] + """ + return [] + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: list[T] + """ + return [] + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: list[T] + """ + return [] + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: T + """ + pass + + def __setitem__(self, i, y): + """Item i is replaced by y. + + :type i: numbers.Integral + :type y: T + :rtype: None + """ + pass + + def __delitem__(self, i): + """Remove i-th item. + + :type i: numbers.Integral + :rtype: None + """ + pass + + def append(self, x): + """Appends x to the end of the sequence. + + :type x: T + :rtype: None + """ + pass + + def extend(self, t): + """Extends the sequence with the contents of t. + + :type t: collections.Iterable[T] + :rtype: None + """ + pass + + def count(self, x): + """Total number of occurrences of x in the sequence. + + :type x: T + :rtype: int + """ + return 0 + + def index(self, x, i=None, j=None): + """Index of the first occurrence of x in the sequence. + + :type x: T + :type i: numbers.Integral | None + :type j: numbers.Integral | none + :rtype: int + """ + return 0 + + def insert(self, i, x): + """Inserts x into the sequence at the index given by i. + + :type i: numbers.Number + :type x: T + :rtype: None + """ + pass + + def pop(self, i=-1): + """Retrieves the item at i and also removes it from the sequence. + + :type i: numbers.Number + :rtype: T + """ + pass + + def remove(self, x): + """Remove the first item x from the sequence. + + :type x: T + :rtype: None + """ + pass + + def sort(self, cmp=None, key=None, reverse=False): + """Sort the items of the sequence in place. + + :type cmp: ((T, T) -> int) | None + :type key: ((T) -> object) | None + :type reverse: bool + :rtype: None + """ + pass + + +class tuple(object): + """Tuple object.""" + + def __add__(self, y): + """The concatenation of x and y. + + :type y: tuple + :rtype: tuple + """ + pass + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: tuple + """ + pass + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: tuple + """ + pass + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: object | unknown + """ + pass + + def count(self, x): + """Total number of occurrences of x in the sequence. + + :type x: object + :rtype: int + """ + return 0 + + def index(self, x, i=None, j=None): + """Index of the first occurrence of x in the sequence. + + :type x: object + :type i: numbers.Integral | None + :type j: numbers.Integral | none + :rtype: int + """ + return 0 + + +class dict(object): + """Dictionary object.""" + + def __init__(self, iterable=None, **kwargs): + """Create a dictionary object. + + :type iterable: collections.Iterable[(T, V)] + :rtype: dict[T, V] + """ + pass + + def __len__(self): + """Return the number of items in the dictionary d. + + :rtype: int + """ + return 0 + + def __getitem__(self, key): + """Return the item of d with key key. + + :type key: T + :rtype: V + """ + pass + + def __setitem__(self, key, value): + """Set d[key] to value. + + :type key: T + :type value: V + :rtype: None + """ + pass + + def __delitem__(self, key): + """Remove d[key] from d. + + :type key: T + :rtype: None + """ + pass + + def copy(self): + """Return a shallow copy of the dictionary. + + :rtype: dict[T, V] + """ + return self + + @staticmethod + def fromkeys(seq, value=None): + """Create a new dictionary with keys from seq and values set to value. + + :type seq: collections.Iterable[T] + :type value: V + :rtype: dict[T, V] + """ + return {} + + def get(self, key, default=None): + """Return the value for key if key is in the dictionary, else default. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def has_key(self, key): + """Return True if d has a key key, else False. + + :type key: T + :rtype: bool + """ + return False + + def items(self): + """Return a copy of the dictionary's list of (key, value) pairs. + + :rtype: list[(T, V)] + """ + return [] + + def iteritems(self): + """Return an iterator over the dictionary's (key, value) pairs. + + :rtype: collections.Iterable[(T, V)] + """ + return [] + + def iterkeys(self): + """Return an iterator over the dictionary's keys. + + :rtype: collections.Iterable[T] + """ + return [] + + def itervalues(self): + """Return an iterator over the dictionary's values. + + :rtype: collections.Iterable[V] + """ + return [] + + def keys(self): + """Return a copy of the dictionary's list of keys. + + :rtype: list[T] + """ + return [] + + def pop(self, key, default=None): + """If key is in the dictionary, remove it and return its value, else + return default. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def popitem(self): + """Remove and return an arbitrary (key, value) pair from the + dictionary. + + :rtype: (T, V) + """ + pass + + def setdefault(self, key, default=None): + """If key is in the dictionary, return its value. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def update(self, other=None, **kwargs): + """Update the dictionary with the key/value pairs from other, + overwriting existing keys. + + :type other: dict[T, V] | collections.Iterable[(T, V)] + :rtype: None + """ + pass + + def values(): + """Return a copy of the dictionary's list of values. + + :rtype: list[V] + """ + return [] + + +class file(object): + """File object.""" + + def __init__(self, name, mode='r', buffering=-1): + """Create a file object. + + :type name: string + :type mode: string + :type buffering: numbers.Integral + """ + self.name = name + self.mode = mode + + def fileno(self): + """Return the integer "file descriptor" that is used by the + underlying implementation to request I/O operations from the + operating system. + + :rtype: int + """ + return 0 + + def isatty(self): + """Return True if the file is connected to a tty(-like) device, + else False. + + :rtype: bool + """ + return False + + def next(self): + """Returns the next input line. + + :rtype: bytes | unicode + """ + return '' + + def read(self, size=-1): + """Read at most size bytes from the file (less if the read hits EOF + before obtaining size bytes). + + :type size: numbers.Integral + :rtype: bytes | unicode + """ + return '' + + def readline(self, size=-1): + """Read one entire line from the file. + + :type size: numbers.Integral + :rtype: bytes | unicode + """ + return '' + + def readlines(self, sizehint=-1): + """Read until EOF using readline() and return a list containing the + lines thus read. + + :type sizehint: numbers.Integral + :rtype: list[bytes | unicode] + """ + return [] + + def xreadlines(self): + """This method returns the same thing as iter(f). + + :rtype: collections.Iterable[bytes | unicode] + """ + return [] + + def seek(self, offset, whence=0): + """Set the file's current position, like stdio's fseek(). + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def tell(self): + """Return the file's current position, like stdio's ftell(). + + :rtype: int + """ + return 0 + + def truncate(self, size=-1): + """Truncate the file's size. + + :type size: numbers.Integral + :rtype: None + """ + pass + + def write(self, str): + """"Write a string to the file. + + :type str: bytes | unicode + :rtype: None + """ + pass + + def writelines(self, sequence): + """Write a sequence of strings to the file. + + :type sequence: collections.Iterable[bytes | unicode] + :rtype: None + """ + pass + + +class __generator(object): + """A mock class representing the generator function type.""" + def __init__(self, value): + """Create a generator object. + + :type value: T + :rtype: __generator[T] + """ + self.gi_code = None + self.gi_frame = None + self.gi_running = 0 + + def __iter__(self): + """Defined to support iteration over container.""" + pass + + def next(self): + """Return the next item from the container. + + :rtype: T + """ + pass + + def close(self): + """Raises new GeneratorExit exception inside the generator to + terminate the iteration. + + :rtype: None + """ + pass + + def send(self, value): + """Resumes the generator and "sends" a value that becomes the + result of the current yield-expression. + + :rtype: T + """ + pass + + def throw(self, type, value=None, traceback=None): + """Used to raise an exception inside the generator. + + :rtype: None + """ + pass + +class __function(object): + """A mock class representing function type.""" + + def __init__(self): + self.__name__ = '' + self.__doc__ = '' + self.__dict__ = '' + self.__module__ = '' + + self.func_defaults = {} + self.func_globals = {} + self.func_closure = None + self.func_code = None + self.func_name = '' + self.func_doc = '' + self.func_dict = '' + + if sys.version_info >= (2, 6): + self.__defaults__ = {} + self.__globals__ = {} + self.__closure__ = None + self.__code__ = None + + +class __method(object): + """A mock class representing method type (both bound and unbound).""" + + def __init__(self): + self.im_class = None + self.im_self = None + self.im_func = None + + if sys.version_info >= (2, 6): + self.__func__ = None + self.__self__ = None diff --git a/python/helpers/python-skeletons/asyncio/__init__.py b/python/helpers/python-skeletons/asyncio/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/helpers/python-skeletons/asyncio/events.py b/python/helpers/python-skeletons/asyncio/events.py new file mode 100644 index 000000000000..aaf86ff1bb23 --- /dev/null +++ b/python/helpers/python-skeletons/asyncio/events.py @@ -0,0 +1,12 @@ +"""Skeleton for 'asyncio' stdlib module.""" + + +import asyncio + + +def get_event_loop(): + """Get the event loop for the current context. + + :rtype: asyncio.AbstractEventLoop + """ + pass diff --git a/python/helpers/python-skeletons/behave.py b/python/helpers/python-skeletons/behave.py new file mode 100644 index 000000000000..3b1b58208f80 --- /dev/null +++ b/python/helpers/python-skeletons/behave.py @@ -0,0 +1,60 @@ +# coding=utf-8 +""" +Python Behave skeletons (https://pythonhosted.org/behave/) +""" + + +def given(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def when(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def then(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def step(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass +def Given(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def When(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def Then(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass + +def Step(pattern): + """Decorates a function, so that it will become a new step + definition. + :param pattern pattern to match, may be regular expression or something else depends on step matcher + """ + pass \ No newline at end of file diff --git a/python/helpers/python-skeletons/builtins.py b/python/helpers/python-skeletons/builtins.py new file mode 100644 index 000000000000..bff1b83c210a --- /dev/null +++ b/python/helpers/python-skeletons/builtins.py @@ -0,0 +1,2046 @@ +"""Skeletons for Python 3 built-in symbols.""" + + +def abs(number): + """Return the absolute value of the argument. + + :type number: T + :rtype: T | unknown + """ + return number + + +def all(iterable): + """Return True if bool(x) is True for all values x in the iterable. + + :type iterable: collections.Iterable + :rtype: bool + """ + return False + + +def any(iterable): + """Return True if bool(x) is True for any x in the iterable. + + :type iterable: collections.Iterable + :rtype: bool + """ + return False + + +def bin(number): + """Return the binary representation of an integer or long integer. + + :type number: numbers.Number + :rtype: str + """ + return '' + + +def callable(object): + """Return whether the object is callable (i.e., some kind of function). + Note that classes are callable, as are instances with a __call__() method. + + :rtype: bool + """ + return False + + +def chr(i): + """Return a string of one character with ordinal i; 0 <= i < 256. + + :type i: numbers.Integral + :rtype: str + """ + return '' + + +def dir(object=None): + """If called without an argument, return the names in the current scope. + Else, return an alphabetized list of names comprising (some of) the + attributes of the given object, and of attributes reachable from it. + + :rtype: list[str] + """ + return [] + + +def divmod(x, y): + """Return the tuple ((x-x%y)/y, x%y). + + :type x: numbers.Number + :type y: numbers.Number + :rtype: (int | long | float | unknown, int | long | float | unknown) + """ + return 0, 0 + + +def filter(function_or_none, sequence): + """Return those items of sequence for which function(item) is true. If + function is None, return the items that are true. If sequence is a tuple + or string, return the same type, else return a list. + + :type function_or_none: collections.Callable | None + :type sequence: T <= list | collections.Iterable | bytes | str + :rtype: T + """ + return sequence + + +def getattr(object, name, default=None): + """Get a named attribute from an object; getattr(x, 'y') is equivalent to + x.y. When a default argument is given, it is returned when the attribute + doesn't exist; without it, an exception is raised in that case. + + :type name: str + """ + pass + + +def globals(): + """Return the dictionary containing the current scope's global variables. + + :rtype: dict[str, unknown] + """ + return {} + + +def hasattr(object, name): + """Return whether the object has an attribute with the given name. + + :type name: str + :rtype: bool + """ + return False + + +def hash(object): + """Return a hash value for the object. + + :rtype: int + """ + return 0 + + +def hex(number): + """Return the hexadecimal representation of an integer or long integer. + + :type number: numbers.Integral + :rtype: str + """ + return '' + + +def id(object): + """Return the identity of an object. + + :rtype: int + """ + return 0 + + +def isinstance(object, class_or_type_or_tuple): + """Return whether an object is an instance of a class or of a subclass + thereof. + + :rtype: bool + """ + return False + + +def issubclass(C, B): + """Return whether class C is a subclass (i.e., a derived class) of class B. + + :rtype: bool + """ + return False + + +def iter(object, sentinel=None): + """Get an iterator from an object. In the first form, the argument must + supply its own iterator, or be a sequence. In the second form, the callable + is called until it returns the sentinel. + + :type object: collections.Iterable[T] | (() -> object) + :type sentinel: object | None + :rtype: collections.Iterator[T] + """ + return [] + + +def len(object): + """Return the number of items of a sequence or mapping. + + :type object: collections.Sized + :rtype: int + """ + return 0 + + +def locals(): + """Update and return a dictionary containing the current scope's local + variables. + + :rtype: dict[str, unknown] + """ + return {} + + +def map(function, sequence, *sequence_1): + """Return a list of the results of applying the function to the items of + the argument sequence(s). + + :type function: ((T) -> V) | None + :type sequence: collections.Iterable[T] + :rtype: list[V] | bytes | str + """ + pass + + +def next(iterator, default=None): + """Return the next item from the iterator. + + :type iterator: collections.Iterator[T] + :rtype: T + """ + pass + + +def oct(number): + """Return the octal representation of an integer or long integer. + + :type number: numbers.Integral + :rtype: str + """ + return '' + + +def open(name, mode='r', buffering=-1, encoding=None, errors=None, newline=None, + closefd=None, opener=None): + """Open a file, returns a file object. + + :type name: str + :type mode: str + :type buffering: numbers.Integral + :type encoding: str | None + :type errors: str | None + :rtype: file + """ + return file() + + +def ord(c): + """Return the integer ordinal of a one-character string. + + :type c: str + :rtype: int + """ + return 0 + + +def pow(x, y, z=None): + """With two arguments, equivalent to x**y. With three arguments, + equivalent to (x**y) % z, but may be more efficient (e.g. for longs). + + :type x: numbers.Number + :type y: numbers.Number + :type z: numbers.Number | None + :rtype: int | long | float | complex + """ + return 0 + + +def print(*objects, sep=' ', end='\n', file=None, flush=False): + """Print objects to the stream file, separated by sep and followed by end. + + :type sep: str + :type end: str + :type flush: bool + :rtype: None + """ + pass + + +class range(object): + """range object.""" + + def __init__(self, start, stop=None, step=None): + """Create a range object. + + :type start: numbers.Integral + :type stop: numbers.Integral | None + :type step: numbers.Integral | None + :rtype: range[int] + """ + pass + + +def repr(object): + """ + Return the canonical string representation of the object. + + :rtype: str + """ + return '' + + +def round(number, ndigits=None): + """Round a number to a given precision in decimal digits (default 0 digits). + + :type number: object + :type ndigits: numbers.Integral | None + :rtype: float + """ + return 0.0 + + +class slice(object): + def __init__(self, start, stop=None, step=None): + """Create a slice object. This is used for extended slicing (e.g. + a[0:10:2]). + + :type start: numbers.Integral + :type stop: numbers.Integral | None + :type step: numbers.Integral | None + """ + return + + +def vars(object=None): + """Without arguments, equivalent to locals(). With an argument, equivalent + to object.__dict__. + + :rtype: dict[str, unknown] + """ + return {} + + +class object: + """ The most base type.""" + + @staticmethod + def __new__(cls, *more): + """Create a new object. + + :type cls: T + :rtype: T + """ + pass + + +class type(object): + """Type of object.""" + + def __instancecheck__(cls, instance): + """Return true if instance should be considered a (direct or indirect) + instance of class. + """ + return False + + def __subclasscheck__(cls, subclass): + """Return true if subclass should be considered a (direct or indirect) + subclass of class. + """ + return False + + +class enumerate(object): + """enumerate object.""" + + def __init__(self, iterable, start=0): + """Create an enumerate object. + + :type iterable: collections.Iterable[T] + :type start: int | long + :rtype: enumerate[int, T] + """ + pass + + def next(self): + """Return the next value, or raise StopIteration. + + :rtype: (int, T) + """ + pass + + def __iter__(self): + """x.__iter__() <==> iter(x). + + :rtype: enumerate[int, T] + """ + return self + + +class int(object): + """Integer numeric type.""" + + def __init__(self, x=None, base=10): + """Convert a number or string x to an integer, or return 0 if no + arguments are given. + + :type x: object + :type base: numbers.Integral + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __pow__(self, y, modulo=None): + """x to the power y. + + :type y: numbers.Number + :type modulo: numbers.Integral | None + :rtype: int + """ + return 0 + + def __lshift__(self, n): + """x shifted left by n bits. + + :type n: numbers.Integral + :rtype: int + """ + return 0 + + def __rshift__(self, n): + """x shifted right by n bits. + + :type n: numbers.Integral + :rtype: int + """ + return 0 + + def __and__(self, y): + """Bitwise and of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __or__(self, y): + """Bitwise or of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __xor__(self, y): + """Bitwise exclusive or of x and y. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rlshift__(self, y): + """y shifted left by x bits. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rrshift__(self, y): + """y shifted right by n bits. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rand__(self, y): + """Bitwise and of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __ror__(self, y): + """Bitwise or of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rxor__(self, y): + """Bitwise exclusive or of y and x. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: int + """ + return 0 + + def __pos__(self): + """x unchanged. + + :rtype: int + """ + return 0 + + def __neg__(self): + """x negated. + + :rtype: int + """ + return 0 + + def __invert__(self): + """The bits of x inverted. + + :rtype: int + """ + return 0 + + +class float(object): + """Floating point numeric type.""" + + def __init__(self, x=None): + """Convert a string or a number to floating point. + + :type x: object + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __pow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: float + """ + return 0.0 + + def __pos__(self): + """x unchanged. + + :rtype: float + """ + return 0.0 + + def __neg__(self): + """x negated. + + :rtype: float + """ + return 0.0 + + +class complex(object): + """Complex numeric type.""" + + def __init__(self, real=None, imag=None): + """Create a complex number with the value real + imag*j or convert a + string or number to a complex number. + + :type real: object + :type imag: object + """ + pass + + def __add__(self, y): + """Sum of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __sub__(self, y): + """Difference of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __mul__(self, y): + """Product of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __floordiv__(self, y): + """Floored quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __mod__(self, y): + """Remainder of x / y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __pow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __div__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __truediv__(self, y): + """Quotient of x and y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __radd__(self, y): + """Sum of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rsub__(self, y): + """Difference of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rmul__(self, y): + """Product of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rfloordiv__(self, y): + """Floored quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rmod__(self, y): + """Remainder of y / x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rpow__(self, y): + """x to the power y. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rdiv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __rtruediv__(self, y): + """Quotient of y and x. + + :type y: numbers.Number + :rtype: complex + """ + return 0j + + def __pos__(self): + """x unchanged. + + :rtype: complex + """ + return 0j + + def __neg__(self): + """x negated. + + :rtype: complex + """ + return 0j + + +class bytes(object): + """Bytes object.""" + + def __init__(self, source='', encoding='utf8', errors='strict'): + """Construct an immutable array of bytes. + + :type source: object + :type encoding: str + :type errors: str + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: bytes + :rtype: bytes + """ + return b'' + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: bytes + """ + return b'' + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: bytes + """ + return b'' + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: int + """ + return 0 + + def __iter__(self): + """Iterator over bytes. + + :rtype: collections.Iterator[int] + """ + return [] + + def capitalize(self): + """Return a copy of the string with its first character capitalized + and the rest lowercased. + + :rtype: bytes + """ + return b'' + + def center(self, width, fillchar=' '): + """Return centered in a string of length width. + + :type width: numbers.Integral + :type fillchar: bytes + :rtype: bytes + """ + return b'' + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of substring + sub in the range [start, end]. + + :type sub: bytes + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: int + """ + return 0 + + def decode(self, encoding='utf-8', errors='strict'): + """Return a string decoded from the given bytes. + + :type encoding: str + :type errors: str + :rtype: str + """ + return '' + + def endswith(self, suffix, start=None, end=None): + """Return True if the string ends with the specified suffix, + otherwise return False. + + :type suffix: bytes | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def find(self, sub, start=None, end=None): + """Return the lowest index in the string where substring sub is + found, such that sub is contained in the slice s[start:end]. + + :type sub: bytes + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def index(self, sub, start=None, end=None): + """Like find(), but raise ValueError when the substring is not + found. + + :type sub: bytes + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def isalnum(self): + """Return true if all characters in the string are alphanumeric and + there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isalpha(self): + """Return true if all characters in the string are alphabetic and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isdigit(self): + """Return true if all characters in the string are digits and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def islower(self): + """Return true if all cased characters in the string are lowercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def isspace(self): + """Return true if there are only whitespace characters in the + string and there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def istitle(self): + """Return true if the string is a titlecased string and there is at + least one character, for example uppercase characters may only + follow uncased characters and lowercase characters only cased ones. + + :rtype: bool + """ + return False + + def isupper(self): + """Return true if all cased characters in the string are uppercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def join(self, iterable): + """Return a string which is the concatenation of the strings in the + iterable. + + :type iterable: collections.Iterable[bytes] + :rtype: bytes + """ + return b'' + + def ljust(self, width, fillchar=' '): + """Return the string left justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: bytes + :rtype: bytes + """ + return b'' + + def lower(self): + """Return a copy of the string with all the cased characters + converted to lowercase. + + :rtype: bytes + """ + return b'' + + def lstrip(self, chars=None): + """Return a copy of the string with leading characters removed. + + :type chars: bytes | None + :rtype: bytes + """ + return b'' + + def partition(self, sep): + """Split the string at the first occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: bytes + :rtype: (bytes, bytes, bytes) + """ + return b'', b'', b'' + + def replace(self, old, new, count=-1): + """Return a copy of the string with all occurrences of substring + old replaced by new. + + :type old: bytes + :type new: bytes + :type count: numbers.Integral + :rtype: bytes + """ + return b'' + + def rfind(self, sub, start=None, end=None): + """Return the highest index in the string where substring sub is + found, such that sub is contained within s[start:end]. + + :type sub: bytes + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rindex(self, sub, start=None, end=None): + """Like rfind(), but raise ValueError when the substring is not + found. + + :type sub: bytes + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rjust(self, width, fillchar=' '): + """Return the string right justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: bytes + :rtype: bytes + """ + return b'' + + def rpartition(self, sep): + """Split the string at the last occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: bytes + :rtype: (bytes, bytes, bytes) + """ + return b'', b'', b'' + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: bytes | None + :type maxsplit: numbers.Integral + :rtype: list[bytes] + """ + return [] + + def rstrip(self, chars=None): + """Return a copy of the string with trailing characters removed. + + :type chars: bytes | None + :rtype: bytes + """ + return b'' + + def split(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: bytes | None + :type maxsplit: numbers.Integral + :rtype: list[bytes] + """ + return [] + + def splitlines(self, keepends=False): + """Return a list of the lines in the string, breaking at line + boundaries. + + :type keepends: bool + :rtype: list[bytes] + """ + return [] + + def startswith(self, prefix, start=None, end=None): + """Return True if string starts with the prefix, otherwise return + False. + + :type prefix: bytes | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def strip(self, chars=None): + """Return a copy of the string with the leading and trailing + characters removed. + + :type chars: bytes | None + :rtype: bytes + """ + return b'' + + def swapcase(self): + """Return a copy of the string with uppercase characters converted + to lowercase and vice versa. + + :rtype: bytes + """ + return b'' + + def title(self): + """Return a titlecased version of the string where words start with + an uppercase character and the remaining characters are lowercase. + + :rtype: bytes + """ + return b'' + + def upper(self): + """Return a copy of the string with all the cased characters + converted to uppercase. + + :rtype: bytes + """ + return b'' + + def zfill(self, width): + """Return the numeric string left filled with zeros in a string of + length width. + + :type width: numbers.Integral + :rtype: bytes + """ + return b'' + + +class str(object): + """String object.""" + + def __init__(self, object='', encoding='utf-8', errors='strict'): + """Construct an immutable string. + + :type object: object + :type encoding: str + :type errors: str + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: str + :rtype: str + """ + return '' + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: str + """ + return '' + + def __mod__(self, y): + """x % y. + + :rtype: str + """ + return '' + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: str + """ + return '' + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: str + """ + return '' + + def __iter__(self): + """Iterator over bytes. + + :rtype: collections.Iterator[str] + """ + return [] + + def capitalize(self): + """Return a copy of the string with its first character capitalized + and the rest lowercased. + + :rtype: str + """ + return '' + + def center(self, width, fillchar=' '): + """Return centered in a string of length width. + + :type width: numbers.Integral + :type fillchar: str + :rtype: str + """ + return '' + + def count(self, sub, start=None, end=None): + """Return the number of non-overlapping occurrences of substring + sub in the range [start, end]. + + :type sub: str + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: int + """ + return 0 + + def encode(self, encoding='utf-8', errors='strict'): + """Return an encoded version of the string as a bytes object. + + :type encoding: str + :type errors: str + :rtype: bytes + """ + return b'' + + def endswith(self, suffix, start=None, end=None): + """Return True if the string ends with the specified suffix, + otherwise return False. + + :type suffix: str | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def find(self, sub, start=None, end=None): + """Return the lowest index in the string where substring sub is + found, such that sub is contained in the slice s[start:end]. + + :type sub: str + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def index(self, sub, start=None, end=None): + """Like find(), but raise ValueError when the substring is not + found. + + :type sub: str + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def isalnum(self): + """Return true if all characters in the string are alphanumeric and + there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isalpha(self): + """Return true if all characters in the string are alphabetic and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def isdigit(self): + """Return true if all characters in the string are digits and there + is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def islower(self): + """Return true if all cased characters in the string are lowercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def isspace(self): + """Return true if there are only whitespace characters in the + string and there is at least one character, false otherwise. + + :rtype: bool + """ + return False + + def istitle(self): + """Return true if the string is a titlecased string and there is at + least one character, for example uppercase characters may only + follow uncased characters and lowercase characters only cased ones. + + :rtype: bool + """ + return False + + def isupper(self): + """Return true if all cased characters in the string are uppercase + and there is at least one cased character, false otherwise. + + :rtype: bool + """ + return False + + def join(self, iterable): + """Return a string which is the concatenation of the strings in the + iterable. + + :type iterable: collections.Iterable[str] + :rtype: str + """ + return '' + + def ljust(self, width, fillchar=' '): + """Return the string left justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: str + :rtype: str + """ + return '' + + def lower(self): + """Return a copy of the string with all the cased characters + converted to lowercase. + + :rtype: str + """ + return '' + + def lstrip(self, chars=None): + """Return a copy of the string with leading characters removed. + + :type chars: str | None + :rtype: str + """ + return '' + + def partition(self, sep): + """Split the string at the first occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: str + :rtype: (str, str, str) + """ + return '', '', '' + + def replace(self, old, new, count=-1): + """Return a copy of the string with all occurrences of substring + old replaced by new. + + :type old: str + :type new: str + :type count: numbers.Integral + :rtype: str + """ + return '' + + def rfind(self, sub, start=None, end=None): + """Return the highest index in the string where substring sub is + found, such that sub is contained within s[start:end]. + + :type sub: str + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rindex(self, sub, start=None, end=None): + """Like rfind(), but raise ValueError when the substring is not + found. + + :type sub: str + :type start: numbers.Integral | None + :type end: numbers.Integral | none + :rtype: int + """ + return 0 + + def rjust(self, width, fillchar=' '): + """Return the string right justified in a string of length width. + Padding is done using the specified fillchar (default is a space). + + :type width: numbers.Integral + :type fillchar: str + :rtype: str + """ + return '' + + def rpartition(self, sep): + """Split the string at the last occurrence of sep, and return a + 3-tuple containing the part before the separator, the separator + itself, and the part after the separator. + + :type sep: str + :rtype: (str, str, str) + """ + return '', '', '' + + def rsplit(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: str | None + :type maxsplit: numbers.Integral + :rtype: list[str] + """ + return [] + + def rstrip(self, chars=None): + """Return a copy of the string with trailing characters removed. + + :type chars: str | None + :rtype: str + """ + return '' + + def split(self, sep=None, maxsplit=-1): + """Return a list of the words in the string, using sep as the + delimiter string. + + :type sep: str | None + :type maxsplit: numbers.Integral + :rtype: list[str] + """ + return [] + + def splitlines(self, keepends=False): + """Return a list of the lines in the string, breaking at line + boundaries. + + :type keepends: bool + :rtype: list[str] + """ + return [] + + def startswith(self, prefix, start=None, end=None): + """Return True if string starts with the prefix, otherwise return + False. + + :type prefix: str | tuple + :type start: numbers.Integral | None + :type end: numbers.Integral | None + :rtype: bool + """ + return False + + def strip(self, chars=None): + """Return a copy of the string with the leading and trailing + characters removed. + + :type chars: str | None + :rtype: str + """ + return '' + + def swapcase(self): + """Return a copy of the string with uppercase characters converted + to lowercase and vice versa. + + :rtype: str + """ + return '' + + def title(self): + """Return a titlecased version of the string where words start with + an uppercase character and the remaining characters are lowercase. + + :rtype: str + """ + return '' + + def upper(self): + """Return a copy of the string with all the cased characters + converted to uppercase. + + :rtype: str + """ + return '' + + def zfill(self, width): + """Return the numeric string left filled with zeros in a string of + length width. + + :type width: numbers.Integral + :rtype: str + """ + return '' + + +class list(object): + """List object.""" + + def __init__(self, iterable=None): + """Create a list object. + + :type iterable: collections.Iterable[T] + :rtype: list[T] + """ + pass + + def __add__(self, y): + """The concatenation of x and y. + + :type y: list[T] + :rtype: list[T] + """ + return [] + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: list[T] + """ + return [] + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: list[T] + """ + return [] + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: T + """ + pass + + def __setitem__(self, i, y): + """Item i is replaced by y. + + :type i: numbers.Integral + :type y: T + :rtype: None + """ + pass + + def __delitem__(self, i): + """Remove i-th item. + + :type i: numbers.Integral + :rtype: None + """ + + def append(self, x): + """Appends x to the end of the sequence. + + :type x: T + :rtype: None + """ + pass + + def extend(self, t): + """Extends the sequence with the contents of t. + + :type t: collections.Iterable[T] + :rtype: None + """ + pass + + def count(self, x): + """Total number of occurrences of x in the sequence. + + :type x: T + :rtype: int + """ + return 0 + + def index(self, x, i=None, j=None): + """Index of the first occurrence of x in the sequence. + + :type x: T + :type i: numbers.Integral | None + :type j: numbers.Integral | none + :rtype: int + """ + return 0 + + def insert(self, i, x): + """Inserts x into the sequence at the index given by i. + + :type i: numbers.Number + :type x: T + :rtype: None + """ + pass + + def pop(self, i=-1): + """Retrieves the item at i and also removes it from the sequence. + + :type i: numbers.Number + :rtype: T + """ + pass + + def remove(self, x): + """Remove the first item x from the sequence. + + :type x: T + :rtype: None + """ + pass + + def sort(self, cmp=None, key=None, reverse=False): + """Sort the items of the sequence in place. + + :type cmp: ((T, T) -> int) | None + :type key: ((T) -> object) | None + :type reverse: bool + :rtype: None + """ + pass + + +class tuple(object): + """Tuple object.""" + + def __add__(self, y): + """The concatenation of x and y. + + :type y: tuple + :rtype: tuple + """ + pass + + def __mul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: tuple + """ + pass + + def __rmul__(self, n): + """n shallow copies of x concatenated. + + :type n: numbers.Integral + :rtype: tuple + """ + pass + + def __getitem__(self, y): + """y-th item of x, origin 0. + + :type y: numbers.Integral + :rtype: object | unknown + """ + pass + + def count(self, x): + """Total number of occurrences of x in the sequence. + + :type x: object + :rtype: int + """ + return 0 + + def index(self, x, i=None, j=None): + """Index of the first occurrence of x in the sequence. + + :type x: object + :type i: numbers.Integral | None + :type j: numbers.Integral | none + :rtype: int + """ + return 0 + + +class dict(object): + """Dictionary object.""" + + def __init__(self, iterable=None, **kwargs): + """Create a dictionary object. + + :type iterable: collections.Iterable[T, V] + :rtype: dict[T, V] + """ + pass + + def __len__(self): + """Return the number of items in the dictionary d. + + :rtype: int + """ + return 0 + + def __getitem__(self, key): + """Return the item of d with key key. + + :type key: T + :rtype: V + """ + pass + + def __setitem__(self, key, value): + """Set d[key] to value. + + :type key: T + :type value: V + :rtype: None + """ + pass + + def __delitem__(self, key): + """Remove d[key] from d. + + :type key: T + :rtype: None + """ + pass + + def copy(self): + """Return a shallow copy of the dictionary. + + :rtype: dict[T, V] + """ + return self + + @staticmethod + def fromkeys(seq, value=None): + """Create a new dictionary with keys from seq and values set to value. + + :type seq: collections.Iterable[T] + :type value: V + :rtype: dict[T, V] + """ + return {} + + def get(self, key, default=None): + """Return the value for key if key is in the dictionary, else default. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def items(self): + """Return a copy of the dictionary's list of (key, value) pairs. + + :rtype: collections.Iterable[(T, V)] + """ + return [] + + def keys(self): + """Return a copy of the dictionary's list of keys. + + :rtype: collections.Iterable[T] + """ + return [] + + def pop(self, key, default=None): + """If key is in the dictionary, remove it and return its value, else + return default. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def popitem(self): + """Remove and return an arbitrary (key, value) pair from the + dictionary. + + :rtype: (T, V) + """ + pass + + def setdefault(self, key, default=None): + """If key is in the dictionary, return its value. + + :type key: T + :type default: V | None + :rtype: V + """ + pass + + def update(self, other=None, **kwargs): + """Update the dictionary with the key/value pairs from other, + overwriting existing keys. + + :type other: dict[T, V] | collections.Iterable[(T, V)] + :rtype: None + """ + pass + + def values(): + """Return a copy of the dictionary's list of values. + + :rtype: collections.Iterable[V] + """ + return [] + + +class __generator(object): + """A mock class representing the generator function type.""" + def __init__(self, value): + """Create a generator object. + + :type value: T + :rtype: __generator[T] + """ + self.gi_code = None + self.gi_frame = None + self.gi_running = 0 + + def __iter__(self): + """Defined to support iteration over container.""" + pass + + def __next__(self): + """Return the next item from the container. + + :rtype: T + """ + pass + + def close(self): + """Raises new GeneratorExit exception inside the generator to + terminate the iteration. + + :rtype: None + """ + pass + + def send(self, value): + """Resumes the generator and "sends" a value that becomes the + result of the current yield-expression. + + :rtype: T + """ + pass + + def throw(self, type, value=None, traceback=None): + """Used to raise an exception inside the generator. + + :rtype: None + """ + pass + +class __function(object): + """A mock class representing function type.""" + + def __init__(self): + self.__name__ = '' + self.__doc__ = '' + self.__dict__ = '' + self.__module__ = '' + + self.__annotations__ = {} + self.__defaults__ = {} + self.__globals__ = {} + self.__kwdefaults__ = {} + self.__closure__ = None + self.__code__ = None + + if sys.version_info >= (3, 3): + self.__qualname__ = '' + +class __method(object): + """A mock class representing bound method type.""" + + def __init__(self): + self.__func__ = None + self.__self__ = None diff --git a/python/helpers/python-skeletons/cStringIO.py b/python/helpers/python-skeletons/cStringIO.py new file mode 100644 index 000000000000..8d7b954fcf99 --- /dev/null +++ b/python/helpers/python-skeletons/cStringIO.py @@ -0,0 +1,131 @@ +"""Skeleton for 'cStringIO' stdlib module.""" + + +import cStringIO + + +def StringIO(s=None): + """Return a StringIO-like stream for reading or writing. + + :type s: T <= bytes | unicode + :rtype: cStringIO.OutputType[T] + """ + return cStringIO.OutputType(s) + + +class OutputType(object): + def __init__(self, s): + """Create an OutputType object. + + :rtype: cStringIO.OutputType[T <= bytes | unicode] + """ + pass + + def getvalue(self): + """Retrieve the entire contents of the "file" at any time before the + StringIO object's close() method is called. + + :rtype: T + """ + pass + + def close(self): + """Free the memory buffer. + + :rtype: None + """ + pass + + def flush(self): + """Flush the internal buffer. + + :rtype: None + """ + pass + + def isatty(self): + """Return True if the file is connected to a tty(-like) device, + else False. + + :rtype: bool + """ + return False + + def __iter__(self): + """Return an iterator over lines. + + :rtype: cStringIO.OutputType[T] + """ + return self + + def next(self): + """Returns the next input line. + + :rtype: T + """ + pass + + def read(self, size=-1): + """Read at most size bytes or characters from the buffer. + + :type size: numbers.Integral + :rtype: T + """ + pass + + def readline(self, size=-1): + """Read one entire line from the buffer. + + :type size: numbers.Integral + :rtype: T + """ + pass + + def readlines(self, sizehint=-1): + """Read until EOF using readline() and return a list containing the + lines thus read. + + :type sizehint: numbers.Integral + :rtype: list[T] + """ + return [] + + def seek(self, offset, whence=0): + """Set the buffer's current position, like stdio's fseek(). + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def tell(self): + """Return the buffer's current position, like stdio's ftell(). + + :rtype: int + """ + return 0 + + def truncate(self, size=-1): + """Truncate the buffer's size. + + :type size: numbers.Integral + :rtype: None + """ + pass + + def write(self, str): + """"Write bytes or a string to the buffer. + + :type str: T + :rtype: None + """ + pass + + def writelines(self, sequence): + """Write a sequence of bytes or strings to the buffer. + + :type sequence: collections.Iterable[T] + :rtype: None + """ + pass diff --git a/python/helpers/python-skeletons/collections.py b/python/helpers/python-skeletons/collections.py new file mode 100644 index 000000000000..ec23ec8d8169 --- /dev/null +++ b/python/helpers/python-skeletons/collections.py @@ -0,0 +1,26 @@ +"""Skeleton for 'collections' stdlib module.""" + + +import sys +import collections + + +class Iterator(collections.Iterable): + def __init__(self): + """ + :rtype: collections.Iterator[T] + """ + pass + + if sys.version_info >= (3, 0): + def __next__(self): + """ + :rtype: T + """ + pass + + def next(self): + """ + :rtype: T + """ + pass diff --git a/python/helpers/python-skeletons/datetime.py b/python/helpers/python-skeletons/datetime.py new file mode 100644 index 000000000000..355052a24cc5 --- /dev/null +++ b/python/helpers/python-skeletons/datetime.py @@ -0,0 +1,625 @@ +"""Skeleton for 'datetime' stdlib module.""" + + +import sys +import datetime as _datetime +from time import struct_time + + +class timedelta(object): + """A timedelta object represents a duration, the difference between two + dates or times.""" + + def __init__(self, days=0, seconds=0, microseconds=0, milliseconds=0, + minutes=0, hours=0, weeks=0): + """Create a timedelta object. + + :type days: numbers.Real + :type seconds: numbers.Real + :type microseconds: numbers.Real + :type milliseconds: numbers.Real + :type minutes: numbers.Real + :type hours: numbers.Real + :type weeks: numbers.Real + """ + self.days = 0 + self.seconds = 0 + self.microseconds = 0 + + def __add__(self, other): + """Add timedelta, date or datetime. + + :type other: T <= _datetime.timedelta | _datetime.date | _datetime.datetime + :rtype: T + """ + pass + + def __radd__(self, other): + """Add timedelta, date or datetime. + + :type other: T <= _datetime.timedelta | _datetime.date | _datetime.datetime + :rtype: T + """ + pass + + def __sub__(self, other): + """Subtract timedelta, date or datetime. + + :type other: _datetime.timedelta | _datetime.date | _datetime.datetime + :rtype: _datetime.timedelta | _datetime.date | _datetime.datetime + """ + pass + + def __rsub__(self, other): + """Subtract timedelta, date or datetime. + + :type other: _datetime.timedelta | _datetime.date | _datetime.datetime + :rtype: _datetime.timedelta | _datetime.date | _datetime.datetime + """ + pass + + def __mul__(self, other): + """Multiply by an integer. + + :type other: numbers.Integral + :rtype: _datetime.timedelta + """ + return _datetime.timedelta() + + def __rmul__(self, other): + """Multiply by an integer. + + :type other: numbers.Integral + :rtype: _datetime.timedelta + """ + return _datetime.timedelta() + + def __floordiv__(self, other): + """Divide by an integer or a timedelta. + + :type other: numbers.Integral | _datetime.timedelta + :rtype: _datetime.timedelta | int + """ + pass + + def __div__(self, other): + """Divide by an integer. + + :type other: numbers.Integral + :rtype: _datetime.timedelta + """ + pass + + def __truediv__(self, other): + """Divide by a float or a timedelta. + + :type other: numbers.Real | _datetime.timedelta + :rtype: _datetime.timedelta | float + """ + pass + + if sys.version_info >= (2, 7): + def total_seconds(self): + """Return the total number of seconds contained in the duration. + + :rtype: int + """ + return 0 + + min = _datetime.timedelta() + max = _datetime.timedelta() + resoultion = _datetime.timedelta() + + +class date(object): + """An idealized naive date, assuming the current Gregorian calendar always + was, and always will be, in effect.""" + + def __init__(self, year, month, day): + """Create a date object. + + :type year: numbers.Integral + :type month: numbers.Integral + :type day: numbers.Integral + """ + self.year = year + self.month = month + self.day = day + + @classmethod + def today(cls): + """Return the current local date. + + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + @classmethod + def fromtimestamp(cls, timestamp): + """Return the local date corresponding to the POSIX timestamp, such as + is returned by time.time(). + + :type timestamp: numbers.Real + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + @classmethod + def fromordinal(cls, ordinal): + """Return the date corresponding to the proleptic Gregorian ordinal, + where January 1 of year 1 has ordinal 1. + + :type ordinal: numbers.Integral + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + def __add__(self, other): + """Add timedelta. + + :type other: _datetime.timedelta + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + def __radd__(self, other): + """Add timedelta. + + :type other: _datetime.timedelta + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + def __sub__(self, other): + """Subtract date or timedelta. + + :type other: _datetime.date | _datetime.timedelta + :rtype: _datetime.timedelta | _datetime.date + """ + pass + + def __rsub__(self, other): + """Subtract date. + + :type other: _datetime.date + :rtype: _datetime.timedelta + """ + return _datetime.timedelta() + + def replace(self, year=None, month=None, day=None): + """Return a date with the same value, except for those parameters given + new values by whichever keyword arguments are specified. + + :type year: numbers.Integral + :type month: numbers.Integral + :type day: numbers.Integral + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + def timetuple(self): + """Return a time.struct_time such as returned by time.localtime(). + + :rtype: struct_time + """ + return struct_time() + + def toordinal(self): + """Return the proleptic Gregorian ordinal of the date, where January 1 + of year 1 has ordinal 1. + + :rtype: int + """ + return 0 + + def weekday(self): + """Return the day of the week as an integer, where Monday is 0 and + Sunday is 6. + + :rtype: int + """ + return 0 + + def isoweekday(self): + """Return the day of the week as an integer, where Monday is 1 and + Sunday is 7. + + :rtype: int + """ + return 0 + + def isocalendar(self): + """Return a 3-tuple, (ISO year, ISO week number, ISO weekday). + + :rtype: (int, int, int) + """ + return (0, 0, 0) + + def isoformat(self): + """Return a string representing the date in ISO 8601 format, + 'YYYY-MM-DD'. + + :rtype: string + """ + return str() + + def ctime(self): + """Return a string representing the date. + + :rtype: string + """ + return str() + + def strftime(self, format): + """Return a string representing the date, controlled by an explicit + format string. + + :type format: string + :rtype: string + """ + return str() + + min = _datetime.date(0, 0, 0) + max = _datetime.date(0, 0, 0) + resoultion = _datetime.timedelta() + + +class datetime(object): + """A datetime object is a single object containing all the information from + a date object and a time object.""" + + def __init__(self, year, month, day, hour=0, minute=0, second=0, + microsecond=0, tzinfo=None): + """Create a datetime object. + + :type year: numbers.Integral + :type month: numbers.Integral + :type day: numbers.Integral + :type hour: numbers.Integral + :type minute: numbers.Integral + :type second: numbers.Integral + :type microsecond: numbers.Integral + :type tzinfo: _datetime.tzinfo | None + """ + self.year = year + self.month = month + self.day = day + self.hour = hour + self.minute = minute + self.second = second + self.microsecond = microsecond + self.tzinfo = tzinfo + + @classmethod + def today(cls): + """Return the current local datetime, with tzinfo None. + + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def now(cls, tz=None): + """Return the current local date and time. + + :type tz: _datetime.tzinfo | None + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def utcnow(cls): + """Return the current UTC date and time, with tzinfo None. + + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def fromtimestamp(cls, timestamp, tz=None): + """Return the local date and time corresponding to the POSIX timestamp, + such as is returned by time.time(). + + :type timestamp: numbers.Real + :type tz: _datetime.tzinfo | None + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def utcfromtimestamp(cls, timestamp): + """Return the UTC datetime corresponding to the POSIX timestamp, with + tzinfo None. + + :type timestamp: numbers.Real + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def fromordinal(cls, ordinal): + """Return the datetime corresponding to the proleptic Gregorian + ordinal. + + :type ordinal: numbers.Integral + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def combine(cls, date, time): + """Return a new datetime object whose date components are equal to the + given date object's, and whose time components and tzinfo attributes + are equal to the given time object's. + + :type date: _datetime.date + :type time: _datetime.time + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + @classmethod + def strptime(cls, date_string, format): + """Return a datetime corresponding to date_string, parsed according to + format. + + :type date_string: string + :type format: string + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + def __add__(self, other): + """Add timedelta. + + :type other: _datetime.timedelta + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + def __radd__(self, other): + """Add timedelta. + + :type other: _datetime.timedelta + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + def __sub__(self, other): + """Subtract timedelta or datetime. + + :type other: _datetime.timedelta | _datetime.datetime + :rtype: _datetime.datetime | _datetime.timedelta + """ + pass + + def __rsub__(self, other): + """Subtract datetime. + + :type other: _datetime.datetime + :rtype: _datetime.timedelta + """ + return _datetime.timedelta() + + def date(self): + """Return date object with same year, month and day. + + :rtype: _datetime.date + """ + return _datetime.date(0, 0, 0) + + def time(self): + """Return time object with same hour, minute, second and microsecond. + + :rtype: _datetime.time + """ + return _datetime.time() + + def timetz(self): + """Return time object with same hour, minute, second, microsecond, and + tzinfo attributes. + + :rtype: _datetime.time + """ + return _datetime.time() + + def replace(self, year=None, month=None, day=None, hour=None, minute=None, + second=None, microsecond=None, tzinfo=None): + """Return a datetime with the same attributes, except for those + attributes given new values by whichever keyword arguments are + specified. + + :type year: numbers.Integral + :type month: numbers.Integral + :type day: numbers.Integral + :type hour: numbers.Integral + :type minute: numbers.Integral + :type second: numbers.Integral + :type microsecond: numbers.Integral + :type tzinfo: _datetime.tzinfo | None + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + def astimezone(self, tz): + """Return a datetime object with new tzinfo attribute tz, adjusting the + date and time data so the result is the same UTC time as self, but in + tz's local time. + + :type tz: _datetime.tzinfo + :rtype: _datetime.datetime + """ + return _datetime.datetime(0, 0, 0) + + def utcoffset(self): + """If tzinfo is None, returns None, else returns + self.tzinfo.utcoffset(self). + + :rtype: _datetime.timedelta | None + """ + return _datetime.timedelta() + + def dst(self): + """If tzinfo is None, returns None, else returns self.tzinfo.dst(self). + + :rtype: _datetime.timedelta | None + """ + return _datetime.timedelta() + + def tzname(self): + """If tzinfo is None, returns None, else returns + self.tzinfo.tzname(self). + + :rtype: string | None + """ + return str() + + def timetuple(self): + """Return a time.struct_time such as returned by time.localtime(). + + :rtype: struct_time + """ + return struct_time() + + def utctimetuple(self): + """If datetime instance d is naive, this is the same as d.timetuple() + except that tm_isdst is forced to 0 regardless of what d.dst() returns. + + :rtype: struct_time + """ + return struct_time() + + def toordinal(self): + """Return the proleptic Gregorian ordinal of the date. + + :rtype: int + """ + return 0 + + def weekday(self): + """Return the day of the week as an integer, where Monday is 0 and + Sunday is 6. + + :rtype: int + """ + return 0 + + def isoweekday(self): + """Return the day of the week as an integer, where Monday is 1 and + Sunday is 7. + + :rtype: int + """ + return 0 + + def isocalendar(self): + """Return a 3-tuple, (ISO year, ISO week number, ISO weekday). + + :rtype: (int, int, int) + """ + return (0, 0, 0) + + def isoformat(self, sep='T'): + """Return a string representing the date and time in ISO 8601 format. + + :type sep: string + :rtype: string + """ + return str() + + def ctime(self): + """Return a string representing the date and time. + + :rtype: string + """ + return str() + + def strftime(self, format): + """Return a string representing the date and time, controlled by an + explicit format string. + + :type format: string + :rtype: string + """ + return str() + + min = _datetime.datetime(0, 0, 0) + max = _datetime.datetime(0, 0, 0) + resoultion = _datetime.timedelta() + + +class time(object): + """A time object represents a (local) time of day, independent of any + particular day, and subject to adjustment via a tzinfo object.""" + + def __init__(self, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): + """Create a time object. + + :type hour: numbers.Integral + :type minute: numbers.Integral + :type second: numbers.Integral + :type microsecond: numbers.Integral + :type tzinfo: _datetime.tzinfo | None + """ + self.hour = hour + self.minute = minute + self.second = second + self.microsecond = microsecond + sefl.tzinfo = tzinfo + + def replace(self, hour=None, minute=None, second=None, microsecond=None, + tzinfo=None): + """Return a time with the same value, except for those attributes given + new values by whichever keyword arguments are specified. + + :type hour: numbers.Integral + :type minute: numbers.Integral + :type second: numbers.Integral + :type microsecond: numbers.Integral + :type tzinfo: _datetime.tzinfo | None + :rtype: _datetime.time + """ + return _datetime.time() + + def isoformat(self): + """Return a string representing the time in ISO 8601 format. + + :rtype: string + """ + return str() + + def strftime(self, format): + """Return a string representing the time, controlled by an explicit + format string. + + :type format: string + :rtype: string + """ + return str() + + def utcoffset(self): + """If tzinfo is None, returns None, else returns + self.tzinfo.utcoffset(self). + + :rtype: _datetime.timedelta | None + """ + return _datetime.timedelta() + + def dst(self): + """If tzinfo is None, returns None, else returns self.tzinfo.dst(self). + + :rtype: _datetime.timedelta | None + """ + return _datetime.timedelta() + + def tzname(self): + """If tzinfo is None, returns None, else returns + self.tzinfo.tzname(self). + + :rtype: string | None + """ + return str() + + min = _datetime.time() + max = _datetime.time() + resoultion = _datetime.timedelta() diff --git a/python/helpers/python-skeletons/decimal.py b/python/helpers/python-skeletons/decimal.py new file mode 100644 index 000000000000..ec4e30d8733f --- /dev/null +++ b/python/helpers/python-skeletons/decimal.py @@ -0,0 +1,82 @@ +"""Skeleton for 'decimal' stdlib module.""" + + +import decimal + + +def getcontext(): + """Returns this thread's context. + + :rtype: decimal.Context + """ + return decimal.Context() + + +def setcontext(context): + """Set this thread's context to context. + + :type context: decimal.Context + :rtype: None + """ + pass + + +class Decimal(object): + """Floating point class for decimal arithmetic.""" + + def __add__(self, other, context=None): + """Returns self + other. + + :type other: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() + + def __sub__(self, other, context=None): + """Return self - other. + + :type other: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() + + def __mul__(self, other, context=None): + """Return self * other. + + :type other: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() + + + def __truediv__(self, other, context=None): + """Return self / other. + + :type other: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() + + + def __floordiv__(self, other, context=None): + """Return self // other. + + :type other: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() + + def __pow__(self, other, modulo=None, context=None): + """Return self ** other [ % modulo]. + + :type other: numbers.Number + :type modulo: numbers.Number + :type context: decimal.Context | None + :rtype: decimal.Decimal + """ + return decimal.Decimal() diff --git a/python/helpers/python-skeletons/functools.py b/python/helpers/python-skeletons/functools.py new file mode 100644 index 000000000000..dec64529b6ef --- /dev/null +++ b/python/helpers/python-skeletons/functools.py @@ -0,0 +1,16 @@ +"""Skeleton for 'functools' stdlib module.""" + + +def reduce(function, sequence, initial=None): + """Apply a function of two arguments cumulatively to the items of a + sequence, from left to right, so as to reduce the sequence to a single + value. + + :type function: collections.Callable + :type sequence: collections.Iterable + :type initial: T + :rtype: T | unknown + """ + return initial + + diff --git a/python/helpers/python-skeletons/io.py b/python/helpers/python-skeletons/io.py new file mode 100644 index 000000000000..120548a11378 --- /dev/null +++ b/python/helpers/python-skeletons/io.py @@ -0,0 +1,622 @@ +"""Skeleton for 'io' stdlib module.""" + + +from __future__ import unicode_literals +import sys +import io + + +def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, + closefd=True, opener=None): + """This is an alias for the builtin open() function. + + :type file: string + :type mode: string + :type buffering: numbers.Integral + :type encoding: string | None + :type errors: string | None + :type newline: string | None + :type closefd: bool + :type opener: ((string, int) -> int) | None + :rtype: io.FileIO[bytes] | io.TextIOWrapper[unicode] + """ + pass + + +class IOBase(object): + """The abstract base class for all I/O classes, acting on streams of + bytes. + + :type closed: bool + """ + + def __init__(self, *args, **kwargs): + """Private constructor of IOBase. + + :rtype: io.IOBase[T <= bytes | unicode] + """ + self.closed = False + + def __iter__(self): + """Iterate over lines. + + :rtype: collections.Iterator[T] + """ + return [] + + def close(self): + """Flush and close this stream. + + :rtype: None + """ + pass + + def fileno(self): + """Return the underlying file descriptor (an integer) of the stream if + it exists. + + :rtype: int + """ + return 0 + + def flush(self): + """Flush the write buffers of the stream if applicable. + + :rtype: None + """ + pass + + def isatty(self): + """Return True if the stream is interactive (i.e., connected to a + terminal/tty device). + + :rtype: bool + """ + return False + + def readable(self): + """Return True if the stream can be read from. + + :rtype: bool + """ + return False + + def readline(self, limit=-1): + """Read and return one line from the stream. + + :type limit: numbers.Integral + :rtype: T + """ + pass + + def readlines(self, hint=-1): + """Read and return a list of lines from the stream. + + :type hint: numbers.Integral + :rtype: list[T] + """ + return [] + + def seek(self, offset, whence=io.SEEK_SET): + """Change the stream position to the given byte offset. + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def seekable(self): + """Return True if the stream supports random access. + + :rtype: bool + """ + return False + + def tell(self): + """Return the current stream position. + + :rtype: int + """ + return 0 + + def truncate(self, size=None): + """Resize the stream to the given size in bytes (or the current + position if size is not specified). + + :type size: numbers.Integral | None + :rtype: None + """ + pass + + def writable(self): + """Return True if the stream supports writing. + + :rtype: bool + """ + return False + + def writelines(self, lines): + """Write a list of lines to the stream. + + :type lines: collections.Iterable[T] + :rtype: None + """ + pass + + +class RawIOBase(io.IOBase): + """Base class for raw binary I/O.""" + + def __init__(self, *args, **kwargs): + """Private constructor of RawIOBase. + + :rtype: io.RawIOBase[bytes] + """ + pass + + def read(self, n=1): + """Read up to n bytes from the object and return them. + + :type n: numbers.Integral + :rtype: bytes + """ + return b'' + + def readall(self): + """Read and return all the bytes from the stream until EOF, using + multiple calls to the stream if necessary. + + :rtype: bytes + """ + return b'' + + def readinto(self, b): + """Read up to len(b) bytes into bytearray b and return the number of + bytes read. + + :type b: bytearray + :rtype: int + """ + return 0 + + def write(self, b): + """Write the given bytes or bytearray object, b, to the underlying raw + stream and return the number of bytes written. + + :type b: bytes | bytearray + :rtype: int + """ + return 0 + + +class BufferedIOBase(io.IOBase): + """Base class for binary streams that support some kind of buffering.""" + + def __init__(self, *args, **kwargs): + """Private constructor of BufferedIOBase. + + :rtype: io.BufferedIOBase[bytes] + """ + pass + + if sys.version_info >= (2, 7): + def detach(self): + """Separate the underlying raw stream from the buffer and return + it. + + :rtype: None + """ + pass + + def read1(self, n=-1): + """Read and return up to n bytes, with at most one call to the + underlying raw stream's read() method. + + :type n: numbers.Integral + :rtype: bytes + """ + return b'' + + +class FileIO(io.RawIOBase): + """FileIO represents an OS-level file containing bytes data. + + :type name: string + :type mode: string + :type closefd: bool + :type closed: bool + """ + + def __init__(self, name, mode='r', closefd=True): + """Create a FileIO object. + + :type name: string + :type mode: string + :type closefd: bool + :rtype: io.FileIO[bytes] + """ + self.name = name + self.mode = mode + self.closefd = closefd + self.closed = False + pass + + def __iter__(self): + """Iterate over lines. + + :rtype: collections.Iterator[bytes] + """ + return [] + + def close(self): + """Flush and close this stream. + + :rtype: None + """ + pass + + def fileno(self): + """Return the underlying file descriptor (an integer) of the stream if + it exists. + + :rtype: int + """ + return 0 + + def flush(self): + """Flush the write buffers of the stream if applicable. + + :rtype: None + """ + pass + + def isatty(self): + """Return True if the stream is interactive (i.e., connected to a + terminal/tty device). + + :rtype: bool + """ + return False + + def readable(self): + """Return True if the stream can be read from. + + :rtype: bool + """ + return False + + def readline(self, limit=-1): + """Read and return one line from the stream. + + :type limit: numbers.Integral + :rtype: bytes + """ + return b'' + + def readlines(self, hint=-1): + """Read and return a list of lines from the stream. + + :type hint: numbers.Integral + :rtype: list[bytes] + """ + return [] + + def seek(self, offset, whence=io.SEEK_SET): + """Change the stream position to the given byte offset. + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def seekable(self): + """Return True if the stream supports random access. + + :rtype: bool + """ + return False + + def tell(self): + """Return the current stream position. + + :rtype: int + """ + return 0 + + def truncate(self, size=None): + """Resize the stream to the given size in bytes (or the current + position if size is not specified). + + :type size: numbers.Integral | None + :rtype: None + """ + pass + + def writable(self): + """Return True if the stream supports writing. + + :rtype: bool + """ + return False + + def writelines(self, lines): + """Write a list of lines to the stream. + + :type lines: collections.Iterable[bytes] + :rtype: None + """ + pass + + def read(self, n=1): + """Read up to n bytes from the object and return them. + + :type n: numbers.Integral + :rtype: bytes + """ + return b'' + + def readall(self): + """Read and return all the bytes from the stream until EOF, using + multiple calls to the stream if necessary. + + :rtype: bytes + """ + return b'' + + def readinto(self, b): + """Read up to len(b) bytes into bytearray b and return the number of + bytes read. + + :type b: bytearray + :rtype: int + """ + return 0 + + def write(self, b): + """Write the given bytes or bytearray object, b, to the underlying raw + stream and return the number of bytes written. + + :type b: bytes | bytearray + :rtype: int + """ + return 0 + + +class BytesIO(io.BufferedIOBase): + """A stream implementation using an in-memory bytes buffer.""" + + def __init__(self, initial_bytes=None): + """Create a BytesIO object. + + :rtype: io.BytesIO[bytes] + """ + pass + + if sys.version_info >= (3, 2): + def getbuffer(self): + """Return a readable and writable view over the contents of the + buffer without copying them. + + :rtype: bytearray + """ + return bytearray() + + def getvalue(self): + """Return bytes containing the entire contents of the buffer. + + :rtype: bytes + """ + return b'' + + +class TextIOBase(io.IOBase): + """Base class for text streams. + + :type encoding: string + :type errors: string + :type newlines: string | tuple | None + :type buffer: BufferedIOBase + """ + + def __init__(self, *args, **kwargs): + """Private constructor of TextIOBase. + + :rtype: TextIOBase[unicode] + """ + self.encoding = str() + self.errors = str() + self.newlines = None + self.buffer = BufferedIOBase() + + if sys.version_info >= (2, 7): + def detach(self): + """Separate the underlying raw stream from the buffer and return + it. + + :rtype: None + """ + pass + + def read(self, n=None): + """Read and return at most n characters from the stream as a single + unicode. + + :type n: numbers.Integral | None + :rtype: unicode + """ + return '' + + def write(self, s): + """Write the unicode string s to the stream and return the number of + characters written. + + :type b: unicode + :rtype: int + """ + return 0 + + +class TextIOWrapper(io.TextIOBase): + """A buffered text stream over a BufferedIOBase binary stream. + + :type buffer: io.BufferedIOBase + :type encoding: string + :type errors: string + :type newlines: string + :type line_buffering: bool + :type name: string + """ + + def __init__(self, buffer, encoding=None, errors=None, newline=None, + line_buffering=False): + """Creat a TextIOWrapper object. + + :type buffer: io.BufferedIOBase + :type encoding: string | None + :type errors: string | None + :type newline: string | None + :type line_buffering: bool + :rtype: io.TextIOWrapper[unicode] + """ + self.name = '' + self.buffer = buffer + self.encoding = encoding + self.errors = errors + self.newlines = newline + self.line_buffering = line_buffering + + def __iter__(self): + """Iterate over lines. + + :rtype: collections.Iterator[unicode] + """ + return [] + + def close(self): + """Flush and close this stream. + + :rtype: None + """ + pass + + def fileno(self): + """Return the underlying file descriptor (an integer) of the stream if + it exists. + + :rtype: int + """ + return 0 + + def flush(self): + """Flush the write buffers of the stream if applicable. + + :rtype: None + """ + pass + + def isatty(self): + """Return True if the stream is interactive (i.e., connected to a + terminal/tty device). + + :rtype: bool + """ + return False + + def readable(self): + """Return True if the stream can be read from. + + :rtype: bool + """ + return False + + def readline(self, limit=-1): + """Read and return one line from the stream. + + :type limit: numbers.Integral + :rtype: unicode + """ + pass + + def readlines(self, hint=-1): + """Read and return a list of lines from the stream. + + :type hint: numbers.Integral + :rtype: list[unicode] + """ + return [] + + def seek(self, offset, whence=io.SEEK_SET): + """Change the stream position to the given byte offset. + + :type offset: numbers.Integral + :type whence: numbers.Integral + :rtype: None + """ + pass + + def seekable(self): + """Return True if the stream supports random access. + + :rtype: bool + """ + return False + + def tell(self): + """Return the current stream position. + + :rtype: int + """ + return 0 + + def truncate(self, size=None): + """Resize the stream to the given size in bytes (or the current + position if size is not specified). + + :type size: numbers.Integral | None + :rtype: None + """ + pass + + def writable(self): + """Return True if the stream supports writing. + + :rtype: bool + """ + return False + + def writelines(self, lines): + """Write a list of lines to the stream. + + :type lines: collections.Iterable[unicode] + :rtype: None + """ + pass + + if sys.version_info >= (2, 7): + def detach(self): + """Separate the underlying raw stream from the buffer and return + it. + + :rtype: None + """ + pass + + def read(self, n=None): + """Read and return at most n characters from the stream as a single + unicode. + + :type n: numbers.Integral | None + :rtype: unicode + """ + return '' + + def write(self, s): + """Write the unicode string s to the stream and return the number of + characters written. + + :type b: unicode + :rtype: int + """ + return 0 \ No newline at end of file diff --git a/python/helpers/python-skeletons/lettuce/__init__.py b/python/helpers/python-skeletons/lettuce/__init__.py new file mode 100644 index 000000000000..f414331d090a --- /dev/null +++ b/python/helpers/python-skeletons/lettuce/__init__.py @@ -0,0 +1,2 @@ +# coding=utf-8 +__author__ = 'Ilya.Kazakevich' diff --git a/python/helpers/python-skeletons/lettuce/terrain.py b/python/helpers/python-skeletons/lettuce/terrain.py new file mode 100644 index 000000000000..2f7a3735c360 --- /dev/null +++ b/python/helpers/python-skeletons/lettuce/terrain.py @@ -0,0 +1,68 @@ +# coding=utf-8 +""" +Lettuce terrain hooks: http://lettuce.it/reference/terrain.html +""" +__author__ = 'Ilya.Kazakevich' + + +class __When(object): + @staticmethod + def all(function): + """ + Runs before/after all features, scenarios and steps + """ + pass + + @staticmethod + def each_step(function): + """ + Runs before/after each step + """ + pass + + @staticmethod + def each_scenario(function): + """ + Runs before/after each scenario + """ + pass + + @staticmethod + def each_background(function): + """ + Runs before/after each background + """ + pass + + @staticmethod + def each_feature(function): + """ + Runs before/after each feature + """ + pass + + @staticmethod + def each_app(function): + """ + Runs before/after each Django app. + """ + pass + + @staticmethod + def runserver(function): + """ + Runs before/after lettuce starts up the built-in http server. + """ + pass + + @staticmethod + def handle_request(function): + """ + Runs before/after lettuce’s built-in HTTP server responds to a request. + """ + pass + + +before = __When() +after = __When() + diff --git a/python/helpers/python-skeletons/math.py b/python/helpers/python-skeletons/math.py new file mode 100644 index 000000000000..63887f373bdf --- /dev/null +++ b/python/helpers/python-skeletons/math.py @@ -0,0 +1,381 @@ +"""Skeleton for 'math' stdlib module.""" + + +import sys +import math + + +def ceil(x): + """Return the ceiling of x as a float, the smallest integer value greater + than or equal to x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 6): + def copysign(x, y): + """Return x with the sign of y. On a platform that supports signed + zeros, copysign(1.0, -0.0) returns -1.0. + + :type x: numbers.Real + :type y: numbers.Real + :rtype: float + """ + return 0.0 + + +def fabs(x): + """Return the absolute value of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 6): + def factorial(x): + """Return x factorial. + + :type x: numbers.Integral + :rtype: int + """ + return 0 + + +def floor(x): + """Return the floor of x as a float, the largest integer value less than or + equal to x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def fmod(x, y): + """Return fmod(x, y), as defined by the platform C library. + + :type x: numbers.Real + :type y: numbers.Real + :rtype: float + """ + return 0.0 + + +def frexp(x): + """Return the mantissa and exponent of x as the pair (m, e). + + :type x: numbers.Real + :rtype: (float, int) + """ + return 0.0, 0 + + +if sys.version_info >= (2, 6): + def fsum(iterable): + """Return an accurate floating point sum of values in the iterable. + + :type iterable: collections.Iterable[numbers.Real] + :rtype: float + """ + return 0.0 + + def isinf(x): + """Check if the float x is positive or negative infinity. + + :type x: numbers.Real + :rtype: bool + """ + return False + + def isnan(x): + """Check if the float x is a NaN (not a number). + + :type x: numbers.Real + :rtype: bool + """ + return False + + +def ldexp(x, i): + """Return x * (2**i). + + :type x: numbers.Real + :type i: numbers.Integral + :rtype: float + """ + return 0.0 + + +def modf(x): + """Return the fractional and integer parts of x. + + :type x: numbers.Real + :rtype: (float, float) + """ + return 0.0, 0.0 + + +if sys.version_info >= (2, 6): + def trunc(x): + """Return the Real value x truncated to an Integral (usually a long + integer). + + :type x: numbers.Real + :rtype: int + """ + return 0 + + +def exp(x): + """Return e**x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 7): + def expm1(x): + """Return e**x - 1. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def log(x, base=math.e): + """With one argument, return the natural logarithm of x (to base e). + + With two arguments, return the logarithm of x to the given base, calculated + as log(x)/log(base). + + :type x: numbers.Real + :type base: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 6): + def log1p(x): + """Return the natural logarithm of 1+x (base e). + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def log10(x): + """Return the base-10 logarithm of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def pow(x, y): + """Return x raised to the power y. + + :type x: numbers.Real + :type y: numbers.Real + :rtype: float + """ + return 0.0 + + +def sqrt(x): + """Return the square root of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def acos(x): + """Return the arc cosine of x, in radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def asin(x): + """Return the arc sine of x, in radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def atan(x): + """Return the arc tangent of x, in radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def atan2(y, x): + """Return atan(y / x), in radians. + + :type y: numbers.Real + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def cos(x): + """Return the cosine of x radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def hypot(x, y): + """Return the Euclidean norm, sqrt(x*x + y*y). + + :type x: numbers.Real + :type y: numbers.Real + :rtype: float + """ + return 0.0 + + +def sin(x): + """Return the sine of x radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def tan(x): + """Return the tangent of x radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def degrees(x): + """Converts angle x from radians to degrees. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def radians(x): + """Converts angle x from degrees to radians. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 6): + def acosh(x): + """Return the inverse hyperbolic cosine of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + def asinh(x): + """Return the inverse hyperbolic sine of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + def atanh(x): + """Return the inverse hyperbolic tangent of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def cosh(x): + """Return the hyperbolic cosine of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def sinh(x): + """Return the hyperbolic sine of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +def tanh(x): + """Return the hyperbolic tangent of x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + +if sys.version_info >= (2, 7): + def erf(x): + """Return the error function at x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + def erfc(x): + """Return the complementary error function at x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + def gamma(x): + """Return the Gamma function at x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 + + def lgamma(x): + """Return the natural logarithm of the absolute value of the Gamma + function at x. + + :type x: numbers.Real + :rtype: float + """ + return 0.0 diff --git a/python/helpers/python-skeletons/multiprocessing/__init__.py b/python/helpers/python-skeletons/multiprocessing/__init__.py new file mode 100644 index 000000000000..de9d1ddfa3ca --- /dev/null +++ b/python/helpers/python-skeletons/multiprocessing/__init__.py @@ -0,0 +1,280 @@ +"""Skeleton for 'multiprocessing' stdlib module.""" + + +from multiprocessing.pool import Pool + + +class Process(object): + def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): + self.name = '' + self.daemon = False + self.authkey = None + self.exitcode = None + self.ident = 0 + self.pid = 0 + self.sentinel = None + + def run(self): + pass + + def start(self): + pass + + def terminate(self): + pass + + def join(self, timeout=None): + pass + + def is_alive(self): + return False + + +class ProcessError(Exception): + pass + + +class BufferTooShort(ProcessError): + pass + + +class AuthenticationError(ProcessError): + pass + + +class TimeoutError(ProcessError): + pass + + +class Connection(object): + def send(self, obj): + pass + + def recv(self): + pass + + def fileno(self): + return 0 + + def close(self): + pass + + def poll(self, timeout=None): + pass + + def send_bytes(self, buffer, offset=-1, size=-1): + pass + + def recv_bytes(self, maxlength=-1): + pass + + def recv_bytes_into(self, buffer, offset=-1): + pass + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + +def Pipe(duplex=True): + return Connection(), Connection() + + +class Queue(object): + def __init__(self, maxsize=-1): + self._maxsize = maxsize + + def qsize(self): + return 0 + + def empty(self): + return False + + def full(self): + return False + + def put(self, obj, block=True, timeout=None): + pass + + def put_nowait(self, obj): + pass + + def get(self, block=True, timeout=None): + pass + + def get_nowait(self): + pass + + def close(self): + pass + + def join_thread(self): + pass + + def cancel_join_thread(self): + pass + + +class SimpleQueue(object): + def empty(self): + return False + + def get(self): + pass + + def put(self, item): + pass + + +class JoinableQueue(multiprocessing.Queue): + def task_done(self): + pass + + def join(self): + pass + + +def active_childern(): + """ + :rtype: list[multiprocessing.Process] + """ + return [] + + +def cpu_count(): + return 0 + + +def current_process(): + """ + :rtype: multiprocessing.Process + """ + return Process() + + +def freeze_support(): + pass + + +def get_all_start_methods(): + return [] + + +def get_context(method=None): + pass + + +def get_start_method(allow_none=False): + pass + + +def set_executable(path): + pass + + +def set_start_method(method): + pass + + +class Barrier(object): + def __init__(self, parties, action=None, timeout=None): + self.parties = parties + self.n_waiting = 0 + self.broken = False + + def wait(self, timeout=None): + pass + + def reset(self): + pass + + def abort(self): + pass + + +class Semaphore(object): + def __init__(self, value=1): + pass + + def acquire(self, blocking=True, timeout=None): + pass + + def release(self): + pass + + +class BoundedSemaphore(multiprocessing.Semaphore): + pass + + +class Condition(object): + def __init__(self, lock=None): + pass + + def acquire(self, *args): + pass + + def release(self): + pass + + def wait(self, timeout=None): + pass + + def wait_for(self, predicate, timeout=None): + pass + + def notify(self, n=1): + pass + + def notify_all(self): + pass + + +class Event(object): + def is_set(self): + return False + + def set(self): + pass + + def clear(self): + pass + + def wait(self, timeout=None): + pass + + +class Lock(object): + def acquire(self, blocking=True, timeout=-1): + pass + + def release(self): + pass + + +class RLock(object): + def acquire(self, blocking=True, timeout=-1): + pass + + def release(self): + pass + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + +def Value(typecode_or_type, *args, **kwargs): + pass + + +def Array(typecode_or_type, size_or_initializer, lock=True): + pass + + +def Manager(): + return multiprocessing.SyncManager() diff --git a/python/helpers/python-skeletons/multiprocessing/managers.py b/python/helpers/python-skeletons/multiprocessing/managers.py new file mode 100644 index 000000000000..53cf1b5de3f1 --- /dev/null +++ b/python/helpers/python-skeletons/multiprocessing/managers.py @@ -0,0 +1,76 @@ +"""Skeleton for 'multiprocessing.managers' stdlib module.""" + + +import threading +import queue +import multiprocessing +import multiprocessing.managers + + +class BaseManager(object): + def __init__(self, address=None, authkey=None): + self.address = address + + def start(self, initializer=None, initargs=None): + pass + + def get_server(self): + pass + + def connect(self): + pass + + def shutdown(self): + pass + + @classmethod + def register(cls, typeid, callable=None, proxytype=None, exposed=None, + method_to_typeid=None, create_method=None): + pass + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + +class SyncManager(multiprocessing.managers.BaseManager): + def Barrier(self, parties, action=None, timeout=None): + return threading.Barrier(parties, action, timeout) + + def BoundedSemaphore(self, value=None): + return threading.BoundedSemaphore(value) + + def Condition(self, lock=None): + return threading.Condition(lock) + + def Event(self): + return threading.Event() + + def Lock(self): + return threading.Lock() + + def Namespace(self): + pass + + def Queue(self, maxsize=None): + return queue.Queue() + + def RLock(self): + return threading.RLock() + + def Semaphore(self, value=None): + return threading.Semaphore(value) + + def Array(self, typecode, sequence): + pass + + def Value(self, typecode, value): + pass + + def dict(self, mapping_or_sequence): + pass + + def list(self, sequence): + pass diff --git a/python/helpers/python-skeletons/nose/__init__.py b/python/helpers/python-skeletons/nose/__init__.py new file mode 100644 index 000000000000..6469f9af5578 --- /dev/null +++ b/python/helpers/python-skeletons/nose/__init__.py @@ -0,0 +1,5 @@ +"""Skeleton for 'nose' module. + +Project: nose 1.3 +Skeleton by: Andrey Vlasovskikh +""" diff --git a/python/helpers/python-skeletons/nose/tools/__init__.py b/python/helpers/python-skeletons/nose/tools/__init__.py new file mode 100644 index 000000000000..3175d4c87648 --- /dev/null +++ b/python/helpers/python-skeletons/nose/tools/__init__.py @@ -0,0 +1,181 @@ +"""Skeleton for 'nose.tools' module. + +Project: nose 1.3 +Skeleton by: Andrey Vlasovskikh +""" + + +import sys + + +def assert_equal(first, second, msg=None): + """Fail if the two objects are unequal as determined by the '==' operator. + """ + pass + + +def assert_not_equal(first, second, msg=None): + """Fail if the two objects are equal as determined by the '==' operator. + """ + pass + + +def assert_true(expr, msg=None): + """Check that the expression is true.""" + pass + + +def assert_false(expr, msg=None): + """Check that the expression is false.""" + pass + + +if sys.version_info >= (2, 7): + def assert_is(expr1, expr2, msg=None): + """Just like assert_true(a is b), but with a nicer default message.""" + pass + + def assert_is_not(expr1, expr2, msg=None): + """Just like assert_true(a is not b), but with a nicer default message. + """ + pass + + def assert_is_none(obj, msg=None): + """Same as assert_true(obj is None), with a nicer default message. + """ + pass + + def assert_is_not_none(obj, msg=None): + """Included for symmetry with assert_is_none.""" + pass + + def assert_in(member, container, msg=None): + """Just like assert_true(a in b), but with a nicer default message.""" + pass + + def assert_not_in(member, container, msg=None): + """Just like assert_true(a not in b), but with a nicer default message. + """ + pass + + def assert_is_instance(obj, cls, msg=None): + """Same as assert_true(isinstance(obj, cls)), with a nicer default + message. + """ + pass + + def assert_not_is_instance(obj, cls, msg=None): + """Included for symmetry with assert_is_instance.""" + pass + + +def assert_raises(excClass, callableObj=None, *args, **kwargs): + """Fail unless an exception of class excClass is thrown by callableObj when + invoked with arguments args and keyword arguments kwargs. + + If called with callableObj omitted or None, will return a + context object used like this:: + + with assert_raises(SomeException): + do_something() + + :rtype: unittest.case._AssertRaisesContext | None + """ + pass + + +if sys.version_info >= (2, 7): + def assert_raises_regexp(expected_exception, expected_regexp, + callable_obj=None, *args, **kwargs): + """Asserts that the message in a raised exception matches a regexp. + + :rtype: unittest.case._AssertRaisesContext | None + """ + pass + + +def assert_almost_equal(first, second, places=None, msg=None, delta=None): + """Fail if the two objects are unequal as determined by their difference + rounded to the given number of decimal places (default 7) and comparing to + zero, or by comparing that the between the two objects is more than the + given delta. + """ + pass + + +def assert_not_almost_equal(first, second, places=None, msg=None, delta=None): + """Fail if the two objects are equal as determined by their difference + rounded to the given number of decimal places (default 7) and comparing to + zero, or by comparing that the between the two objects is less than the + given delta. + """ + pass + + +if sys.version_info >= (2, 7): + def assert_greater(a, b, msg=None): + """Just like assert_true(a > b), but with a nicer default message.""" + pass + + def assert_greater_equal(a, b, msg=None): + """Just like assert_true(a >= b), but with a nicer default message.""" + pass + + def assert_less(a, b, msg=None): + """Just like assert_true(a < b), but with a nicer default message.""" + pass + + def assert_less_equal(a, b, msg=None): + """Just like self.assertTrue(a <= b), but with a nicer default + message. + """ + pass + + def assert_regexp_matches(text, expected_regexp, msg=None): + """Fail the test unless the text matches the regular expression.""" + pass + + def assert_not_regexp_matches(text, unexpected_regexp, msg=None): + """Fail the test if the text matches the regular expression.""" + pass + + def assert_items_equal(expected_seq, actual_seq, msg=None): + """An unordered sequence specific comparison. It asserts that + actual_seq and expected_seq have the same element counts. + """ + pass + + def assert_dict_contains_subset(expected, actual, msg=None): + """Checks whether actual is a superset of expected.""" + pass + + def assert_multi_line_equal(first, second, msg=None): + """Assert that two multi-line strings are equal.""" + pass + + def assert_sequence_equal(seq1, seq2, msg=None, seq_type=None): + """An equality assertion for ordered sequences (like lists and tuples). + """ + pass + + def assert_list_equal(list1, list2, msg=None): + """A list-specific equality assertion.""" + pass + + def assert_tuple_equal(tuple1, tuple2, msg=None): + """A tuple-specific equality assertion.""" + pass + + def assert_set_equal(set1, set2, msg=None): + """A set-specific equality assertion.""" + pass + + def assert_dict_equal(d1, d2, msg=None): + """A dict-specific equality assertion.""" + pass + + +assert_equals = assert_equal +assert_not_equals = assert_not_equal +assert_almost_equals = assert_almost_equal +assert_not_almost_equals = assert_not_almost_equal diff --git a/python/helpers/python-skeletons/numpy/__init__.py b/python/helpers/python-skeletons/numpy/__init__.py new file mode 100644 index 000000000000..7d5a37a4ef3d --- /dev/null +++ b/python/helpers/python-skeletons/numpy/__init__.py @@ -0,0 +1,10 @@ +"""Skeleton for 'numpy' module. + +Project: NumPy 1.8.0 +""" + +from . import core +from .core import * + +__all__ = [] +__all__.extend(core.__all__) \ No newline at end of file diff --git a/python/helpers/python-skeletons/numpy/core/__init__.py b/python/helpers/python-skeletons/numpy/core/__init__.py new file mode 100644 index 000000000000..f23ee9aa8c6e --- /dev/null +++ b/python/helpers/python-skeletons/numpy/core/__init__.py @@ -0,0 +1,3 @@ +from . import multiarray + +__all__ = [] \ No newline at end of file diff --git a/python/helpers/python-skeletons/numpy/core/multiarray.py b/python/helpers/python-skeletons/numpy/core/multiarray.py new file mode 100644 index 000000000000..f7f106ac31cb --- /dev/null +++ b/python/helpers/python-skeletons/numpy/core/multiarray.py @@ -0,0 +1,202 @@ +class ndarray(object): + """ + ndarray(shape, dtype=float, buffer=None, offset=0, + strides=None, order=None) + + An array object represents a multidimensional, homogeneous array + of fixed-size items. An associated data-type object describes the + format of each element in the array (its byte-order, how many bytes it + occupies in memory, whether it is an integer, a floating point number, + or something else, etc.) + + Arrays should be constructed using `array`, `zeros` or `empty` (refer + to the See Also section below). The parameters given here refer to + a low-level method (`ndarray(...)`) for instantiating an array. + + For more information, refer to the `numpy` module and examine the + the methods and attributes of an array. + + Parameters + ---------- + (for the __new__ method; see Notes below) + + shape : tuple of ints + Shape of created array. + dtype : data-type, optional + Any object that can be interpreted as a numpy data type. + buffer : object exposing buffer interface, optional + Used to fill the array with data. + offset : int, optional + Offset of array data in buffer. + strides : tuple of ints, optional + Strides of data in memory. + order : {'C', 'F'}, optional + Row-major or column-major order. + + Attributes + ---------- + T : ndarray + Transpose of the array. + data : buffer + The array's elements, in memory. + dtype : dtype object + Describes the format of the elements in the array. + flags : dict + Dictionary containing information related to memory use, e.g., + 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc. + flat : numpy.flatiter object + Flattened version of the array as an iterator. The iterator + allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for + assignment examples; TODO). + imag : ndarray + Imaginary part of the array. + real : ndarray + Real part of the array. + size : int + Number of elements in the array. + itemsize : int + The memory use of each array element in bytes. + nbytes : int + The total number of bytes required to store the array data, + i.e., ``itemsize * size``. + ndim : int + The array's number of dimensions. + shape : tuple of ints + Shape of the array. + strides : tuple of ints + The step-size required to move from one element to the next in + memory. For example, a contiguous ``(3, 4)`` array of type + ``int16`` in C-order has strides ``(8, 2)``. This implies that + to move from element to element in memory requires jumps of 2 bytes. + To move from row-to-row, one needs to jump 8 bytes at a time + (``2 * 4``). + ctypes : ctypes object + Class containing properties of the array needed for interaction + with ctypes. + base : ndarray + If the array is a view into another array, that array is its `base` + (unless that array is also a view). The `base` array is where the + array data is actually stored. + + See Also + -------- + array : Construct an array. + zeros : Create an array, each element of which is zero. + empty : Create an array, but leave its allocated memory unchanged (i.e., + it contains "garbage"). + dtype : Create a data-type. + + Notes + ----- + There are two modes of creating an array using ``__new__``: + + 1. If `buffer` is None, then only `shape`, `dtype`, and `order` + are used. + 2. If `buffer` is an object exposing the buffer interface, then + all keywords are interpreted. + + No ``__init__`` method is needed because the array is fully initialized + after the ``__new__`` method. + + Examples + -------- + These examples illustrate the low-level `ndarray` constructor. Refer + to the `See Also` section above for easier ways of constructing an + ndarray. + + First mode, `buffer` is None: + + >>> np.ndarray(shape=(2,2), dtype=float, order='F') + array([[ -1.13698227e+002, 4.25087011e-303], + [ 2.88528414e-306, 3.27025015e-309]]) #random + + Second mode: + + >>> np.ndarray((2,), buffer=np.array([1,2,3]), + ... offset=np.int_().itemsize, + ... dtype=int) # offset = 1*itemsize, i.e. skip first element + array([2, 3]) + """ + pass + + def __mul__(self, y): # real signature unknown; restored from __doc__ + """ + x.__mul__(y) <==> x*y + + Returns + ------- + out : ndarray + """ + pass + + def __rmul__(self, y): # real signature unknown; restored from __doc__ + """ + x.__rmul__(y) <==> x*y + + Returns + ------- + out : ndarray + """ + pass + + def __abs__(self): # real signature unknown; restored from __doc__ + """ + x.__abs__() <==> abs(x) + + Returns + ------- + out : ndarray + """ + pass + + def __add__(self, y): # real signature unknown; restored from __doc__ + """ + x.__add__(y) <==> x+y + + Returns + ------- + out : ndarray + """ + pass + + def __copy__(self, order=None): # real signature unknown; restored from __doc__ + """ + a.__copy__([order]) + + Return a copy of the array. + + Parameters + ---------- + order : {'C', 'F', 'A'}, optional + If order is 'C' (False) then the result is contiguous (default). + If order is 'Fortran' (True) then the result has fortran order. + If order is 'Any' (None) then the result has fortran order + only if the array already is in fortran order. + + Returns + ------- + out : ndarray + """ + pass + + + def __div__(self, y): # real signature unknown; restored from __doc__ + """ + x.__div__(y) <==> x/y + + Returns + ------- + out : ndarray + """ + pass + + + def __sub__(self, y): # real signature unknown; restored from __doc__ + """ + x.__sub__(y) <==> x-y + + Returns + ------- + out : ndarray + """ + pass \ No newline at end of file diff --git a/python/helpers/python-skeletons/os/__init__.py b/python/helpers/python-skeletons/os/__init__.py new file mode 100644 index 000000000000..f7e6844392b2 --- /dev/null +++ b/python/helpers/python-skeletons/os/__init__.py @@ -0,0 +1,1257 @@ +"""Skeleton for 'os' stdlib module.""" + + +from __future__ import unicode_literals +import sys + + +error = OSError + + +def ctermid(): + """Return the filename corresponding to the controlling terminal of the + process. + + :rtype: string + """ + return '' + + +def getegid(): + """Return the effective group id of the current process. + + :rtype: int + """ + return 0 + + +def geteuid(): + """Return the current process's effective user id. + + :rtype: int + """ + return 0 + + +def getgid(): + """Return the real group id of the current process. + + :rtype: int + """ + return 0 + + +def getgroups(): + """Return list of supplemental group ids associated with the current + process. + + :rtype: list[int] + """ + return [] + + +if sys.version_info >= (2, 7): + def initgroups(username, gid): + """Call the system initgroups() to initialize the group access list + with all of the groups of which the specified username is a member, + plus the specified group id. + + :type username: string + :type gid: int + :rtype: None + """ + pass + + +def getlogin(): + """Return the name of the user logged in on the controlling terminal of the + process. + + :rtype: string + """ + return '' + + +def getpgid(pid): + """Return the process group id of the process with process id pid. + + :type pid: int + :rtype: int + """ + return 0 + + +def getpgrp(): + """Return the id of the current process group. + + :rtype: int + """ + return 0 + + +def getpid(): + """Return the current process id. + + :rtype: int + """ + return 0 + + +def getppid(): + """Return the parent's process id. + + :rtype: int + """ + return 0 + + +if sys.version_info >= (2, 7): + def getresuid(): + """Return a tuple (ruid, euid, suid) denoting the current process's + real, effective, and saved user ids. + + :rtype: (int, int, int) + """ + return 0, 0, 0 + + def getresgid(): + """Return a tuple (rgid, egid, sgid) denoting the current process's + real, effective, and saved group ids. + + :rtype: (int, int, int) + """ + return 0, 0, 0 + + +def getuid(): + """Return the current process's user id. + + :rtype: int + """ + return 0 + + +def getenv(varname, value=None): + """Return the value of the environment variable varname if it exists, or + value if it doesn't. + + :type varname: string + :type value: T + :rtype: string | T + """ + pass + + +def putenv(varname, value): + """Set the environment variable named varname to the string value. + + :type varname: string + :rtype: None + """ + pass + + +def setegid(egid): + """Set the current process's effective group id. + + :type egid: int + :rtype: None + """ + pass + + +def seteuid(euid): + """Set the current process's effective user id. + + :type euid: int + :rtype: None + """ + pass + + +def setgid(gid): + """Set the current process' group id. + + :type gid: int + :rtype: None + """ + pass + + +def setgroups(groups): + """Set the list of supplemental group ids associated with the current + process to groups. + + :type groups: collections.Iterable[int] + :rtype: None + """ + pass + + +def setpgid(pid, pgrp): + """Call the system call setpgid() to set the process group id of the + process with id pid to the process group with id pgrp. + + :type pid: int + :type pgrp: int + :rtype: None + """ + pass + + +def setregid(rgid, egid): + """Set the current process's real and effective group ids. + + :type rgid: int + :type egid: int + :rtype: None + """ + pass + + +if sys.version_info >= (2, 7): + def setresgid(rgid, egid, sgid): + """Set the current process's real, effective, and saved group ids. + + :type rgid: int + :type egid: int + :type sgid: int + :rtype: None + """ + pass + + def setresuid(ruid, euid, suid): + """Set the current process's real, effective, and saved user ids. + + :type ruid: int + :type euid: int + :type suid: int + :rtype None + """ + pass + + +def setreuid(ruid, euid): + """Set the current process's real and effective user ids. + + :type ruid: int + :type euid: int + :rtype None + """ + pass + + +def setsid(pid): + """Call the system call getsid(). + + :type pid: int + :rtype: None + """ + pass + + +def setuid(uid): + """Set the current process's user id. + + :type uid: int + :rtype: None + """ + pass + + +def strerror(code): + """Return the error message corresponding to the error code in code. + + :type code: int + :rtype: string + """ + return '' + + +def umask(mask): + """Set the current numeric umask and return the previous umask. + + :type mask: int + :rtype: int + """ + return 0 + + +def uname(): + """Return a 5-tuple containing information identifying the current + operating system. + + :rtype: (string, string, string, string, string) + """ + return '', '', '', '', '' + + +def unsetenv(varname): + """Unset (delete) the environment variable named varname. + + :type varname: string + :rtype: None + """ + pass + + +def fdopen(fd, mode='r', bufsize=-1): + """Return an open file object connected to the file descriptor fd. + + :type fd: int + :type mode: string + :type bufsize: int + :rtype: file + """ + return file() + + +def popen(command, mode='r', bufsize=-1): + """Open a pipe to or from command. + + :type command: string + :type mode: string + :type bufsize: int + :rtype: io.FileIO[bytes] + """ + pass + + +def tmpfile(): + """Return a new file object opened in update mode (w+b). + + :rtype: io.FileIO[bytes] + """ + pass + + +def popen2(cmd, mode='r', bufsize=-1): + """Execute cmd as a sub-process and return the file objects (child_stdin, + child_stdout). + + :type cmd: string + :type mode: string + :type bufsize: int + :rtype: (io.FileIO[bytes], io.FileIO[bytes]) + """ + pass + + +def popen3(cmd, mode='r', bufsize=-1): + """Execute cmd as a sub-process and return the file objects (child_stdin, + child_stdout, child_stderr). + + :type cmd: string + :type mode: string + :type bufsize: int + :rtype: (io.FileIO[bytes], io.FileIO[bytes], io.FileIO[bytes]) + """ + pass + + +def popen4(cmd, mode='r', bufsize=-1): + """Execute cmd as a sub-process and return the file objects (child_stdin, + child_stdout_and_stderr). + + :type cmd: string + :type mode: string + :type bufsize: int + :rtype: (io.FileIO[bytes], io.FileIO[bytes]) + """ + pass + + +def close(fd): + """Close file descriptor fd. + + :type fd: int + :rtype: None + """ + pass + + +if sys.version_info >= (2, 6): + def closerange(fd_low, fd_high): + """Close all file descriptors from fd_low (inclusive) to fd_high + (exclusive), ignoring errors. + + :type fd_low: int + :type fd_high: int + :rtype: None + """ + pass + + +def dup(fd): + """Return a duplicate of file descriptor fd. + + :type fd: int + :rtype: int + """ + return 0 + + +def dup2(fd, fd2): + """Duplicate file descriptor fd to fd2, closing the latter first if + necessary. + + :type fd: int + :type fd2: int + :rtype: None + """ + pass + + +if sys.version_info >= (2, 6): + def fchmod(fd, mode): + """Change the mode of the file given by fd to the numeric mode. + + :type fd: int + :type mode: int + :rtype: None + """ + pass + + def fchown(fd, uid, gid): + """Change the owner and group id of the file given by fd to the numeric + uid and gid. + + :type fd: int + :type uid: int + :type gid: int + :rtype: None + """ + pass + + +def fdatasync(fd): + """Force write of file with filedescriptor fd to disk. + + :type fd: int + :rtype: None + """ + pass + + +def fpathconf(fd, name): + """Return system configuration information relevant to an open file. + + :type fd: int + :type name: string | int + """ + pass + + +def fstat(fd): + """Return status for file descriptor fd, like stat(). + + :type fd: int + :rtype: os.stat_result + """ + pass + + +def fstatvfs(fd): + """Return information about the filesystem containing the file associated + with file descriptor fd, like statvfs(). + + :type fd: int + :rtype: os.statvfs_result + """ + pass + + +def fsync(fd): + """Force write of file with filedescriptor fd to disk. + + :type fd: int + :rtype: None + """ + pass + + +def ftruncate(fd, length): + """Truncate the file corresponding to file descriptor fd, so that it is at + most length bytes in size. + + :type fd: int + :type length: numbers.Integral + :rtype: None + """ + pass + + +def isatty(fd): + """Return True if the file descriptor fd is open and connected to a + tty(-like) device, else False. + + :type fd: int + :rtype: bool + """ + return False + + +def lseek(fd, pos, how): + """Set the current position of file descriptor fd to position pos, modified + by how. + + :type fd: int + :type pos: numbers.Integral + :type how: int + :rtype: None + """ + pass + + +def open(file, flags, mode=0o777): + """Open the file file and set various flags according to flags and possibly + its mode according to mode. + + :type file: string + :type flags: int + :type mode: int + :rtype: int + """ + return 0 + + +def openpty(): + """Open a new pseudo-terminal pair. + + :rtype: (int, int) + """ + return 0, 0 + + +def pipe(): + """Create a pipe. + + :rtype: (int, int) + """ + return 0, 0 + + +def read(fd, n): + """Read at most n bytes from file descriptor fd. + + :type fd: int + :type n: numbers.Integral + :rtype: bytes + """ + pass + + +def tcgetpgrp(fd): + """Return the process group associated with the terminal given by fd. + + :type fd: int + :rtype: int + """ + return 0 + + +def tcsetpgrp(fd, pg): + """Set the process group associated with the terminal given by fd to pg. + + :type fd: int + :type pg: int + :rtype: None + """ + pass + + +def ttyname(fd): + """Return a string which specifies the terminal device associated with file + descriptor fd. + + :type fd: int + :rtype: string + """ + return '' + + +def write(fd, str): + """Write the string str to file descriptor fd. Return the number of bytes + actually written. + + :type fd: int + :type str: bytes + :rtype: int + """ + return 0 + + +def access(path, mode): + """Use the real uid/gid to test for access to path. + + :type path: bytes | unicode + :type mode: int + :rtype: bool + """ + return False + + +def chdir(path): + """Change the current working directory to path. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def fchdir(fd): + """Change the current working directory to the directory represented by the + file descriptor fd. + + :type fd: int + :rtype: None + """ + pass + + +def getcwd(): + """Return a string representing the current working directory. + + :rtype: string + """ + return '' + + +if sys.version_info < (3, 0): + def getcwdu(): + """Return a Unicode object representing the current working directory. + + :rtype: unicode + """ + return '' + + +def chflags(path, flags): + """Set the flags of path to the numeric flags. + + :type path: bytes | unicode + :type flags: int + :rtype: None + """ + pass + + +def chroot(path): + """Change the root directory of the current process to path. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def chmod(path, mode): + """Change the mode of path to the numeric mode. + + :type path: bytes | unicode + :type mode: int + :rtype: None + """ + pass + + +def chown(path, uid, gid): + """Change the owner and group id of path to the numeric uid and gid. + + :type path: bytes | unicode + :type uid: int + :type gid: int + :rtype: None + """ + pass + + +def lchflags(path, flags): + """Set the flags of path to the numeric flags, like chflags(), but do not + follow symbolic links. + + :type path: bytes | unicode + :type flags: int + :rtype: None + """ + pass + + +def lchmod(path, mode): + """Change the mode of path to the numeric mode. If path is a symlink, this + affects the symlink rather than the target. + + :type path: bytes | unicode + :type mode: int + :rtype: None + """ + pass + + +def lchown(path, uid, gid): + """Change the owner and group id of path to the numeric uid and gid. This + function will not follow symbolic links. + + :type path: bytes | unicode + :type uid: int + :type gid: int + :rtype: None + """ + pass + + +def link(source, link_name): + """Create a hard link pointing to source named link_name. + + :type source: bytes | unicode + :type link_name: bytes | unicode + :rtype: None + """ + pass + + +def listdir(path): + """Return a list containing the names of the entries in the directory given + by path. + + :type path: T <= bytes | unicode + :rtype: list[T] + """ + return [] + + +def lstat(path): + """Perform the equivalent of an lstat() system call on the given path. + Similar to stat(), but does not follow symbolic links. + + :type path: bytes | unicode + :rtype: os.stat_result + """ + pass + + +def mkfifo(path, mode=0o666): + """Create a FIFO (a named pipe) named path with numeric mode mode. + + :type path: bytes | unicode + :type mode: int + :rtype: None + """ + pass + + +def mknod(filename, mode=0o600, device=0): + """Create a filesystem node (file, device special file or named pipe) named + filename. + + :type filename: bytes | unicode + :type mode: int + :type device: int + :rtype: None + """ + pass + + +def major(device): + """Extract the device major number from a raw device number (usually the + st_dev or st_rdev field from stat). + + :type device: int + :rtype: int + """ + return 0 + + +def minor(device): + """Extract the device minor number from a raw device number (usually the + st_dev or st_rdev field from stat). + + :type device: int + :rtype: int + """ + return 0 + + +def makedev(major, minor): + """Compose a raw device number from the major and minor device numbers. + + :type major: int + :type minor: int + :rtype: int + """ + return 0 + + +def mkdir(path, mode=0o777): + """Create a directory named path with numeric mode mode. + + :type path: bytes | unicode + :type mode: int + :rtype: None + """ + pass + + +def makedirs(path, mode=0o777, exist_ok=False): + """Recursive directory creation function. + + :type path: bytes | unicode + :type mode: int + :type exist_ok: int + :rtype: None + """ + pass + + +def pathconf(path, name): + """Return system configuration information relevant to a named file. + + :type path: bytes | unicode + :type name: int | string + """ + pass + + +def readlink(path): + """Return a string representing the path to which the symbolic link points. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def remove(path): + """Remove (delete) the file path. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def removedirs(path): + """Remove directories recursively. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def rename(src, dst): + """Rename the file or directory src to dst. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def renames(old, new): + """Recursive directory or file renaming function. + + :type old: bytes | unicode + :type new: bytes | unicode + :rtype: None + """ + pass + + +def rmdir(path): + """Remove (delete) the directory path. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def stat(path, dir_fd=None, follow_symlinks=True): + """Perform the equivalent of a stat() system call on the given path. + + :type path: bytes | unicode | int + :type dir_fd: int | None + :type follow_symlinks: bool | None + :rtype: os.stat_result + """ + pass + + +def stat_float_times(newvalue=None): + """Determine whether stat_result represents time stamps as float objects. + + :type newvalue: bool | None + :rtype: bool + """ + return False + + +def statvfs(path): + """Perform a statvfs() system call on the given path. + + :type path: bytes | unicode + :rtype: os.statvfs_result + """ + pass + + +def symlink(source, link_name): + """Create a symbolic link pointing to source named link_name. + + :type source: bytes | unicode + :type link_name: bytes| unicode + :rtype: None + """ + pass + + +def tempnam(dir=None, prefix=None): + """Return a unique path name that is reasonable for creating a temporary + file. + + :type dir: bytes | unicode + :type prefix: bytes | unicode + :rtype: string + """ + return '' + + +def tmpnam(): + """Return a unique path name that is reasonable for creating a temporary + file. + + :rtype: string + """ + return '' + + +def unlink(path): + """Remove (delete) the file path. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def utime(path, times): + """Set the access and modified times of the file specified by path. + + :type path: bytes | unicode + :type times: (numbers.Real, numbers.Real) | None + :rtype: None + """ + pass + + +def walk(top, topdown=True, onerror=None, followlinks=False): + """Generate the file names in a directory tree by walking the tree either + top-down or bottom-up. + + :type top: T <= bytes | unicode + :type topdown: bool + :type onerror: ((Exception) -> None) | None + :rtype: collections.Iterator[(T, list[T], list[T])] + """ + return [] + + +def execl(path, *args): + """Execute a new program, replacing the current process. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def execle(path, *args): + """Execute a new program, replacing the current process. + + :type path: bytes | unicode + :rtype: None + """ + pass + + +def execlp(file, *args): + """Execute a new program, replacing the current process. + + :type file: bytes | unicode + :rtype: None + """ + pass + + +def execlpe(file, *args): + """Execute a new program, replacing the current process. + + :type file: bytes | unicode + :rtype: None + """ + pass + + +def execv(path, args): + """Execute a new program, replacing the current process. + + :type path: bytes | unicode + :type args: collections.Iterable + :rtype: None + """ + pass + + +def execve(path, args, env): + """Execute a new program, replacing the current process. + + :type path: bytes | unicode + :type args: collections.Iterable + :type env: collections.Mapping + :rtype: None + """ + pass + + +def execvp(file, args): + """Execute a new program, replacing the current process. + + :type file: bytes | unicode + :type args: collections.Iterable + :rtype: None + """ + pass + + +def execvpe(file, args, env): + """Execute a new program, replacing the current process. + + :type file: bytes | unicode + :type args: collections.Iterable + :type env: collections.Mapping + :rtype: None + """ + pass + + +def _exit(n): + """Exit the process with status n, without calling cleanup handlers, + flushing stdio buffers, etc. + + :type n: int + :rtype: None + """ + pass + + +def fork(): + """Fork a child process. + + :rtype: int + """ + return 0 + + +def forkpty(): + """Fork a child process, using a new pseudo-terminal as the child's + controlling terminal. + + :rtype: (int, int) + """ + return 0, 0 + + +def kill(pid, sig): + """Send signal sig to the process pid. + + :type pid: int + :type sig: int + :rtype: None + """ + pass + + +def killpg(pgid, sig): + """Send the signal sig to the process group pgid. + + :type pgid: int + :type sig: int + :rtype: None + """ + pass + + +def nice(increment): + """Add increment to the process's "niceness". + + :type increment: int + :rtype: int + """ + return 0 + + +def plock(op): + """Lock program segments into memory. + + :rtype: None + """ + pass + + +def spawnl(mode, path, *args): + """Execute the program path in a new process. + + :type mode: int + :type path: bytes | unicode + :rtype: int + """ + return 0 + + +def spawnle(mode, path, *args): + """Execute the program path in a new process. + + :type mode: int + :type path: bytes | unicode + :rtype: int + """ + return 0 + + +def spawnlp(mode, file, *args): + """Execute the program path in a new process. + + :type mode: int + :type file: bytes | unicode + :rtype: int + """ + return 0 + + +def spawnlpe(mode, file, *args): + """Execute the program path in a new process. + + :type mode: int + :type file: bytes | unicode + :rtype: int + """ + return 0 + + +def spawnv(mode, path, args): + """Execute the program path in a new process. + + :type mode: int + :type path: bytes | unicode + :type args: collections.Iterable + :rtype: int + """ + return 0 + + +def spawnve(mode, path, args, env): + """Execute the program path in a new process. + + :type mode: int + :type path: bytes | unicode + :type args: collections.Iterable + :type env: collections.Mapping + :rtype: int + """ + return 0 + + +def spawnvp(mode, file, args): + """Execute the program path in a new process. + + :type mode: int + :type file: bytes | unicode + :type args: collections.Iterable + :rtype: int + """ + return 0 + + +def spawnvpe(mode, file, args, env): + """Execute the program path in a new process. + + :type mode: int + :type file: bytes | unicode + :type args: collections.Iterable + :type env: collections.Mapping + :rtype: int + """ + return 0 + + +def system(command): + """Execute the command (a string) in a subshell. + + :type command: bytes | unicode + :rtype: int + """ + return 0 + + +def times(): + """Return a 5-tuple of floating point numbers indicating accumulated + (processor or other) times, in seconds. + + :rtype: (float, float, float, float, float) + """ + return 0.0, 0.0, 0.0, 0.0, 0.0 + + +def wait(): + """Wait for completion of a child process, and return a tuple containing + its pid and exit status indication + + :rtype: (int, int) + """ + return 0, 0 + + +def waitpid(pid, options): + """Wait for completion of a child process given by process id pid, and + return a tuple containing its process id and exit status indication. + + :type pid: int + :type options: int + :rtype: (int, int) + """ + return 0, 0 + + +def wait3(options): + """Similar to waitpid(), except no process id argument is given and a + 3-element tuple containing the child's process id, exit status indication, + and resource usage information is returned. + + :type options: int + :rtype: (int, int, resource.struct_rusage) + """ + pass + + +def wait4(pid, options): + """Similar to waitpid(), except a 3-element tuple, containing the child's + process id, exit status indication, and resource usage information is + returned. + + :type pid: int + :type options: int + :rtype: (int, int, resource.struct_rusage) + """ + pass + + +def urandom(n): + """Return a string of n random bytes suitable for cryptographic use. + + :type n: int + :rtype: bytes + """ + return b'' \ No newline at end of file diff --git a/python/helpers/python-skeletons/os/path.py b/python/helpers/python-skeletons/os/path.py new file mode 100644 index 000000000000..2dbfd4cf7928 --- /dev/null +++ b/python/helpers/python-skeletons/os/path.py @@ -0,0 +1,293 @@ +"""Skeleton for 'os.path' stdlib module.""" + + +import sys +import os + + +def abspath(path): + """Return a normalized absolutized version of the pathname path. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def basename(path): + """Return the base name of pathname path. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def commonprefix(list): + """Return the longest path prefix (taken character-by-character) that is a + prefix of all paths in list. + + :type list: collections.Iterable[T <= bytes | unicode] + :rtype T + """ + pass + + +def dirname(path): + """Return the directory name of pathname path. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def exists(path): + """Return True if path refers to an existing path. Returns False for broken + symbolic links. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def lexists(path): + """Return True if path refers to an existing path. Returns True for broken + symbolic links. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def expanduser(path): + """On Unix and Windows, return the argument with an initial component of ~ + or ~user replaced by that user's home directory. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def expandvars(path): + """Return the argument with environment variables expanded. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def getatime(path): + """Return the time of last access of path. + + :type path: bytes | unicode + :rtype: float + """ + return 0.0 + + +def getmtime(path): + """Return the time of last modification of path. + + :type path: bytes | unicode + :rtype: float + """ + return 0.0 + + +def getctime(path): + """Return the system's ctime. + + :type path: bytes | unicode + :rtype: float + """ + return 0.0 + + +def getsize(path): + """Return the size, in bytes, of path. + + :type path: bytes | unicode + :rtype: int + """ + return 0 + + +def isabs(path): + """Return True if path is an absolute pathname. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def isfile(path): + """Return True if path is an existing regular file. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def isdir(path): + """Return True if path is an existing directory. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def islink(path): + """Return True if path refers to a directory entry that is a symbolic link. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def ismount(path): + """Return True if pathname path is a mount point: a point in a file system + where a different file system has been mounted. + + :type path: bytes | unicode + :rtype: bool + """ + return False + + +def join(path, *paths): + """Join one or more path components intelligently. + + :type path: T <= bytes | unicode + :type paths: collections.Iterable[T] + :rtype: T + """ + return path + + +def normcase(path): + """Normalize the case of a pathname. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def normpath(path): + """Normalize a pathname by collapsing redundant separators and up-level + references. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def realpath(path): + """Return the canonical path of the specified filename, eliminating any + symbolic links encountered in the path. + + :type path: T <= bytes | unicode + :rtype: T + """ + return path + + +def relpath(path, start=os.curdir): + """Return a relative filepath to path either from the current directory or + from an optional start directory. + + :type path: T <= bytes | unicode + :type start: T + :rtype: T + """ + return path + + +def samefile(path1, path2): + """Return True if both pathname arguments refer to the same file or + directory. + + :type path1: bytes | unicode + :type path2: bytes | unicode + :rtype: bool + """ + return False + + +def sameopenfile(fp1, fp2): + """Return True if the file descriptors fp1 and fp2 refer to the same file. + + :type fp1: int + :type fp2: int + :rtype: bool + """ + return False + + +def samestat(stat1, stat2): + """Return True if the stat tuples stat1 and stat2 refer to the same file. + + :type stat1: os.stat_result | tuple + :type stat2: os.stat_result | tuple + :rtype: bool + """ + return False + + +def split(path): + """Split the pathname path into a pair, (head, tail). + + :type path: T <= bytes | unicode + :rtype: (T, T) + """ + return path, path + + +def splitdrive(path): + """Split the pathname path into a pair (drive, tail). + + :type path: T <= bytes | unicode + :rtype: (T, T) + """ + return path, path + + +def splitext(path): + """Split the pathname path into a pair (root, ext). + + :type path: T <= bytes | unicode + :rtype: (T, T) + """ + return path, path + + +def splitunc(path): + """Split the pathname path into a pair (unc, rest). + + :type path: T <= bytes | unicode + :rtype: (T, T) + """ + return path, path + + +if sys.version_info < (3, 0): + def walk(path, visit, arg): + """Calls the function visit with arguments (arg, dirname, names) for + each directory in the directory tree rooted at path. + + :type path: T <= bytes | unicode + :type visit: (V, T, list[T]) -> None + :type arg: V + :rtype: None + """ + pass diff --git a/python/helpers/python-skeletons/pathlib.py b/python/helpers/python-skeletons/pathlib.py new file mode 100644 index 000000000000..7ecc3e50ad9d --- /dev/null +++ b/python/helpers/python-skeletons/pathlib.py @@ -0,0 +1,373 @@ +"""Skeleton for 'pathlib' stdlib module.""" + +import pathlib + + +class PurePath(object): + def __new__(cls, *pathsegments): + """ + :rtype: pathlib.PurePath + """ + return cls.__new__(*pathsegments) + + def __truediv__(self, key): + """ + :type key: string | pathlib.PurePath + :rtype: pathlib.PurePath + """ + return pathlib.PurePath() + + def __rtruediv__(self, key): + """ + :type key: string | pathlib.PurePath + :rtype: pathlib.PurePath + """ + return pathlib.PurePath() + + @property + def parts(self): + """ + :rtype: tuple[str] + """ + return () + + @property + def drive(self): + """ + :rtype: str + """ + return '' + + @property + def root(self): + """ + :rtype: str + """ + return '' + + @property + def anchor(self): + """ + :rtype: str + """ + return '' + + @property + def parent(self): + """ + :rtype: pathlib.PurePath | unknown + """ + return pathlib.PurePath() + + @property + def name(self): + """ + :rtype: str + """ + return '' + + @property + def suffix(self): + """ + :rtype: str + """ + return '' + + @property + def suffixes(self): + """ + :rtype: list[str] + """ + return [] + + @property + def stem(self): + """ + :rtype: str + """ + return '' + + def as_posix(self): + """ + :rtype: str + """ + return '' + + def as_uri(self): + """ + :rtype: str + """ + return '' + + def is_absolute(self): + """ + :rtype: bool + """ + return False + + def is_reserved(self): + """ + :rtype: bool + """ + return False + + def joinpath(self, *other): + """ + :rtype: pathlib.PurePath + """ + return pathlib.PurePath() + + def match(self, pattern): + """ + :type pattern: string + :rtype: bool + """ + return False + + def relative_to(self, *other): + """ + :rtype: pathlib.PurePath + """ + return pathlib.PurePath() + +class PurePosixPath(pathlib.PurePath): + pass + + +class PureWindowsPath(pathlib.PurePath): + pass + + +class Path(pathlib.PurePath): + def __new__(cls, *pathsegments): + """ + :rtype: pathlib.Path + """ + return cls.__new__(*pathsegments) + + def __truediv__(self, key): + """ + :type key: string | pathlib.Path + :rtype: pathlib.Path + """ + return pathlib.Path() + + def __rtruediv__(self, key): + """ + :type key: string | pathlib.Path + :rtype: pathlib.Path + """ + return pathlib.Path() + + @property + def parents(self): + """ + :rtype: collections.Sequence[pathlib.Path] + """ + return [] + + @property + def parent(self): + """ + :rtype: pathlib.Path + """ + return pathlib.Path() + + def joinpath(self, *other): + """ + :rtype: pathlib.Path + """ + return pathlib.Path() + + def relative_to(self, *other): + """ + :rtype: pathlib.Path + """ + return pathlib.Path() + + @classmethod + def cwd(cls): + """ + :rtype: pathlib.Path + """ + return pathlib.Path() + + def stat(self): + """ + :rtype: os.stat_result + """ + pass + + def chmod(self, mode): + """ + :rtype mode: int + :rtype: None + """ + pass + + def exists(self): + """ + :rtype: bool + """ + return False + + def glob(self, pattern): + """ + :type pattern: string + :rtype: collections.Iterable[pathlib.Path] + """ + return [] + + def group(self): + """ + :rtype: str + """ + return '' + + def is_dir(self): + """ + :rtype: bool + """ + return False + + def is_file(self): + """ + :rtype: bool + """ + return False + + def is_file(self): + """ + :rtype: bool + """ + return False + + def is_symlink(self): + """ + :rtype: bool + """ + return False + + def is_socket(self): + """ + :rtype: bool + """ + return False + + def is_fifo(self): + """ + :rtype: bool + """ + return False + + def is_block_device(self): + """ + :rtype: bool + """ + return False + + def is_char_device(self): + """ + :rtype: bool + """ + return False + + def iterdir(self): + """ + :rtype: collections.Iterable[pathlib.Path] + """ + return [] + + def lchmod(self, mode): + """ + :rtype mode: int + :rtype: None + """ + pass + + def lstat(self): + """ + :rtype: os.stat_result + """ + pass + + def mkdir(self, mode=0o777, parents=False): + """ + :type mode: int + :type parents: bool + :rtype: None + """ + pass + + def open(self, mode='r', buffering=-1, encoding=None, errors=None, + newline=None): + """ + :type mode: string + :type buffering: numbers.Integral + :type encoding: string | None + :type errors: string | None + :type newline: string | None + :rtype: io.FileIO[bytes] | io.TextIOWrapper[unicode] + """ + pass + + def owner(self): + """ + :rtype: str + """ + return '' + + def rename(self, target): + """ + :type target: string | pathlib.Path + :rtype: None + """ + pass + + def replace(self, target): + """ + :type target: string | pathlib.Path + :rtype: None + """ + pass + + def resolve(self): + """ + :rtype: pathlib.Path + """ + return pathlib.Path() + + def rglob(self, pattern): + """ + :type pattern: string + :rtype: collections.Iterable[pathlib.Path] + """ + return [] + + def rmdir(self): + """ + :rtype: None + """ + pass + + def symlink_to(self, target, target_is_directory=False): + """ + :type target: string | pathlib.Path + :type target_is_directory: bool + :rtype: None + """ + pass + + def touch(self, mode=0o777, exist_ok=True): + """ + :type mode: int + :type exist_ok: bool + :rtype: None + """ + pass + + def unlink(self): + """ + :rtype: None + """ + pass diff --git a/python/helpers/python-skeletons/pickle.py b/python/helpers/python-skeletons/pickle.py new file mode 100644 index 000000000000..38e5a47b1b3b --- /dev/null +++ b/python/helpers/python-skeletons/pickle.py @@ -0,0 +1,81 @@ +"""Skeleton for 'pickle' stdlib module.""" + + +HIGHEST_PROTOCOL = 0 +DEFAULT_PROTOCOL = 0 + + +def dump(obj, file, protocol=None, fix_imports=True): + """Write a pickled representation of obj to the open file object file. + + :type protocol: numbers.Integral | None + :rtype: None + """ + pass + + +def dumps(obj, protocol=None, fix_imports=True): + """Return the pickled representation of the object as a bytes object, + instead of writing it to a file. + + :type protocol: numbers.Integral | None + :rtype: bytes + """ + return b'' + + +def load(file, fix_imports=True, encoding='ASCII', errors='strict'): + """Read a pickled object representation from the open file object file and + return the reconstituted object hierarchy specified therein. + """ + pass + + +def loads(bytes_object, fix_imports=True, encoding='ASCII', errors='strict'): + """Read a pickled object representation from the open file object file and + return the reconstituted object hierarchy specified therein. + """ + pass + + +class PickleError(Exception): + pass + + +class PicklingError(PickleError): + pass + + +class UnpicklingError(PickleError): + pass + + +class Pickler(object): + """This takes a binary file for writing a pickle data stream.""" + + def __init__(self, file, protocol=None, fix_imports=True): + self.dispatch_table = None + self.fast = False + + def dump(self, obj): + pass + + def persistent_id(self, obj): + pass + + +class Unpickler(object): + """This takes a binary file for reading a pickle data stream.""" + + def __init__(self, file, fix_imports=True, encoding='ASCII', + errors='strict'): + pass + + def load(self): + pass + + def persistent_load(self, pid): + pass + + def find_class(self, module, name): + pass diff --git a/python/helpers/python-skeletons/re.py b/python/helpers/python-skeletons/re.py new file mode 100644 index 000000000000..151ddc9b7257 --- /dev/null +++ b/python/helpers/python-skeletons/re.py @@ -0,0 +1,277 @@ +"""Skeleton for 're' stdlib module.""" + + +def compile(pattern, flags=0): + """Compile a regular expression pattern, returning a pattern object. + + :type pattern: bytes | unicode + :type flags: int + :rtype: __Regex + """ + pass + + +def search(pattern, string, flags=0): + """Scan through string looking for a match, and return a corresponding + match instance. Return None if no position in the string matches. + + :type pattern: bytes | unicode | __Regex + :type string: T <= bytes | unicode + :type flags: int + :rtype: __Match[T] | None + """ + pass + + +def match(pattern, string, flags=0): + """Matches zero or more characters at the beginning of the string. + + :type pattern: bytes | unicode | __Regex + :type string: T <= bytes | unicode + :type flags: int + :rtype: __Match[T] | None + """ + pass + + +def split(pattern, string, maxsplit=0, flags=0): + """Split string by the occurrences of pattern. + + :type pattern: bytes | unicode | __Regex + :type string: T <= bytes | unicode + :type maxsplit: int + :type flags: int + :rtype: list[T] + """ + pass + + +def findall(pattern, string, flags=0): + """Return a list of all non-overlapping matches of pattern in string. + + :type pattern: bytes | unicode | __Regex + :type string: T <= bytes | unicode + :type flags: int + :rtype: list[T] + """ + pass + + +def finditer(pattern, string, flags=0): + """Return an iterator over all non-overlapping matches for the pattern in + string. For each match, the iterator returns a match object. + + :type pattern: bytes | unicode | __Regex + :type string: T <= bytes | unicode + :type flags: int + :rtype: collections.Iterable[__Match[T]] + """ + pass + + +def sub(pattern, repl, string, count=0, flags=0): + """Return the string obtained by replacing the leftmost non-overlapping + occurrences of pattern in string by the replacement repl. + + :type pattern: bytes | unicode | __Regex + :type repl: bytes | unicode | collections.Callable + :type string: T <= bytes | unicode + :type count: int + :type flags: int + :rtype: T + """ + pass + + +def subn(pattern, repl, string, count=0, flags=0): + """Return the tuple (new_string, number_of_subs_made) found by replacing + the leftmost non-overlapping occurrences of pattern with the + replacement repl. + + :type pattern: bytes | unicode | __Regex + :type repl: bytes | unicode | collections.Callable + :type string: T <= bytes | unicode + :type count: int + :type flags: int + :rtype: (T, int) + """ + pass + + +def escape(string): + """Escape all the characters in pattern except ASCII letters and numbers. + + :type string: T <= bytes | unicode + :type: T + """ + pass + + +class __Regex(object): + """Mock class for a regular expression pattern object.""" + + def __init__(self, flags, groups, groupindex, pattern): + """Create a new pattern object. + + :type flags: int + :type groups: int + :type groupindex: dict[bytes | unicode, int] + :type pattern: bytes | unicode + """ + self.flags = flags + self.groups = groups + self.groupindex = groupindex + self.pattern = pattern + + def search(self, string, pos=0, endpos=-1): + """Scan through string looking for a match, and return a corresponding + match instance. Return None if no position in the string matches. + + :type string: T <= bytes | unicode + :type pos: int + :type endpos: int + :rtype: __Match[T] | None + """ + pass + + def match(self, string, pos=0, endpos=-1): + """Matches zero | more characters at the beginning of the string. + + :type string: T <= bytes | unicode + :type pos: int + :type endpos: int + :rtype: __Match[T] | None + """ + pass + + def split(self, string, maxsplit=0): + """Split string by the occurrences of pattern. + + :type string: T <= bytes | unicode + :type maxsplit: int + :rtype: list[T] + """ + pass + + def findall(self, string, pos=0, endpos=-1): + """Return a list of all non-overlapping matches of pattern in string. + + :type string: T <= bytes | unicode + :type pos: int + :type endpos: int + :rtype: list[T] + """ + pass + + def finditer(self, string, pos=0, endpos=-1): + """Return an iterator over all non-overlapping matches for the + pattern in string. For each match, the iterator returns a + match object. + + :type string: T <= bytes | unicode + :type pos: int + :type endpos: int + :rtype: collections.Iterable[__Match[T]] + """ + pass + + def sub(self, repl, string, count=0): + """Return the string obtained by replacing the leftmost non-overlapping + occurrences of pattern in string by the replacement repl. + + :type repl: bytes | unicode | collections.Callable + :type string: T <= bytes | unicode + :type count: int + :rtype: T + """ + pass + + def subn(self, repl, string, count=0): + """Return the tuple (new_string, number_of_subs_made) found by replacing + the leftmost non-overlapping occurrences of pattern with the + replacement repl. + + :type repl: bytes | unicode | collections.Callable + :type string: T <= bytes | unicode + :type count: int + :rtype: (T, int) + """ + pass + + +class __Match(object): + """Mock class for a match object.""" + + def __init__(self, pos, endpos, lastindex, lastgroup, re, string): + """Create a new match object. + + :type pos: int + :type endpos: int + :type lastindex: int | None + :type lastgroup: int | bytes | unicode | None + :type re: __Regex + :type string: bytes | unicode + :rtype: __Match[T] + """ + self.pos = pos + self.endpos = endpos + self.lastindex = lastindex + self.lastgroup = lastgroup + self.re = re + self.string = string + + def expand(self, template): + """Return the string obtained by doing backslash substitution on the + template string template. + + :type template: T + :rtype: T + """ + pass + + def group(self, *args): + """Return one or more subgroups of the match. + + :rtype: T | tuple + """ + pass + + def groups(self, default=None): + """Return a tuple containing all the subgroups of the match, from 1 up + to however many groups are in the pattern. + + :rtype: tuple + """ + pass + + def groupdict(self, default=None): + """Return a dictionary containing all the named subgroups of the match, + keyed by the subgroup name. + + :rtype: dict[bytes | unicode, T] + """ + pass + + def start(self, group=0): + """Return the index of the start of the substring matched by group. + + :type group: int | bytes | unicode + :rtype: int + """ + pass + + def end(self, group=0): + """Return the index of the end of the substring matched by group. + + :type group: int | bytes | unicode + :rtype: int + """ + pass + + def span(self, group=0): + """Return a 2-tuple (start, end) for the substring matched by group. + + :type group: int | bytes | unicode + :rtype: (int, int) + """ + pass diff --git a/python/helpers/python-skeletons/shutil.py b/python/helpers/python-skeletons/shutil.py new file mode 100644 index 000000000000..9ee3c130c06c --- /dev/null +++ b/python/helpers/python-skeletons/shutil.py @@ -0,0 +1,99 @@ +"""Skeleton for 'shutil' stdlib module.""" + + +import sys + + +def copyfile(src, dst): + """Copy the contents (no metadata) of the file named src to a file named + dst. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def copymode(src, dst): + """Copy the permission bits from src to dst. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def copystat(src, dst): + """Copy the permission bits, last access time, last modification time, and + flags from src to dst. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def copy(src, dst): + """Copy the file src to the file or directory dst. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def copy2(src, dst): + """Similar to shutil.copy(), but metadata is copied as well. + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass + + +def ignore_patterns(*patterns): + """This factory function creates a function that can be used as a callable + for copytree()'s ignore argument, ignoring files and directories that match + one of the glob-style patterns provided. + + :type patterns: collections.Iterable[bytes | unicode] + :rtype: (bytes | unicode, list[bytes | unicode]) -> collections.Iterable[bytes | unicode] + """ + return lambda path, files: [] + + +def copytree(src, dst, symlinks=False, ignore=None): + """Recursively copy an entire directory tree rooted at src. + + :type src: bytes | unicode + :type dst: bytes | unicode + :type symlinks: bool + :type ignore: ((bytes | unicode, list[bytes | unicode]) -> collections.Iterable[bytes | unicode]) | None + :rtype: None + """ + pass + + +def rmtree(path, ignore_errors=False, onerror=None): + """Delete an entire directory tree. + + :type path: bytes | unicode + :type ignore_errors: bool + :type onerror: (unknown, bytes | unicode, unknown) -> None + :rtype: None + """ + + +def move(src, dst): + """Recursively move a file or directory (src) to another location (dst). + + :type src: bytes | unicode + :type dst: bytes | unicode + :rtype: None + """ + pass diff --git a/python/helpers/python-skeletons/sqlite3.py b/python/helpers/python-skeletons/sqlite3.py new file mode 100644 index 000000000000..c60baed6598f --- /dev/null +++ b/python/helpers/python-skeletons/sqlite3.py @@ -0,0 +1,190 @@ +"""Skeleton for 'sqlite3' stdlib module.""" + + +import sqlite3 + + +def connect(database, timeout=5.0, detect_types=0, isolation_level=None, + check_same_thread=False, factory=None, cached_statements=100): + """Opens a connection to the SQLite database file database. + + :type database: bytes | unicode + :type timeout: float + :type detect_types: int + :type isolation_level: string | None + :type check_same_thread: bool + :type factory: (() -> sqlite3.Connection) | None + :rtype: sqlite3.Connection + """ + return sqlite3.Connection() + + +def register_converter(typename, callable): + """Registers a callable to convert a bytestring from the database into a + custom Python type. + + :type typename: string + :type callable: (bytes) -> unknown + :rtype: None + """ + pass + + +def register_adapter(type, callable): + """Registers a callable to convert the custom Python type type into one of + SQLite's supported types. + + :type type: type + :type callable: (unknown) -> unknown + :rtype: None + """ + pass + + +def complete_statement(sql): + """Returns True if the string sql contains one or more complete SQL + statements terminated by semicolons. + + :type sql: string + :rtype: bool + """ + return False + + +def enable_callback_tracebacks(flag): + """By default you will not get any tracebacks in user-defined functions, + aggregates, converters, authorizer callbacks etc. + + :type flag: bool + :rtype: None + """ + pass + + +class Connection(object): + """A SQLite database connection.""" + + def cursor(self, cursorClass=None): + """ + :type cursorClass: type | None + :rtype: sqlite3.Cursor + """ + return sqlite3.Cursor() + + def execute(self, sql, parameters=()): + """This is a nonstandard shortcut that creates an intermediate cursor + object by calling the cursor method, then calls the cursor's execute + method with the parameters given. + + :type sql: string + :type parameters: collections.Iterable + :rtype: sqlite3.Cursor + """ + pass + + def executemany(self, sql, seq_of_parameters=()): + """This is a nonstandard shortcut that creates an intermediate cursor + object by calling the cursor method, then calls the cursor's + executemany method with the parameters given. + + :type sql: string + :type seq_of_parameters: collections.Iterable[collections.Iterable] + :rtype: sqlite3.Cursor + """ + pass + + def executescript(self, sql_script): + """This is a nonstandard shortcut that creates an intermediate cursor + object by calling the cursor method, then calls the cursor's + executescript method with the parameters given. + + :type sql_script: bytes | unicode + :rtype: sqlite3.Cursor + """ + pass + + def create_function(self, name, num_params, func): + """Creates a user-defined function that you can later use from within + SQL statements under the function name name. + + :type name: string + :type num_params: int + :type func: collections.Callable + :rtype: None + """ + pass + + + def create_aggregate(self, name, num_params, aggregate_class): + """Creates a user-defined aggregate function. + + :type name: string + :type num_params: int + :type aggregate_class: type + :rtype: None + """ + pass + + def create_collation(self, name, callable): + """Creates a collation with the specified name and callable. + + :type name: string + :type callable: collections.Callable + :rtype: None + """ + pass + + +class Cursor(object): + """A SQLite database cursor.""" + + def execute(self, sql, parameters=()): + """Executes an SQL statement. + + :type sql: string + :type parameters: collections.Iterable + :rtype: sqlite3.Cursor + """ + pass + + def executemany(self, sql, seq_of_parameters=()): + """Executes an SQL command against all parameter sequences or mappings + found in the sequence. + + :type sql: string + :type seq_of_parameters: collections.Iterable[collections.Iterable] + :rtype: sqlite3.Cursor + """ + pass + + def executescript(self, sql_script): + """This is a nonstandard convenience method for executing multiple SQL + statements at once. + + :type sql_script: bytes | unicode + :rtype: sqlite3.Cursor + """ + pass + + def fetchone(self): + """Fetches the next row of a query result set, returning a single + sequence, or None when no more data is available. + + :rtype: tuple | None + """ + pass + + def fetchmany(self, size=-1): + """Fetches the next set of rows of a query result, returning a list. + + :type size: numbers.Integral + :rtype: list[tuple] + """ + return [] + + def fetchall(self): + """Fetches all (remaining) rows of a query result, returning a list. + + :rtype: list[tuple] + """ + return [] diff --git a/python/helpers/python-skeletons/struct.py b/python/helpers/python-skeletons/struct.py new file mode 100644 index 000000000000..1891d96a5e7a --- /dev/null +++ b/python/helpers/python-skeletons/struct.py @@ -0,0 +1,106 @@ +"""Skeleton for 'struct' stdlib module.""" + + +from __future__ import unicode_literals +import sys + + +def pack(fmt, *values): + """Return a string containing the values packed according to the given + format. + + :type fmt: bytes | unicode + :rtype: bytes + """ + return b'' + + +def unpack(fmt, string): + """Unpack the string according to the given format. + + :type fmt: bytes | unicode + :type string: bytestring + :rtype: tuple + """ + pass + + +def pack_into(fmt, buffer, offset, *values): + """"Pack the values according to the given format, write the packed + bytes into the writable buffer starting at offset. + + :type fmt: bytes | unicode + :type offset: int | long + :rtype: bytes + """ + return b'' + +def unpack_from(fmt, buffer, offset=0): + """Unpack the buffer according to the given format. + + :type fmt: bytes | unicode + :type offset: int | long + :rtype: tuple + """ + pass + + +def calcsize(fmt): + """Return the size of the struct (and hence of the string) corresponding to + the given format. + + :type fmt: bytes | unicode + :rtype: int + """ + return 0 + + +class Struct(object): + """Struct object which writes and reads binary data according to the format + string. + + :param format: The format string used to construct this Struct object. + :type format: bytes | unicode + + :param size: The calculated size of the struct corresponding to format. + :type size: int + """ + + def __init__(self, format): + """Create a new Struct object. + + :type format: bytes | unicode + """ + self.format = format + self.size = 0 + + def pack(self, *values): + """Identical to the pack() function, using the compiled format. + + :rtype: bytes + """ + return b'' + + def pack_into(self, buffer, offset, *values): + """Identical to the pack_into() function, using the compiled format. + + :type offset: int | long + :rtype: bytes + """ + return b'' + + def unpack(self, string): + """Identical to the unpack() function, using the compiled format. + + :type string: bytestring + :rtype: tuple + """ + pass + + def unpack_from(self, buffer, offset=0): + """Identical to the unpack_from() function, using the compiled format. + + :type offset: int | long + :rtype: tuple + """ + pass diff --git a/python/helpers/python-skeletons/subprocess.py b/python/helpers/python-skeletons/subprocess.py new file mode 100644 index 000000000000..aa3af255d4a2 --- /dev/null +++ b/python/helpers/python-skeletons/subprocess.py @@ -0,0 +1,140 @@ +"""Skeleton for 'subprocess' stdlib module.""" + + +def call(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, + universal_newlines=False, startupinfo=None, creationflags=0, + timeout=None, restore_signals=True, start_new_session=False, + pass_fds=()): + """Run the command described by args. + + :type args: collections.Iterable[bytes | unicode] + :type bufsize: int + :type executable: bytes | unicode | None + :type close_fds: bool + :type shell: bool + :type cwd: bytes | unicode | None + :type env: collections.Mapping | None + :type universal_newlines: bool + :type creationflags: int + :rtype: int + """ + return 0 + + +def check_call(args, bufsize=0, executable=None, stdin=None, stdout=None, + stderr=None, preexec_fn=None, close_fds=False, shell=False, + cwd=None, env=None, universal_newlines=False, startupinfo=None, + creationflags=0, timeout=None, restore_signals=True, + start_new_session=False, pass_fds=()): + """Run command with arguments. Wait for command to complete. If the return + code was zero then return, otherwise raise CalledProcessError. + + :type args: collections.Iterable[bytes | unicode] + :type bufsize: int + :type executable: bytes | unicode | None + :type close_fds: bool + :type shell: bool + :type cwd: bytes | unicode | None + :type env: collections.Mapping | None + :type universal_newlines: bool + :type creationflags: int + :rtype: int + """ + return 0 + + +def check_output(args, bufsize=0, executable=None, stdin=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, cwd=None, + env=None, universal_newlines=False, startupinfo=None, + creationflags=0, timeout=None, restore_signals=True, + start_new_session=False, pass_fds=()): + """Run command with arguments and return its output as a byte string. + + :type args: collections.Iterable[bytes | unicode] + :type bufsize: int + :type executable: bytes | unicode | None + :type close_fds: bool + :type shell: bool + :type cwd: bytes | unicode | None + :type env: collections.Mapping | None + :type universal_newlines: bool + :type creationflags: int + :rtype: bytes + """ + pass + + +class Popen(object): + """Execute a child program in a new process. + + :type returncode: int + """ + + def __init__(self, args, bufsize=0, executable=None, stdin=None, + stdout=None, stderr=None, preexec_fn=None, close_fds=False, + shell=False, cwd=None, env=None, universal_newlines=False, + startupinfo=None, creationflags=0, timeout=None, + restore_signals=True, start_new_session=False, pass_fds=()): + """Popen constructor. + + :type args: collections.Iterable[bytes | unicode] + :type bufsize: int + :type executable: bytes | unicode | None + :type close_fds: bool + :type shell: bool + :type cwd: bytes | unicode | None + :type env: collections.Mapping | None + :type universal_newlines: bool + :type creationflags: int + """ + self.stdin = stdin + self.stdout = stdout + self.stderr = stderr + self.pid = 0 + self.returncode = 0 + + def poll(self): + """Check if child process has terminated. + + :rtype: int + """ + return 0 + + def wait(self, timeout=None): + """Wait for child process to terminate. + + :rtype: int + """ + return 0 + + def communicate(self, input=None, timeout=None): + """Interact with process: Send data to stdin. Read data from stdout and + stderr, until end-of-file is reached. + + :type input: bytes | unicode | None + :rtype: (bytes, bytes) + """ + return b'', b'' + + def send_signal(self, signal): + """Sends the signal signal to the child. + + :type signal: int + :rtype: None + """ + pass + + def terminate(self): + """Stop the child. + + :rtype: None + """ + pass + + def kill(self): + """Kills the child. + + :rtype: None + """ + pass From 444dce0373904fd14a6765c19ee651a33318bebe Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Tue, 7 Oct 2014 17:41:39 +0400 Subject: [PATCH 24/26] a fix for completion from non-primary caret (IDEA-123396) --- ...MulticaretCompletionFromNonPrimaryCaretWithTab.java | 4 ++++ ...aretCompletionFromNonPrimaryCaretWithTab_after.java | 4 ++++ .../codeInsight/completion/NormalCompletionTest.groovy | 4 ++++ .../completion/CompletionInitializationContext.java | 10 +++++++++- .../completion/CodeCompletionHandlerBase.java | 7 ++++--- .../completion/CompletionProgressIndicator.java | 10 ++++++++++ 6 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab.java create mode 100644 java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab_after.java diff --git a/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab.java b/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab.java new file mode 100644 index 000000000000..6b63d4ade364 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab.java @@ -0,0 +1,4 @@ +class Foo {{ + blah + // blah +}} diff --git a/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab_after.java b/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab_after.java new file mode 100644 index 000000000000..74b8e61afb4d --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normal/MulticaretCompletionFromNonPrimaryCaretWithTab_after.java @@ -0,0 +1,4 @@ +class Foo {{ + return + // return +}} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy index f5fc39041106..3391bb407e43 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy @@ -1428,6 +1428,10 @@ class XInternalError {} myFixture.assertPreferredCompletionItems(0, "arraycopy") } + public void testMulticaretCompletionFromNonPrimaryCaretWithTab() { + doTest '\t' + } + public void "test complete lowercase class name"() { myFixture.addClass("package foo; public class myClass {}") myFixture.configureByText "a.java", """ diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionInitializationContext.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionInitializationContext.java index 2c152b595421..a932262a5c7e 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionInitializationContext.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionInitializationContext.java @@ -39,14 +39,17 @@ public class CompletionInitializationContext { public static @NonNls final String DUMMY_IDENTIFIER = CompletionUtilCore.DUMMY_IDENTIFIER; public static @NonNls final String DUMMY_IDENTIFIER_TRIMMED = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED; private final Editor myEditor; + @NotNull + private final Caret myCaret; private final PsiFile myFile; private final CompletionType myCompletionType; private final int myInvocationCount; private final OffsetMap myOffsetMap; private String myDummyIdentifier = DUMMY_IDENTIFIER; - public CompletionInitializationContext(final Editor editor, final Caret caret, final PsiFile file, final CompletionType completionType, int invocationCount) { + public CompletionInitializationContext(final Editor editor, final @NotNull Caret caret, final PsiFile file, final CompletionType completionType, int invocationCount) { myEditor = editor; + myCaret = caret; myFile = file; myCompletionType = completionType; myInvocationCount = invocationCount; @@ -92,6 +95,11 @@ public class CompletionInitializationContext { return myEditor; } + @NotNull + public Caret getCaret() { + return myCaret; + } + @NotNull public CompletionType getCompletionType() { return myCompletionType; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 507578a566f2..397d30993ac9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -193,7 +193,7 @@ public class CodeCompletionHandlerBase { insertDummyIdentifier(initializationContext[0], hasModifiers, invocationCount); } - private CompletionInitializationContext runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, Caret caret) { + private CompletionInitializationContext runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, @NotNull Caret caret) { final Ref current = Ref.create(null); CompletionInitializationContext context = new CompletionInitializationContext(editor, caret, psiFile, myCompletionType, invocationCount) { CompletionContributor dummyIdentifierChanger; @@ -296,7 +296,8 @@ public class CodeCompletionHandlerBase { final Semaphore freezeSemaphore = new Semaphore(); freezeSemaphore.down(); - final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, parameters, this, freezeSemaphore, + final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, initContext.getCaret(), + parameters, this, freezeSemaphore, initContext.getOffsetMap(), hasModifiers, lookup); Disposer.register(indicator, hostMap); Disposer.register(indicator, context.getOffsetMap()); @@ -602,7 +603,7 @@ public class CodeCompletionHandlerBase { final CompletionLookupArranger.StatisticsUpdate update) { final Editor editor = indicator.getEditor(); - final int caretOffset = editor.getCaretModel().getOffset(); + final int caretOffset = indicator.getCaret().getOffset(); int idEndOffset = indicator.getIdentifierEndOffset(); if (idEndOffset < 0) { idEndOffset = CompletionInitializationContext.calcDefaultIdentifierEnd(editor, caretOffset); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index 68da01327408..4b5b7b5c90e9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -39,6 +39,7 @@ import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; @@ -88,6 +89,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; public class CompletionProgressIndicator extends ProgressIndicatorBase implements CompletionProcess, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionProgressIndicator"); private final Editor myEditor; + @NotNull + private final Caret myCaret; private final CompletionParameters myParameters; private final CodeCompletionHandlerBase myHandler; private final LookupImpl myLookup; @@ -132,6 +135,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private final int myStartCaret; public CompletionProgressIndicator(final Editor editor, + @NotNull Caret caret, CompletionParameters parameters, CodeCompletionHandlerBase handler, Semaphore freezeSemaphore, @@ -139,6 +143,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement boolean hasModifiers, LookupImpl lookup) { myEditor = editor; + myCaret = caret; myParameters = parameters; myHandler = handler; myFreezeSemaphore = freezeSemaphore; @@ -575,6 +580,11 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement return myEditor; } + @NotNull + public Caret getCaret() { + return myCaret; + } + public boolean isRepeatedInvocation(CompletionType completionType, Editor editor) { if (completionType != myParameters.getCompletionType() || editor != myEditor) { return false; From 887cdc399f5f16827ea4262a3d2a5c24353434f1 Mon Sep 17 00:00:00 2001 From: "Vladislav.Soroka" Date: Tue, 7 Oct 2014 17:42:20 +0400 Subject: [PATCH 25/26] external system: release remote processes of communication manager during the component disposing --- .../RemoteExternalSystemCommunicationManager.java | 8 +++++++- .../service/project/manage/ProjectDataManager.java | 10 ++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java index 83d2359ff498..2d8d1176eadc 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java @@ -30,6 +30,7 @@ import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.rmi.RemoteProcessSupport; import com.intellij.execution.runners.ProgramRunner; +import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.impl.stores.StorageUtil; @@ -72,7 +73,7 @@ import java.util.concurrent.atomic.AtomicReference; * @author Denis Zhdanov * @since 8/9/13 3:37 PM */ -public class RemoteExternalSystemCommunicationManager implements ExternalSystemCommunicationManager { +public class RemoteExternalSystemCommunicationManager implements ExternalSystemCommunicationManager, Disposable { private static final Logger LOG = Logger.getInstance("#" + RemoteExternalSystemCommunicationManager.class.getName()); @@ -265,4 +266,9 @@ public class RemoteExternalSystemCommunicationManager implements ExternalSystemC public void clear() { mySupport.stopAll(true); } + + @Override + public void dispose() { + shutdown(false); + } } diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataManager.java index 2c8e10a0d7e9..7f638bbaa5a1 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataManager.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataManager.java @@ -86,6 +86,8 @@ public class ProjectDataManager { @SuppressWarnings("unchecked") public void importData(@NotNull Collection> nodes, @NotNull Project project, boolean synchronous) { + if(project.isDisposed()) return; + Map, List>> grouped = ExternalSystemApiUtil.group(nodes); for (Map.Entry, List>> entry : grouped.entrySet()) { // Simple class cast makes ide happy but compiler fails. @@ -99,6 +101,8 @@ public class ProjectDataManager { @SuppressWarnings("unchecked") public void importData(@NotNull Key key, @NotNull Collection> nodes, @NotNull Project project, boolean synchronous) { + if(project.isDisposed()) return; + ensureTheDataIsReadyToUse(nodes); List> services = myServices.getValue().get(key); if (services == null) { @@ -148,11 +152,13 @@ public class ProjectDataManager { } public void updateExternalProjectData(@NotNull Project project, @NotNull ExternalProjectInfo externalProjectInfo) { - ExternalProjectsDataStorage.getInstance(project).add(externalProjectInfo); + if(!project.isDisposed()) { + ExternalProjectsDataStorage.getInstance(project).add(externalProjectInfo); + } } @Nullable public ExternalProjectInfo getExternalProjectData(@NotNull Project project, @NotNull ProjectSystemId projectSystemId, @NotNull String externalProjectPath) { - return ExternalProjectsDataStorage.getInstance(project).get(projectSystemId, externalProjectPath); + return !project.isDisposed() ? ExternalProjectsDataStorage.getInstance(project).get(projectSystemId, externalProjectPath) : null; } } From 7011529ec5c1720e49a42d3bb64e532b8ec9ad67 Mon Sep 17 00:00:00 2001 From: "Vladislav.Soroka" Date: Tue, 7 Oct 2014 17:56:55 +0400 Subject: [PATCH 26/26] gradle: gradle daemon jvm arguments changed + tests diagnostic --- .../project/GradleExecutionHelper.java | 8 ++++++- .../importing/GradleImportingTestCase.java | 3 ++- .../builder/AbstractModelBuilderTest.java | 21 ++++++++++++------- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java index cc5e5c52c38b..19337a39a90c 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java @@ -152,6 +152,12 @@ public class GradleExecutionHelper { commandLineArgs.add(GradleConstants.OFFLINE_MODE_CMD_OPTION); } + final Application application = ApplicationManager.getApplication(); + if(application != null && application.isUnitTestMode()) { + commandLineArgs.add("--info"); + commandLineArgs.add("--recompile-scripts"); + } + if (!commandLineArgs.isEmpty()) { LOG.info("Passing command-line args to Gradle Tooling API: " + commandLineArgs); // filter nulls and empty strings @@ -224,7 +230,7 @@ public class GradleExecutionHelper { } } catch (Throwable e) { - // ignore + LOG.debug("Gradle connection close error", e); } } } diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleImportingTestCase.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleImportingTestCase.java index 2cf4c7125918..c655f96344a7 100644 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleImportingTestCase.java +++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleImportingTestCase.java @@ -30,9 +30,9 @@ import org.gradle.wrapper.GradleWrapperMain; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.gradle.remote.GradleJavaHelper; import org.jetbrains.plugins.gradle.settings.DistributionType; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; +import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleConstants; import org.junit.Rule; import org.junit.rules.TestName; @@ -73,6 +73,7 @@ public abstract class GradleImportingTestCase extends ExternalSystemImportingTes public void setUp() throws Exception { super.setUp(); myProjectSettings = new GradleProjectSettings(); + GradleSettings.getInstance(myProject).setGradleVmOptions("-Xmx64m -XX:MaxPermSize=64m"); System.setProperty(ExternalSystemExecutionSettings.REMOTE_PROCESS_IDLE_TTL_IN_MS_KEY, String.valueOf(GRADLE_DAEMON_TTL_MS)); configureWrapper(); } diff --git a/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java index 3874bd2cab04..f556d474bba7 100644 --- a/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java +++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java @@ -123,14 +123,19 @@ public abstract class AbstractModelBuilderTest { ((DefaultGradleConnector)connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS); ProjectConnection connection = connector.connect(); - final ProjectImportAction projectImportAction = new ProjectImportAction(false); - projectImportAction.addExtraProjectModelClasses(getModels()); - BuildActionExecuter buildActionExecutor = connection.action(projectImportAction); - File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses()); - assertNotNull(initScript); - buildActionExecutor.withArguments("--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath()); - allModels = buildActionExecutor.run(); - assertNotNull(allModels); + try { + final ProjectImportAction projectImportAction = new ProjectImportAction(false); + projectImportAction.addExtraProjectModelClasses(getModels()); + BuildActionExecuter buildActionExecutor = connection.action(projectImportAction); + File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses()); + assertNotNull(initScript); + buildActionExecutor.setJvmArguments("-Xmx64m", "-XX:MaxPermSize=64m"); + buildActionExecutor.withArguments("--info", "--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath()); + allModels = buildActionExecutor.run(); + assertNotNull(allModels); + } finally { + connection.close(); + } } @NotNull