Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|> help=("Stop the script after successfully retrieving one pair of "
"credentials"),
action='store_true')
parser.add_argument(
"-lC",
"--lure10-capture",
help=("Capture the BSSIDs of the APs that are discovered during "
"AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
"-lE",
"--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
parser.add_argument(
<|code_end|>
. Use current file imports:
(import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC))
and context including class names, function names, or small code snippets from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "-cP", |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# pylint: skip-file
logger = logging.getLogger(__name__)
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
# Interface selection
parser.add_argument(
"-i",
"--interface",
help=("Manually choose an interface that supports both AP and monitor " +
"modes for spawning the rogue AP as well as mounting additional " +
"Wi-Fi attacks from Extensions (i.e. deauth). " +
"Example: -i wlan1"))
parser.add_argument(
"-eI",
"--extensionsinterface",
help=("Manually choose an interface that supports monitor mode for " +
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context including class names, function names, and sometimes code from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "deauthenticating the victims. " + "Example: -eI wlan1")) |
Continue the code snippet: <|code_start|>def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
# Interface selection
parser.add_argument(
"-i",
"--interface",
help=("Manually choose an interface that supports both AP and monitor " +
"modes for spawning the rogue AP as well as mounting additional " +
"Wi-Fi attacks from Extensions (i.e. deauth). " +
"Example: -i wlan1"))
parser.add_argument(
"-eI",
"--extensionsinterface",
help=("Manually choose an interface that supports monitor mode for " +
"deauthenticating the victims. " + "Example: -eI wlan1"))
parser.add_argument(
"-aI",
"--apinterface",
type=opmode.validate_ap_interface,
help=("Manually choose an interface that supports AP mode for " +
"spawning the rogue AP. " + "Example: -aI wlan0"))
parser.add_argument(
"-iI",
"--internetinterface",
help=("Choose an interface that is connected on the Internet" +
"Example: -iI ppp0"))
parser.add_argument(
"-pI",
<|code_end|>
. Use current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (classes, functions, or code) from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "--protectinterface", |
Given snippet: <|code_start|>
logger = logging.getLogger(__name__)
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
# Interface selection
parser.add_argument(
"-i",
"--interface",
help=("Manually choose an interface that supports both AP and monitor " +
"modes for spawning the rogue AP as well as mounting additional " +
"Wi-Fi attacks from Extensions (i.e. deauth). " +
"Example: -i wlan1"))
parser.add_argument(
"-eI",
"--extensionsinterface",
help=("Manually choose an interface that supports monitor mode for " +
"deauthenticating the victims. " + "Example: -eI wlan1"))
parser.add_argument(
"-aI",
"--apinterface",
type=opmode.validate_ap_interface,
help=("Manually choose an interface that supports AP mode for " +
"spawning the rogue AP. " + "Example: -aI wlan0"))
parser.add_argument(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
which might include code, classes, or functions. Output only the next line. | "-iI", |
Predict the next line after this snippet: <|code_start|> "-nD",
"--nodeauth",
help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
type=int,
help=("Channels to deauth. " +
"Example: --deauth-channels 1,3,7"))
parser.add_argument(
"-e",
"--essid",
help=("Enter the ESSID of the rogue Access Point. " +
"This option will skip Access Point selection phase. " +
"Example: --essid 'Free WiFi'"))
parser.add_argument(
"-dE",
"--deauth-essid",
help=("Deauth all the BSSIDs in the WLAN with that ESSID."))
parser.add_argument(
"-p",
"--phishingscenario",
help=("Choose the phishing scenario to run." +
"This option will skip the scenario selection phase. " +
"Example: -p firmware_upgrade"))
parser.add_argument(
"-pK",
"--presharedkey",
<|code_end|>
using the current file's imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and any relevant context from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help=("Add WPA/WPA2 protection on the rogue Access Point. " + |
Continue the code snippet: <|code_start|> help=("Add WPA/WPA2 protection on the rogue Access Point. " +
"Example: -pK s3cr3tp4ssw0rd"))
parser.add_argument(
"-hC",
"--handshake-capture",
help=("Capture of the WPA/WPA2 handshakes for verifying passphrase. " +
"Requires cowpatty. " +
"Example : -hC capture.pcap"))
parser.add_argument(
"-qS",
"--quitonsuccess",
help=("Stop the script after successfully retrieving one pair of "
"credentials"),
action='store_true')
parser.add_argument(
"-lC",
"--lure10-capture",
help=("Capture the BSSIDs of the APs that are discovered during "
"AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
"-lE",
"--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
<|code_end|>
. Use current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (classes, functions, or code) from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | parser.add_argument( |
Predict the next line for this snippet: <|code_start|> help="Determine the full path of the file that will store any captured credentials",
default=None)
parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
parser.add_argument("-cM", "--channel-monitor",
help="Monitor if target access point changes the channel.",
action="store_true")
parser.add_argument("-wP", "--wps-pbc",
help="Monitor if the button on a WPS-PBC Registrar is pressed.",
action="store_true")
parser.add_argument("-wAI", "--wpspbc-assoc-interface",
help="The WLAN interface used for associating to the WPS AccessPoint.",
)
parser.add_argument(
"-kB",
"--known-beacons",
help="Broadcast a number of beacon frames advertising popular WLANs",
action='store_true')
parser.add_argument(
"-fH",
"--force-hostapd",
help="Force the usage of hostapd installed in the system",
action='store_true')
parser.add_argument("-pPD",
"--phishing-pages-directory",
help="Search for phishing pages in this location")
parser.add_argument(
"--dnsmasq-conf",
help="Determine the full path of a custom dnmasq.conf file",
<|code_end|>
with the help of current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
, which may contain function names, class names, or code. Output only the next line. | default='/tmp/dnsmasq.conf') |
Next line prediction: <|code_start|> "--mac-ap-interface",
help=("Specify the MAC address of the AP interface"))
parser.add_argument(
"-iEM",
"--mac-extensions-interface",
help=("Specify the MAC address of the extensions interface"))
parser.add_argument(
"-iNM",
"--no-mac-randomization",
help=("Do not change any MAC address"),
action='store_true')
parser.add_argument(
"-kN",
"--keepnetworkmanager",
action='store_true',
help=("Do not kill NetworkManager"))
parser.add_argument(
"-nE",
"--noextensions",
help=("Do not load any extensions."),
action='store_true')
parser.add_argument(
"-nD",
"--nodeauth",
help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
<|code_end|>
. Use current file imports:
(import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC))
and context including class names, function names, or small code snippets from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | type=int, |
Predict the next line for this snippet: <|code_start|>
class TestConditionals(object):
"""
"""
def test_not_num1(self):
ret = codetest("""
return not 1
""")
assert ret.getval() == 1
def test_not_num2(self):
ret = codetest("""
<|code_end|>
with the help of current file imports:
from .helpers import codetest
and context from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
, which may contain function names, class names, or code. Output only the next line. | return not 2 |
Given the following code snippet before the placeholder: <|code_start|> tests for the lua if then else and various comparisons
"""
def test_simple_repeat(self):
ret = codetest("""
x = 0
repeat
x = x + 1
until x == 10
return x
""")
assert ret.getval() == 10
def test_simple_repeat_false(self):
ret = codetest("""
x = 99
repeat
x = x + 1
until x > 0
return x
""")
assert ret.getval() == 100
def test_nested_repeat(self):
ret = codetest("""
i = 0
x = 0
repeat
i = i + 1
x = x + 1
<|code_end|>
, predict the next line using imports from the current file:
from .helpers import codetest
and context including class names, function names, and sometimes code from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | j = 5 |
Given the following code snippet before the placeholder: <|code_start|> x = 0
for i=1,10,1 do
x = x + 1
for i=11,15,1 do
x = x + 2
end
end
return x
""")
assert ret.getval() == 110
def test_backwards_fori_loop(self):
ret = codetest("""
x = 0
for i=10,1,-1 do
x = x + 1
end
return x
""")
assert ret.getval() == 10
def test_nested_backwards_fori_loop(self):
ret = codetest("""
x = 0
for i=10,1,-1 do
x = x + 1
for i=11,15,1 do
x = x + 2
end
end
<|code_end|>
, predict the next line using imports from the current file:
from .helpers import codetest
and context including class names, function names, and sometimes code from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | return x |
Given the code snippet: <|code_start|>
def test_addition(self):
f = test_file(src="""
-- short add
x = 10
y = 5
z = y + y + x
print(z)
print(z+y)
--a = 100+y
lx = 1234567890.55
ly = 99999999
print(lx+ly)
--print(lx+1234567890)
""", suffix=".l"
)
out = subprocess.check_output([TestCompiled.PYLUA_BIN, f.name])
assert out == "20\n25\n1334567889.550000\n"
def test_if_with_num(self):
f = test_file(src="""
x = 10
y = 5
if x == 10 then
print ("OK1")
end
if x ~= 10 then
print ("F1")
<|code_end|>
, generate the next line using the imports in this file:
import os
import subprocess
from luna.tests.helpers import test_file
and context (functions, classes, or occasionally code) from other files:
# Path: luna/tests/helpers.py
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | end |
Predict the next line after this snippet: <|code_start|>
class TestPattern2(object):
def test_single_char_no_match(self):
expr = StateChar('c', StateMatch())
result = find2(expr, 'xyz', 0)
assert list(result) == [(-1, -1)]
def test_single_char_one_match(self):
expr = StateChar('c', StateMatch())
result = find2(expr, 'asdasdxcz', 0)
assert list(result) == [(8, 8)]
def test_single_char_more_matches(self):
expr = StateChar('c', StateMatch())
result = find2(expr, 'xyzaaaccaa', 0)
assert list(result) == [(7, 7), (8, 8)]
<|code_end|>
using the current file's imports:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and any relevant context from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
. Output only the next line. | def test_two_chars_no_matches(self): |
Given the following code snippet before the placeholder: <|code_start|> def test_match_evil(self):
expr = compile_re('(a|b)*a(a|b){5}a(a|b)*')
result = find2(expr, 'aaaababababba', 0)
assert list(result) == [(1, 13)]
def test_match_evil_no_match(self):
expr = compile_re('(a|b)*a(a|b){5}a(a|b)*')
result = find2(expr, 'aaaaaaxbbbbaaaaabbbbbbb', 0)
assert list(result) == [(-1, -1)]
def test_single_char_build_expr(self):
expr = compile_re('a')
assert isinstance(expr, StateChar)
assert expr.start == ord('a')
assert expr.stop == ord('a')
def test_two_chars_build_expr(self):
expr = compile_re('ab')
assert isinstance(expr, StateChar)
assert expr.start == ord('a')
assert isinstance(expr.out, StateChar)
assert expr.out.start == ord('b')
def test_three_chars_build_expr(self):
expr = compile_re('abc')
assert isinstance(expr, StateChar)
assert expr.start == ord('a')
assert isinstance(expr.out, StateChar)
assert expr.out.start == ord('b')
assert isinstance(expr.out.out, StateChar)
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and context including class names, function names, and sometimes code from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
. Output only the next line. | assert expr.out.out.start == ord('c') |
Given snippet: <|code_start|> # %a*
node = node.out
assert isinstance(node, StateSplit)
assert isinstance(node.out, StateCharRange)
assert node.out.start == ord('A')
assert node.out.stop == ord('z')
assert node.out.out == node
# match
node = node.out2
assert isinstance(node, StateMatch)
def test_build_expr_simple_or(self):
expr = compile_re('a|b', False)
# |
assert isinstance(expr, StateSplit)
# a
node = expr.out
assert isinstance(node, StateChar)
assert node.stop == ord('a')
assert isinstance(node.out, StateMatch)
# b
node = expr.out2
assert isinstance(node, StateChar)
assert node.stop == ord('b')
assert isinstance(node.out, StateMatch)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and context:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
which might include code, classes, or functions. Output only the next line. | def test_build_group_star(self): |
Predict the next line for this snippet: <|code_start|> def test_two_chars_one_match(self):
expr = StateChar('a', StateChar('b', StateMatch()))
result = find2(expr, 'ccvvvbbajbajbabb', 0)
assert list(result) == [(14, 15)]
def tests_find_two_chars_matches(self):
expr = StateChar('a', StateChar('b', StateMatch()))
result = find2(expr, 'baaaabbacaabbcc', 0)
assert list(result) == [(5, 6), (11, 12)]
def test_three_chars_no_matches(self):
expr = StateChar('a', StateChar('b', StateChar('c', StateMatch())))
result = find2(expr, 'ccababababababacccbaccabbbc', 0)
assert list(result) == [(-1, -1)]
def test_three_chars_one_match(self):
expr = StateChar('a', StateChar('b', StateChar('c', StateMatch())))
result = find2(expr, 'ccabababccbababacccbaccabbbc', 0)
assert list(result) == [(7, 9)]
def test_three_chars_two_matches(self):
expr = StateChar('a', StateChar('b', StateChar('c', StateMatch())))
result = find2(expr, 'babcccabababccbababacccbaccabbbc', 0)
assert list(result) == [(2, 4), (11, 13)]
def test_three_chars_one_matches_offset(self):
expr = StateChar('a', StateChar('b', StateChar('c', StateMatch())))
result = find2(expr, 'abcjjjabc', 4)
assert list(result) == [(7, 9)]
<|code_end|>
with the help of current file imports:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and context from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
, which may contain function names, class names, or code. Output only the next line. | def test_three_chars_negative_offset_no_match(self): |
Next line prediction: <|code_start|> def test_single_char_one_match(self):
expr = StateChar('c', StateMatch())
result = find2(expr, 'asdasdxcz', 0)
assert list(result) == [(8, 8)]
def test_single_char_more_matches(self):
expr = StateChar('c', StateMatch())
result = find2(expr, 'xyzaaaccaa', 0)
assert list(result) == [(7, 7), (8, 8)]
def test_two_chars_no_matches(self):
expr = StateChar('a', StateChar('b', StateMatch()))
result = find2(expr, 'acbaaubbbbb', 0)
assert list(result) == [(-1, -1)]
def test_two_chars_one_match(self):
expr = StateChar('a', StateChar('b', StateMatch()))
result = find2(expr, 'ccvvvbbajbajbabb', 0)
assert list(result) == [(14, 15)]
def tests_find_two_chars_matches(self):
expr = StateChar('a', StateChar('b', StateMatch()))
result = find2(expr, 'baaaabbacaabbcc', 0)
assert list(result) == [(5, 6), (11, 12)]
def test_three_chars_no_matches(self):
expr = StateChar('a', StateChar('b', StateChar('c', StateMatch())))
result = find2(expr, 'ccababababababacccbaccabbbc', 0)
assert list(result) == [(-1, -1)]
<|code_end|>
. Use current file imports:
(import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
))
and context including class names, function names, or small code snippets from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
. Output only the next line. | def test_three_chars_one_match(self): |
Given the code snippet: <|code_start|> assert list(result) == [(2, 5), (9, 12)]
def test_chained_grouped_or_match(self):
expr = compile_re('x(aa|bb)(cc|dd)x')
result = find2(expr, 'axaaddaxbbccxxaacx', 0)
assert list(result) == [(8, 13)]
def test_chained_grouped_or_no_match(self):
expr = compile_re('x(aa|bb)(cc|dd)x')
result = find2(expr, 'xaaccddxxaaddddxxaacc', 0)
assert list(result) == [(-1, -1)]
def test_grouped_star(self):
expr = compile_re('(ab)*')
result = find2(expr, 'ababababab', 0)
assert list(result) == [(1, 10)]
def test_grouped_star_between_chars_match(self):
expr = compile_re('x(ab)*x')
result = find2(expr, 'ababxababxabab', 0)
assert list(result) == [(5, 10)]
def test_grouped_star_between_chars_no_match(self):
expr = compile_re('x(ab)*x')
result = find2(expr, 'ababxabababab', 0)
assert list(result) == [(-1, -1)]
def test_grouped_star_and_or_match(self):
expr = compile_re('x((aa)*|(bb)*)x')
result = find2(expr, 'xaaaaaaxxx', 0)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and context (functions, classes, or occasionally code) from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
. Output only the next line. | assert list(result) == [(1, 8), (9, 10)] |
Predict the next line after this snippet: <|code_start|> assert isinstance(node.out, StateMatch)
def test_build_group_or(self):
expr = compile_re('(aa|bb)', False)
# |
assert isinstance(expr, StateSplit)
# aa
node = expr.out
assert isinstance(node, StateChar)
assert node.stop == ord('a')
node = node.out
assert isinstance(node, StateChar)
assert node.stop == ord('a')
assert isinstance(node.out, StateMatch)
# bb
node = expr.out2
assert isinstance(node, StateChar)
assert node.stop == ord('b')
node = node.out
assert isinstance(node, StateChar)
assert node.stop == ord('b')
assert isinstance(node.out, StateMatch)
def test_build_group_or_between_chars(self):
expr = compile_re('x(aa|bb)x')
# xaax
assert isinstance(expr, StateChar)
<|code_end|>
using the current file's imports:
import pytest
from luna.modules.patterns import (
StateMatch, StateChar, find2, StateSplit, StateDot, StateCharRange,
compile_re
)
and any relevant context from other files:
# Path: luna/modules/patterns.py
# class StateMatch(State):
# def __init__(self):
# pass
#
# def clone(self, seen):
# return StateMatch()
#
# class StateChar(StateCharRange):
# def __init__(self, c, out):
# StateCharRange.__init__(self, c, c, out)
#
# def find2(expr, string, start):
# assert isinstance(start, int)
# if start < 0:
# start = len(string) + start
# # if negative offset is bigger than length of string
# # start at the beginning
# if start < 0:
# start = 0
# start = int(start)
#
# found = False
# i = start
# while i < len(string):
# match = False
# valid = True
# j = i
# state = expr
# backtrack = []
# while valid and not match and (j < len(string) or len(backtrack) > 0):
# if j >= len(string) and len(backtrack) > 0:
# state, j = backtrack.pop()
# if isinstance(state, StateCharRange):
# if not state.match(string[j]):
# if len(backtrack) == 0:
# valid = False
# else:
# state, j = backtrack.pop()
# else:
# state = state.out
# j += 1
# elif isinstance(state, StateMatch):
# match = True
# elif isinstance(state, StateSplit):
# backtrack.append((state.out2, j))
# state = state.out
# else:
# valid = False
# if j == len(string):
# if (isinstance(state, StateMatch) or
# (isinstance(state, StateSplit) and
# isinstance(state.out2, StateMatch))):
# match = True
# if match:
# found = True
# yield (i+1, j)
# if j > i:
# i = j
# else:
# i += 1
# else:
# i += 1
# if not found:
# yield (-1, -1)
#
# class StateSplit(State):
# def __init__(self, out, out2):
# self.out = out
# self.out2 = out2
#
# class StateDot(StateCharRange):
# def __init__(self, out):
# StateCharRange.__init__(self, ' ', ' ', out)
#
# def match(self, c):
# return True
#
# class StateCharRange(State):
# def __init__(self, c1, c2, out):
# self.start = ord(c1)
# self.stop = ord(c2)
# self.out = out
#
# def match(self, c):
# return ord(c) >= self.start and ord(c) <= self.stop
#
# def compile_re(pattern, plain=False):
# tokens = tokenize(pattern)
# return tokens_to_expression(tokens)
. Output only the next line. | assert expr.start == ord('x') |
Using the snippet: <|code_start|> def test_mulvn_float_int(self):
ret = codetest("""
x = 90000
return x * 0.5
""")
assert ret.getval() == 45000
def test_mulvn_int_float(self):
ret = codetest("""
x = 0.5
return x * 90000
""")
assert ret.getval() == 45000
def test_mulnv(self):
ret = codetest("""
x = 9
return 4 * x
""")
assert ret.getval() == 36
def test_mulnv_long(self):
ret = codetest("""
x = 90000
return 100000 * x
""")
assert ret.getval() == 90000 * 100000
def test_mulnv_float_int(self):
ret = codetest("""
<|code_end|>
, determine the next line of code. You have imports:
from .helpers import codetest
and context (class names, function names, or code) available:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | x = 90000 |
Here is a snippet: <|code_start|>
class TestDivision(object):
def test_divvn(self):
ret = codetest("""
x = 4
return x / 2
""")
assert ret.getval() == 2
def test_divnv(self):
ret = codetest("""
<|code_end|>
. Write the next line using the current file imports:
from .helpers import codetest
and context from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
, which may include functions, classes, or code. Output only the next line. | x = 4 |
Next line prediction: <|code_start|>
class TestReturn(object):
"""
"""
def test_return_more_ints(self):
ret = codetest("""
function foo(i)
if i > 0 then
return i, foo(i-1)
<|code_end|>
. Use current file imports:
(from .helpers import codetest)
and context including class names, function names, or small code snippets from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | else |
Continue the code snippet: <|code_start|> assert ret.n_val == 30
def test_tonumber_int(self):
ret = codetest("""
x = tonumber("100")
return x + 19
""")
assert ret.n_val == 119
def test_tonumber_float(self):
ret = codetest("""
x = tonumber("1.55")
return x + 19
""")
assert ret.n_val == 20.55
def test_tonumber_invalid(self):
ret = codetest("""
x = tonumber("str")
if x == nil then
return 10
else
return 99
end
""")
assert ret.n_val == 10
def test_type_int(self):
ret = codetest("""
x = 10
<|code_end|>
. Use current file imports:
import pytest
from ..helpers import codetest, test_file
and context (classes, functions, or code) from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | return type(x) |
Next line prediction: <|code_start|>
class TestBuiltin(object):
def test_print_str(self, capsys):
codetest("""
<|code_end|>
. Use current file imports:
(import pytest
from ..helpers import codetest, test_file)
and context including class names, function names, or small code snippets from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | print("hallo") |
Next line prediction: <|code_start|>
ENTRY_POINT = create_entry_point()
class TestMain(object):
def test_with_bytecode_file(self):
f = luabytecode_file("x = 1")
assert ENTRY_POINT(['', f.name]) == 0
<|code_end|>
. Use current file imports:
(import os
from luna.main import create_entry_point
from luna.tests.helpers import luabytecode_file, test_file)
and context including class names, function names, or small code snippets from other files:
# Path: luna/main.py
# def create_entry_point():
# def entry_point(argv):
# try:
# filename = argv[1]
# except IndexError:
# print "You must supply a filename"
# print (argv)
# return 1
#
# file_, ext = argv[1].rsplit('.', 1)
# """
# if ext not in ('l', 'lc'):
# print("Unsupported extension %s" %ext)
# return 1
# """
#
# if _needs_compilation(file_+'.lc', filename):
# ret = os.system('luajit -b %s %s' %(filename, filename+'c'))
# if ret:
# print("Error compiling %s using luajit" % filename)
# return 1
#
# if not ext.endswith('c'):
# filename += 'c'
#
# flags, protos = Parser(filename).parse()
# interpreter = Interpreter(flags, protos)
# interpreter.run()
#
# return 0
# return entry_point
#
# Path: luna/tests/helpers.py
# def luabytecode_file(src):
# f = test_file(src, suffix='.l')
# compile_file(f)
# return open(f.name+'c')
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | def test_with_lua_file(self): |
Given the following code snippet before the placeholder: <|code_start|>
ENTRY_POINT = create_entry_point()
class TestMain(object):
def test_with_bytecode_file(self):
f = luabytecode_file("x = 1")
assert ENTRY_POINT(['', f.name]) == 0
def test_with_lua_file(self):
f = test_file("x = 1", suffix=".l")
assert ENTRY_POINT(['', f.name]) == 0
assert os.path.exists(f.name+'c')
def test_with_non_exisiting_file(self, tmpdir):
<|code_end|>
, predict the next line using imports from the current file:
import os
from luna.main import create_entry_point
from luna.tests.helpers import luabytecode_file, test_file
and context including class names, function names, and sometimes code from other files:
# Path: luna/main.py
# def create_entry_point():
# def entry_point(argv):
# try:
# filename = argv[1]
# except IndexError:
# print "You must supply a filename"
# print (argv)
# return 1
#
# file_, ext = argv[1].rsplit('.', 1)
# """
# if ext not in ('l', 'lc'):
# print("Unsupported extension %s" %ext)
# return 1
# """
#
# if _needs_compilation(file_+'.lc', filename):
# ret = os.system('luajit -b %s %s' %(filename, filename+'c'))
# if ret:
# print("Error compiling %s using luajit" % filename)
# return 1
#
# if not ext.endswith('c'):
# filename += 'c'
#
# flags, protos = Parser(filename).parse()
# interpreter = Interpreter(flags, protos)
# interpreter.run()
#
# return 0
# return entry_point
#
# Path: luna/tests/helpers.py
# def luabytecode_file(src):
# f = test_file(src, suffix='.l')
# compile_file(f)
# return open(f.name+'c')
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | assert ENTRY_POINT(['', tmpdir.dirname+'/'+'foo.l']) == 1 |
Given snippet: <|code_start|>
ENTRY_POINT = create_entry_point()
class TestMain(object):
def test_with_bytecode_file(self):
f = luabytecode_file("x = 1")
assert ENTRY_POINT(['', f.name]) == 0
def test_with_lua_file(self):
f = test_file("x = 1", suffix=".l")
assert ENTRY_POINT(['', f.name]) == 0
assert os.path.exists(f.name+'c')
def test_with_non_exisiting_file(self, tmpdir):
assert ENTRY_POINT(['', tmpdir.dirname+'/'+'foo.l']) == 1
def test_with_invalid_extension(self):
f = test_file("int main(void{};", suffix=".c")
assert ENTRY_POINT(['', f.name]) == 1
def test_with_invalid_lua_file(self):
f = test_file("this is no lua code", suffix=".l")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from luna.main import create_entry_point
from luna.tests.helpers import luabytecode_file, test_file
and context:
# Path: luna/main.py
# def create_entry_point():
# def entry_point(argv):
# try:
# filename = argv[1]
# except IndexError:
# print "You must supply a filename"
# print (argv)
# return 1
#
# file_, ext = argv[1].rsplit('.', 1)
# """
# if ext not in ('l', 'lc'):
# print("Unsupported extension %s" %ext)
# return 1
# """
#
# if _needs_compilation(file_+'.lc', filename):
# ret = os.system('luajit -b %s %s' %(filename, filename+'c'))
# if ret:
# print("Error compiling %s using luajit" % filename)
# return 1
#
# if not ext.endswith('c'):
# filename += 'c'
#
# flags, protos = Parser(filename).parse()
# interpreter = Interpreter(flags, protos)
# interpreter.run()
#
# return 0
# return entry_point
#
# Path: luna/tests/helpers.py
# def luabytecode_file(src):
# f = test_file(src, suffix='.l')
# compile_file(f)
# return open(f.name+'c')
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
which might include code, classes, or functions. Output only the next line. | assert ENTRY_POINT(['', f.name]) == 1 |
Predict the next line after this snippet: <|code_start|>
class Interpreter(object):
def __init__(self, flags, root_frame):
self.flags = flags
self.root_frame = root_frame
def run(self):
<|code_end|>
using the current file's imports:
from luna.objspace import ObjectSpace
from luna.helpers import debug_print
and any relevant context from other files:
# Path: luna/objspace.py
# class ObjectSpace(object):
# def __init__(self):
# self.globals = {}
# self.modules = {}
# self.registers = [W_Object()] * 10
# self.globals.update(Builtin.methods)
# self.add_module(TableModule)
# self.add_module(MathModule)
# self.add_module(StringModule)
#
# def add_module(self, moduledef):
# self.globals[moduledef.name] = moduledef.methods
# self.modules[moduledef.name] = moduledef
#
# Path: luna/helpers.py
# def debug_print(args):
# if DEBUG:
# print(args)
. Output only the next line. | returnvalue = None |
Using the snippet: <|code_start|>
class Interpreter(object):
def __init__(self, flags, root_frame):
self.flags = flags
self.root_frame = root_frame
def run(self):
<|code_end|>
, determine the next line of code. You have imports:
from luna.objspace import ObjectSpace
from luna.helpers import debug_print
and context (class names, function names, or code) available:
# Path: luna/objspace.py
# class ObjectSpace(object):
# def __init__(self):
# self.globals = {}
# self.modules = {}
# self.registers = [W_Object()] * 10
# self.globals.update(Builtin.methods)
# self.add_module(TableModule)
# self.add_module(MathModule)
# self.add_module(StringModule)
#
# def add_module(self, moduledef):
# self.globals[moduledef.name] = moduledef.methods
# self.modules[moduledef.name] = moduledef
#
# Path: luna/helpers.py
# def debug_print(args):
# if DEBUG:
# print(args)
. Output only the next line. | returnvalue = None |
Given the following code snippet before the placeholder: <|code_start|> """)
out, _ = capsys.readouterr()
assert out == "13 13\n"
def test_find_simple_pattern_big_negative_offset_match(self, capsys):
codetest("""
x, y = string.find("Hello Lua user", "e", -100)
print(x, y)
""")
out, _ = capsys.readouterr()
assert out == "2 2\n"
def test_find_simple_pattern_big_offset_match(self, capsys):
codetest("""
x, y = string.find("Hello Lua user", "e", 100)
print(x, y)
""")
out, _ = capsys.readouterr()
assert out == "nil nil\n"
def test_find_pattern_with_special_a_match(self, capsys):
codetest("""
x, y = string.find('123a23aB9Z', '%a%a')
print(x, y)
""")
out, _ = capsys.readouterr()
assert out == "7 8\n"
def test_find_pattern_with_special_no_match(self, capsys):
codetest("""
<|code_end|>
, predict the next line using imports from the current file:
from ..helpers import codetest
and context including class names, function names, and sometimes code from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | x, y = string.find('123a23a 9Z', '%a%a') |
Given snippet: <|code_start|>
class ModuleDef(object):
def __init__(self, name):
self.name = name
self.methods = W_Table()
def function(self, name):
def adder(func):
self.methods.set(W_Str(name), LuaBuiltinFrame(func))
return adder
def add_constant(self, name, w_const):
self.methods.set(W_Str(name), w_const)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from luna.luaframe import LuaBuiltinFrame
from luna.w_objects import W_Table, W_Str
and context:
# Path: luna/luaframe.py
# class LuaBuiltinFrame(LuaFrame):
# def __init__(self, function):
# self.function = function
# self.registers = []
#
# def call(self, args, space):
# return self.function(args)
#
# def clone(self):
# # no need to cleon, LuaBuilinFrame has no state
# return self
#
# Path: luna/w_objects.py
# class W_Table(W_Object):
# def __init__(self):
# self.content = {}
#
# def size(self):
# return len(self.content)
#
# def get(self, key):
# try:
# w_v = self.content[key.hash()]
# assert isinstance(w_v, W_Object)
# return w_v
# except KeyError:
# return W_Pri(0)
#
# def set(self, key, val):
# self.content[key.hash()] = val
#
# def clone(self):
# # TODO: deep copy expceted here?
# cpy = W_Table()
# cpy.content = self.content.copy()
# return cpy
#
# def hash(self):
# return compute_identity_hash(self.content)
#
# def values(self):
# return self.content.values()
#
# def items(self):
# return self.content.items()
#
# class W_Str(W_Object):
# def __init__(self, val):
# self.s_val = val
#
# def getval(self):
# return self.s_val
#
# def eq(self, w_other):
# if isinstance(w_other, W_Str):
# return self.s_val == w_other.getval()
# else:
# assert isinstance(w_other, W_Pri)
# if w_other.n_val == 0:
# return self.s_val is None
# else:
# assert 0
#
# def neq(self, w_other):
# return not self.eq(w_other)
#
# def gt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val > w_other.s_val
#
# def lt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val < w_other.s_val
#
# def le(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val <= w_other.s_val
#
# def ge(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val >= w_other.s_val
#
# def to_str(self):
# return str(self.s_val)
#
# def clone(self):
# return W_Str(self.s_val)
#
# def hash(self):
# return compute_hash(self.s_val)
which might include code, classes, or functions. Output only the next line. | class BuiltinDef(object): |
Predict the next line after this snippet: <|code_start|>
class ModuleDef(object):
def __init__(self, name):
self.name = name
self.methods = W_Table()
def function(self, name):
def adder(func):
self.methods.set(W_Str(name), LuaBuiltinFrame(func))
return adder
<|code_end|>
using the current file's imports:
from luna.luaframe import LuaBuiltinFrame
from luna.w_objects import W_Table, W_Str
and any relevant context from other files:
# Path: luna/luaframe.py
# class LuaBuiltinFrame(LuaFrame):
# def __init__(self, function):
# self.function = function
# self.registers = []
#
# def call(self, args, space):
# return self.function(args)
#
# def clone(self):
# # no need to cleon, LuaBuilinFrame has no state
# return self
#
# Path: luna/w_objects.py
# class W_Table(W_Object):
# def __init__(self):
# self.content = {}
#
# def size(self):
# return len(self.content)
#
# def get(self, key):
# try:
# w_v = self.content[key.hash()]
# assert isinstance(w_v, W_Object)
# return w_v
# except KeyError:
# return W_Pri(0)
#
# def set(self, key, val):
# self.content[key.hash()] = val
#
# def clone(self):
# # TODO: deep copy expceted here?
# cpy = W_Table()
# cpy.content = self.content.copy()
# return cpy
#
# def hash(self):
# return compute_identity_hash(self.content)
#
# def values(self):
# return self.content.values()
#
# def items(self):
# return self.content.items()
#
# class W_Str(W_Object):
# def __init__(self, val):
# self.s_val = val
#
# def getval(self):
# return self.s_val
#
# def eq(self, w_other):
# if isinstance(w_other, W_Str):
# return self.s_val == w_other.getval()
# else:
# assert isinstance(w_other, W_Pri)
# if w_other.n_val == 0:
# return self.s_val is None
# else:
# assert 0
#
# def neq(self, w_other):
# return not self.eq(w_other)
#
# def gt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val > w_other.s_val
#
# def lt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val < w_other.s_val
#
# def le(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val <= w_other.s_val
#
# def ge(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val >= w_other.s_val
#
# def to_str(self):
# return str(self.s_val)
#
# def clone(self):
# return W_Str(self.s_val)
#
# def hash(self):
# return compute_hash(self.s_val)
. Output only the next line. | def add_constant(self, name, w_const): |
Based on the snippet: <|code_start|>
class ModuleDef(object):
def __init__(self, name):
self.name = name
self.methods = W_Table()
def function(self, name):
def adder(func):
self.methods.set(W_Str(name), LuaBuiltinFrame(func))
<|code_end|>
, predict the immediate next line with the help of imports:
from luna.luaframe import LuaBuiltinFrame
from luna.w_objects import W_Table, W_Str
and context (classes, functions, sometimes code) from other files:
# Path: luna/luaframe.py
# class LuaBuiltinFrame(LuaFrame):
# def __init__(self, function):
# self.function = function
# self.registers = []
#
# def call(self, args, space):
# return self.function(args)
#
# def clone(self):
# # no need to cleon, LuaBuilinFrame has no state
# return self
#
# Path: luna/w_objects.py
# class W_Table(W_Object):
# def __init__(self):
# self.content = {}
#
# def size(self):
# return len(self.content)
#
# def get(self, key):
# try:
# w_v = self.content[key.hash()]
# assert isinstance(w_v, W_Object)
# return w_v
# except KeyError:
# return W_Pri(0)
#
# def set(self, key, val):
# self.content[key.hash()] = val
#
# def clone(self):
# # TODO: deep copy expceted here?
# cpy = W_Table()
# cpy.content = self.content.copy()
# return cpy
#
# def hash(self):
# return compute_identity_hash(self.content)
#
# def values(self):
# return self.content.values()
#
# def items(self):
# return self.content.items()
#
# class W_Str(W_Object):
# def __init__(self, val):
# self.s_val = val
#
# def getval(self):
# return self.s_val
#
# def eq(self, w_other):
# if isinstance(w_other, W_Str):
# return self.s_val == w_other.getval()
# else:
# assert isinstance(w_other, W_Pri)
# if w_other.n_val == 0:
# return self.s_val is None
# else:
# assert 0
#
# def neq(self, w_other):
# return not self.eq(w_other)
#
# def gt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val > w_other.s_val
#
# def lt(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val < w_other.s_val
#
# def le(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val <= w_other.s_val
#
# def ge(self, w_other):
# assert isinstance(w_other, W_Str)
# return self.s_val >= w_other.s_val
#
# def to_str(self):
# return str(self.s_val)
#
# def clone(self):
# return W_Str(self.s_val)
#
# def hash(self):
# return compute_hash(self.s_val)
. Output only the next line. | return adder |
Predict the next line for this snippet: <|code_start|>
class ObjectSpace(object):
def __init__(self):
self.globals = {}
self.modules = {}
self.registers = [W_Object()] * 10
self.globals.update(Builtin.methods)
self.add_module(TableModule)
self.add_module(MathModule)
self.add_module(StringModule)
def add_module(self, moduledef):
<|code_end|>
with the help of current file imports:
from luna.w_objects import W_Object
from luna.modules.builtin import Builtin
from luna.modules.table import TableModule
from luna.modules.lmath import MathModule
from luna.modules.string import StringModule
and context from other files:
# Path: luna/w_objects.py
# class W_Object(object):
# def __init__(self):
# self.n_val = 0
# self.s_val = ''
# self.content = {}
#
# def eq(self, w_other):
# raise NotImplementedError('eq not supported by this class')
#
# def neq(self, w_other):
# raise NotImplementedError('neq not supported by this class')
#
# def gt(self, other):
# raise NotImplementedError('gt not supported by this class')
#
# def lt(self, other):
# raise NotImplementedError('lt not supported by this class')
#
# def ge(self, other):
# raise NotImplementedError('ge not supported by this class')
#
# def le(self, other):
# raise NotImplementedError('le not supported by this class')
#
# def is_true(self):
# return True
#
# def to_str(self):
# raise NotImplementedError('to_str not supported by this class')
#
# def clone(self):
# raise NotImplementedError('clone not supported by this class')
#
# def get_val(self, key):
# raise NotImplementedError('to_str not supported by this class')
#
# def hash(self):
# raise NotImplementedError('hash not supported by this class')
#
# Path: luna/modules/builtin.py
# def method_assert(args):
# def method_print(args):
# def method_loadfile(args):
# def method_loadstring(args):
# def method_tonumber(args):
# def method_type(args):
#
# Path: luna/modules/table.py
# def method_concat(args):
# def method_insert(args):
# def method_maxn(args):
# def method_remove(args):
#
# Path: luna/modules/lmath.py
# def method_floor(args):
# def method_sin(args):
# def method_mod(args):
#
# Path: luna/modules/string.py
# def handle_args(args):
# def method_find(args):
# def method_match(args):
# def method_gsub(args):
, which may contain function names, class names, or code. Output only the next line. | self.globals[moduledef.name] = moduledef.methods |
Based on the snippet: <|code_start|>
def test_nested_function_tailcall(self):
"""
Tests CALLMT with user defined function
"""
ret = codetest("""
function f(x)
y = x+1
return y
end
return f(f(5))
""")
assert ret.getval() == 7
def test_nested_function_tailcall_builtin(self):
"""
Tests CALLMT with builtin function
"""
ret = codetest("""
return math.sin(math.sin(1))
""")
assert ret.getval() == 0.7456241416655579
def test_nested_function_call(self):
"""
Tests CALLM with user function
"""
ret = codetest("""
function f(x)
y = x+1
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from .helpers import codetest
and context (classes, functions, sometimes code) from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | return y |
Here is a snippet: <|code_start|> z = x + y
return z
""")
assert ret.getval() == 262144
def test_addvv_float(self):
ret = codetest("""
x = 6.5
y = 1.2
return x + y
""")
assert ret.getval() == 7.7
def test_addvn(self):
ret = codetest("""
x = 131072
return x+10
""")
assert ret.getval() == 131082
def test_addvn_long(self):
ret = codetest("""
x = 1310720
return x+10000000
""")
assert ret.getval() == 11310720
def test_addnv(self):
ret = codetest("""
x = 131
<|code_end|>
. Write the next line using the current file imports:
from .helpers import codetest
and context from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
, which may include functions, classes, or code. Output only the next line. | return 10 + x |
Using the snippet: <|code_start|>
class TestSubtraction(object):
def test_subvn(self):
ret = codetest("""
<|code_end|>
, determine the next line of code. You have imports:
from .helpers import codetest
and context (class names, function names, or code) available:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | x = 6500 |
Using the snippet: <|code_start|>
class TestMath(object):
def test_huge(self, capsys):
ret = codetest("""
return math.huge
""")
assert ret.n_val == sys.maxint
def test_floor_1(self, capsys):
ret = codetest("""
return math.floor(1.9)
""")
assert ret.n_val == 1
def test_floor_2(self, capsys):
ret = codetest("""
<|code_end|>
, determine the next line of code. You have imports:
import sys
import pytest
from ..helpers import codetest, test_file
and context (class names, function names, or code) available:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
#
# def test_file(src='', suffix=''):
# f = tempfile.NamedTemporaryFile(suffix=suffix)
# f.write(src)
# f.flush()
# return f
. Output only the next line. | return math.floor(1.0) |
Predict the next line for this snippet: <|code_start|>
class TestIf(object):
"""
tests for the lua if then else and various comparisons
"""
def test_isnen_false_with_eq(self):
ret = codetest("""
x = 99
if x == 99 then
return 2
end
return 9
""")
assert ret.getval() == 2
def test_isnen_true_with_eq(self):
ret = codetest("""
x = 99;
if x == 88 then
<|code_end|>
with the help of current file imports:
from .helpers import codetest
and context from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
, which may contain function names, class names, or code. Output only the next line. | return 2; |
Next line prediction: <|code_start|> return x
""")
assert ret.s_val == ""
def test_cat_strs(self):
ret = codetest("""
return "hal".."lo"
""")
assert ret.s_val == "hallo"
def test_cat_ints(self):
ret = codetest("""
return 100 .. 99
""")
assert ret.s_val == "10099"
def test_cat_str_int(self):
ret = codetest("""
return "hallo" .. 99
""")
assert ret.s_val == "hallo99"
def test_cat_int_str_int(self):
ret = codetest("""
return 1 .. ", " .. 99
""")
assert ret.s_val == "1, 99"
def test_compare_string_with_nil(self):
ret = codetest("""
<|code_end|>
. Use current file imports:
(import pytest
from .helpers import codetest)
and context including class names, function names, or small code snippets from other files:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
. Output only the next line. | return nil ~= "foo" |
Given snippet: <|code_start|>
def test_set_get_num_key_str(self):
ret = codetest("""
x = {}
x[1] = "str"
return x[1]
""")
assert ret.getval() == "str"
def test_set_get_var_str_key_num(self):
ret = codetest("""
x = {}
key = "key"
x[key] = 99
return x[key]
""")
assert ret.getval() == 99
def test_set_get_var_str_key_str(self):
ret = codetest("""
x = {}
key = "key"
x[key] = "str"
return x[key]
""")
assert ret.getval() == "str"
def test_table_as_array_num(self):
ret = codetest("""
x = { 5, 2, 3}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .helpers import codetest
and context:
# Path: luna/tests/helpers.py
# def codetest(src):
# f = luabytecode_file(src)
# flags, protos = Parser(f.name).parse()
# interpreter = Interpreter(flags, protos)
# ret = interpreter.run()
# return ret
which might include code, classes, or functions. Output only the next line. | return x[1] + x[3] |
Based on the snippet: <|code_start|>from __future__ import print_function
class Command(BaseCommand):
args = '<english title or slug>'
help = 'Create a new rst blog post'
option_list = (
make_option(
'--draft', '-d', dest='draft', default=False, action='store_true',
help='Is is a draft (unpublished) ? [Default: "%default"]'),
) + BaseCommand.option_list
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('Single argument of English title or slug '
'is required')
title_or_slug = args[0]
slug = slugify(title_or_slug)
draft = int(options['draft'])
ctx = {
'slug': slug,
<|code_end|>
, predict the immediate next line with the help of imports:
import codecs
import os
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.template.defaultfilters import slugify
from django.template.loader import render_to_string
from django.utils import translation
from optparse import make_option
from statirator.blog.utils import get_blog_dir
and context (classes, functions, sometimes code) from other files:
# Path: statirator/blog/utils.py
# def get_blog_dir():
# "Returns the blog directory from settings, or default one if not found"
#
# from django.conf import settings
#
# return getattr(settings, 'BLOG_DIR',
# os.path.join(settings.ROOT_DIR, 'blog'))
. Output only the next line. | 'draft': draft, |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
register = Library()
# tag cloud from django-taggit-templatetags:
# https://github.com/feuervogel/django-taggit-templatetags
T_MAX = getattr(settings, 'TAGCLOUD_MAX', 6.0)
T_MIN = getattr(settings, 'TAGCLOUD_MIN', 1.0)
def get_queryset(language):
qs = I18NTag.objects.filter(language=language)
qs = qs.annotate(num_times=Count('blog_i18ntaggeditem_items'))
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.db.models import Count
from django.template.base import Node, Library, TemplateSyntaxError
from statirator.blog.models import I18NTag, Post
and context (classes, functions, or code) from other files:
# Path: statirator/blog/models.py
# class I18NTag(models.Model, TranslationsMixin):
# """Extend Taggit's Tag:
#
# * Add a language field
# * slug will be appended the locale, since we can't override the uniqute in
# the abstract model
# * slug_no_locale will have the actual slug
#
# """
#
# SLUG_FIELD_FOR_TRANSLATIONS = 'slug_no_locale' # we need to override this
#
# name = models.CharField(verbose_name=_('Name'), max_length=100)
# slug = models.SlugField(verbose_name=_('Slug'), unique=True,
# max_length=100)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# slug_no_locale = models.SlugField(verbose_name=_('Slug without locale'),
# unique=False, max_length=100)
#
# class Meta:
# unique_together = ('language', 'slug_no_locale')
#
# @i18n_permalink
# def get_absolute_url(self):
# return ('blog_tag', (), {'slug': self.slug_no_locale})
#
# @i18n_permalink
# def get_feed_url(self):
# return ('blog_tag_feed', (), {'slug': self.slug_no_locale})
#
# def save(self, *args, **kwargs):
# if not self.pk and not self.slug:
# self.slug = self.slugify(self.name)
# from django.db import router
# using = kwargs.get("using") or router.db_for_write(
# type(self), instance=self)
# # Make sure we write to the same db for all attempted writes,
# # with a multi-master setup, theoretically we could try to
# # write and rollback on different DBs
# kwargs["using"] = using
# # Be oportunistic and try to save the tag, this should work for
# # most cases ;)
# try:
# with atomic(using=using):
# res = super(I18NTag, self).save(*args, **kwargs)
# return res
# except IntegrityError:
# pass
# # Now try to find existing slugs with similar names
# slugs = set(I18NTag.objects.filter(slug__startswith=self.slug)
# .values_list('slug', flat=True))
# i = 1
# while True:
# slug = self.slugify(self.name, i)
# if slug not in slugs:
# self.slug = slug
# # We purposely ignore concurrecny issues here for now.
# # (That is, till we found a nice solution...)
# return super(I18NTag, self).save(*args, **kwargs)
# i += 1
# else:
# return super(I18NTag, self).save(*args, **kwargs)
#
# __str__ = TagBase.__str__
# slugify = TagBase.slugify
#
# class Post(models.Model, TranslationsMixin):
# """Multilingual blog posts"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# is_published = models.BooleanField(default=True, max_length=200)
# excerpt = models.TextField(blank=True, null=True)
# content = models.TextField()
# pubdate = models.DateTimeField(db_index=True)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# image = models.CharField(max_length=255, blank=True, null=True)
#
# tags = TaggableManager(through=I18NTaggedItem)
#
# def __unicode__(self):
# return self.title
#
# @i18n_permalink
# def get_absolute_url(self):
# from .utils import get_post_urlpattern_keys
#
# keys = get_post_urlpattern_keys()
#
# kwargs = {k: getattr(self, k) for k in keys}
#
# return ('blog_post', (), kwargs)
#
# def get_next(self):
# return self.get_next_by_pubdate(language=self.language,
# is_published=True)
#
# def get_previous(self):
# return self.get_previous_by_pubdate(language=self.language,
# is_published=True)
#
# @property
# def tags_list(self):
# return self.tags.values_list('name', flat=True)
#
# @property
# def year(self):
# return self.pubdate.year
#
# @property
# def month(self):
# """Get a 2 digit formatted month"""
# return self.pubdate.strftime('%m')
#
# @property
# def day(self):
# """Get a 2 digit formatted day"""
# return self.pubdate.strftime('%d')
. Output only the next line. | return qs |
Predict the next line after this snippet: <|code_start|>
# tag cloud from django-taggit-templatetags:
# https://github.com/feuervogel/django-taggit-templatetags
T_MAX = getattr(settings, 'TAGCLOUD_MAX', 6.0)
T_MIN = getattr(settings, 'TAGCLOUD_MIN', 1.0)
def get_queryset(language):
qs = I18NTag.objects.filter(language=language)
qs = qs.annotate(num_times=Count('blog_i18ntaggeditem_items'))
return qs
def get_weight_fun(t_min, t_max, f_min, f_max):
def weight_fun(f_i, t_min=t_min, t_max=t_max, f_min=f_min, f_max=f_max):
# Prevent a division by zero here, found to occur under some
# pathological but nevertheless actually occurring circumstances.
if f_max == f_min:
mult_fac = 1.0
else:
mult_fac = float(t_max - t_min) / float(f_max - f_min)
return t_max - (f_max - f_i) * mult_fac
return weight_fun
class TagListNode(Node):
"Simple tag list, ordered by count"
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.db.models import Count
from django.template.base import Node, Library, TemplateSyntaxError
from statirator.blog.models import I18NTag, Post
and any relevant context from other files:
# Path: statirator/blog/models.py
# class I18NTag(models.Model, TranslationsMixin):
# """Extend Taggit's Tag:
#
# * Add a language field
# * slug will be appended the locale, since we can't override the uniqute in
# the abstract model
# * slug_no_locale will have the actual slug
#
# """
#
# SLUG_FIELD_FOR_TRANSLATIONS = 'slug_no_locale' # we need to override this
#
# name = models.CharField(verbose_name=_('Name'), max_length=100)
# slug = models.SlugField(verbose_name=_('Slug'), unique=True,
# max_length=100)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# slug_no_locale = models.SlugField(verbose_name=_('Slug without locale'),
# unique=False, max_length=100)
#
# class Meta:
# unique_together = ('language', 'slug_no_locale')
#
# @i18n_permalink
# def get_absolute_url(self):
# return ('blog_tag', (), {'slug': self.slug_no_locale})
#
# @i18n_permalink
# def get_feed_url(self):
# return ('blog_tag_feed', (), {'slug': self.slug_no_locale})
#
# def save(self, *args, **kwargs):
# if not self.pk and not self.slug:
# self.slug = self.slugify(self.name)
# from django.db import router
# using = kwargs.get("using") or router.db_for_write(
# type(self), instance=self)
# # Make sure we write to the same db for all attempted writes,
# # with a multi-master setup, theoretically we could try to
# # write and rollback on different DBs
# kwargs["using"] = using
# # Be oportunistic and try to save the tag, this should work for
# # most cases ;)
# try:
# with atomic(using=using):
# res = super(I18NTag, self).save(*args, **kwargs)
# return res
# except IntegrityError:
# pass
# # Now try to find existing slugs with similar names
# slugs = set(I18NTag.objects.filter(slug__startswith=self.slug)
# .values_list('slug', flat=True))
# i = 1
# while True:
# slug = self.slugify(self.name, i)
# if slug not in slugs:
# self.slug = slug
# # We purposely ignore concurrecny issues here for now.
# # (That is, till we found a nice solution...)
# return super(I18NTag, self).save(*args, **kwargs)
# i += 1
# else:
# return super(I18NTag, self).save(*args, **kwargs)
#
# __str__ = TagBase.__str__
# slugify = TagBase.slugify
#
# class Post(models.Model, TranslationsMixin):
# """Multilingual blog posts"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# is_published = models.BooleanField(default=True, max_length=200)
# excerpt = models.TextField(blank=True, null=True)
# content = models.TextField()
# pubdate = models.DateTimeField(db_index=True)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# image = models.CharField(max_length=255, blank=True, null=True)
#
# tags = TaggableManager(through=I18NTaggedItem)
#
# def __unicode__(self):
# return self.title
#
# @i18n_permalink
# def get_absolute_url(self):
# from .utils import get_post_urlpattern_keys
#
# keys = get_post_urlpattern_keys()
#
# kwargs = {k: getattr(self, k) for k in keys}
#
# return ('blog_post', (), kwargs)
#
# def get_next(self):
# return self.get_next_by_pubdate(language=self.language,
# is_published=True)
#
# def get_previous(self):
# return self.get_previous_by_pubdate(language=self.language,
# is_published=True)
#
# @property
# def tags_list(self):
# return self.tags.values_list('name', flat=True)
#
# @property
# def year(self):
# return self.pubdate.year
#
# @property
# def month(self):
# """Get a 2 digit formatted month"""
# return self.pubdate.strftime('%m')
#
# @property
# def day(self):
# """Get a 2 digit formatted day"""
# return self.pubdate.strftime('%d')
. Output only the next line. | def __init__(self, language, asvar): |
Predict the next line for this snippet: <|code_start|> def shutdown(self):
print("\nShutting down")
self._shutdown = True
self.httpd_server.shutdown()
self.httpd_thread.join()
def filesystem_watcher(self):
lock = threading.Lock()
ignore_re = None
to_ignore = ['\.pyc']
pipeline_css = getattr(settings, 'PIPELINE_CSS', None)
for k, v in pipeline_css.iteritems():
source_filenames = v.get('source_filenames', [])
for res in source_filenames:
if res.endswith('.less'):
to_ignore.append(res.replace('.less', '\.css'))
if to_ignore:
ignore_re = re.compile('.*(' + '|'.join(to_ignore) + ')$')
def watch():
while not self._shutdown:
with lock:
if filesystem_changed(
settings.ROOT_DIR,
ignore_dirs=[settings.BUILD_DIR],
ignore_re=ignore_re):
<|code_end|>
with the help of current file imports:
import os
import re
import time
import threading
import BaseHTTPServer
import SimpleHTTPServer
import SocketServer
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import NoArgsCommand, BaseCommand
from optparse import make_option
from statirator.core.utils import filesystem_changed
from django.conf import settings
and context from other files:
# Path: statirator/core/utils.py
# def filesystem_changed(root_dir, ignore_dirs=None, ignore_re=None):
# "Do we have new, changed, or deleted files under ``root_dir``"
#
# global _mtimes, _win
#
# found = {}
#
# if ignore_dirs is None:
# ignore_dirs = []
#
# for root, dirs, files in os.walk(root_dir):
# dirs[:] = [x for x in dirs
# if x[0] != '.' and
# os.path.abspath(os.path.join(root, x)) not in ignore_dirs]
#
# for resource in files:
# full = os.path.join(root, resource)
# if ignore_re and ignore_re.match(full):
# continue
#
# stat = os.stat(full)
# mtime = stat.st_mtime
# if _win:
# mtime -= stat.st_ctime
#
# found[full] = int(mtime)
#
# if found != _mtimes:
# _mtimes = found.copy()
# return True
#
# return False
, which may contain function names, class names, or code. Output only the next line. | call_command('generate') |
Predict the next line for this snippet: <|code_start|> def get_translations(self):
"Query set for the translations"
self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS)
self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS)
slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug}
lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang}
return self.__class__.objects.filter(**slug).exclude(**lang)
def get_language(self):
"Get the language display for this item's language"
attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS)
return getattr(self, attr)()
class DummyTranslation(object):
"""Dummy translations for views to put in template context in case there's no
actual object"""
def __init__(self, request, language=None, title=None, path=None):
self.title = title
self.request = request
self.language = language or request.LANGUAGE_CODE
self.path = path or request.path
def get_translations(self):
for code, name in settings.LANGUAGES:
if code != self.language:
<|code_end|>
with the help of current file imports:
from django.conf import settings
from .utils import path_to_lang, LANGS_DICT
and context from other files:
# Path: statirator/core/utils.py
# def path_to_lang(path, lang):
# "Translate one path to another languge, takes into account "
#
# prefix = postfix = ''
#
# if path.startswith('/'):
# path = path[1:]
# prefix = '/'
# if path.endswith('/'):
# path = path[:-1]
# postfix = '/'
#
# bits = path.split('/')
#
# #TODO fix for multi domain or prefixed default language
# if bits[0] in LANGS_DICT:
# bits.pop(0)
# else: # assume it's the default language.
# pass
#
# if lang != settings.LANGUAGE_CODE:
# bits.insert(0, lang)
#
# return prefix + '/'.join(bits) + postfix
#
# LANGS_DICT = dict(settings.LANGUAGES)
, which may contain function names, class names, or code. Output only the next line. | yield DummyTranslation(self.request, code, name, self.path) |
Here is a snippet: <|code_start|>from __future__ import absolute_import
class TranslationsMixin(object):
"Helper for getting transalations"
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from .utils import path_to_lang, LANGS_DICT
and context from other files:
# Path: statirator/core/utils.py
# def path_to_lang(path, lang):
# "Translate one path to another languge, takes into account "
#
# prefix = postfix = ''
#
# if path.startswith('/'):
# path = path[1:]
# prefix = '/'
# if path.endswith('/'):
# path = path[:-1]
# postfix = '/'
#
# bits = path.split('/')
#
# #TODO fix for multi domain or prefixed default language
# if bits[0] in LANGS_DICT:
# bits.pop(0)
# else: # assume it's the default language.
# pass
#
# if lang != settings.LANGUAGE_CODE:
# bits.insert(0, lang)
#
# return prefix + '/'.join(bits) + postfix
#
# LANGS_DICT = dict(settings.LANGUAGES)
, which may include functions, classes, or code. Output only the next line. | SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed |
Given snippet: <|code_start|>
PAGE_TYPES = (
('rst', 'reStructured Text'),
('html', 'Django template'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db import models
from django.conf import settings
from statirator.core.utils import i18n_permalink
from statirator.core.models import TranslationsMixin
and context:
# Path: statirator/core/utils.py
# def i18n_permalink(*args):
# """Return the correct URL in case of not the default language.
# relaces djangos models.permalink.
#
# Assumes the name of the i18n version of the url pattern is prefix with
# 'i18n_' (This is done in the statirator's default urls.py).
#
# It looks for a `language` field for the instance. If the name is different,
# pass it as the first param to the decorator. e.g::
#
# @i18n_permalink('lang_code')
# def get_absolute_url(self):
# return (...)
#
# """
# def outer(f):
# @functools.wraps(f)
# def wrapper(obj, *args, **kwargs):
#
# bits = f(obj, *args, **kwargs)
# name = bits[0]
#
# lang = getattr(obj, language_field)
# return i18n_reverse(lang, name, None, *bits[1:3])
#
# return wrapper
#
# if len(args) == 1 and callable(args[0]):
# # No arguments, this is the decorator
# # Set default values for the arguments
# language_field = 'language'
# return outer(args[0])
# else:
# language_field = args[0]
# return outer
#
# Path: statirator/core/models.py
# class TranslationsMixin(object):
# "Helper for getting transalations"
#
# SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed
# LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed
#
# def get_translations(self):
# "Query set for the translations"
#
# self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS)
# self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS)
#
# slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug}
# lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang}
# return self.__class__.objects.filter(**slug).exclude(**lang)
#
# def get_language(self):
# "Get the language display for this item's language"
#
# attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS)
# return getattr(self, attr)()
which might include code, classes, or functions. Output only the next line. | ) |
Here is a snippet: <|code_start|>from __future__ import absolute_import
class PagesSiteMap(Sitemap):
def items(self):
"Return the items starting with defualt language and it's index page"
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.sitemaps import Sitemap
from django.conf import settings
from .models import Page
and context from other files:
# Path: statirator/pages/models.py
# class Page(models.Model, TranslationsMixin):
# """A multilingual page"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# content = models.TextField()
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# page_type = models.CharField(max_length=5, choices=PAGE_TYPES)
# description = models.CharField(max_length=255, blank=True, null=True)
#
# def __unicode__(self):
# return self.title or self.slug
#
# @i18n_permalink
# def get_absolute_url(self):
# # index is a special case
# if self.slug == 'index':
# return ('pages_index', (), {})
#
# return ('pages_page', (), {'slug': self.slug})
, which may include functions, classes, or code. Output only the next line. | default = settings.LANGUAGE_CODE |
Using the snippet: <|code_start|>from __future__ import print_function
class Command(BaseCommand):
help = "Walk the resources, builds the db, and generates the static site"
def handle(self, *args, **options):
self.syncdb()
self.create_sites()
self.read_resources()
self.gen_static()
self.collect_static_media()
def print_title(self, title):
print()
print(title)
print(len(title) * '-')
<|code_end|>
, determine the next line of code. You have imports:
import logging
from django.core.management import call_command
from django.core.management.base import BaseCommand
from statirator.core.utils import find_readers
from django.conf import settings
from django.contrib.sites.models import Site
and context (class names, function names, or code) available:
# Path: statirator/core/utils.py
# def find_readers():
# """Auto discover readers in installed apps.
#
# Each readers.py should have the READERS list with reader classes
# """
#
# from django.conf import settings
# from django.utils.importlib import import_module
# from django.utils.module_loading import module_has_submodule
#
# readers = []
# for app in settings.INSTALLED_APPS:
# mod = import_module(app)
# # Attempt to import the app's admin module.
# try:
# walk_mod = import_module('%s.readers' % app)
# if hasattr(walk_mod, 'READERS'):
# readers.extend(walk_mod.READERS)
# else:
# logging.warn(
# 'readers found in app %s, but has no READERS attrib',
# app)
# except:
# # Decide whether to bubble up this error. If the app just
# # doesn't have an readers module, we can ignore the error
# # attempting to import it, otherwise we want it to bubble up.
# if module_has_submodule(mod, 'readers'):
# raise
#
# return readers
. Output only the next line. | def syncdb(self): |
Continue the code snippet: <|code_start|>from __future__ import print_function, absolute_import
def update_post(slug, lang_code, defaults):
with translation.override(lang_code):
page, created = Page.objects.get_or_create(
slug=slug,
language=lang_code,
defaults=defaults)
if not created:
for field, val in defaults.iteritems():
setattr(page, field, val)
# get the title from the template
t = Template(page.content)
req = RequestFactory().get(page.get_absolute_url(), LANGUAGE_CODE=lang_code)
page.title = render_block_to_string(
t, 'title', context_instance=RequestContext(req))
page.description = render_block_to_string(
t, 'description', context_instance=RequestContext(req))
page.save()
def html_reader():
"Finds django html pages, parses them and loads into the db."
for page in find_files(get_pages_dir(), ['.html']):
<|code_end|>
. Use current file imports:
import os
from django.conf import settings
from django.template import Template, RequestContext
from django.utils import translation
from django.test.client import RequestFactory
from statirator.core.utils import find_files, render_block_to_string
from .utils import get_pages_dir
from .models import Page
and context (classes, functions, or code) from other files:
# Path: statirator/core/utils.py
# def find_files(root, extensions):
# """Generator finding files from a root dir with specific extensions
#
# :param root: Root directory for the search
# :param extensions: List of extensions to search (e.g: ['.rst', '.txt'])
# """
#
# for root, dirs, files in os.walk(root):
# for f in files:
# if os.path.splitext(f)[1] in extensions:
# yield os.path.join(root, f)
#
# def render_block_to_string(template_or_name, block, dictionary=None,
# context_instance=None):
# """
# Loads the given template_name and renders the given block with the given dictionary as
# context. Returns a string.
#
# Can be used to extract data from template blocks (e.g: get the title from
# {% block title %}{% endblock %})
#
# """
# from django.template import Context, Template
#
# dictionary = dictionary or {}
# if isinstance(template_or_name, Template):
# t = template_or_name
# else:
# t = get_template(template_or_name)
#
# if context_instance:
# context_instance.update(dictionary)
# else:
# context_instance = Context(dictionary)
# return render_template_block(t, block, context_instance)
#
# Path: statirator/pages/utils.py
# def get_pages_dir():
# "Returns the pages directory from settings, or default one if not found"
#
# from django.conf import settings
#
# return getattr(settings, 'PAGES_DIR',
# os.path.join(settings.ROOT_DIR, 'pages'))
#
# Path: statirator/pages/models.py
# class Page(models.Model, TranslationsMixin):
# """A multilingual page"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# content = models.TextField()
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# page_type = models.CharField(max_length=5, choices=PAGE_TYPES)
# description = models.CharField(max_length=255, blank=True, null=True)
#
# def __unicode__(self):
# return self.title or self.slug
#
# @i18n_permalink
# def get_absolute_url(self):
# # index is a special case
# if self.slug == 'index':
# return ('pages_index', (), {})
#
# return ('pages_page', (), {'slug': self.slug})
. Output only the next line. | print('Processing {0}'.format(page)) |
Based on the snippet: <|code_start|>from __future__ import print_function, absolute_import
def update_post(slug, lang_code, defaults):
with translation.override(lang_code):
page, created = Page.objects.get_or_create(
slug=slug,
language=lang_code,
defaults=defaults)
if not created:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from django.conf import settings
from django.template import Template, RequestContext
from django.utils import translation
from django.test.client import RequestFactory
from statirator.core.utils import find_files, render_block_to_string
from .utils import get_pages_dir
from .models import Page
and context (classes, functions, sometimes code) from other files:
# Path: statirator/core/utils.py
# def find_files(root, extensions):
# """Generator finding files from a root dir with specific extensions
#
# :param root: Root directory for the search
# :param extensions: List of extensions to search (e.g: ['.rst', '.txt'])
# """
#
# for root, dirs, files in os.walk(root):
# for f in files:
# if os.path.splitext(f)[1] in extensions:
# yield os.path.join(root, f)
#
# def render_block_to_string(template_or_name, block, dictionary=None,
# context_instance=None):
# """
# Loads the given template_name and renders the given block with the given dictionary as
# context. Returns a string.
#
# Can be used to extract data from template blocks (e.g: get the title from
# {% block title %}{% endblock %})
#
# """
# from django.template import Context, Template
#
# dictionary = dictionary or {}
# if isinstance(template_or_name, Template):
# t = template_or_name
# else:
# t = get_template(template_or_name)
#
# if context_instance:
# context_instance.update(dictionary)
# else:
# context_instance = Context(dictionary)
# return render_template_block(t, block, context_instance)
#
# Path: statirator/pages/utils.py
# def get_pages_dir():
# "Returns the pages directory from settings, or default one if not found"
#
# from django.conf import settings
#
# return getattr(settings, 'PAGES_DIR',
# os.path.join(settings.ROOT_DIR, 'pages'))
#
# Path: statirator/pages/models.py
# class Page(models.Model, TranslationsMixin):
# """A multilingual page"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# content = models.TextField()
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# page_type = models.CharField(max_length=5, choices=PAGE_TYPES)
# description = models.CharField(max_length=255, blank=True, null=True)
#
# def __unicode__(self):
# return self.title or self.slug
#
# @i18n_permalink
# def get_absolute_url(self):
# # index is a special case
# if self.slug == 'index':
# return ('pages_index', (), {})
#
# return ('pages_page', (), {'slug': self.slug})
. Output only the next line. | for field, val in defaults.iteritems(): |
Using the snippet: <|code_start|> t = Template(page.content)
req = RequestFactory().get(page.get_absolute_url(), LANGUAGE_CODE=lang_code)
page.title = render_block_to_string(
t, 'title', context_instance=RequestContext(req))
page.description = render_block_to_string(
t, 'description', context_instance=RequestContext(req))
page.save()
def html_reader():
"Finds django html pages, parses them and loads into the db."
for page in find_files(get_pages_dir(), ['.html']):
print('Processing {0}'.format(page))
slug, ext = os.path.splitext(os.path.basename(page))
with open(page) as p:
template_content = p.read()
# we create one for each language. Less efficient, but will work we
# i18n_permalink without further hacking
#
# Each template will be renderd for each language, so make sure to
# have language logic in the template
for lang_code, lang_name in settings.LANGUAGES:
defaults = dict(content=template_content, page_type='html')
update_post(slug, lang_code, defaults)
<|code_end|>
, determine the next line of code. You have imports:
import os
from django.conf import settings
from django.template import Template, RequestContext
from django.utils import translation
from django.test.client import RequestFactory
from statirator.core.utils import find_files, render_block_to_string
from .utils import get_pages_dir
from .models import Page
and context (class names, function names, or code) available:
# Path: statirator/core/utils.py
# def find_files(root, extensions):
# """Generator finding files from a root dir with specific extensions
#
# :param root: Root directory for the search
# :param extensions: List of extensions to search (e.g: ['.rst', '.txt'])
# """
#
# for root, dirs, files in os.walk(root):
# for f in files:
# if os.path.splitext(f)[1] in extensions:
# yield os.path.join(root, f)
#
# def render_block_to_string(template_or_name, block, dictionary=None,
# context_instance=None):
# """
# Loads the given template_name and renders the given block with the given dictionary as
# context. Returns a string.
#
# Can be used to extract data from template blocks (e.g: get the title from
# {% block title %}{% endblock %})
#
# """
# from django.template import Context, Template
#
# dictionary = dictionary or {}
# if isinstance(template_or_name, Template):
# t = template_or_name
# else:
# t = get_template(template_or_name)
#
# if context_instance:
# context_instance.update(dictionary)
# else:
# context_instance = Context(dictionary)
# return render_template_block(t, block, context_instance)
#
# Path: statirator/pages/utils.py
# def get_pages_dir():
# "Returns the pages directory from settings, or default one if not found"
#
# from django.conf import settings
#
# return getattr(settings, 'PAGES_DIR',
# os.path.join(settings.ROOT_DIR, 'pages'))
#
# Path: statirator/pages/models.py
# class Page(models.Model, TranslationsMixin):
# """A multilingual page"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# content = models.TextField()
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# page_type = models.CharField(max_length=5, choices=PAGE_TYPES)
# description = models.CharField(max_length=255, blank=True, null=True)
#
# def __unicode__(self):
# return self.title or self.slug
#
# @i18n_permalink
# def get_absolute_url(self):
# # index is a special case
# if self.slug == 'index':
# return ('pages_index', (), {})
#
# return ('pages_page', (), {'slug': self.slug})
. Output only the next line. | READERS = [html_reader] |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
TEST_DOC = """
:slug: some-post-title-slugified
:draft: 1
:datetime: 2012-09-12 16:03:15
This will be ignored in main meta section
.. --
=================
English title
=================
:lang: en
:tags: Tag1, Tag2
The content of the English post
And another paragraph
.. --
====================
<|code_end|>
with the help of current file imports:
import datetime
from django.utils import unittest
from statirator.core.utils import find_readers
from statirator.core.readers import dummy_reader
from statirator.core.parsers import parse_rst
and context from other files:
# Path: statirator/core/utils.py
# def find_readers():
# """Auto discover readers in installed apps.
#
# Each readers.py should have the READERS list with reader classes
# """
#
# from django.conf import settings
# from django.utils.importlib import import_module
# from django.utils.module_loading import module_has_submodule
#
# readers = []
# for app in settings.INSTALLED_APPS:
# mod = import_module(app)
# # Attempt to import the app's admin module.
# try:
# walk_mod = import_module('%s.readers' % app)
# if hasattr(walk_mod, 'READERS'):
# readers.extend(walk_mod.READERS)
# else:
# logging.warn(
# 'readers found in app %s, but has no READERS attrib',
# app)
# except:
# # Decide whether to bubble up this error. If the app just
# # doesn't have an readers module, we can ignore the error
# # attempting to import it, otherwise we want it to bubble up.
# if module_has_submodule(mod, 'readers'):
# raise
#
# return readers
#
# Path: statirator/core/readers.py
# def dummy_reader():
# "Just for tests"
#
# Path: statirator/core/parsers.py
# def parse_rst(content):
# """Parse multilingual rst document. Content should contain a metadata
# section which is the same for all languages, and sections for each
# language. the sections should be separated by comment of "--"". e.g::
#
# :slug: some-post-title-slugified
# :draft: 1
# :datetime: 2012-09-12 16:03:15
# :excerpt: Short description
# :image: /img/some_image.png
#
# This will be ignored in main meta section
#
# .. --
#
# =================
# English title
# =================
#
# :lang: en
# :tags: Tag1, Tag2
#
# The content of the English post
#
# And another paragraph
#
# .. --
#
# ====================
# כותרת עברית
# ====================
#
# :lang: he
# :tags: פייתון|python, Heb Tag2|slug
#
# The content of the post in Hebrew
#
# Returned value is a genearator::
#
# (common metadata, '', content),
# (metadata, title, content),
# (metadata, title, content) ...
# """
#
# parts = re.split(r'^\.\.\s+--\s*$', content, flags=re.M)
#
# for part in parts:
# content = ''
# title = ''
# metadata = {}
#
# tree = publish_doctree(part, settings_overrides=DEFAULTS)
#
# for info in tree.traverse(docinfo):
# for field in info.children:
# name_el, body_el = field.children
# name = name_el.astext().lower()
# if name in FIELDS:
# body = body_el.astext()
# transform = FIELDS[name]
#
# metadata[name] = transform(body) if transform else body
#
# writer = html5writer.SemanticHTML5Writer()
# publish_from_doctree(tree, writer=writer)
# content = writer.parts['body']
# title = writer.parts['title']
# yield metadata, title, content
, which may contain function names, class names, or code. Output only the next line. | כותרת עברית |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
TEST_DOC = """
:slug: some-post-title-slugified
:draft: 1
:datetime: 2012-09-12 16:03:15
This will be ignored in main meta section
.. --
=================
English title
=================
:lang: en
:tags: Tag1, Tag2
The content of the English post
And another paragraph
.. --
====================
כותרת עברית
====================
<|code_end|>
. Use current file imports:
(import datetime
from django.utils import unittest
from statirator.core.utils import find_readers
from statirator.core.readers import dummy_reader
from statirator.core.parsers import parse_rst)
and context including class names, function names, or small code snippets from other files:
# Path: statirator/core/utils.py
# def find_readers():
# """Auto discover readers in installed apps.
#
# Each readers.py should have the READERS list with reader classes
# """
#
# from django.conf import settings
# from django.utils.importlib import import_module
# from django.utils.module_loading import module_has_submodule
#
# readers = []
# for app in settings.INSTALLED_APPS:
# mod = import_module(app)
# # Attempt to import the app's admin module.
# try:
# walk_mod = import_module('%s.readers' % app)
# if hasattr(walk_mod, 'READERS'):
# readers.extend(walk_mod.READERS)
# else:
# logging.warn(
# 'readers found in app %s, but has no READERS attrib',
# app)
# except:
# # Decide whether to bubble up this error. If the app just
# # doesn't have an readers module, we can ignore the error
# # attempting to import it, otherwise we want it to bubble up.
# if module_has_submodule(mod, 'readers'):
# raise
#
# return readers
#
# Path: statirator/core/readers.py
# def dummy_reader():
# "Just for tests"
#
# Path: statirator/core/parsers.py
# def parse_rst(content):
# """Parse multilingual rst document. Content should contain a metadata
# section which is the same for all languages, and sections for each
# language. the sections should be separated by comment of "--"". e.g::
#
# :slug: some-post-title-slugified
# :draft: 1
# :datetime: 2012-09-12 16:03:15
# :excerpt: Short description
# :image: /img/some_image.png
#
# This will be ignored in main meta section
#
# .. --
#
# =================
# English title
# =================
#
# :lang: en
# :tags: Tag1, Tag2
#
# The content of the English post
#
# And another paragraph
#
# .. --
#
# ====================
# כותרת עברית
# ====================
#
# :lang: he
# :tags: פייתון|python, Heb Tag2|slug
#
# The content of the post in Hebrew
#
# Returned value is a genearator::
#
# (common metadata, '', content),
# (metadata, title, content),
# (metadata, title, content) ...
# """
#
# parts = re.split(r'^\.\.\s+--\s*$', content, flags=re.M)
#
# for part in parts:
# content = ''
# title = ''
# metadata = {}
#
# tree = publish_doctree(part, settings_overrides=DEFAULTS)
#
# for info in tree.traverse(docinfo):
# for field in info.children:
# name_el, body_el = field.children
# name = name_el.astext().lower()
# if name in FIELDS:
# body = body_el.astext()
# transform = FIELDS[name]
#
# metadata[name] = transform(body) if transform else body
#
# writer = html5writer.SemanticHTML5Writer()
# publish_from_doctree(tree, writer=writer)
# content = writer.parts['body']
# title = writer.parts['title']
# yield metadata, title, content
. Output only the next line. | :lang: he |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import
class PagesRenderer(StaticSiteRenderer):
def get_paths(self):
paths = []
for lang_code, lang_name in settings.LANGUAGES:
activate(lang_code)
items = Page.objects.filter(language=lang_code)
paths.extend([i.get_absolute_url() for i in items])
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.utils.translation import activate
from django_medusa.renderers import StaticSiteRenderer
from .models import Page
and any relevant context from other files:
# Path: statirator/pages/models.py
# class Page(models.Model, TranslationsMixin):
# """A multilingual page"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# content = models.TextField()
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# page_type = models.CharField(max_length=5, choices=PAGE_TYPES)
# description = models.CharField(max_length=255, blank=True, null=True)
#
# def __unicode__(self):
# return self.title or self.slug
#
# @i18n_permalink
# def get_absolute_url(self):
# # index is a special case
# if self.slug == 'index':
# return ('pages_index', (), {})
#
# return ('pages_page', (), {'slug': self.slug})
. Output only the next line. | return paths |
Given the code snippet: <|code_start|>
# we need to make sure the pages slug won't catch the /en/ etc for index pages
# in various languages
langs_re = '|'.join(x[0] for x in settings.LANGUAGES)
sitemaps = {
'pages': psitemap.PagesSiteMap,
'blog': bsitemap.BlogSiteMap,
}
urlpatterns = patterns(
'',
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/$',
views.PostView.as_view(), name='blog_post'),
url(r'^archive/$', views.ArchiveView.as_view(), name='blog_archive'),
url(r'^blog\.rss$', feeds.PostsFeed(), name='blog_feed'),
url(r'^tags/$', views.TagsView.as_view(), name='blog_tags'),
url(r'^tags/(?P<slug>[-\w]+)/$', views.TagView.as_view(), name='blog_tag'),
url(r'^tags/(?P<slug>[-\w]+)/tag.rss$', feeds.TagFeed(),
name='blog_tag_feed'),
# keep those last
url(r'^$', pviews.PageView.as_view(), {'slug': 'index'}, name='pages_index'),
url(r'^(?P<slug>(?!%s)[-\w]+)/$' % langs_re, pviews.PageView.as_view(),
name='pages_page'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from statirator.blog import views, feeds
from statirator.pages import views as pviews, sitemap as psitemap
from statirator.blog import sitemap as bsitemap
and context (functions, classes, or occasionally code) from other files:
# Path: statirator/blog/views.py
# class PostView(DetailView):
# class ArchiveView(ListView):
# class TagView(DetailView):
# class TagsView(TemplateView):
# def get_queryset(self):
# def get_queryset(self):
# def get_context_data(self, **kwargs):
# def get_object(self):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
#
# Path: statirator/blog/feeds.py
# class PostsFeed(LanguageFeed):
# class TagFeed(LanguageFeed):
# def title(self):
# def link(self):
# def items(self):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
# def item_categories(self, item):
# def get_object(self, request, slug):
# def title(self, obj):
# def items(self, obj):
# def link(self, obj):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
#
# Path: statirator/pages/views.py
# class PageView(DetailView):
# def get_queryset(self):
# def render_to_response(self, context, **response_kwargs):
#
# Path: statirator/pages/sitemap.py
# class PagesSiteMap(Sitemap):
# def items(self):
#
# Path: statirator/blog/sitemap.py
# class BlogSiteMap(Sitemap):
# def items(self):
. Output only the next line. | ) |
Using the snippet: <|code_start|>
# we need to make sure the pages slug won't catch the /en/ etc for index pages
# in various languages
langs_re = '|'.join(x[0] for x in settings.LANGUAGES)
sitemaps = {
'pages': psitemap.PagesSiteMap,
'blog': bsitemap.BlogSiteMap,
}
urlpatterns = patterns(
'',
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/$',
views.PostView.as_view(), name='blog_post'),
url(r'^archive/$', views.ArchiveView.as_view(), name='blog_archive'),
url(r'^blog\.rss$', feeds.PostsFeed(), name='blog_feed'),
url(r'^tags/$', views.TagsView.as_view(), name='blog_tags'),
url(r'^tags/(?P<slug>[-\w]+)/$', views.TagView.as_view(), name='blog_tag'),
url(r'^tags/(?P<slug>[-\w]+)/tag.rss$', feeds.TagFeed(),
name='blog_tag_feed'),
# keep those last
url(r'^$', pviews.PageView.as_view(), {'slug': 'index'}, name='pages_index'),
url(r'^(?P<slug>(?!%s)[-\w]+)/$' % langs_re, pviews.PageView.as_view(),
name='pages_page'),
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from statirator.blog import views, feeds
from statirator.pages import views as pviews, sitemap as psitemap
from statirator.blog import sitemap as bsitemap
and context (class names, function names, or code) available:
# Path: statirator/blog/views.py
# class PostView(DetailView):
# class ArchiveView(ListView):
# class TagView(DetailView):
# class TagsView(TemplateView):
# def get_queryset(self):
# def get_queryset(self):
# def get_context_data(self, **kwargs):
# def get_object(self):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
#
# Path: statirator/blog/feeds.py
# class PostsFeed(LanguageFeed):
# class TagFeed(LanguageFeed):
# def title(self):
# def link(self):
# def items(self):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
# def item_categories(self, item):
# def get_object(self, request, slug):
# def title(self, obj):
# def items(self, obj):
# def link(self, obj):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
#
# Path: statirator/pages/views.py
# class PageView(DetailView):
# def get_queryset(self):
# def render_to_response(self, context, **response_kwargs):
#
# Path: statirator/pages/sitemap.py
# class PagesSiteMap(Sitemap):
# def items(self):
#
# Path: statirator/blog/sitemap.py
# class BlogSiteMap(Sitemap):
# def items(self):
. Output only the next line. | ) |
Given snippet: <|code_start|>sitemaps = {
'pages': psitemap.PagesSiteMap,
'blog': bsitemap.BlogSiteMap,
}
urlpatterns = patterns(
'',
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/$',
views.PostView.as_view(), name='blog_post'),
url(r'^archive/$', views.ArchiveView.as_view(), name='blog_archive'),
url(r'^blog\.rss$', feeds.PostsFeed(), name='blog_feed'),
url(r'^tags/$', views.TagsView.as_view(), name='blog_tags'),
url(r'^tags/(?P<slug>[-\w]+)/$', views.TagView.as_view(), name='blog_tag'),
url(r'^tags/(?P<slug>[-\w]+)/tag.rss$', feeds.TagFeed(),
name='blog_tag_feed'),
# keep those last
url(r'^$', pviews.PageView.as_view(), {'slug': 'index'}, name='pages_index'),
url(r'^(?P<slug>(?!%s)[-\w]+)/$' % langs_re, pviews.PageView.as_view(),
name='pages_page'),
)
# make all the urls patterns again, with i18n translations, that way default
# language is not prefixed
urlpatterns += i18n_patterns(
'',
*[url(x._regex, x.callback, x.default_args, name='i18n_' + x.name)
for x in urlpatterns]
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from statirator.blog import views, feeds
from statirator.pages import views as pviews, sitemap as psitemap
from statirator.blog import sitemap as bsitemap
and context:
# Path: statirator/blog/views.py
# class PostView(DetailView):
# class ArchiveView(ListView):
# class TagView(DetailView):
# class TagsView(TemplateView):
# def get_queryset(self):
# def get_queryset(self):
# def get_context_data(self, **kwargs):
# def get_object(self):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
#
# Path: statirator/blog/feeds.py
# class PostsFeed(LanguageFeed):
# class TagFeed(LanguageFeed):
# def title(self):
# def link(self):
# def items(self):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
# def item_categories(self, item):
# def get_object(self, request, slug):
# def title(self, obj):
# def items(self, obj):
# def link(self, obj):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
#
# Path: statirator/pages/views.py
# class PageView(DetailView):
# def get_queryset(self):
# def render_to_response(self, context, **response_kwargs):
#
# Path: statirator/pages/sitemap.py
# class PagesSiteMap(Sitemap):
# def items(self):
#
# Path: statirator/blog/sitemap.py
# class BlogSiteMap(Sitemap):
# def items(self):
which might include code, classes, or functions. Output only the next line. | urlpatterns += patterns('django.contrib.sitemaps.views', |
Predict the next line for this snippet: <|code_start|>
# we need to make sure the pages slug won't catch the /en/ etc for index pages
# in various languages
langs_re = '|'.join(x[0] for x in settings.LANGUAGES)
sitemaps = {
'pages': psitemap.PagesSiteMap,
'blog': bsitemap.BlogSiteMap,
}
urlpatterns = patterns(
'',
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/$',
views.PostView.as_view(), name='blog_post'),
url(r'^archive/$', views.ArchiveView.as_view(), name='blog_archive'),
url(r'^blog\.rss$', feeds.PostsFeed(), name='blog_feed'),
url(r'^tags/$', views.TagsView.as_view(), name='blog_tags'),
url(r'^tags/(?P<slug>[-\w]+)/$', views.TagView.as_view(), name='blog_tag'),
url(r'^tags/(?P<slug>[-\w]+)/tag.rss$', feeds.TagFeed(),
name='blog_tag_feed'),
# keep those last
url(r'^$', pviews.PageView.as_view(), {'slug': 'index'}, name='pages_index'),
url(r'^(?P<slug>(?!%s)[-\w]+)/$' % langs_re, pviews.PageView.as_view(),
name='pages_page'),
)
# make all the urls patterns again, with i18n translations, that way default
# language is not prefixed
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from statirator.blog import views, feeds
from statirator.pages import views as pviews, sitemap as psitemap
from statirator.blog import sitemap as bsitemap
and context from other files:
# Path: statirator/blog/views.py
# class PostView(DetailView):
# class ArchiveView(ListView):
# class TagView(DetailView):
# class TagsView(TemplateView):
# def get_queryset(self):
# def get_queryset(self):
# def get_context_data(self, **kwargs):
# def get_object(self):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
#
# Path: statirator/blog/feeds.py
# class PostsFeed(LanguageFeed):
# class TagFeed(LanguageFeed):
# def title(self):
# def link(self):
# def items(self):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
# def item_categories(self, item):
# def get_object(self, request, slug):
# def title(self, obj):
# def items(self, obj):
# def link(self, obj):
# def item_title(self, item):
# def item_pubdate(self, item):
# def item_description(self, item):
#
# Path: statirator/pages/views.py
# class PageView(DetailView):
# def get_queryset(self):
# def render_to_response(self, context, **response_kwargs):
#
# Path: statirator/pages/sitemap.py
# class PagesSiteMap(Sitemap):
# def items(self):
#
# Path: statirator/blog/sitemap.py
# class BlogSiteMap(Sitemap):
# def items(self):
, which may contain function names, class names, or code. Output only the next line. | urlpatterns += i18n_patterns( |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
class BlogSiteMap(Sitemap):
def items(self):
"Return the items starting with defualt language and it's index page"
<|code_end|>
with the help of current file imports:
from django.contrib.sitemaps import Sitemap
from django.conf import settings
from django.core.urlresolvers import reverse
from statirator.core.models import DummyTranslation
from .models import Post, I18NTag
and context from other files:
# Path: statirator/core/models.py
# class DummyTranslation(object):
# """Dummy translations for views to put in template context in case there's no
# actual object"""
#
# def __init__(self, request, language=None, title=None, path=None):
# self.title = title
# self.request = request
# self.language = language or request.LANGUAGE_CODE
# self.path = path or request.path
#
# def get_translations(self):
# for code, name in settings.LANGUAGES:
# if code != self.language:
# yield DummyTranslation(self.request, code, name, self.path)
#
# def get_language(self):
# return LANGS_DICT.get(self.language)
#
# def get_absolute_url(self):
# return path_to_lang(self.path, self.language)
#
# Path: statirator/blog/models.py
# class Post(models.Model, TranslationsMixin):
# """Multilingual blog posts"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# is_published = models.BooleanField(default=True, max_length=200)
# excerpt = models.TextField(blank=True, null=True)
# content = models.TextField()
# pubdate = models.DateTimeField(db_index=True)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# image = models.CharField(max_length=255, blank=True, null=True)
#
# tags = TaggableManager(through=I18NTaggedItem)
#
# def __unicode__(self):
# return self.title
#
# @i18n_permalink
# def get_absolute_url(self):
# from .utils import get_post_urlpattern_keys
#
# keys = get_post_urlpattern_keys()
#
# kwargs = {k: getattr(self, k) for k in keys}
#
# return ('blog_post', (), kwargs)
#
# def get_next(self):
# return self.get_next_by_pubdate(language=self.language,
# is_published=True)
#
# def get_previous(self):
# return self.get_previous_by_pubdate(language=self.language,
# is_published=True)
#
# @property
# def tags_list(self):
# return self.tags.values_list('name', flat=True)
#
# @property
# def year(self):
# return self.pubdate.year
#
# @property
# def month(self):
# """Get a 2 digit formatted month"""
# return self.pubdate.strftime('%m')
#
# @property
# def day(self):
# """Get a 2 digit formatted day"""
# return self.pubdate.strftime('%d')
#
# class I18NTag(models.Model, TranslationsMixin):
# """Extend Taggit's Tag:
#
# * Add a language field
# * slug will be appended the locale, since we can't override the uniqute in
# the abstract model
# * slug_no_locale will have the actual slug
#
# """
#
# SLUG_FIELD_FOR_TRANSLATIONS = 'slug_no_locale' # we need to override this
#
# name = models.CharField(verbose_name=_('Name'), max_length=100)
# slug = models.SlugField(verbose_name=_('Slug'), unique=True,
# max_length=100)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# slug_no_locale = models.SlugField(verbose_name=_('Slug without locale'),
# unique=False, max_length=100)
#
# class Meta:
# unique_together = ('language', 'slug_no_locale')
#
# @i18n_permalink
# def get_absolute_url(self):
# return ('blog_tag', (), {'slug': self.slug_no_locale})
#
# @i18n_permalink
# def get_feed_url(self):
# return ('blog_tag_feed', (), {'slug': self.slug_no_locale})
#
# def save(self, *args, **kwargs):
# if not self.pk and not self.slug:
# self.slug = self.slugify(self.name)
# from django.db import router
# using = kwargs.get("using") or router.db_for_write(
# type(self), instance=self)
# # Make sure we write to the same db for all attempted writes,
# # with a multi-master setup, theoretically we could try to
# # write and rollback on different DBs
# kwargs["using"] = using
# # Be oportunistic and try to save the tag, this should work for
# # most cases ;)
# try:
# with atomic(using=using):
# res = super(I18NTag, self).save(*args, **kwargs)
# return res
# except IntegrityError:
# pass
# # Now try to find existing slugs with similar names
# slugs = set(I18NTag.objects.filter(slug__startswith=self.slug)
# .values_list('slug', flat=True))
# i = 1
# while True:
# slug = self.slugify(self.name, i)
# if slug not in slugs:
# self.slug = slug
# # We purposely ignore concurrecny issues here for now.
# # (That is, till we found a nice solution...)
# return super(I18NTag, self).save(*args, **kwargs)
# i += 1
# else:
# return super(I18NTag, self).save(*args, **kwargs)
#
# __str__ = TagBase.__str__
# slugify = TagBase.slugify
, which may contain function names, class names, or code. Output only the next line. | default = settings.LANGUAGE_CODE |
Next line prediction: <|code_start|>from __future__ import absolute_import
class BlogSiteMap(Sitemap):
def items(self):
"Return the items starting with defualt language and it's index page"
default = settings.LANGUAGE_CODE
langs = [default] + [x[0] for x in settings.LANGUAGES if x[0] != default]
items = []
for lang in langs:
for slug in ('blog_archive', 'blog_tags'):
dummy = DummyTranslation(None, lang, slug, reverse(slug))
<|code_end|>
. Use current file imports:
(from django.contrib.sitemaps import Sitemap
from django.conf import settings
from django.core.urlresolvers import reverse
from statirator.core.models import DummyTranslation
from .models import Post, I18NTag)
and context including class names, function names, or small code snippets from other files:
# Path: statirator/core/models.py
# class DummyTranslation(object):
# """Dummy translations for views to put in template context in case there's no
# actual object"""
#
# def __init__(self, request, language=None, title=None, path=None):
# self.title = title
# self.request = request
# self.language = language or request.LANGUAGE_CODE
# self.path = path or request.path
#
# def get_translations(self):
# for code, name in settings.LANGUAGES:
# if code != self.language:
# yield DummyTranslation(self.request, code, name, self.path)
#
# def get_language(self):
# return LANGS_DICT.get(self.language)
#
# def get_absolute_url(self):
# return path_to_lang(self.path, self.language)
#
# Path: statirator/blog/models.py
# class Post(models.Model, TranslationsMixin):
# """Multilingual blog posts"""
#
# title = models.CharField(max_length=200)
# slug = models.SlugField(max_length=200)
# is_published = models.BooleanField(default=True, max_length=200)
# excerpt = models.TextField(blank=True, null=True)
# content = models.TextField()
# pubdate = models.DateTimeField(db_index=True)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# image = models.CharField(max_length=255, blank=True, null=True)
#
# tags = TaggableManager(through=I18NTaggedItem)
#
# def __unicode__(self):
# return self.title
#
# @i18n_permalink
# def get_absolute_url(self):
# from .utils import get_post_urlpattern_keys
#
# keys = get_post_urlpattern_keys()
#
# kwargs = {k: getattr(self, k) for k in keys}
#
# return ('blog_post', (), kwargs)
#
# def get_next(self):
# return self.get_next_by_pubdate(language=self.language,
# is_published=True)
#
# def get_previous(self):
# return self.get_previous_by_pubdate(language=self.language,
# is_published=True)
#
# @property
# def tags_list(self):
# return self.tags.values_list('name', flat=True)
#
# @property
# def year(self):
# return self.pubdate.year
#
# @property
# def month(self):
# """Get a 2 digit formatted month"""
# return self.pubdate.strftime('%m')
#
# @property
# def day(self):
# """Get a 2 digit formatted day"""
# return self.pubdate.strftime('%d')
#
# class I18NTag(models.Model, TranslationsMixin):
# """Extend Taggit's Tag:
#
# * Add a language field
# * slug will be appended the locale, since we can't override the uniqute in
# the abstract model
# * slug_no_locale will have the actual slug
#
# """
#
# SLUG_FIELD_FOR_TRANSLATIONS = 'slug_no_locale' # we need to override this
#
# name = models.CharField(verbose_name=_('Name'), max_length=100)
# slug = models.SlugField(verbose_name=_('Slug'), unique=True,
# max_length=100)
# language = models.CharField(max_length=5, choices=settings.LANGUAGES,
# blank=True, default=settings.LANGUAGE_CODE)
# slug_no_locale = models.SlugField(verbose_name=_('Slug without locale'),
# unique=False, max_length=100)
#
# class Meta:
# unique_together = ('language', 'slug_no_locale')
#
# @i18n_permalink
# def get_absolute_url(self):
# return ('blog_tag', (), {'slug': self.slug_no_locale})
#
# @i18n_permalink
# def get_feed_url(self):
# return ('blog_tag_feed', (), {'slug': self.slug_no_locale})
#
# def save(self, *args, **kwargs):
# if not self.pk and not self.slug:
# self.slug = self.slugify(self.name)
# from django.db import router
# using = kwargs.get("using") or router.db_for_write(
# type(self), instance=self)
# # Make sure we write to the same db for all attempted writes,
# # with a multi-master setup, theoretically we could try to
# # write and rollback on different DBs
# kwargs["using"] = using
# # Be oportunistic and try to save the tag, this should work for
# # most cases ;)
# try:
# with atomic(using=using):
# res = super(I18NTag, self).save(*args, **kwargs)
# return res
# except IntegrityError:
# pass
# # Now try to find existing slugs with similar names
# slugs = set(I18NTag.objects.filter(slug__startswith=self.slug)
# .values_list('slug', flat=True))
# i = 1
# while True:
# slug = self.slugify(self.name, i)
# if slug not in slugs:
# self.slug = slug
# # We purposely ignore concurrecny issues here for now.
# # (That is, till we found a nice solution...)
# return super(I18NTag, self).save(*args, **kwargs)
# i += 1
# else:
# return super(I18NTag, self).save(*args, **kwargs)
#
# __str__ = TagBase.__str__
# slugify = TagBase.slugify
. Output only the next line. | items.append(dummy) |
Continue the code snippet: <|code_start|>
pygame.display.flip()
display.wait(self.FEEDBACK_DURATION)
# Display blank screen (ITI)
display.blank_screen(self.screen, self.background, self.ITI)
def display_sequence(self, sequence):
for i, number in enumerate(sequence):
# Display number
self.screen.blit(self.background, (0, 0))
display.text(self.screen, self.stim_font, number, "center", "center")
pygame.display.flip()
display.wait(self.STIM_DURATION)
# Display blank screen
display.blank_screen(
self.screen, self.background, self.BETWEEN_STIM_DURATION
)
def run(self):
# Instructions screen
self.screen.blit(self.background, (0, 0))
display.text(self.screen, self.font, "Sternberg Task", "center", 100)
display.text(
self.screen,
self.font,
"You will see a sequence of numbers, one at a time. "
<|code_end|>
. Use current file imports:
import os
import sys
import random
import time
import pandas as pd
import pygame
from pygame.locals import *
from itertools import product
from utils import display
and context (classes, functions, or code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
. Output only the next line. | "Try your best to memorize them", |
Predict the next line after this snippet: <|code_start|> project_name = self.projectNameValue.text()
researcher = self.researcherValue.text()
dir_path = self.dirValue.text()
# Check all fields have been filled
if project_name != "" and researcher != "" and dir_path != "":
# Get list of all project names
saved_projects = []
for person in self.project_list.keys():
for project in self.project_list[person].keys():
saved_projects.append(project)
# Save if project name is not already in use
if project_name not in set(saved_projects):
project_info = {"created": time.time(), "path": dir_path}
try:
self.project_list[researcher][project_name] = project_info
except KeyError:
self.project_list[researcher] = {}
self.project_list[researcher][project_name] = project_info
with open(os.path.join(self.base_dir, "projects.txt"), "w+") as f:
json.dump(self.project_list, f, indent=4)
self.close()
else:
QtWidgets.QMessageBox.warning(
<|code_end|>
using the current file's imports:
import os
import json
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_new_window_qt
and any relevant context from other files:
# Path: designer/project_new_window_qt.py
# class Ui_NewProjectWindow(object):
# def setupUi(self, NewProjectWindow):
# def retranslateUi(self, NewProjectWindow):
. Output only the next line. | self, "Error", "Project name already exists" |
Given snippet: <|code_start|> return user_sequence
def check_answer(self, user_string, actual_string):
if user_string[::-1] == actual_string:
return True
else:
return False
def run(self):
# Instructions
self.screen.blit(self.background, (0, 0))
display.text(
self.screen,
self.font,
"Backwards Digit Span",
"center",
self.screen_y / 2 - 300,
)
display.text(
self.screen,
self.font,
"You will be shown a number sequence, " "one number at a time",
100,
self.screen_y / 2 - 200,
)
display.text(
self.screen,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import random
import pandas as pd
import numpy as np
import pygame
from pygame.locals import *
from utils import display
and context:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
which might include code, classes, or functions. Output only the next line. | self.font, |
Based on the snippet: <|code_start|> # Display fixation in the center
display.image(self.screen, self.img_fixation, "center", "center")
# Display cue above and below fixation
display.image(
self.screen,
self.img_cue,
"center",
self.screen_y / 2 - self.fixation_h - self.TARGET_OFFSET,
)
display.image(
self.screen,
self.img_cue,
"center",
self.screen_y / 2 + self.TARGET_OFFSET,
)
elif cue_type == "spatial":
cue_location = data["location"][trial_num]
# Display fixation in the center
display.image(self.screen, self.img_fixation, "center", "center")
# Display cue at target location
if cue_location == "top":
display.image(
self.screen,
self.img_cue,
"center",
self.screen_y / 2 - self.fixation_h - self.TARGET_OFFSET,
)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import time
import pandas as pd
import numpy as np
import pygame
from pygame.locals import *
from itertools import product
from utils import display
and context (classes, functions, sometimes code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
. Output only the next line. | elif cue_location == "bottom": |
Based on the snippet: <|code_start|>class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
def __init__(self, base_dir, project_dir, res_width, res_height):
super(BatteryWindow, self).__init__()
# Setup the main window UI
self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context (classes, functions, sometimes code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.set_default_settings() |
Next line prediction: <|code_start|> self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
self.set_default_settings()
# Set initial window size/pos from saved settings
self.settings.beginGroup("MainWindow")
self.resize(self.settings.value("size"))
<|code_end|>
. Use current file imports:
(import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg)
and context including class names, function names, or small code snippets from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.move(self.settings.value("pos")) |
Here is a snippet: <|code_start|>
class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
def __init__(self, base_dir, project_dir, res_width, res_height):
super(BatteryWindow, self).__init__()
# Setup the main window UI
self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
, which may include functions, classes, or code. Output only the next line. | self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon)) |
Here is a snippet: <|code_start|> # Initialize task settings
self.task_fullscreen = None
self.task_borderless = None
self.task_width = None
self.task_height = None
# Keep reference to the about and settings window objects
self.about = None
self.update = None
self.settings_window = None
# Initialize pygame screen
self.pygame_screen = None
# Define URLs
self.links = values.get_links()
# Make data folder if it doesnt exist
self.dataPath = os.path.join(self.project_dir, "data")
if not os.path.isdir(self.dataPath):
os.makedirs(self.dataPath)
# Handle menu bar item click events
self.actionExit.triggered.connect(self.close)
self.actionSettings.triggered.connect(self.show_settings)
self.actionDocumentation.triggered.connect(self.show_documentation)
self.actionLicense.triggered.connect(self.show_license)
self.actionContribute.triggered.connect(self.show_contribute)
self.actionBrowse_Issues.triggered.connect(self.show_browse_issues)
self.actionReport_Bug.triggered.connect(self.show_new_issue)
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
, which may include functions, classes, or code. Output only the next line. | self.actionRequest_Feature.triggered.connect(self.show_new_issue) |
Given the code snippet: <|code_start|>
# Initialize pygame screen
self.pygame_screen = None
# Define URLs
self.links = values.get_links()
# Make data folder if it doesnt exist
self.dataPath = os.path.join(self.project_dir, "data")
if not os.path.isdir(self.dataPath):
os.makedirs(self.dataPath)
# Handle menu bar item click events
self.actionExit.triggered.connect(self.close)
self.actionSettings.triggered.connect(self.show_settings)
self.actionDocumentation.triggered.connect(self.show_documentation)
self.actionLicense.triggered.connect(self.show_license)
self.actionContribute.triggered.connect(self.show_contribute)
self.actionBrowse_Issues.triggered.connect(self.show_browse_issues)
self.actionReport_Bug.triggered.connect(self.show_new_issue)
self.actionRequest_Feature.triggered.connect(self.show_new_issue)
self.actionCheck_for_updates.triggered.connect(self.show_update)
self.actionAbout.triggered.connect(self.show_about)
# Bind button events
self.cancelButton.clicked.connect(self.close)
self.startButton.clicked.connect(self.start)
self.randomOrderCheck.clicked.connect(self.random_order_selected)
self.selectAllButton.clicked.connect(self.select_all)
self.deselectAllButton.clicked.connect(self.deselect_all)
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context (functions, classes, or occasionally code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.upButton.clicked.connect(self.move_up) |
Continue the code snippet: <|code_start|> # Setup the main window UI
self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
self.set_default_settings()
# Set initial window size/pos from saved settings
self.settings.beginGroup("MainWindow")
<|code_end|>
. Use current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context (classes, functions, or code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.resize(self.settings.value("size")) |
Based on the snippet: <|code_start|>
# Initialize pygame screen
self.pygame_screen = None
# Define URLs
self.links = values.get_links()
# Make data folder if it doesnt exist
self.dataPath = os.path.join(self.project_dir, "data")
if not os.path.isdir(self.dataPath):
os.makedirs(self.dataPath)
# Handle menu bar item click events
self.actionExit.triggered.connect(self.close)
self.actionSettings.triggered.connect(self.show_settings)
self.actionDocumentation.triggered.connect(self.show_documentation)
self.actionLicense.triggered.connect(self.show_license)
self.actionContribute.triggered.connect(self.show_contribute)
self.actionBrowse_Issues.triggered.connect(self.show_browse_issues)
self.actionReport_Bug.triggered.connect(self.show_new_issue)
self.actionRequest_Feature.triggered.connect(self.show_new_issue)
self.actionCheck_for_updates.triggered.connect(self.show_update)
self.actionAbout.triggered.connect(self.show_about)
# Bind button events
self.cancelButton.clicked.connect(self.close)
self.startButton.clicked.connect(self.start)
self.randomOrderCheck.clicked.connect(self.random_order_selected)
self.selectAllButton.clicked.connect(self.select_all)
self.deselectAllButton.clicked.connect(self.deselect_all)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context (classes, functions, sometimes code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.upButton.clicked.connect(self.move_up) |
Given snippet: <|code_start|> self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
self.set_default_settings()
# Set initial window size/pos from saved settings
self.settings.beginGroup("MainWindow")
self.resize(self.settings.value("size"))
self.move(self.settings.value("pos"))
self.settings.endGroup()
# Initialize task settings
self.task_fullscreen = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
which might include code, classes, or functions. Output only the next line. | self.task_borderless = None |
Given snippet: <|code_start|> self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
self.set_default_settings()
# Set initial window size/pos from saved settings
self.settings.beginGroup("MainWindow")
self.resize(self.settings.value("size"))
self.move(self.settings.value("pos"))
self.settings.endGroup()
# Initialize task settings
self.task_fullscreen = None
self.task_borderless = None
self.task_width = None
self.task_height = None
# Keep reference to the about and settings window objects
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
which might include code, classes, or functions. Output only the next line. | self.about = None |
Given the following code snippet before the placeholder: <|code_start|> self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False)
# Read and save default settings
self.set_default_settings()
# Set initial window size/pos from saved settings
self.settings.beginGroup("MainWindow")
self.resize(self.settings.value("size"))
self.move(self.settings.value("pos"))
self.settings.endGroup()
# Initialize task settings
self.task_fullscreen = None
self.task_borderless = None
self.task_width = None
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context including class names, function names, and sometimes code from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.task_height = None |
Given the code snippet: <|code_start|>
class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
def __init__(self, base_dir, project_dir, res_width, res_height):
super(BatteryWindow, self).__init__()
# Setup the main window UI
self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
self.project_dir = project_dir
self.res_width = res_width
self.res_height = res_height
# Create/open settings file with no registry fallback
self.settings_file = os.path.join(self.project_dir, "battery_settings.ini")
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context (functions, classes, or occasionally code) from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
. Output only the next line. | self.settings = QtCore.QSettings(self.settings_file, QtCore.QSettings.IniFormat) |
Predict the next line for this snippet: <|code_start|>
class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
def __init__(self, base_dir, project_dir, res_width, res_height):
super(BatteryWindow, self).__init__()
# Setup the main window UI
self.setupUi(self)
# Set app icon
self.setWindowIcon(QtGui.QIcon(os.path.join("images", "icon_sml.png")))
self.github_icon = os.path.join("images", "github_icon.png")
self.actionDocumentation.setIcon(QtGui.QIcon(self.github_icon))
self.actionLicense.setIcon(QtGui.QIcon(self.github_icon))
self.actionContribute.setIcon(QtGui.QIcon(self.github_icon))
self.actionBrowse_Issues.setIcon(QtGui.QIcon(self.github_icon))
self.actionReport_Bug.setIcon(QtGui.QIcon(self.github_icon))
self.actionRequest_Feature.setIcon(QtGui.QIcon(self.github_icon))
# Get passed values
self.base_dir = base_dir
<|code_end|>
with the help of current file imports:
import os
import sys
import random
import datetime
import pygame
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import display, values
from designer import battery_window_qt
from interface import about_dialog, update_dialog, settings_window
from tasks import ant, flanker, mrt, sart, ravens, digitspan_backwards, sternberg
and context from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
#
# Path: utils/values.py
# def get_version():
# def get_links():
#
# Path: designer/battery_window_qt.py
# class Ui_CognitiveBattery(object):
# def setupUi(self, CognitiveBattery):
# def retranslateUi(self, CognitiveBattery):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: interface/settings_window.py
# class SettingsWindow(QtWidgets.QDialog, settings_window_qt.Ui_SettingsDialog):
# def __init__(self, parent, settings):
# def set_windowed_options_state(self, state):
# def task_fullscreen_checkbox(self):
# def save_window_information(self):
# def save_settings(self):
# def cancel_settings(self):
#
# Path: tasks/ant.py
# class ANT(object):
# def __init__(self, screen, background, blocks=3):
# def create_block(self, block_num, combinations, trial_type):
# def display_flanker(self, flanker_type, location, direction):
# def display_trial(self, trial_num, data, trial_type):
# def run_block(self, block_num, total_blocks, block_type):
# def run(self):
#
# Path: tasks/flanker.py
# class Flanker(object):
# def __init__(
# self,
# screen,
# background,
# dark_mode=False,
# sets_practice=3,
# sets_main=25,
# blocks_compat=1,
# blocks_incompat=0,
# block_order="compatible",
# ):
# def create_block(self, block_num, combinations, trial_type, compatibility):
# def display_flanker(self, flanker_type, direction):
# def display_trial(self, trial_num, data):
# def run_block(
# self, block_num, total_blocks, block_type, compatibility, second_half=False
# ):
# def run(self):
#
# Path: tasks/mrt.py
# class MRT(object):
# def __init__(self, screen, background):
# def pressSpace(self, x, y):
# def mainExperiment(self, section, data):
# def run(self):
#
# Path: tasks/sart.py
# class SART(object):
# def __init__(self, screen, background):
# def display_trial(self, i, data):
# def run(self):
#
# Path: tasks/ravens.py
# class Ravens(object):
# def __init__(self, screen, background, start=13, numTrials=12):
# def pressSpace(self, x, y):
# def displayTrial(self, i, data, type):
# def run(self):
#
# Path: tasks/digitspan_backwards.py
# class DigitspanBackwards(object):
# def __init__(self, screen, background):
# def display_numbers(self, i, data):
# def number_entry(self):
# def check_answer(self, user_string, actual_string):
# def run(self):
#
# Path: tasks/sternberg.py
# class Sternberg(object):
# def __init__(self, screen, background, blocks=2):
# def create_trials(self, combinations):
# def display_trial(self, df, i, r, trial_type):
# def display_sequence(self, sequence):
# def run(self):
, which may contain function names, class names, or code. Output only the next line. | self.project_dir = project_dir |
Using the snippet: <|code_start|> # Use the 29mm mask image (as described by Robertson 1997)
self.img_mask = pygame.image.load(os.path.join(self.image_path, "mask_29.png"))
# Create trial sequence
self.number_set = list(range(1, 10)) * 25 # Numbers 1-9
random.shuffle(self.number_set)
self.trial_num = list(range(1, len(self.number_set) + 1))
# Create output dataframe
self.all_data = pd.DataFrame()
self.all_data["trial"] = self.trial_num
self.all_data["stimulus"] = self.number_set
def display_trial(self, i, data):
# Randomly choose font size for this trial
size_index = random.randint(0, len(self.stim_fonts) - 1)
trial_font = self.stim_fonts[size_index]
key_press = 0
data.set_value(i, "RT", 1150)
# Display number
self.screen.blit(self.background, (0, 0))
display.text(
self.screen,
trial_font,
str(data["stimulus"][i]),
"center",
"center",
(255, 255, 255),
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import time
import random
import pandas as pd
import pygame
from pygame.locals import *
from utils import display
and context (class names, function names, or code) available:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
. Output only the next line. | ) |
Given the code snippet: <|code_start|>
# Open web browser to the documentation page
def show_documentation(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["github"]))
# Open web browser to the license page
def show_license(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["license"]))
# Open web browser to the github develop branch for contribution
def show_contribute(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["develop"]))
# Open web browser to the github issues page
def show_browse_issues(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["issues"]))
# Open web browser to the github new issue post
def show_new_issue(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["new_issue"]))
# Open web browser to the github releases page
def show_releases(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.links["releases"]))
# Create a new AboutDialog object and display it
def show_about(self):
# If the about dialog does not exist, create one
if self.about is None:
self.about = about_dialog.AboutDialog(self)
<|code_end|>
, generate the next line using the imports in this file:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context (functions, classes, or occasionally code) from other files:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.about.show() |
Given the following code snippet before the placeholder: <|code_start|> self.researcherValue.setText(researcher)
self.createdValue.setText(created_time)
self.dirValue.setText(project_path)
if os.path.isdir(project_path):
self.dirValue.setStyleSheet("QLabel {color: black;}")
self.dirInvalid.setText("")
else:
self.dirValue.setStyleSheet("QLabel {color: red;}")
self.dirInvalid.setText("(Error: invalid path)")
# Enable buttons and labels
self.researcherLabel.show()
self.createdLabel.show()
self.dirLabel.show()
self.openButton.setEnabled(True)
self.deleteButton.setEnabled(True)
def start(self, event):
if not os.path.isdir(self.dirValue.text()):
QtWidgets.QMessageBox.warning(self, "Error", "Invalid project path")
else:
self.main_battery = battery_window.BatteryWindow(
self.base_dir, self.dirValue.text(), self.res_width, self.res_height
)
self.main_battery.show()
self.close()
def delete_project(self):
# Check which project has been selected
<|code_end|>
, predict the next line using imports from the current file:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context including class names, function names, and sometimes code from other files:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | researcher = self.researcherValue.text() |
Here is a snippet: <|code_start|> created_time = datetime.fromtimestamp(created_unix).strftime(
"%d/%m/%Y @ %H:%M"
)
project_path = self.project_list[researcher][project_name]["path"]
self.projectName.setText(project_name)
self.researcherValue.setText(researcher)
self.createdValue.setText(created_time)
self.dirValue.setText(project_path)
if os.path.isdir(project_path):
self.dirValue.setStyleSheet("QLabel {color: black;}")
self.dirInvalid.setText("")
else:
self.dirValue.setStyleSheet("QLabel {color: red;}")
self.dirInvalid.setText("(Error: invalid path)")
# Enable buttons and labels
self.researcherLabel.show()
self.createdLabel.show()
self.dirLabel.show()
self.openButton.setEnabled(True)
self.deleteButton.setEnabled(True)
def start(self, event):
if not os.path.isdir(self.dirValue.text()):
QtWidgets.QMessageBox.warning(self, "Error", "Invalid project path")
else:
self.main_battery = battery_window.BatteryWindow(
self.base_dir, self.dirValue.text(), self.res_width, self.res_height
<|code_end|>
. Write the next line using the current file imports:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context from other files:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
, which may include functions, classes, or code. Output only the next line. | ) |
Given the following code snippet before the placeholder: <|code_start|>
self.res_width = res_width
self.res_height = res_height
self.base_dir = base_dir
# Define URLs
self.links = values.get_links()
# Check if project file exists
if not os.path.isfile(os.path.join(self.base_dir, "projects.txt")):
self.project_list = {}
self.save_projects(self.project_list)
else:
self.project_list = self.refresh_projects()
# Make info labels invisible at start
self.researcherLabel.hide()
self.createdLabel.hide()
self.dirLabel.hide()
# Handle menu bar item click events
self.actionNewProject.triggered.connect(self.new_project)
self.actionExit.triggered.connect(self.close)
self.actionDocumentation.triggered.connect(self.show_documentation)
self.actionLicense.triggered.connect(self.show_license)
self.actionContribute.triggered.connect(self.show_contribute)
self.actionBrowse_Issues.triggered.connect(self.show_browse_issues)
self.actionReport_Bug.triggered.connect(self.show_new_issue)
self.actionRequest_Feature.triggered.connect(self.show_new_issue)
self.actionCheck_for_updates.triggered.connect(self.show_update)
<|code_end|>
, predict the next line using imports from the current file:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context including class names, function names, and sometimes code from other files:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.actionAbout.triggered.connect(self.show_about) |
Based on the snippet: <|code_start|> # If update dialog exists, bring it to the front
else:
self.update.activateWindow()
self.update.raise_()
def project_click(self, item):
if item.parent():
researcher = item.parent().text(0)
project_name = item.text(0)
created_unix = self.project_list[researcher][project_name]["created"]
created_time = datetime.fromtimestamp(created_unix).strftime(
"%d/%m/%Y @ %H:%M"
)
project_path = self.project_list[researcher][project_name]["path"]
self.projectName.setText(project_name)
self.researcherValue.setText(researcher)
self.createdValue.setText(created_time)
self.dirValue.setText(project_path)
if os.path.isdir(project_path):
self.dirValue.setStyleSheet("QLabel {color: black;}")
self.dirInvalid.setText("")
else:
self.dirValue.setStyleSheet("QLabel {color: red;}")
self.dirInvalid.setText("(Error: invalid path)")
# Enable buttons and labels
self.researcherLabel.show()
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context (classes, functions, sometimes code) from other files:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.createdLabel.show() |
Using the snippet: <|code_start|> json.dump(projects, f, indent=4)
def refresh_projects(self):
# Load most recent saved project list from file
with open(os.path.join(self.base_dir, "projects.txt"), "r") as f:
projects = json.load(f)
# Clear existing tree widget
self.projectTree.clear()
# Get all researcher names
all_researchers = sorted(projects.keys(), key=lambda x: x.lower())
for person in all_researchers:
# Add researcher root node
personItem = QtWidgets.QTreeWidgetItem([person])
font = personItem.font(0)
font.setBold(True)
personItem.setFont(0, font)
self.projectTree.addTopLevelItem(personItem)
# Add project name for each researcher
all_projects = sorted(projects[person].keys(), key=lambda x: x.lower())
for project in all_projects:
projectItem = QtWidgets.QTreeWidgetItem([project])
personItem.addChild(projectItem)
self.projectTree.expandAll()
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import project_window_qt
from interface import about_dialog, battery_window, project_new_window, update_dialog
from utils import values
and context (class names, function names, or code) available:
# Path: designer/project_window_qt.py
# class Ui_ProjectWindow(object):
# def setupUi(self, ProjectWindow):
# def retranslateUi(self, ProjectWindow):
#
# Path: interface/about_dialog.py
# class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
#
# Path: interface/battery_window.py
# class BatteryWindow(QtWidgets.QMainWindow, battery_window_qt.Ui_CognitiveBattery):
# def __init__(self, base_dir, project_dir, res_width, res_height):
# def set_default_settings(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_settings(self):
# def show_about(self):
# def show_update(self):
# def error_dialog(self, message):
# def random_order_selected(self):
# def select_all(self):
# def deselect_all(self):
# def move_up(self):
# def move_down(self):
# def get_settings(self):
# def closeEvent(self, event):
# def start(self):
#
# Path: interface/project_new_window.py
# class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
# def __init__(self, base_dir, project_list):
# def select_file(self):
# def create_project(self):
#
# Path: interface/update_dialog.py
# class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
# def __init__(self, parent=None):
# def check_version(self):
# def show_releases(self):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.projectName.setText("") |
Next line prediction: <|code_start|> # Only save some options if fullscreen is not selected
if not self.task_fullscreen:
self.settings.setValue(
"borderless",
str(self.settings_task_borderless_checkbox.isChecked()).lower(),
)
self.settings.setValue("width", self.settings_task_width_value.text())
self.settings.setValue("height", self.settings_task_height_value.text())
# Task beep setting
self.settings.setValue(
"taskBeep", str(self.settings_task_beep_checkbox.isChecked()).lower()
)
self.settings.endGroup()
# ANT settings
self.settings.beginGroup("AttentionNetworkTest")
self.settings.setValue("numBlocks", self.settings_ant_blocks_value.text())
self.settings.endGroup()
# Flanker settings
self.settings.beginGroup("Flanker")
self.settings.setValue(
"darkMode", str(self.settings_flanker_dark.isChecked()).lower()
)
self.settings.setValue(
"setsPractice", self.settings_flanker_practice_sets_value.text()
)
self.settings.setValue(
<|code_end|>
. Use current file imports:
(from PyQt5 import QtCore, QtGui, QtWidgets
from designer import settings_window_qt)
and context including class names, function names, or small code snippets from other files:
# Path: designer/settings_window_qt.py
# class Ui_SettingsDialog(object):
# def setupUi(self, SettingsDialog):
# def retranslateUi(self, SettingsDialog):
. Output only the next line. | "setsMain", self.settings_flanker_main_sets_value.text() |
Predict the next line for this snippet: <|code_start|>from __future__ import division, print_function
if __name__ == "__main__":
# Get application directory
base_dir = os.path.dirname(os.path.realpath(__file__))
# Create project manager window
app = QtWidgets.QApplication(sys.argv)
screen_resolution = app.desktop().screenGeometry()
project_manager = project_window.ProjectWindow(
base_dir, screen_resolution.width(), screen_resolution.height()
<|code_end|>
with the help of current file imports:
import os
import sys
from PyQt5 import QtWidgets
from interface import project_window
and context from other files:
# Path: interface/project_window.py
# class ProjectWindow(QtWidgets.QMainWindow, project_window_qt.Ui_ProjectWindow):
# def __init__(self, base_dir, res_width, res_height):
# def new_project(self):
# def show_documentation(self):
# def show_license(self):
# def show_contribute(self):
# def show_browse_issues(self):
# def show_new_issue(self):
# def show_releases(self):
# def show_about(self):
# def show_update(self):
# def project_click(self, item):
# def start(self, event):
# def delete_project(self):
# def save_projects(self, projects):
# def refresh_projects(self):
, which may contain function names, class names, or code. Output only the next line. | ) |
Here is a snippet: <|code_start|> self.screen,
self.font,
"In example above, you should press the RIGHT key.",
100,
self.screen_y / 2 + 120,
self.colour_font,
)
display.text(
self.screen,
self.font,
"Respond as quickly, and as accurately, as you can",
100,
self.screen_y / 2 + 200,
self.colour_font,
)
display.text_space(
self.screen,
self.font,
"center",
(self.screen_y / 2) + 300,
self.colour_font,
)
pygame.display.flip()
display.wait_for_space()
# Instructions Practice
self.screen.blit(self.background, (0, 0))
display.text(
<|code_end|>
. Write the next line using the current file imports:
import sys
import time
import pandas as pd
import numpy as np
import pygame
from pygame.locals import *
from itertools import product
from utils import display
and context from other files:
# Path: utils/display.py
# def blank_screen(screen, background, duration):
# def image(screen, img, x, y):
# def text(screen, font, text_string, x, y, colour=(0, 0, 0)):
# def text_space(screen, font, x, y, colour=(0, 0, 0)):
# def wait(duration):
# def wait_for_space():
, which may include functions, classes, or code. Output only the next line. | self.screen, |
Using the snippet: <|code_start|>
class AboutDialog(QtWidgets.QDialog, about_dialog_qt.Ui_Dialog):
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
# Setup the about dialog box
self.setupUi(self)
# Set version number
self.versionValue.setText(values.get_version())
# Add icon image
base_dir = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
) # Get parent directory
pixmap = QtGui.QPixmap(os.path.join(base_dir, "images", "icon.png"))
<|code_end|>
, determine the next line of code. You have imports:
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from designer import about_dialog_qt
from utils import values
and context (class names, function names, or code) available:
# Path: designer/about_dialog_qt.py
# class Ui_Dialog(object):
# def setupUi(self, Dialog):
# def retranslateUi(self, Dialog):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.icon.setPixmap(pixmap) |
Predict the next line for this snippet: <|code_start|>
# Bind button events
self.btn_update.clicked.connect(self.show_releases)
self.btn_close.clicked.connect(self.close)
# Check for updates
self.check_version()
def check_version(self):
try:
url = urllib.request.urlopen(self.links["rss"])
# convert to string:
data = url.read()
url.close()
# entire feed
root = etree.fromstring(data)
releases = []
for child in root.findall(".//{http://www.w3.org/2005/Atom}entry"):
releases.append(child[0].text)
latest_version = releases[0].split("/")[-1]
self.latest_value.setText(latest_version)
if self.current_version == latest_version:
self.info.setText("No updates available.")
self.current_value.setStyleSheet("color: green")
else:
self.btn_update.setEnabled(True)
<|code_end|>
with the help of current file imports:
import urllib
from designer import update_dialog_qt
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import values
from xml.etree import ElementTree as etree
and context from other files:
# Path: designer/update_dialog_qt.py
# class Ui_Dialog(object):
# def setupUi(self, Dialog):
# def retranslateUi(self, Dialog):
#
# Path: utils/values.py
# def get_version():
# def get_links():
, which may contain function names, class names, or code. Output only the next line. | self.info.setText("New version available...") |
Next line prediction: <|code_start|>
class UpdateDialog(QtWidgets.QDialog, update_dialog_qt.Ui_Dialog):
def __init__(self, parent=None):
super(UpdateDialog, self).__init__(parent)
# Setup the update dialog box
self.setupUi(self)
# Set version number
self.current_version = values.get_version()
self.current_value.setText(self.current_version)
# Define URLs
self.links = values.get_links()
# Delete the object when dialog is closed
<|code_end|>
. Use current file imports:
(import urllib
from designer import update_dialog_qt
from PyQt5 import QtCore, QtGui, QtWidgets
from utils import values
from xml.etree import ElementTree as etree)
and context including class names, function names, or small code snippets from other files:
# Path: designer/update_dialog_qt.py
# class Ui_Dialog(object):
# def setupUi(self, Dialog):
# def retranslateUi(self, Dialog):
#
# Path: utils/values.py
# def get_version():
# def get_links():
. Output only the next line. | self.setAttribute(QtCore.Qt.WA_DeleteOnClose) |
Based on the snippet: <|code_start|>
def decode(vocab, value):
if isinstance(value, int):
try:
return vocab.strings[value]
except KeyError:
<|code_end|>
, predict the immediate next line with the help of imports:
from configargparse import ArgParser
from ucca.textutil import get_vocab
from tupa.model_util import save_json
from tupa.scripts.export import load_model
and context (classes, functions, sometimes code) from other files:
# Path: tupa/model_util.py
# def save_json(filename, d):
# """
# Save dictionary to JSON file
# :param filename: file to write to
# :param d: dictionary to save
# """
# remove_existing(filename)
# print("Saving to '%s'." % filename)
# with open(filename, "w") as h:
# json.dump(d, h, default=jsonify)
#
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
. Output only the next line. | pass |
Based on the snippet: <|code_start|>
def main():
argparser = ArgParser(description="Load TUPA model and save again to a different file.")
argparser.add_argument("models", nargs="+", help="model file basename(s) to load")
argparser.add_argument("-s", "--suffix", default=".1", help="filename suffix to append")
args = argparser.parse_args()
for filename in args.models:
model = load_model(filename)
model.filename += args.suffix
model.classifier.filename += args.suffix
<|code_end|>
, predict the immediate next line with the help of imports:
from configargparse import ArgParser
from tupa.scripts.export import load_model
and context (classes, functions, sometimes code) from other files:
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
. Output only the next line. | model.save() |
Using the snippet: <|code_start|>
matplotlib.use("Agg")
np.seterr("raise")
REPLACEMENTS = (
("axes_", ""),
<|code_end|>
, determine the next line of code. You have imports:
from collections import OrderedDict
from configargparse import ArgParser
from scipy.misc import imresize
from matplotlib.ticker import MaxNLocator
from tupa.scripts.export import load_model
from tqdm import tqdm
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import re
and context (class names, function names, or code) available:
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
. Output only the next line. | ("_", " "), |
Next line prediction: <|code_start|>class DefaultOrderedDict(OrderedDict, Labels):
# Source: http://stackoverflow.com/a/6190500/223267
def __init__(self, default_factory=None, *args, size=None, **kwargs):
if default_factory is not None and not callable(default_factory):
raise TypeError("default_factory must be callable")
Labels.__init__(self, size)
self._all = []
OrderedDict.__init__(self, *args, **kwargs)
self._all = list(self.keys())
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
args = tuple() if self.default_factory is None else self.default_factory,
return type(self), args, None, None, iter(self.items())
def copy(self):
return self.__copy__()
<|code_end|>
. Use current file imports:
(import sys
import time
import csv
import json
import numpy as np
import os
import pickle
import pprint as pp
import shutil
import copy
from collections import OrderedDict, Counter, defaultdict
from glob import glob
from operator import itemgetter
from tqdm import tqdm
from .labels import Labels)
and context including class names, function names, or small code snippets from other files:
# Path: tupa/labels.py
# class Labels:
# def __init__(self, size):
# self.size = size # Maximum number of labels, NOT enforced here but by the user
#
# @property
# def all(self):
# raise NotImplementedError()
#
# @all.setter
# def all(self, labels):
# raise NotImplementedError()
#
# def save(self, skip=False):
# return (None if skip else self.all), self.size
#
# def load(self, all_size):
# self.all, self.size = all_size
. Output only the next line. | def __copy__(self): |
Based on the snippet: <|code_start|> add(group, "--rnn", choices=["None"] + list(RNNS), default=DEFAULT_RNN, help="type of recurrent neural network")
add(group, "--gated", type=int, nargs="?", default=2, help="gated input to BiRNN and MLP")
NN_ARG_NAMES.update(get_group_arg_names(group))
return ap
class FallbackNamespace(Namespace):
def __init__(self, fallback, kwargs=None):
super().__init__(**(kwargs or {}))
self._fallback = fallback
self._children = {}
def __getattr__(self, item):
if item.startswith("_"):
return getattr(super(), item)
return getattr(super(), item, getattr(self._fallback, item))
def __getitem__(self, item):
if item:
name, _, rest = item.partition(SEPARATOR)
return self._children.setdefault(name, FallbackNamespace(self))[rest]
return self
def vars(self):
return {k: v for k, v in vars(self).items() if not k.startswith("_")}
def items(self):
return self.vars().items()
def update(self, kwargs):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import shlex
import dynet_config
import numpy as np
from copy import deepcopy
from configargparse import ArgParser, Namespace, ArgumentDefaultsHelpFormatter, SUPPRESS
from logbook import Logger, FileHandler, StderrHandler
from semstr.cfgutil import Singleton, add_verbose_arg, add_boolean_option, get_group_arg_names
from semstr.convert import UCCA_EXT, CONVERTERS
from ucca import constructions
from tupa.classifiers.nn.constants import *
from tupa.model_util import load_enum
and context (classes, functions, sometimes code) from other files:
# Path: tupa/model_util.py
# def load_enum(filename):
# if filename == "-":
# return IdentityVocab()
# else:
# with open(filename, encoding="utf-8") as f:
# return Vocab(tqdm(csv.reader(f), desc="Loading '%s'" % filename, file=sys.stdout, unit=" rows"))
. Output only the next line. | for key, value in kwargs.items(): |
Given the code snippet: <|code_start|>#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
from recommonmark.parser import CommonMarkParser
from unittest.mock import MagicMock
from tupa.__version__ import VERSION as release
and context (functions, classes, or occasionally code) from other files:
# Path: tupa/__version__.py
# VERSION = "1.4.2"
. Output only the next line. | man_pages = [ |
Next line prediction: <|code_start|> # noinspection PyBroadException
def run(self):
# Install requirements
self.announce("Installing dependencies...")
run(["pip", "--no-cache-dir", "install"] + install_requires, check=True)
# Install actual package
_install.run(self)
setup(name="TUPA",
version=VERSION,
description="Transition-based UCCA Parser",
long_description=long_description,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.6",
"Topic :: Text Processing :: Linguistic",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
author="Daniel Hershcovich",
author_email="daniel.hershcovich@gmail.com",
url="https://github.com/huji-nlp/tupa",
setup_requires=["pypandoc"],
install_requires=install_requires,
extras_require={"server": open(os.path.join("server", "requirements.txt")).read().splitlines(),
<|code_end|>
. Use current file imports:
(import os
import sys
import pypandoc
from subprocess import run
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
from tupa.__version__ import VERSION)
and context including class names, function names, or small code snippets from other files:
# Path: tupa/__version__.py
# VERSION = "1.4.2"
. Output only the next line. | "viz": ["scipy", "pillow", "matplotlib"], |
Based on the snippet: <|code_start|>
class EmptyFeatureExtractor(FeatureExtractor):
def __init__(self):
super().__init__()
<|code_end|>
, predict the immediate next line with the help of imports:
from .feature_extractor import FeatureExtractor
and context (classes, functions, sometimes code) from other files:
# Path: tupa/features/feature_extractor.py
# class FeatureExtractor:
# """
# Object to extract features from the parser state to be used in action classification
# """
#
# def __init__(self, feature_templates=(), params=None, omit_features=None):
# assert all(FEATURE_TEMPLATE_PATTERN.match(f) for f in feature_templates), \
# "Features do not match pattern: " + ", ".join(
# f for f in feature_templates if not FEATURE_TEMPLATE_PATTERN.match(f))
# # convert the list of features textual descriptions to the actual fields
# self.feature_templates = [
# FeatureTemplate(feature_name, tuple(FeatureTemplateElement(*m.group(1, 2, 3, 4), omit_features)
# for m in re.finditer(FEATURE_ELEMENT_PATTERN, feature_name)))
# for feature_name in feature_templates]
# self.params = {} if params is None else params
# self.omit_features = omit_features
#
# def extract_features(self, state):
# """
# Calculate feature values according to current state
# :param state: current state of the parser
# """
# raise NotImplementedError()
#
# def init_features(self, state):
# """
# Calculate feature values for initial state
# :param state: initial state of the parser
# """
# pass
#
# def init_param(self, key):
# pass
#
# def finalize(self):
# return self
#
# def unfinalize(self):
# pass
#
# def save(self, filename, save_init=True):
# pass
#
# def load(self, filename, order=None):
# pass
#
# def all_features(self):
# return sorted(list(map(str, self.feature_templates)))
. Output only the next line. | def extract_features(self, state): |
Given snippet: <|code_start|>
MLP_PARAM_PATTERN = re.compile(r"[Wb]\d+")
class MultilayerPerceptron(SubModel):
def __init__(self, config, args, model, layers=None, layer_dim=None, output_dim=None, num_labels=None, params=None,
**kwargs):
super().__init__(params=params, **kwargs)
self.config = config
self.args = args
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from itertools import groupby
from .constants import ACTIVATIONS, INITIALIZERS, CategoricalParameter
from .sub_model import SubModel
from .util import randomize_orthonormal
import dynet as dy
import re
and context:
# Path: tupa/classifiers/nn/constants.py
# ACTIVATIONS = {
# "cube": "cube",
# "tanh": "tanh",
# "sigmoid": "logistic",
# "relu": "rectify",
# }
#
# INITIALIZERS = {
# # "saxe": "SaxeInitializer",
# "glorot_uniform": "GlorotInitializer",
# "normal": "NormalInitializer",
# }
#
# class CategoricalParameter:
# def __init__(self, values, string):
# self._value = self._string = None
# self.values = values
# self.string = string
#
# def __call__(self):
# import dynet as dy
# return getattr(dy, self._value)
#
# @property
# def string(self):
# return self._string
#
# @string.setter
# def string(self, s):
# self._string = s
# self._value = self.values.get(s)
#
# def __str__(self):
# return self._string
#
# Path: tupa/classifiers/nn/sub_model.py
# class SubModel:
# def __init__(self, params=None, save_path=(), shared=False, copy_shared=False):
# self.params = OrderedDict() if params is None else params # string (param identifier) -> parameter
# self.save_path = save_path
# self.shared = shared
# self.copy_shared = copy_shared
#
# def save_sub_model(self, d, *args):
# self.get_sub_dict(d).update(args + (("param_keys", list(self.params.keys())),))
# return list(self.params.values())
#
# def load_sub_model(self, d, *args, load_path=None):
# d = self.get_sub_dict(d, load_path=load_path)
# param_keys = d.get("param_keys", ())
# assert len(param_keys) <= len(args), "%s loaded values: expected %d, got %d" % ("/".join(self.save_path),
# len(param_keys), len(args))
# self.params.clear()
# self.params.update(zip(param_keys, args))
# return d
#
# def get_sub_dict(self, d, load_path=None):
# for element in load_path or self.save_path:
# d = d.setdefault(element, OrderedDict())
# return d
#
# def params_str(self):
# return "/".join(self.save_path) + (": " if self.save_path else "") + ", ".join(self.params.keys())
#
# def invalidate_caches(self):
# for model in self.sub_models():
# model.invalidate_caches()
#
# def sub_models(self):
# return ()
#
# Path: tupa/classifiers/nn/util.py
# def randomize_orthonormal(*parameters, activation=None): # Saxe et al., 2014 (https://arxiv.org/abs/1312.6120)
# for param in parameters:
# shape = param.shape()
# if len(shape) == 2 and shape[0] == shape[1] > 1:
# init, _, _ = np.linalg.svd(np.random.randn(*shape))
# if str(activation) == "relu":
# init *= np.sqrt(2)
# param.set_value(init)
which might include code, classes, or functions. Output only the next line. | self.model = model |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.