prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): <|fim_middle|> <|fim▁end|>
return True
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def <|fim_middle|>(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
__init__
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def <|fim_middle|>(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
eval_attr11
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def <|fim_middle|>(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
eval_attr12
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def <|fim_middle|>(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True <|fim▁end|>
eval_attr13
<|file_name|>HUnitDaughter2Woman_ConnectedLHS.py<|end_file_name|><|fim▁begin|>from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def <|fim_middle|>(self, PreNode, graph): return True <|fim▁end|>
constraint
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option)<|fim▁hole|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))<|fim▁end|>
# any later version. # This file is distributed in the hope that it will be useful,
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if <|fim_middle|> lse: print("{0} is not a leap year".format(year)) <|fim▁end|>
(year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) e
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if <|fim_middle|> else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) <|fim▁end|>
(year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: pri <|fim_middle|> else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) <|fim▁end|>
nt("{0} is a leap year".format(year))
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: pri <|fim_middle|> else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) <|fim▁end|>
nt("{0} is not a leap year".format(year))
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: pri <|fim_middle|> lse: print("{0} is not a leap year".format(year)) <|fim▁end|>
nt("{0} is a leap year".format(year)) e
<|file_name|>leap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: pri <|fim_middle|> <|fim▁end|>
nt("{0} is not a leap year".format(year))
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for comic project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys SITE_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))<|fim▁hole|> os.environ.setdefault("PYTHON_EGG_CACHE", "/tmp/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "comic.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)<|fim▁end|>
sys.path.append(SITE_ROOT) sys.path.append(os.path.join(SITE_ROOT,"comic"))
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char<|fim▁hole|># else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
# cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): <|fim_middle|> def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): <|fim_middle|> if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: <|fim_middle|> #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
print("You should provide cmd line arguments!") exit(1)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): <|fim_middle|> else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
cipher.append(caesar(symbol, kplainText))
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: <|fim_middle|> print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
cipher.append(symbol)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): <|fim_middle|> else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
return chr(((ord(char) - 65 + kplainText) % 26) + 65)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: <|fim_middle|> if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
return chr(((ord(char) - 97 + kplainText) % 26) + 97)
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": <|fim_middle|> # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
main()
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def <|fim_middle|>(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def caesar(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
main
<|file_name|>caesar.py<|end_file_name|><|fim▁begin|>import cs50 import sys def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) #if sys.argv[1].isalpha() == False: #print("You should provide valid key!") #exit(1) kplainText = int(sys.argv[1]) cipher = [] plainText = cs50.get_string() for symbol in plainText: if symbol.isalpha(): cipher.append(caesar(symbol, kplainText)) else: cipher.append(symbol) print("".join(cipher)) exit(0) def <|fim_middle|>(char, kplainText): if char.isupper(): return chr(((ord(char) - 65 + kplainText) % 26) + 65) else: return chr(((ord(char) - 97 + kplainText) % 26) + 97) if __name__ == "__main__": main() # #include <ctype.h> # #include <string.h> # #include <cs50.h> # #include <stdio.h> # #include <stdlib.h> # //define my caesarCipher # void caesarCipher(char* plainText,int key); # def int main(int argc, char* argv[]): # //{//????????????????/char* # if argc is not 2: # # { # print("Usage: ./caesar k\n") # #return 1 # #} # #//printf(" %s\n", argv[1]); # int key = atoi(sys.argv[1]) # char plainText[101] # print("plaintext: ")#;//ask user # fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++ # print("ciphertext: ")#;//print the ciphered text # caesarCipher(plainText,key) # //system(pause);//connect out if not use wind---------------------------??????????????? # # return 0; # #} # void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin # int i = 0 # char cipher # int cipherValue # while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++) # if isalpha(plainText[i]) and islower(plainText[i]): # cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97) # cipher = (char)(cipherValue);printf("%c", cipher) # i++ # else: # if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char # cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65) # cipher = (char)(cipherValue) # print("%c", cipher) # i++ # else: #//if not isaplha low or up # print("%c", plainText[i]) # i++ # print("\n") #}<|fim▁end|>
caesar
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0)<|fim▁hole|> for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close()<|fim▁end|>
i = 0
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): <|fim_middle|> class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close() <|fim▁end|>
""" Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n]
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close()
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): <|fim_middle|> def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close() <|fim▁end|>
self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n')
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): <|fim_middle|> <|fim▁end|>
(user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close()
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): <|fim_middle|> self.log_file.close() <|fim▁end|>
self.log_file.close() sys.exit(-1)
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def <|fim_middle|>(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close() <|fim▁end|>
chunks
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def <|fim_middle|>(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def handle(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close() <|fim▁end|>
hard_log
<|file_name|>massemailtxt.py<|end_file_name|><|fim▁begin|>import os.path import time from django.core.management.base import BaseCommand from django.conf import settings import mitxmako.middleware as middleware from django.core.mail import send_mass_mail import sys import datetime middleware.MakoMiddleware() def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i + n] class Command(BaseCommand): help = \ '''Sends an e-mail to all users in a text file. E.g. manage.py userlist.txt message logfile.txt rate userlist.txt -- list of all users message -- prefix for template with message logfile.txt -- where to log progress rate -- messages per second ''' log_file = None def hard_log(self, text): self.log_file.write(datetime.datetime.utcnow().isoformat() + ' -- ' + text + '\n') def <|fim_middle|>(self, *args, **options): (user_file, message_base, logfilename, ratestr) = args users = [u.strip() for u in open(user_file).readlines()] message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render() subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip() rate = int(ratestr) self.log_file = open(logfilename, "a+", buffering=0) i = 0 for users in chunks(users, rate): emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users] self.hard_log(" ".join(users)) send_mass_mail(emails, fail_silently=False) time.sleep(1) print datetime.datetime.utcnow().isoformat(), i i = i + len(users) # Emergency interruptor if os.path.exists("/tmp/stopemails.txt"): self.log_file.close() sys.exit(-1) self.log_file.close() <|fim▁end|>
handle
<|file_name|>task_5_6.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Velyan A. S. # 27.05.2016 print("\nназвание одного из двух спутников Марса:") import random satellite=["Фобос", "Деймос"] s=random.choice(satellite) print(s) input("Нажмите Enter для выхода")<|fim▁end|>
# Задача 5. Вариант 6. # Напишите программу, которая бы при запуске случайным образом отображала название одного из двух спутников Марса.
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from models import Connection from django import forms class ConnectionForm(forms.ModelForm): class Meta: model = Connection<|fim▁hole|><|fim▁end|>
exclude = ('d_object_id',)
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from models import Connection from django import forms class ConnectionForm(forms.ModelForm): <|fim_middle|> <|fim▁end|>
class Meta: model = Connection exclude = ('d_object_id',)
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from models import Connection from django import forms class ConnectionForm(forms.ModelForm): class Meta: <|fim_middle|> <|fim▁end|>
model = Connection exclude = ('d_object_id',)
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and<|fim▁hole|># --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir)<|fim▁end|>
# limitations under the License. # --- This file has been autogenerated --- #
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: <|fim_middle|> # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
"""Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): <|fim_middle|> # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}')
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: <|fim_middle|> def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
"""Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots)
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: <|fim_middle|> EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
"""Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}'
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): <|fim_middle|> <|fim▁end|>
"""Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir)
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: <|fim_middle|> return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
return f'{n_shots // 1000}k'
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: <|fim_middle|> if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
base_dir = DEFAULT_BASE_DIR
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): <|fim_middle|> # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
print(f"{task} already exists. Skipping.") return
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def <|fim_middle|>(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
fn
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def <|fim_middle|>(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
_abbrev_n_shots
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def <|fim_middle|>(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def run_readout_scan(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
_abbrev_grid_qubit
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --- This file has been autogenerated --- # # --- from docs/Readout-Data-Collection.ipynb --- # # --- Do not edit this file directly --- # import os import numpy as np import sympy import cirq import recirq @recirq.json_serializable_dataclass(namespace='recirq.readout_scan', registry=recirq.Registry, frozen=True) class ReadoutScanTask: """Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid which is primarily affected by readout error. See Also: :py:func:`run_readout_scan` Attributes: dataset_id: A unique identifier for this dataset. device_name: The device to run on, by name. n_shots: The number of repetitions for each theta value. qubit: The qubit to benchmark. resolution_factor: We select the number of points in the linspace so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are always included. The total number of theta evaluations is resolution_factor * 4 + 1. """ dataset_id: str device_name: str n_shots: int qubit: cirq.GridQubit resolution_factor: int @property def fn(self): n_shots = _abbrev_n_shots(n_shots=self.n_shots) qubit = _abbrev_grid_qubit(self.qubit) return (f'{self.dataset_id}/' f'{self.device_name}/' f'q-{qubit}/' f'ry_scan_{self.resolution_factor}_{n_shots}') # Define the following helper functions to make nicer `fn` keys # for the tasks: def _abbrev_n_shots(n_shots: int) -> str: """Shorter n_shots component of a filename""" if n_shots % 1000 == 0: return f'{n_shots // 1000}k' return str(n_shots) def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str: """Formatted grid_qubit component of a filename""" return f'{qubit.row}_{qubit.col}' EXPERIMENT_NAME = 'readout-scan' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') def <|fim_middle|>(task: ReadoutScanTask, base_dir=None): """Execute a :py:class:`ReadoutScanTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task} already exists. Skipping.") return # Create a simple circuit theta = sympy.Symbol('theta') circuit = cirq.Circuit([ cirq.ry(theta).on(task.qubit), cirq.measure(task.qubit, key='z') ]) # Use utilities to map sampler names to Sampler objects sampler = recirq.get_sampler_by_name(device_name=task.device_name) # Use a sweep over theta values. # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi # The total number of points is resolution_factor * 4 + 1 n_special_points: int = 5 resolution_factor = task.resolution_factor theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2, resolution_factor * (n_special_points - 1) + 1) thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()]) flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep) # Run the jobs print(f"Collecting data for {task.qubit}", flush=True) results = sampler.run_sweep(program=flat_circuit, params=flat_sweep, repetitions=task.n_shots) # Save the results recirq.save(task=task, data={ 'thetas': thetas, 'all_bitstrings': [ recirq.BitArray(np.asarray(r.measurements['z'])) for r in results] }, base_dir=base_dir) <|fim▁end|>
run_readout_scan
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v:<|fim▁hole|> # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return<|fim▁end|>
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): <|fim_middle|> def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
""" Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): <|fim_middle|> def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
""" k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v))
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): <|fim_middle|> <|fim▁end|>
""" Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: <|fim_middle|> else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
generate = True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: <|fim_middle|> if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: <|fim_middle|> else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v)
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: <|fim_middle|> if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
generate = True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: <|fim_middle|> res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N)
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: <|fim_middle|> while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
return True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: <|fim_middle|> context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
return True
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v <|fim_middle|> def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
G.addEdge((u, v))
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) <|fim_middle|> else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
break
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p <|fim_middle|> else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
break
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! <|fim_middle|> # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n)
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: <|fim_middle|> else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10)
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: <|fim_middle|> return <|fim▁end|>
for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i))
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def <|fim_middle|>(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
run
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def <|fim_middle|>(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
k_n
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def <|fim_middle|>(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return <|fim▁end|>
moment
<|file_name|>spectrum_analyzer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 # mA laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) <|fim▁hole|>freq_min = 0 freq_max = sampling_rate / mhz / 2 # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break<|fim▁end|>
mhz = 1e6 sampling_rate = 125e6
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright (c) 2014 Hamilton Kibbe <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software.<|fim▁hole|># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. """ PyAbleton A library for creating and editing Ableton Live instrument/effect presets in Python. """ __author__ = '[email protected]' __version__ = '1.0' import presets<|fim▁end|>
#
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.map, name='map'),<|fim▁hole|>]<|fim▁end|>
url(r'^mapSim', views.mapSim, name='mapSim'), url(r'^api/getPos', views.getPos, name='getPos'), url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'),
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception:<|fim▁hole|> m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1<|fim▁end|>
self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self):
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): <|fim_middle|> __plugin__ = TF1 <|fim▁end|>
url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): <|fim_middle|> def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
return cls.url_re.match(url) is not None
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): <|fim_middle|> def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): <|fim_middle|> def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel)
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): <|fim_middle|> __plugin__ = TF1 <|fim▁end|>
m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: <|fim_middle|> def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel)
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: <|fim_middle|> __plugin__ = TF1 <|fim▁end|>
channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def <|fim_middle|>(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
can_handle_url
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def <|fim_middle|>(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
_get_hds_streams
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def <|fim_middle|>(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
_get_hls_streams
<|file_name|>tf1.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def <|fim_middle|>(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1 <|fim▁end|>
_get_streams
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class <|fim▁hole|>except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES<|fim▁end|>
:param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): <|fim_middle|> def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): <|fim_middle|> else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Converts the given bytes into a string """ if type(data) is str: return data return str(data)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): <|fim_middle|> def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8")
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): <|fim_middle|> # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8")
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): <|fim_middle|> except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): <|fim_middle|> # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
""" Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 <|fim_middle|> else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: <|fim_middle|> return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
return str(string)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: <|fim_middle|> return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
return data
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 <|fim_middle|> # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8")
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: <|fim_middle|> return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
return string
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: <|fim_middle|> return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
return data
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ".".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def <|fim_middle|>(string): """ Converts the given string into bytes """ # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """ return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES <|fim▁end|>
to_bytes