Пример #1
0
        def do_GET(self):
            # Parse query string, make sure we have a callback.
            url = urlparse(self.path)
            if '.jsonp' != url.path[-6:]: return SimpleHTTPRequestHandler.do_GET(self)
            query = parse_qs(url.query)
            if 'callback' not in query: raise Exception('No callback specified')
            callback = query['callback'][-1]

            # Get data for different JSONp calls
            try:
                if '/colorvalue.jsonp' == url.path:
                    data = color.colorvalue(query['colordef'][0], query['txo[]'])
                elif '/makeconversion.jsonp' == url.path:
                    data = color.makeconversion(loads(query['txspec'][0]))
                elif '/receive.jsonp' == url.path:
                    data = message.receive()
                elif '/send.jsonp' == url.path:
                    data = message.send(query['subject'][0], query['body'][0])
                elif '/signrawtransaction.jsonp' == url.path:
                    data = bitcoin.signrawtransaction(
                        query['rawtx'][0],
                        loads(query['inputs'][0]),
                        query['keys[]']
                    )
                else:
                    data = {'error': 'Did not understand ' + url.path}

            except (KeyError, ValueError): data = {'error': 'Wrong parameters', 'query': query}

            # Send the reply as jsonp
            self.send_response(200)
            self.send_header('Content-type', 'application/javascript')
            self.end_headers()
            self.wfile.write(bytes(callback + '(' + dumps(data) + ');', 'UTF-8'))
Пример #2
0
def test_channel_messages_start_excess():
    'Start >= total messages case'
    workspace_reset()

    ret = register_and_create()
    user1 = ret['user']
    token1 = user1['token']
    channelInfo = ret['channel']
    channel_id = channelInfo['channel_id']

    payload = {'token': token1, 'channel_id': channel_id, 'message': "hello"}

    # Send message
    message.send(payload)

    # InputError when start >= total messages, e.g. 50 >= 1
    with pytest.raises(InputError) as e:
        channel.messages(token1, channel_id, 50)
Пример #3
0
    def create_cmake(self, cmake_path=None):
        """
        Create CMakeLists.txt file in wanted path

        :param cmake_path: path where CMakeLists.txt should be write
        :type cmake_path: str
        """

        if cmake_path is None:
            send('CMakeLists will be build in current directory.', '')
            self.cmake = open('CMakeLists.txt', 'w')
        else:
            send('CmakeLists.txt will be build in : ' + str(cmake_path),
                 'warn')
            if cmake_path[-1:] == '/' or cmake_path[-1:] == '\\':
                self.cmake = open(str(cmake_path) + 'CMakeLists.txt', 'w')
            else:
                self.cmake = open(str(cmake_path) + '/CMakeLists.txt', 'w')
Пример #4
0
 def write_include_dir(self):
     """
     Include Directories : Add include directories required for compilation.
     """
     incl_dir = self.tree.find(
         '//ns:ItemGroup/ns:ClCompile/ns:AdditionalIncludeDirectories',
         namespaces=self.ns)
     if incl_dir is not None:
         self.cmake.write('# Include directories \n')
         inc_dir = incl_dir.text.replace('$(ProjectDir)', './')
         for i in inc_dir.split(';'):
             i = i.replace('\\', '/')
             i = re.sub(r'\$\((.+?)\)', r'$ENV{\1}', i)
             self.cmake.write('include_directories(' + i + ')\n')
             msg.send('Include Directories found : ' + i, 'warn')
         self.cmake.write('\n')
     else:
         msg.send('Include Directories not found for this project.', 'warn')
Пример #5
0
    def create_data(self):
        # Write variables
        variables = ProjectVariables(self.data)
        variables.define_variable()
        files = ProjectFiles(self.data)
        files.write_variables()
        variables.define_project()
        variables.define_target()

        # Write Macro
        macros = Macro()
        macros.write_macro(self.data)

        # Write Output Variables
        variables.write_output()

        # Write Include Directories
        depends = Dependencies(self.data)
        if self.data['includes']:
            depends.write_include_dir()
        else:
            send('Include Directories is not set.', '')

        # Write Dependencies
        depends.write_dependencies()

        # Add additional code or not
        if self.data['additional_code'] is not None:
            files.add_additional_code(self.data['additional_code'])

        # Write Flags
        all_flags = Flags(self.data)
        all_flags.write_flags()

        # Write and add Files
        files.write_files()
        files.add_artefact()

        # Link with other dependencies
        depends.link_dependencies()

        # Close CMake file
        self.data['cmake'].close()
Пример #6
0
def test_channel_messages_invalid_channel():
    'Invalid channel case'
    workspace_reset()

    ret = register_and_create()
    user1 = ret['user']
    token1 = user1['token']
    channelInfo = ret['channel']
    channel_id = channelInfo['channel_id']

    payload = {'token': token1, 'channel_id': channel_id, 'message': "hello"}

    # Send message
    message.send(payload)

    # InputError when we try to check messages in an invalid channel
    # Invalid channel_id = 100
    with pytest.raises(InputError) as e:
        channel.messages(token1, 100, 0)
Пример #7
0
 def add_additional_code(self, file_to_add):
     if file_to_add != '':
         try:
             fc = open(file_to_add, 'r')
             self.cmake.write(
                 '############# Additional Code #############\n')
             self.cmake.write(
                 '# Provides from external file.            #\n')
             self.cmake.write(
                 '###########################################\n\n')
             for line in fc:
                 self.cmake.write(line)
             fc.close()
             self.cmake.write('\n')
             send('File of Code is added = ' + file_to_add, 'warn')
         except OSError:
             send(
                 'Wrong data file ! Code was not added, please verify file name or path !',
                 'error')
def send_msg1(user1, channel1):
    '''
    Helper function to send a message
    '''
    payload = {
        'token':user1['token'],
        'channel_id': channel1['channel_id'],
        'message' : 'testing'
    }

    message_test = message.send(payload)
    return message_test
Пример #9
0
def displayOptions(index, client, users):
    while True:
        option = input("\nWhat would you like to do?\n").strip().lower()

        if option == "c":
            return -2
        else:
            if not option:
                return index + 1
            elif option == "b":
                if index > 0:
                    return index - 1
            elif option == "s":
                message.send(users[index].uid, client)
            elif option == "q":
                client.logout()
                sys.exit()
            else:
                print("\nPlease enter a valid command.")
                continue
            return -1
Пример #10
0
def cmd_test(update, context):
    is_manager(update)

    # try if there are 2 arguments passed
    try:
        url = context.args[0]
    except IndexError:
        update.effective_message.reply_text(
            'ERROR: 格式需要为: /test RSS 条目编号(可选)')
        raise
    try:
        rss_d = feed_get(url, update, verbose=True)
    except (IndexError, requests.exceptions.RequestException):
        return
    if len(context.args) < 2 or len(rss_d.entries) <= int(context.args[1]):
        index = 0
    else:
        index = int(context.args[1])
    rss_d.entries[index]['link']
    # update.effective_message.reply_text(rss_d.entries[0]['link'])
    message.send(chatid, rss_d.entries[index]['summary'], rss_d.feed.title, rss_d.entries[index]['link'], context)
Пример #11
0
def test_channel_messages_unauthorised():
    'User is not a member case'
    workspace_reset()

    ret = register_and_create()
    user1 = ret['user']
    token1 = user1['token']
    channelInfo = ret['channel']
    channel_id = channelInfo['channel_id']
    user2 = reg_user2()
    token2 = user2['token']

    payload = {'token': token1, 'channel_id': channel_id, 'message': "hello"}

    # Send message
    message.send(payload)

    # AccessError when user sends message to channel they aren't a member of
    # user2 isn't a member
    with pytest.raises(AccessError) as e:
        channel.messages(token2, channel_id, 0)
Пример #12
0
 def write_output(self):
     """
     Set output for each target
     """
     if ProjectVariables.out_deb or ProjectVariables.out_rel:
         self.cmake.write('############## Artefacts Output #################\n')
         self.cmake.write('# Defines outputs , depending Debug or Release. #\n')
         self.cmake.write('#################################################\n\n')
         if ProjectVariables.out_deb:
             self.cmake.write('if(CMAKE_BUILD_TYPE STREQUAL "Debug")\n')
             self.cmake.write('  set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_DEBUG}")\n')
             self.cmake.write('  set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_DEBUG}")\n')
             self.cmake.write('  set(CMAKE_EXECUTABLE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_DEBUG}")\n')
         if ProjectVariables.out_rel:
             self.cmake.write('else()\n')
             self.cmake.write('  set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_REL}")\n')
             self.cmake.write('  set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_REL}")\n')
             self.cmake.write('  set(CMAKE_EXECUTABLE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${OUTPUT_REL}")\n')
             self.cmake.write('endif()\n\n')
     else:
         msg.send('No Output found or define. CMake will use default ouputs.', 'warn')
Пример #13
0
    def create_data(self, vcxproj=''):
        """
        Get xml data from vcxproj file

        """

        try:
            tree = etree.parse(vcxproj)
            namespace = str(tree.getroot().nsmap)
            ns = {'ns': namespace.partition('\'')[-1].rpartition('\'')[0]}
            self.vcxproj = {
                'tree': tree,
                'ns': ns
            }
            assert 'http://schemas.microsoft.com' in ns['ns']
        except AssertionError:
            send(
                '.vcxproj file cannot be import, because this file does not seem to comply with'
                ' Microsoft xml data !',
                'error'
            )
            exit(1)
        except (OSError, IOError):
            send(
                '.vcxproj file cannot be import. '
                'Please, verify you have rights to this directory or file exists !',
                'error'
            )
            exit(1)
        except etree.XMLSyntaxError:
            send('This file is not a ".vcxproj" file or XML is broken !', 'error')
            exit(1)
Пример #14
0
    def link_dependencies(self):
        """
        Link : Add command to link dependencies to project.

        """

        references = self.tree.xpath('//ns:ProjectReference',
                                     namespaces=self.ns)
        if references:
            self.cmake.write('# Link with other dependencies.\n')
            self.cmake.write('target_link_libraries(${PROJECT_NAME} ')
            for ref in references:
                reference = str(ref.get('Include'))
                path_to_reference = os.path.splitext(
                    ntpath.basename(reference))[0]
                lib = os.path.splitext(ntpath.basename(reference))[0]
                if lib == 'g3log':
                    lib += 'ger'
                self.cmake.write(lib + ' ')
                message = 'External librairy found : %s' % path_to_reference
                send(message, '')
            self.cmake.write(')\n')
            try:
                if self.tree.xpath('//ns:AdditionalDependencies',
                                   namespaces=self.ns)[0] is not None:
                    depend = self.tree.xpath('//ns:AdditionalDependencies',
                                             namespaces=self.ns)[0]
                    listdepends = depend.text.replace(
                        '%(AdditionalDependencies)', '')
                    if listdepends != '':
                        send('Additional Dependencies = %s' % listdepends,
                             'ok')
                    windepends = []
                    for d in listdepends.split(';'):
                        if d != '%(AdditionalDependencies)':
                            if os.path.splitext(d)[1] == '.lib':
                                windepends.append(d)
                    if windepends:
                        self.cmake.write('if(MSVC)\n')
                        self.cmake.write(
                            '   target_link_libraries(${PROJECT_NAME} ')
                        for dep in windepends:
                            self.cmake.write(dep + ' ')
                        self.cmake.write(')\n')
                        self.cmake.write('endif(MSVC)\n')
            except IndexError:
                send('No dependencies', '')
        else:
            send('No dependencies.', '')
Пример #15
0
def rss_monitor(context):
    update_flag = False
    for name, (feed_url, last_url) in rss_dict.items():
        try:
            rss_d = feed_get(feed_url)
        except IndexError:
            # print(f'Get {name} feed failed!')
            print('F', end='')
            continue
        except requests.exceptions.RequestException:
            print('N', end='')
            continue

        if last_url == rss_d.entries[0]['link']:
            print('-', end='')
        else:
            print('\nUpdating', name)
            update_flag = True
            # workaround, avoiding deleted weibo causing the bot send all posts in the feed
            # TODO: log recently sent weibo, so deleted weibo won't be harmful. (If a weibo was deleted while another
            #  weibo was sent between delay duration, the latter won't be fetched.) BTW, if your bot has stopped for
            #  too long that last fetched post do not exist in current RSS feed, all posts won't be fetched and last
            #  fetched post will be reset to the newest post (through it is not fetched).
            last_flag = False
            for entry in rss_d.entries[::-1]:  # push all messages not pushed
                if last_flag:
                    # context.bot.send_message(chatid, rss_d.entries[0]['link'])
                    print('\t- Pushing', entry['link'])
                    message.send(chatid, entry['summary'], rss_d.feed.title, entry['link'], context)

                if last_url == entry['link']:  # a sent post detected, the rest of posts in the list will be sent
                    last_flag = True

            sqlite_write(name, feed_url, str(rss_d.entries[0]['link']), True)  # update db

    if update_flag:
        print('Updated.')
        rss_load()  # update rss_dict
Пример #16
0
 def add_artefact(self):
     """
     Library and Executable
     """
     configurationtype = self.tree.find('//ns:ConfigurationType',
                                        namespaces=self.ns)
     if configurationtype.text == 'DynamicLibrary':
         self.cmake.write('# Add library to build.\n')
         self.cmake.write('add_library(${PROJECT_NAME} SHARED\n')
         msg.send('CMake will build a SHARED Library.', '')
     elif configurationtype.text == 'StaticLibrary':
         self.cmake.write('# Add library to build.\n')
         self.cmake.write('add_library(${PROJECT_NAME} STATIC\n')
         msg.send('CMake will build a STATIC Library.', '')
     else:
         self.cmake.write('# Add executable to build.\n')
         self.cmake.write('add_executable(${PROJECT_NAME} \n')
         msg.send('CMake will build an EXECUTABLE.', '')
     self.cmake.write('   ${SRC_FILES}\n')
     self.cmake.write(')\n\n')
Пример #17
0
def throwBall(ball):
    message.send("==> Throwing ball %s" % ball)

    channel.basic_publish(exchange='', routing_key=other_queue, body=ball)
Пример #18
0
import message

OLDBAUD = 9600

print "Setting NAV5 config to airborne mode..."
navconfig = message.UBXMessage('CFG-NAV5', "\x01\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
(ack, null) = message.send(navconfig, baudrate=OLDBAUD)
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."

print "\nSaving settings to flash..."
(ack, null) = message.send(message.UBXSaveConfig(), OLDBAUD)
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."
    
print "Verifying NAV settings..."
(settings, ack) = message.send(message.UBXPollNav5(), OLDBAUD)
print "New settings: ", settings.payload
Пример #19
0
import message


print "Setting NAV5 config to airborne mode..."
navconfig = message.UBXMessage(
    "CFG-NAV5",
    "\x01\x00\x07\x03\x00\x00\x00\x00\x10'\x00\x00\x05\x00\xfa\x00\xfa\x00d\x00,\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
(ack, null) = message.send(navconfig)
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."

print "\nSetting GLL message rate to 0.."
glloff = message.NMEA_SetRateMsg("GLL", 0)
message.send(glloff)
print "Done."  # NMEA messages don't get ACK'd

print "\nSaving settings to flash..."
(ack, null) = message.send(message.UBXSaveConfig())
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."

print "Verifying NAV settings..."
(settings, ack) = message.send(message.UBXPollNav5())
print "New settings: ", settings.payload
Пример #20
0
def test_send():
    assert message.send(12345, 1 ,"Hello") == 1
Пример #21
0
    for k, v in result.iteritems():
        print '%s : %s' % (k, v)

is_success, result = auth.get_access_token(CorpID, secret)
access_token = result.get('access_token')

# department
# is_success, result = department.get_department_list(access_token)
# print_dict(result)

# message
touser = '******'
toparty = '1868210'
# send_type = 'text'
# content = {'content': 'dingding'}

send_type = 'image'
content = {'media_id': '@lADOAMnd1M0Bqc0CgA'}
is_success, result = message.send(access_token, touser, toparty,
                                  send_type, content)
print result


# media
# media_type = 'image'
# media_file = open('./picture_test.jpg', 'rb')
# is_success, result = media.upload_media(access_token, media_type, media_file)
# print result

# picture_media_id = '@lADOAMnd1M0Bqc0CgA'
Пример #22
0
import message

OLDBAUD = 9600
NEWBAUD = 9600

print "Setting NAV5 config to airborne mode..."
navconfig = message.UBXMessage(
    'CFG-NAV5',
    "\x01\x00\x07\x03\x00\x00\x00\x00\x10'\x00\x00\x05\x00\xfa\x00\xfa\x00d\x00,\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
)
(ack, null) = message.send(navconfig, baudrate=OLDBAUD)
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."

print "\nSetting GLL message rate to 0.."
glloff = message.NMEA_SetRateMsg('GLL', 0)
message.send(glloff, baudrate=OLDBAUD)
print "Done."  # NMEA messages don't get ACK'd

print "\nSetting NEWBAUD rate to %d..." % NEWBAUD
print "Port 1"
setbaudmsg = message.NMEA_SetBaudMessage(1, NEWBAUD)
message.send(setbaudmsg, OLDBAUD)
print "Port 2"
setbaudmsg = message.NMEA_SetBaudMessage(2, NEWBAUD)
message.send(setbaudmsg, baudrate=OLDBAUD)
print "Done."

print "\nSaving settings to flash..."
Пример #23
0
    def define_variable(self):
        """
        Variable : define main variables in CMakeLists.

        """

        # PropertyGroup
        prop_deb_x86 = Vcxproj.get_propertygroup_platform('debug', 'x86')
        prop_deb_x64 = Vcxproj.get_propertygroup_platform('debug', 'x64')
        prop_rel_x86 = Vcxproj.get_propertygroup_platform('release', 'x86')
        prop_rel_x64 = Vcxproj.get_propertygroup_platform('release', 'x64')

        ProjectVariables.out_deb_x86 = self.tree.find('%s/ns:OutDir' %
                                                      prop_deb_x86,
                                                      namespaces=self.ns)
        if ProjectVariables.out_deb_x86 is None:
            ProjectVariables.out_deb_x86 = self.tree.find(prop_deb_x86,
                                                          namespaces=self.ns)

        ProjectVariables.out_deb_x64 = self.tree.find('%s/ns:OutDir' %
                                                      prop_deb_x64,
                                                      namespaces=self.ns)
        if ProjectVariables.out_deb_x64 is None:
            ProjectVariables.out_deb_x64 = self.tree.find(prop_deb_x64,
                                                          namespaces=self.ns)

        ProjectVariables.out_rel_x86 = self.tree.find('%s/ns:OutDir' %
                                                      prop_rel_x86,
                                                      namespaces=self.ns)
        if ProjectVariables.out_rel_x86 is None:
            ProjectVariables.out_rel_x86 = self.tree.find(prop_rel_x86,
                                                          namespaces=self.ns)

        ProjectVariables.out_rel_x64 = self.tree.find('%s/ns:OutDir' %
                                                      prop_rel_x64,
                                                      namespaces=self.ns)
        if ProjectVariables.out_rel_x64 is None:
            ProjectVariables.out_rel_x64 = self.tree.find(prop_rel_x64,
                                                          namespaces=self.ns)

        # CMake Minimum required.
        self.cmake.write(
            'cmake_minimum_required(VERSION 3.0.0 FATAL_ERROR)\n\n')

        # Project Name
        self.cmake.write(
            '################### Variables. ####################\n'
            '# Change if you want modify path or other values. #\n'
            '###################################################\n\n')
        root_projectname = self.tree.xpath('//ns:RootNamespace',
                                           namespaces=self.ns)
        project = False
        if root_projectname:
            projectname = root_projectname[0]
            if projectname.text:
                self.cmake.write('set(PROJECT_NAME ' + projectname.text +
                                 ')\n')
                project = True
        if not project:
            self.cmake.write(
                'set(PROJECT_NAME <PLEASE SET YOUR PROJECT NAME !!>)\n')
            send(
                'No PROJECT NAME found or define. Please set VARIABLE in CMakeLists.txt.',
                'error')

        # Output DIR of artefacts
        self.cmake.write('# Output Variables\n')
        output_deb_x86 = ''
        output_deb_x64 = ''
        output_rel_x86 = ''
        output_rel_x64 = ''
        if self.output is None:
            if ProjectVariables.out_deb_x86 is not None:
                output_deb_x86 = ProjectVariables.out_deb_x86.text.replace(
                    '$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_deb_x64 is not None:
                output_deb_x64 = ProjectVariables.out_deb_x64.text.replace(
                    '$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_rel_x86 is not None:
                output_rel_x86 = ProjectVariables.out_rel_x86.text.replace(
                    '$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_rel_x64 is not None:
                output_rel_x64 = ProjectVariables.out_rel_x64.text.replace(
                    '$(ProjectDir)', '').replace('\\', '/')
        elif self.output:
            if self.output[-1:] == '/' or self.output[-1:] == '\\':
                build_type = '${CMAKE_BUILD_TYPE}'
            else:
                build_type = '/${CMAKE_BUILD_TYPE}'
            output_deb_x86 = self.output + build_type
            output_deb_x64 = self.output + build_type
            output_rel_x86 = self.output + build_type
            output_rel_x64 = self.output + build_type
        else:
            output_deb_x86 = ''
            output_deb_x64 = ''
            output_rel_x86 = ''
            output_rel_x64 = ''

        if output_deb_x64 != '':
            send('Output Debug = ' + output_deb_x64, 'ok')
            self.cmake.write('set(OUTPUT_DEBUG ' + output_deb_x64 + ')\n')
            ProjectVariables.out_deb = True
        elif output_deb_x86 != '':
            send('Output Debug = ' + output_deb_x86, 'ok')
            self.cmake.write('set(OUTPUT_DEBUG ' + output_deb_x86 + ')\n')
            ProjectVariables.out_deb = True
        else:
            send('No Output Debug define.', '')

        if output_rel_x64 != '':
            send('Output Release = ' + output_rel_x64, 'ok')
            self.cmake.write('set(OUTPUT_REL ' + output_rel_x64 + ')\n')
            ProjectVariables.out_rel = True
        elif output_rel_x86 != '':
            send('Output Release = ' + output_rel_x86, 'ok')
            self.cmake.write('set(OUTPUT_REL ' + output_rel_x86 + ')\n')
            ProjectVariables.out_rel = True
        else:
            send('No Output Release define.', '')
Пример #24
0
    def define_win_flags(self):
        # Warning
        warning = self.tree.xpath('//ns:WarningLevel', namespaces=self.ns)[0]
        if warning.text != '':
            lvl = ' /W' + warning.text[-1:]
            self.win_deb_flags += lvl
            self.win_rel_flags += lvl
            msg.send('Warning : ' + warning.text, 'ok')
        else:
            msg.send('No Warning level.', '')

        """ PropertyGroup """
        prop_deb_x86 = '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'"]'
        prop_deb_x64 = '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|x64\'"]'
        prop_rel_x86 = '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'"]'
        prop_rel_x64 = '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]'

        # WholeProgramOptimization
        gl_debug_x86 = self.tree.find(prop_deb_x86 + '/ns:WholeProgramOptimization', namespaces=self.ns)
        gl_debug_x64 = self.tree.find(prop_deb_x64 + '/ns:WholeProgramOptimization', namespaces=self.ns)
        if gl_debug_x86 is not None and gl_debug_x64 is not None:
            if 'true' in gl_debug_x86.text and 'true' in gl_debug_x64.text:
                self.win_deb_flags += ' /GL'
                msg.send('WholeProgramOptimization for Debug', 'ok')
        else:
            msg.send('No WholeProgramOptimization for Debug', '')

        gl_release_x86 = self.tree.find(prop_rel_x86 + '/ns:WholeProgramOptimization', namespaces=self.ns)
        gl_release_x64 = self.tree.find(prop_rel_x64 + '/ns:WholeProgramOptimization', namespaces=self.ns)
        if gl_release_x86 is not None and gl_release_x64 is not None:
            if 'true' in gl_release_x86.text and 'true' in gl_release_x64.text:
                self.win_rel_flags += ' /GL'
                msg.send('WholeProgramOptimization for Release', 'ok')
        else:
            msg.send('No WholeProgramOptimization for Release', '')

        # UseDebugLibraries
        md_debug_x86 = self.tree.find(prop_deb_x86 + '/ns:UseDebugLibraries', namespaces=self.ns)
        md_debug_x64 = self.tree.find(prop_deb_x64 + '/ns:UseDebugLibraries', namespaces=self.ns)
        if md_debug_x64 is not None and md_debug_x86 is not None:
            if 'true' in md_debug_x86.text and 'true' in md_debug_x64.text:
                self.win_deb_flags += ' /MD'
                msg.send('UseDebugLibrairies for Debug', 'ok')
        else:
            msg.send('No UseDebugLibrairies for Debug', '')

        md_release_x86 = self.tree.find(prop_rel_x86 + '/ns:UseDebugLibraries', namespaces=self.ns)
        md_release_x64 = self.tree.find(prop_rel_x64 + '/ns:UseDebugLibraries', namespaces=self.ns)
        if md_release_x86 is not None and md_release_x64 is not None:
            if 'true' in md_release_x86.text and 'true' in md_release_x64.text:
                self.win_rel_flags += ' /MD'
                msg.send('UseDebugLibrairies for Release', 'ok')
        else:
            msg.send('No UseDebugLibrairies for Release', '')

        """ ItemDefinitionGroup """
        item_deb_x86 = '//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'"]'
        item_deb_x64 = '//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|x64\'"]'
        item_rel_x86 = '//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'"]'
        item_rel_x64 = '//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]'

        # RuntimeLibrary
        mdd_debug_x86 = self.tree.find(item_deb_x86 + '/ns:ClCompile/ns:RuntimeLibrary', namespaces=self.ns)
        mdd_debug_x64 = self.tree.find(item_deb_x64 + '/ns:ClCompile/ns:RuntimeLibrary', namespaces=self.ns)
        if mdd_debug_x64 is not None and mdd_debug_x86 is not None:
            if 'MultiThreadedDebugDLL' in mdd_debug_x86.text and 'MultiThreadedDebugDLL' in mdd_debug_x64.text:
                self.win_deb_flags += ' /MDd'
                msg.send('RuntimeLibrary for Debug', 'ok')
        else:
            msg.send('No RuntimeLibrary for Debug', '')

        mdd_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:RuntimeLibrary', namespaces=self.ns)
        mdd_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:RuntimeLibrary', namespaces=self.ns)
        if mdd_release_x86 is not None and mdd_release_x64 is not None:
            if 'MultiThreadedDebugDLL' in mdd_release_x86.text and 'MultiThreadedDebugDLL' in mdd_release_x64.text:
                self.win_rel_flags += ' /MDd'
                msg.send('RuntimeLibrary for Release', 'ok')
        else:
            msg.send('No RuntimeLibrary for Release', '')

        # Optimization
        opt_debug_x86 = self.tree.find(item_deb_x86 + '/ns:ClCompile/ns:Optimization', namespaces=self.ns)
        opt_debug_x64 = self.tree.find(item_deb_x64 + '/ns:ClCompile/ns:Optimization', namespaces=self.ns)
        if opt_debug_x86 is not None and opt_debug_x64 is not None:
            if 'Disabled' in opt_debug_x64.text and 'Disabled' in opt_debug_x86.text:
                self.win_deb_flags += ' /Od'
                msg.send('Optimization for Debug', 'ok')
        else:
            msg.send('No Optimization for Debug', '')

        opt_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:Optimization', namespaces=self.ns)
        opt_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:Optimization', namespaces=self.ns)
        if opt_release_x86 is not None and opt_release_x64 is not None:
            if 'MaxSpeed' in opt_release_x64.text and 'MaxSpeed' in opt_release_x86.text:
                self.win_rel_flags += ' /Od'
                msg.send('Optimization for Release', 'ok')
        else:
            msg.send('No Optimization for Release', '')

        # IntrinsicFunctions
        oi_debug_x86 = self.tree.find(item_deb_x86 + '/ns:ClCompile/ns:IntrinsicFunctions', namespaces=self.ns)
        oi_debug_x64 = self.tree.find(item_deb_x64 + '/ns:ClCompile/ns:IntrinsicFunctions', namespaces=self.ns)
        if oi_debug_x86 is not None and oi_debug_x64 is not None:
            if 'true' in oi_debug_x86.text and 'true' in oi_debug_x64.text:
                self.win_deb_flags += ' /Oi'
                msg.send('IntrinsicFunctions for Debug', 'ok')
        else:
            msg.send('No IntrinsicFunctions for Debug', '')

        oi_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:IntrinsicFunctions', namespaces=self.ns)
        oi_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:IntrinsicFunctions', namespaces=self.ns)
        if oi_release_x86 is not None and oi_release_x64 is not None:
            if 'true' in oi_release_x86.text and 'true' in oi_release_x64.text:
                self.win_rel_flags += ' /Oi'
                msg.send('IntrinsicFunctions for Release', 'ok')
        else:
            msg.send('No IntrinsicFunctions for Release', '')

        # RuntimeTypeInfo
        gr_debug_x86 = self.tree.find(item_deb_x86 + '/ns:ClCompile/ns:RuntimeTypeInfo', namespaces=self.ns)
        gr_debug_x64 = self.tree.find(item_deb_x64 + '/ns:ClCompile/ns:RuntimeTypeInfo', namespaces=self.ns)
        if gr_debug_x64 is not None and gr_debug_x86 is not None:
            if 'true' in gr_debug_x64.text and gr_debug_x86.text:
                self.win_deb_flags += ' /GR'
                msg.send('RuntimeTypeInfo for Debug', 'ok')
        else:
            msg.send('No RuntimeTypeInfo for Debug', '')

        gr_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:RuntimeTypeInfo', namespaces=self.ns)
        gr_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:RuntimeTypeInfo', namespaces=self.ns)
        if gr_release_x86 is not None and gr_release_x64 is not None:
            if 'true' in gr_release_x64.text and gr_release_x86.text:
                self.win_rel_flags += ' /GR'
                msg.send('RuntimeTypeInfo for Release', 'ok')
        else:
            msg.send('No RuntimeTypeInfo for Release', '')

        # FunctionLevelLinking
        gy_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:FunctionLevelLinking', namespaces=self.ns)
        gy_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:FunctionLevelLinking', namespaces=self.ns)
        if gy_release_x86 is not None and gy_release_x64 is not None:
            if 'true' in gy_release_x86.text and 'true' in gy_release_x64.text:
                self.win_rel_flags += ' /Gy'
                msg.send('FunctionLevelLinking for release.', 'ok')
        else:
            msg.send('No FunctionLevelLinking for release.', '')

        # GenerateDebugInformation
        zi_debug_x86 = self.tree.find(item_deb_x86 + '/ns:Link/ns:GenerateDebugInformation', namespaces=self.ns)
        zi_debug_x64 = self.tree.find(item_deb_x64 + '/ns:Link/ns:GenerateDebugInformation', namespaces=self.ns)
        if zi_debug_x86 is not None and zi_debug_x64 is not None:
            if 'true' in zi_debug_x86.text and zi_debug_x64.text:
                self.win_deb_flags += ' /Zi'
                msg.send('GenerateDebugInformation for debug.', 'ok')
        else:
            msg.send('No GenerateDebugInformation for debug.', '')

        zi_release_x86 = self.tree.find(item_rel_x86 + '/ns:Link/ns:GenerateDebugInformation', namespaces=self.ns)
        zi_release_x64 = self.tree.find(item_rel_x64 + '/ns:Link/ns:GenerateDebugInformation', namespaces=self.ns)
        if zi_release_x86 is not None and zi_release_x64 is not None:
            if 'true' in zi_release_x86.text and zi_release_x64.text:
                self.win_rel_flags += ' /Zi'
                msg.send('GenerateDebugInformation for release.', 'ok')
        else:
            msg.send('No GenerateDebugInformation for release.', '')

        # ExceptionHandling
        ehs_debug_x86 = self.tree.find(item_deb_x86 + '/ns:ClCompile/ns:ExceptionHandling', namespaces=self.ns)
        ehs_debug_x64 = self.tree.find(item_deb_x64 + '/ns:ClCompile/ns:ExceptionHandling', namespaces=self.ns)
        if ehs_debug_x86 is not None and ehs_debug_x64 is not None:
            if 'false' in ehs_debug_x86.text and ehs_debug_x64.text:
                msg.send('No ExceptionHandling for debug.', '')
        else:
            self.win_deb_flags += ' /EHsc'
            msg.send('ExceptionHandling for debug.', 'ok')

        ehs_release_x86 = self.tree.find(item_rel_x86 + '/ns:ClCompile/ns:ExceptionHandling', namespaces=self.ns)
        ehs_release_x64 = self.tree.find(item_rel_x64 + '/ns:ClCompile/ns:ExceptionHandling', namespaces=self.ns)
        if ehs_release_x86 is not None and ehs_release_x64 is not None:
            if 'false' in ehs_release_x86.text and ehs_release_x64.text:
                msg.send('No ExceptionHandling option for release.', '')
        else:
            self.win_rel_flags += ' /EHsc'
            msg.send('ExceptionHandling for release.', 'ok')

        # Define FLAGS for Windows
        self.cmake.write('if(MSVC)\n')
        if self.win_deb_flags != '':
            msg.send('Debug   FLAGS found = ' + self.win_deb_flags, 'ok')
            self.cmake.write('   set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}' + self.win_deb_flags + '")\n')
        else:
            msg.send('No Debug   FLAGS found', '')
        if self.win_rel_flags != '':
            msg.send('Release FLAGS found = ' + self.win_rel_flags, 'ok')
            self.cmake.write('   set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}' + self.win_rel_flags + '")\n')
        else:
            msg.send('No Release FLAGS found', '')
        self.cmake.write('endif(MSVC)\n')
Пример #25
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    incoming_num1 = request.values.get(
        'To', '').lower()  #although not necessary but still
    incoming_num2 = request.values.get(
        'From', '').lower()  #the incoming message mobile number
    current = str(datetime.datetime.now())
    resp = MessagingResponse()
    msg = resp.message()
    completionMsg = ""  #this is to store the displayed result
    responded = False
    now = datetime.datetime.now()
    # now = datetime.now()

    current_time = now.strftime("%H:%M:%S")

    logs = "Current Time =", current_time + incoming_num2 + "Message : " + incoming_msg
    print(logs)
    if 'bothelp' in incoming_msg:

        reply = "Hi I am PicoBot, How can I help you ?\n\nType 'contact' for developers contact \n\nType 'tasks' for list of available tasks"
        msg.body(reply)
        # msg.body("test msg")
        responded = True
        completionMsg = reply
    elif ('covidhelp' in incoming_msg):
        l = incoming_msg.split()
        reply = ""
        try:
            city = l[1]
            required = l[2]
            leads = twitter.input_triggers_spinner(city, required)
            print("Lead length=")
            print(len(leads))

            for lead in leads:
                reply += "\n" + lead['full_text'] + "\n-----------------"
        except:
            reply = "Please put your query in given format"
        msg.body(reply)
        responded = True
        completionMsg = reply

    elif ('covidnews' in incoming_msg):
        l = incoming_msg.split()
        reply = ""
        try:
            category = l[1]
            news = getNews(category)
            newstock = news["data"]
            for i in range(len(newstock)):
                reply = news["data"][i]["title"] + "\n\n" + news["data"][i][
                    "content"]
                alink = news["data"][i]["imageUrl"]
                # msg.media(alink)
                message.send(incoming_num2, reply, [alink])

        except:
            reply = "Please put your query in given format"
        msg.body(reply)
        responded = True
        completionMsg = reply

    elif ('covidvaccine' in incoming_msg):
        if ('drive' in incoming_msg):

            reply = cowin.states()
            msg.body(reply)
            responded = True
            completionMsg = reply
        elif ('state' in incoming_msg):

            l = incoming_msg.split()
            id = int(l[2])
            reply = cowin.districts(id)
            # except:
            #     reply= "Please put your query in given format"
            msg.body(reply)
            responded = True
            completionMsg = reply
        else:
            l = incoming_msg.split()
            reply = ""
            # try:

            #     pincode = l[1]
            #     date = l[2]
            #     min_age_limit = 45

            #     reply = cowin.driver(pincode,date,min_age_limit)
            # except:
            #     reply= "Please put your query in given format"

            pincode = l[1]
            # date = l[2]
            min_age_limit = 45

            reply = cowin.driver(pincode)
            # print(reply[10])
            try:
                msg.body(reply[:699])
            except:
                msg.body(reply)
            responded = True
            completionMsg = reply
    if 'covidinfo' in incoming_msg:
        l = incoming_msg.split()
        state = 'india'
        if (len(l) > 1):
            state = ""
            for i in l[1:]:
                state += i + " "
            state = state[:-1]
        c, r, d, a = statistics.driver(state)
        reply = "\n✅Confirmed: " + str(c) + "\n✅Recovered: " + str(
            r) + "\n✅Active: " + str(a) + "\n✅Deceased: " + str(d)
        msg.body(reply)
        responded = True
        completionMsg = reply
    if 'contact' in incoming_msg:
        reply = "Hi I am Gauransh Soni\nSophomore @ IIT Delhi\nEmail - [email protected]\nContact No. 9462447291"
        msg.body(reply)
        responded = True
        completionMsg = reply
    if 'task' in incoming_msg:
        reply = "Here is a list of items I can do\n1)Type 'covidhelp <cityname> <Oxygen or Remedesivir or Plasma>' to get recent leads for asked item\n2)Type 'covidinfo <state>' to get recent statistics of covid cases in your state\n3)Type 'emergency <pincode>' to get the contact number of emergency services in your area\n4)Type 'covidvaccine <pincode>' to check availability of vaccine in your area\n5)Type 'help' to get more info"
        msg.body(reply)
        responded = True
        completionMsg = reply

    if 'quote' in incoming_msg:
        # return a quote
        r = requests.get('https://api.quotable.io/random')
        if r.status_code == 200:
            data = r.json()
            quote = f'{data["content"]} ({data["author"]})'
        else:
            quote = 'I could not retrieve a quote at this time, sorry.'
        msg.body(quote)
        responded = True
        completionMsg = quote
    if 'aurbhai' in incoming_msg:
        # return a cat pic
        msg.body('I love cats')
        msg.media('https://cataas.com/cat')
        responded = True
        completionMsg = 'https://cataas.com/cat'
    if 'wallpaper' in incoming_msg:
        l = incoming_message.split()
        url = l[1]
        try:
            from googlesearch import search
        except ImportError:
            print("No module named 'google' found")
            completionMsg = "No module named 'google' found"
        # to search
        query = url + " unsplash"
        for j in search(query, tld="co.in", num=1, stop=4, pause=2):
            if "https://unsplash.com/s/photos" in j:
                url = j
        a = urllib.request.urlopen(url, context=ctx).read()
        soup = bs(a, 'html.parser')
        L = soup.find_all('a', {'title': "Download photo"})
        x = randint(1, len(L) - 1)
        alink = L[x].get('href')
        msg.media(alink)
        completionMsg = alink
        responded = True
    if 'unsplash' in incoming_msg:
        # return a cat pic
        msg.body('Here You Go ')
        un_img = 'https://source.unsplash.com/random'
        msg.media(un_img)
        responded = True
        completionMsg = un_img
    if 'spam' in incoming_msg:
        # spams
        l = incoming_msg.split()
        countSpam = int(l[1])
        mess = " ".join(l[2:])
        for i in range(countSpam):
            msg.body(mess)
        completionMsg = "Succesfully spammed"
        responded = True
    if 'dank-joke' in incoming_msg:
        #sends a random dank joke
        responseDog = requests.get(
            "https://sv443.net/jokeapi/v2/joke/Any?type=single")
        l = responseDog.json()
        msg.body(l['joke'])
        completionMsg = l['joke']
        responded = True
    if 'dict' in incoming_msg:
        headersDict = {
            'Authorization': 'Token e3d0b4298a9592eb23efa0419b031d2ffadc94d4',
        }
        urlForDict = 'https://owlbot.info/api/v4/dictionary/'
        incoming_msg = 'dict cat'
        l = incoming_msg.split()
        searchTerm = l[1]
        urlForDict += searchTerm
        response = requests.get(urlForDict, headers=headersDict)
        ans = response.json()
        pronounciation = ans['pronunciation']
        defination = ans['definitions'][0]['definition']
        img = ans['definitions'][0]['image_url']
        example = ans['definitions'][0]['example']
        returnString = "*Defination* : " + defination + "\n" + "*usage*: " + example
        msg.body(returnString)
        msg.media(img)
        completionMsg = "successfully sent"
        responded = True
    if 'que' in incoming_msg:
        import urllib.request, urllib.parse, urllib.error
        import xml.etree.ElementTree as ET
        import ssl
        from bs4 import BeautifulSoup as bs

        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        url = ' '.join(incoming_msg.split()[1:])

        try:
            from googlesearch import search
        except ImportError:
            print("No module named 'google' found")

        # to search
        query = url + " stackoverflow"

        for j in search(query, tld="co.in", num=1, stop=1, pause=2):
            url = j
        a = urllib.request.urlopen(url, context=ctx).read()
        soup = bs(a, 'html.parser')
        L = soup.find_all('div', {'class': 'post-text'})
        i = L[1]
        msg.body(i.text)
        print(i.text)
        completionMsg = i.text
        responded = True

    if not responded:
        msg.body('type bothelp')
        completionMsg = "Job Done"
    row = [
        current, incoming_num1[9:], incoming_num2[9:], incoming_msg,
        completionMsg
    ]
    f = open("output.txt", "a")
    if incoming_msg != "":
        myadd = ""
        for string in row:
            myadd += string + " "
        f.write(myadd + "\n")
        f.close()
    # sheet.insert_row(row,index=2)
    return str(resp)
Пример #26
0
import message

OLDBAUD = 9600
NEWBAUD = 4800

print "Setting NAV5 config to airborne mode..."
navconfig = message.UBXMessage('CFG-NAV5', "\x01\x00\x07\x03\x00\x00\x00\x00\x10'\x00\x00\x05\x00\xfa\x00\xfa\x00d\x00,\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
(ack, null) = message.send(navconfig, baudrate=OLDBAUD)
if ack:
    print "ACK: ", ack.emit()
else:
    print "Didn't get ACK."

print "\nSetting GLL message rate to 0.."
glloff = message.NMEA_SetRateMsg('GLL', 0)
message.send(glloff, baudrate=OLDBAUD)
print "Done." # NMEA messages don't get ACK'd

print "\nSetting NEWBAUD rate to %d..." % NEWBAUD
print "Port 1"
setbaudmsg = message.NMEA_SetBaudMessage(1, NEWBAUD)
message.send(setbaudmsg, OLDBAUD)
print "Port 2"
setbaudmsg = message.NMEA_SetBaudMessage(2, NEWBAUD)
message.send(setbaudmsg, baudrate=OLDBAUD)
print "Done."

print "\nSaving settings to flash..."
(ack, null) = message.send(message.UBXSaveConfig(), OLDBAUD)
(ack, null) = message.send(message.UBXSaveConfig(), NEWBAUD)
if ack:
Пример #27
0
def parse_argument():
    """
    Main script : define arguments and send to convertdata.

    """

    data = {
        'vcxproj': None,
        'cmake': None,
        'additional_code': None,
        'includes': None,
        'dependencies': None,
        'cmake_output': None,
        'data': None
    }

    # Init parser
    parser = argparse.ArgumentParser(
        description='Convert file.vcxproj to CMakelists.txt')
    parser.add_argument('-p',
                        help='absolute or relative path of a file.vcxproj')
    parser.add_argument('-o', help='define output.')
    parser.add_argument(
        '-a',
        help='import cmake code from file.cmake to your final CMakeLists.txt')
    parser.add_argument(
        '-D',
        help='replace dependencies found in .vcxproj, separated by colons.')
    parser.add_argument('-O',
                        help='define output of artefact produces by CMake.')
    parser.add_argument(
        '-i',
        help='add include directories in CMakeLists.txt. Default : False')

    # Get args
    args = parser.parse_args()

    # Vcxproj Path
    if args.p is not None:
        temp_path = os.path.splitext(args.p)
        if temp_path[1] == '.vcxproj':
            send('Project to convert = ' + args.p, '')
            project = Vcxproj()
            project.create_data(args.p)
            data['vcxproj'] = project.vcxproj
        else:
            send(
                'This file is not a ".vcxproj". Be sure you give the right file',
                'error')
            exit(1)

    # CMakeLists.txt output
    if args.o is not None:
        cmakelists = CMake()
        if os.path.exists(args.o):
            cmakelists.create_cmake(args.o)
            data['cmake'] = cmakelists.cmake
        else:
            send(
                'This path does not exist. CMakeList.txt will be generated in current directory.',
                'error')
            cmakelists.create_cmake()
        data['cmake'] = cmakelists.cmake
    else:
        cmakelists = CMake()
        cmakelists.create_cmake()
        data['cmake'] = cmakelists.cmake

    # CMake additional Code
    if args.a is not None:
        data['additional_code'] = args.a

    # If replace Dependencies
    if args.D is not None:
        data['dependencies'] = args.D.split(':')

    # Define Output of CMake artefact
    if args.O is not None:
        data['cmake_output'] = args.O

    # Add include directories found in vcxproj
    if args.i is not None:
        if args.i == 'True':
            data['includes'] = True

    # Give all to class: conversata
    all_data = ConvertData(data)
    all_data.create_data()
Пример #28
0
def listen_print_loop(responses, number):
    """Iterates through server responses and prints them.

    The responses passed is a generator that will block until a response
    is provided by the server.

    Each response may contain multiple results, and each result may contain
    multiple alternatives; for details, see https://goo.gl/tjCPAU.  Here we
    print only the transcription for the top alternative of the top result.

    In this case, responses are provided for interim results as well. If the
    response is an interim one, print a line feed at the end of it, to allow
    the next result to overwrite it, until the response is a final one. For the
    final one, print a newline to preserve the finalized transcription.
    """
    num_chars_printed = 0
    for response in responses:
        if not cont:
            print('exiting...')
            return
        if not response.results:
            continue

        # The `results` list is consecutive. For streaming, we only care about
        # the first result being considered, since once it's `is_final`, it
        # moves on to considering the next utterance.
        result = response.results[0]
        if not result.alternatives:
            continue

        # Display the transcription of the top alternative.
        transcript = result.alternatives[0].transcript

        # Display interim results, but with a carriage return at the end of the
        # line, so subsequent lines will overwrite them.
        #
        # If the previous result was longer than this one, we need to print
        # some extra spaces to overwrite the previous result
        overwrite_chars = ' ' * (num_chars_printed - len(transcript))

        if not result.is_final:
            sys.stdout.write(transcript + overwrite_chars + '\r')
            sys.stdout.flush()

            num_chars_printed = len(transcript)

        else:
            print(transcript + overwrite_chars)
            text = str(transcript)
            # The text to analyze

            document = language_types.Document(
                content=text, type=language_enums.Document.Type.PLAIN_TEXT)

            # Detects the sentiment of the text
            sentiment = language_client.analyze_sentiment(
                document=document).document_sentiment
            if sentiment.score < -.5:
                message_text = "Hey, where is your relax bro?\nThis was not very chill:\n\"" + str(
                    document.content) + "\""
                print(message_text)
                send(message_text, number)

            elif sentiment.score < -.15:
                message_text = "I think saying this was a little uncool, dude:\n\"" + str(
                    document.content) + "\""
                print(message_text)
                send(message_text, number)
            else:
                pass

            # # Exit recognition if any of the transcribed phrases could be
            # # one of our keywords.
            # if re.search(r'\b(exit|quit)\b', transcript, re.I):
            #     print('Exiting..')
            #     break

            num_chars_printed = 0
Пример #29
0
import message as ms

ms.setup_connection()

rank = ms.node_id
nodes = ms.n_node
nxt = (rank + 1) % nodes
pre = (rank - 1 + nodes) % nodes

print "My ID is", rank
ms.send(nxt, "Next to %i is %i" % (rank, nxt))

msg = ms.recv(pre)
print msg

ms.close_connection()
Пример #30
0
    def define_variable(self):
        """
        Variable : define main variables in CMakeLists.
        """
        ProjectVariables.out_deb_x86 = self.tree.find(
            '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'"]/ns:OutDir',
            namespaces=self.ns)
        if ProjectVariables.out_deb_x86 is None:
            ProjectVariables.out_deb_x86 = self.tree.find(
                '//ns:PropertyGroup/ns:OutDir[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'"]',
                namespaces=self.ns)
        ProjectVariables.out_deb_x64 = self.tree.find(
            '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|x64\'"]/ns:OutDir',
            namespaces=self.ns)
        if ProjectVariables.out_deb_x64 is None:
            ProjectVariables.out_deb_x64 = self.tree.find(
                '//ns:PropertyGroup/ns:OutDir[@Condition="\'$(Configuration)|$(Platform)\'==\'Debug|x64\'"]',
                namespaces=self.ns)
        ProjectVariables.out_rel_x86 = self.tree.find(
            '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'"]/ns:OutDir',
            namespaces=self.ns)
        if ProjectVariables.out_rel_x86 is None:
            ProjectVariables.out_rel_x86 = self.tree.find(
                '//ns:PropertyGroup/ns:OutDir[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'"]',
                namespaces=self.ns)
        ProjectVariables.out_rel_x64 = self.tree.find(
            '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]/ns:OutDir',
            namespaces=self.ns)
        if ProjectVariables.out_rel_x64 is None:
            ProjectVariables.out_rel_x64 = self.tree.find(
                '//ns:PropertyGroup/ns:OutDir[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]',
                namespaces=self.ns)

        # CMake Minimum required.
        self.cmake.write('cmake_minimum_required(VERSION 3.0.0 FATAL_ERROR)\n\n')

        # Project Name
        projectname = self.tree.xpath('//ns:RootNamespace', namespaces=self.ns)[0]
        self.cmake.write('################### Variables. ####################\n'
                         '# Change if you want modify path or other values. #\n'
                         '###################################################\n\n')
        self.cmake.write('set(PROJECT_NAME ' + projectname.text + ')\n')

        # Output DIR of artefacts
        self.cmake.write('# Output Variables\n')
        output_deb_x86 = ''
        output_deb_x64 = ''
        output_rel_x86 = ''
        output_rel_x64 = ''
        if self.output is None:
            if ProjectVariables.out_deb_x86 is not None:
                output_deb_x86 = ProjectVariables.out_deb_x86.text.replace('$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_deb_x64 is not None:
                output_deb_x64 = ProjectVariables.out_deb_x64.text.replace('$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_rel_x86 is not None:
                output_rel_x86 = ProjectVariables.out_rel_x86.text.replace('$(ProjectDir)', '').replace('\\', '/')
            if ProjectVariables.out_rel_x64 is not None:
                output_rel_x64 = ProjectVariables.out_rel_x64.text.replace('$(ProjectDir)', '').replace('\\', '/')
        elif self.output:
            if self.output[-1:] == '/' or self.output[-1:] == '\\':
                build_type = '${CMAKE_BUILD_TYPE}'
            else:
                build_type = '/${CMAKE_BUILD_TYPE}'
            output_deb_x86 = self.output + build_type
            output_deb_x64 = self.output + build_type
            output_rel_x86 = self.output + build_type
            output_rel_x64 = self.output + build_type
        else:
            output_deb_x86 = ''
            output_deb_x64 = ''
            output_rel_x86 = ''
            output_rel_x64 = ''

        if output_deb_x64 != '':
            msg.send('Output Debug = ' + output_deb_x64, 'ok')
            self.cmake.write('set(OUTPUT_DEBUG ' + output_deb_x64 + ')\n')
            ProjectVariables.out_deb = True
        elif output_deb_x86 != '':
            msg.send('Output Debug = ' + output_deb_x86, 'ok')
            self.cmake.write('set(OUTPUT_DEBUG ' + output_deb_x86 + ')\n')
            ProjectVariables.out_deb = True
        else:
            msg.send('No Output Debug define.', '')

        if output_rel_x64 != '':
            msg.send('Output Release = ' + output_rel_x64, 'ok')
            self.cmake.write('set(OUTPUT_REL ' + output_rel_x64 + ')\n')
            ProjectVariables.out_rel = True
        elif output_rel_x86 != '':
            msg.send('Output Release = ' + output_rel_x86, 'ok')
            self.cmake.write('set(OUTPUT_REL ' + output_rel_x86 + ')\n')
            ProjectVariables.out_rel = True
        else:
            msg.send('No Output Release define.', '')
Пример #31
0
        for (img1, img2) in itertools.combinations(args.imgs, 2):

            i = i + 1
            if i < len(member):
                try:
                    d = getRep(img1) - getRep(img2)
                    percent = -25 * np.dot(d, d) + 100
                    print("Comparing {} with {}.".format(img1, img2))
                    print(
                        "  + Squared l2 distance between representations: {:0.3f}"
                        .format(np.dot(d, d)))
                    print("{:0.2f}".format(percent))
                except Exception as err:
                    print(err)
                    i = len(member)
                    break

                if percent > 90:
                    msg = '1'
                    message.send(i - 1)
                    break
            else:
                break

        path.move(member[i - 1])

        c = socket(AF_INET, SOCK_STREAM)
        c.connect((TCP_IP, TCP_PORT))
        c.sendall(msg.encode())
        c.close()
Пример #32
0
    for k, v in result.iteritems():
        print '%s : %s' % (k, v)


is_success, result = auth.get_access_token(CorpID, secret)
access_token = result.get('access_token')

# department
# is_success, result = department.get_department_list(access_token)
# print_dict(result)

# message
touser = '******'
toparty = '1868210'
# send_type = 'text'
# content = {'content': 'dingding'}

send_type = 'image'
content = {'media_id': '@lADOAMnd1M0Bqc0CgA'}
is_success, result = message.send(access_token, touser, toparty, send_type,
                                  content)
print result

# media
# media_type = 'image'
# media_file = open('./picture_test.jpg', 'rb')
# is_success, result = media.upload_media(access_token, media_type, media_file)
# print result

# picture_media_id = '@lADOAMnd1M0Bqc0CgA'
Пример #33
0
	print ("Checking cache %s" % key)
	value = red.get(key)
	if value is None:
		print ("Nothing in the cache")
		message.send ("Nothing found in the cache")
	else:
		# Cleans the cache
		print ("Found a ball %r " % value)
		message.send ("Found a ball %r " % value)

def initCache():
	print ("Initializing cache")
	global red
	red = redis.StrictRedis(host=CACHE)

print(welcome_message)

# Init message
message.init ()

message.send (welcome_message)

# Init cache
initCache()

# Check cache
checkCache('ping-0')
checkCache('ping-1')


Пример #34
0
 def run(self):
     message.send(self.conn)