working on it ...

Filters

Explore Public Snippets

Sort by

Found 94k snippets

    public by bmooers modified Feb 22, 2018  517  0  4  0

    roundview.py for PyMOL

    rounds off the viewport settings in PyMOL to 2 decimals places and returns on one line.
    // Enter here the actual content of the snippet.						
    
    from __future__ import division
    from __future__ import print_function
    # -*- coding: utf-8 -*-
    
    """
    version 1.0         26 October 2015
        Posted in github for first time.
    version 1.1         23 November 2015
        Corrected description of the rounding off the matrix elements.
        Corrected hard wrapped text the broke the script. 
        Added example of running program as a horizontal script.
        Made code pep8 compliant (changed use of blank lines, 
            removed whitespaces in defualt arguments assignments, 
            inserted whitespaces after commas in lists, 
            removed whitespaces at the ends of lines).
        Added version number.
    version 1.2         23 May 2016
        Edited copyright notice.
        Corrected typos
        
    version 1.3         23 July 2016
        Added missing parenthesis at end of file.
        
       Copyright Notice
      ================
      
         Copyright (C) 2016  Blaine Mooers
        This program 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 of the License.
        This program 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:
        http://www.gnu.org/licenses/.
      The source code in this file is copyrighted, but you can
      freely use and copy it as long as you don't change or remove any of
      the copyright notices.
      
      Blaine Mooers, PhD 
      blaine-mooers@ouhsc.edu
      975 NE 10th St, BRC 466
      University of Oklahoma Health Sciences Center, 
      Oklahoma City, OK, USA 73104
     """
    from pymol import stored, cmd
    __author__ = "Blaine Mooers"
    __copyright__ = "Blaine Mooers, University of Oklahoma Health Sciences Center, Oklahoma City, OK, USA 73104"
    __license__ = "GPL-3"
    __version__ = "1.0.2"
    __credits__ = ["William Beasley","Chiedza Kanyumbu"] 
    # people who reported bug fixes, made suggestions, etc. 
    __date__ = "30 May 2016"
    __maintainer__ = "Blaine Mooers"
    __email__ = "blaine-mooers@ouhsc.edu"
    __status__ = "Production" 
    
    
    def roundview(StoredView=0, decimal_places=2, outname="roundedview.txt"):
    
        """
        DESCRIPTION
        Adds the command "roundview" that gets a view (default is 0,
        the current view; you can get a stored view assigned to some
        other digit with the view command) and rounds to two decimal
        places (two digits to the right of the decimal point) the
        viewpoint matrix elements and rewrites the matrix elements
        on a single line with no whitespaces and a semicolon at the
        end. The saved space eases the making of a single line of
        PyMOL commands separated by semicolons. This enables rapid
        and interactive editing of chunks of PyMOL commands. The
        viewpoints are appended to the bottom of a text file in the
        present working directory called "roundedview.txt". The line
        could be easier to copy from this file than from the command
        history window in the external gui. A semicolon with nothing
        to the right of it at the end of a line of grouped commands
        is harmless.
        USAGE
         
        roundview [view, decimal_places, outname] 
        Note that the values in the [] are optional.
        The default values  for the arguments of the function
        are "0,2, roundedview.txt". 
        Simple one-line example with roundview.py script in current working
        directory--check by typing 'pwd' and 'ls *.py' on the command line. PyMOL
        should return 'roundview.py' in the lisf of files in the external (top) gui.
        Next, paste the following command on the external (top) commandline, hit
        return, and wait 5-10 seconds:
        fetch 1lw9, async=0; run roundview.py; roundview 0,1
        The following view setting will be returned without the blackslash.
        set_view (1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,-155.2,35.1,11.5,9.7,122.3,188.0,-20.0);
        Advanced option:
        Copy roundview.py to the folder ~/.pymol/startup and then
        the command will always be accessible. You may have to 
        create these directories. 
        18 elements of the view matrix (0-17)
        0 - 8 = column-major 3x3 matrix that rotates the model axes
        to camera axes 
        9 - 11 = origin of rotation relative to the camera
        in camera space
        12 - 14 = origin of rotation in model space
        15 = front plane distance from the camera
        16 = rear plane distance from the camera
        17 = orthoscopic flag 
        (not implemented in older versions)
        
        """
        
        #convert the commandline arguments from strings to integers
    
        StoredView = int(StoredView)
        decimal_places = int(decimal_places)
        
        
        #call the get_view function
    
        m = cmd.get_view(StoredView)
    
    
        #Make a list of the elements in the orientation matrix.
    
        myList = [m[0], m[1], m[2], m[3], m[4], m[5], m[6],
            m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14],
            m[15], m[16], m[17]]
    
    
        #Round off the matrix elements to two decimal places (two fractional places)
        #This rounding approach solved the problem of unwanted
        #whitespaces when I tried using a string format statement
    
        myRoundedList = [ round(elem, decimal_places) for elem in myList]
        
        
        #x is the format of the output. The whitespace is required
        #between the "set_view" and "(".
        
        x = 'set_view ({0},{1},{2},{3},{4},{5},{6},{7},\
    {8},{9},{10},{11},{12},{13},{14},{15},{16},{17});'
    
    
        #print to the external gui.
    
        print x.format(*myRoundedList)
    
    
        #Write to a text file.
    
        myFile = open("roundedview.txt", "a")
        myFile.write(x.format(*myRoundedList) + "\n")
        myFile.close()
        return
    
    
        #The extend command makes roundview into a PyMOL command.
    
    cmd.extend("roundview", roundview)

    public by Tech_JA modified Oct 26, 2017  321  0  4  0

    config-highlight.cfg

    https://gist.github.com/dsosby/1122904
    [Obsidian]
    definition-foreground = #678CB1
    error-foreground = #FF0000
    string-background = #293134
    keyword-foreground = #93C763
    normal-foreground = #E0E2E4
    comment-background = #293134
    hit-foreground = #E0E2E4
    builtin-background = #293134
    stdout-foreground = #678CB1
    cursor-foreground = #E0E2E4
    break-background = #293134
    comment-foreground = #66747B
    hilite-background = #2F393C
    hilite-foreground = #E0E2E4
    definition-background = #293134
    stderr-background = #293134
    hit-background = #000000
    console-foreground = #E0E2E4
    normal-background = #293134
    builtin-foreground = #E0E2E4
    stdout-background = #293134
    console-background = #293134
    stderr-foreground = #FB0000
    keyword-background = #293134
    string-foreground = #EC7600
    break-foreground = #E0E2E4
    error-background = #293134						

    public by alejo8591 modified Oct 10, 2017  171  0  2  0

    Python Selenium get cookie value

    Python Selenium get cookie value: scrape.py
    import time
    from selenium import webdriver
    
    driver = webdriver.Chrome('./chromedriver')
    driver.get('https://ui.lkqd.com/login')
    assert 'LKQD' in driver.title
    
    time.sleep(2)
    username_field = driver.find_element_by_name('username')
    username_field.send_keys('myusername')
    
    password_field = driver.find_element_by_name('password')
    password_field.send_keys('mypassword')
    
    submit_button = driver.find_elements_by_xpath("//*[contains(text(), 'Sign In')]")[0]
    submit_button.click()
    time.sleep(2)
    
    cookies_list = driver.get_cookies()
    cookies_dict = {}
    for cookie in cookies_list:
        cookies_dict[cookie['name']] = cookie['value']
    
    session_id = cookies_dict.get('session')
    print(session_id)
    
    driver.quit()
    
    
    

    public by Nick Moore modified Aug 30, 2017  316  0  3  0

    The block structure for SnakeCoin.

    The block structure for SnakeCoin.: snakecoin-block.py
    import hashlib as hasher
    
    class Block:
      def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.hash_block()
      
      def hash_block(self):
        sha = hasher.sha256()
        sha.update(str(self.index) + 
                   str(self.timestamp) + 
                   str(self.data) + 
                   str(self.previous_hash))
        return sha.hexdigest()
    
    
    

    public by lmontealegre modified Aug 22, 2017  398  1  4  0

    CONSTANT Definitions for Database server and SQL scripts

    Standard for defining connections and SQL definitions
    #=================================================================
    # Database Server Connection String
    # Database = AGENTS  Server = <IP>
    #=================================================================
    CNN_AGENTS = {'Server':'<IP>', 'User':'<Name>', 'Password':'<Pwd>', 'Database':'<DBName>'}
    
    #=================================================================
    # SQL Script Definition to Get Gran Total Agent counts
    # Database = AGENTS  Server = <IP>
    #=================================================================
    SQL_WR0TOTALCNTS = '''
    Select
      Count(SOL.SOL_KEY) As NoRec,
      Count(Distinct SOL.AGT_SOL_NO) As CntSOL,
      Sum(SOL.AGT_SOL_NOFILE) As SumSOL_NF,
      Sum(SOL.AGT_SOL_DWLERR) As SumSOL_DWLERR,
      Sum(SOL.AGT_SOL_OK) As SumSOL_OK,
      Sum(SOL.AGT_SOL_DWLOK) As SumSOL_DWLOK,
      Min(Cast(SOL.AGT_DTE_POSTDATE As datetime)) As Min_POSTDATE,
      Max(Cast(SOL.AGT_DTE_POSTDATE As datetime)) As Max_POSTDATE,
      DateDiff(day, Min(Cast(SOL.AGT_DTE_POSTDATE As datetime)), Max(Cast(SOL.AGT_DTE_POSTDATE As datetime))) As DateRange,
      Count(Distinct Cast(SOL.AGT_DTE_POSTDATE As datetime)) As ProcDates,
      Sum(Case When Len(IsNull(SOL.AGT_SOL_DWLPATH, '')) > 0 Then 1 Else 0
      End) As DwlOK,
      Sum((Convert(bigint,SOL.AGT_SOL_DWLBYTE)) / (1048576)) As MB,
      Count(Distinct SOL.AGT_DTE_EVT) As Cnt_RAN_EVT
    From
      AGENTS.dbo.DIBBS_AGN_SOL SOL
    '''
    
    #=================================================================
    # SQL Script Definition to Get Gran Total Agent counts
    # Database = AGENTS  Server = <IP> To be designed
    #=================================================================
    SQL_SelectedDates = '''
    Select
      Count(SOL.SOL_KEY) As NoRec,
      Count(Distinct SOL.AGT_SOL_NO) As CntSOL,
      Sum(SOL.AGT_SOL_NOFILE) As SumSOL_NF,
      Sum(SOL.AGT_SOL_DWLERR) As SumSOL_DWLERR,
      Sum(SOL.AGT_SOL_OK) As SumSOL_OK,
      Sum(SOL.AGT_SOL_DWLOK) As SumSOL_DWLOK,
      Min(Cast(SOL.AGT_DTE_POSTDATE As datetime)) As Min_POSTDATE,
      Max(Cast(SOL.AGT_DTE_POSTDATE As datetime)) As Max_POSTDATE,
      DateDiff(day, Min(Cast(SOL.AGT_DTE_POSTDATE As datetime)), Max(Cast(SOL.AGT_DTE_POSTDATE As datetime))) As DateRange,
      Count(Distinct Cast(SOL.AGT_DTE_POSTDATE As datetime)) As ProcDates,
      Sum(Case When Len(IsNull(SOL.AGT_SOL_DWLPATH, '')) > 0 Then 1 Else 0
      End) As DwlOK,
      Sum((Convert(bigint,SOL.AGT_SOL_DWLBYTE)) / (1048576)) As MB,
      Count(Distinct SOL.AGT_DTE_EVT) As Cnt_RAN_EVT
    From
      AGENTS.dbo.DIBBS_AGN_SOL SOL
    '''

    public by Ari Madian modified Aug 3, 2017  280  2  3  0

    Code to reproduce the "Temperature Circle" visualization.

    Code to reproduce the "Temperature Circle" visualization.: temperatureCircle.py
    #
    # Hi all,
    # this is the Python code I used to make the visualization "Temperature circle"
    # (https://twitter.com/anttilip/status/892318734244884480).
    # Please be aware that originally I wrote this for my tests only so the
    # code was not ment to be published and is a mess and has no comments.
    # Feel free to improve, modify, do whatever you want with it. If you decide
    # to use the code, make an improved version of it, or it is useful for you
    # in some another way I would be happy to know about it. You can contact me
    # for example in Twitter (@anttilip). Unchecked demo data (no quarantees)
    # for year 2017 Jan-Jul is included here and this code draws only a single image.
    # The animation code is basically just a loop through the years. To keep
    # it simple, I only included one year here.
    #
    # Thanks and have fun!
    # Antti
    #
    # ---------
    #
    # Copyright 2017 Antti Lipponen
    #
    # Permission is hereby granted, free of charge, to any person obtaining a copy
    # of this software and associated documentation files (the "Software"), to deal
    # in the Software without restriction, including without limitation the rights
    # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    # copies of the Software, and to permit persons to whom the Software is
    # furnished to do so, subject to the following conditions:
    #
    # The above copyright notice and this permission notice shall be included in all
    # copies or substantial portions of the Software.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
    # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
    # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    
    backgroundcolor = '#faf2eb'
    fontname = 'Lato'
    yearname = '2017'
    
    data2017 = {
        'AMERICA': [
            ['Antigua and Barbuda', 0.68],
            ['Argentina', 0.89],
            ['Bahamas', 0.65],
            ['Barbados', 0.68],
            ['Belize', 1.22],
            ['Bolivia', 1.22],
            ['Brazil', 1.23],
            ['Canada', 1.72],
            ['Chile', 0.93],
            ['Colombia', 0.88],
            ['Costa Rica', 0.76],
            ['Cuba', 0.78],
            ['Dominica', 0.64],
            ['Dominican Republic', 0.82],
            ['Ecuador', 1.16],
            ['El Salvador', 0.66],
            ['Grenada', 0.75],
            ['Guatemala', 1.25],
            ['Guyana', 0.65],
            ['Haiti', 0.56],
            ['Honduras', 1.1],
            ['Jamaica', 0.51],
            ['Mexico', 1.75],
            ['Nicaragua', 0.96],
            ['Panama', 0.65],
            ['Paraguay', 1.02],
            ['Peru', 1.25],
            ['Saint Kitts and Nevis', 0.68],
            ['Saint Lucia', 0.73],
            ['Saint Vincent and the Grenadines', 0.75],
            ['Suriname', 0.62],
            ['Trinidad and Tobago', 0.73],
            ['United States', 1.92],
            ['Uruguay', 1.02],
            ['Venezuela', 0.86],
        ],
        'OCEANIA': [
            ['Australia', 0.77],
            ['Fiji', 0.64],
            ['Kiribati', 0.21],
            ['Marshall Islands', 0.66],
            ['Micronesia', 0.9],
            ['Nauru', 0.82],
            ['New Zealand', 0.47],
            ['Palau', 0.94],
            ['Papua New Guinea', 0.92],
            ['Samoa', 0.77],
            ['Solomon Island', 1.0],
            ['Tonga', 0.86],
            ['Vanuatu', 1.17],
        ],
        'EUROPE': [
            ['Albania', 1.07],
            ['Andorra', 1.88],
            ['Armenia', 0.38],
            ['Austria', 1.66],
            ['Azerbaijan', 0.51],
            ['Belarus', 1.58],
            ['Belgium', 1.79],
            ['Bosnia and Herzegovina', 1.4],
            ['Bulgaria', 0.89],
            ['Croatia', 1.5],
            ['Cyprus', 0.38],
            ['Czech Republic', 1.68],
            ['Denmark', 1.73],
            ['Estonia', 1.67],
            ['Finland', 1.48],
            ['France', 1.62],
            ['Georgia', 0.44],
            ['Germany', 1.76],
            ['Greece', 0.77],
            ['Hungary', 1.49],
            ['Iceland', 1.66],
            ['Ireland', 1.57],
            ['Italy', 1.57],
            ['Latvia', 1.70],
            ['Liechtenstein', 1.74],
            ['Lithuania', 1.70],
            ['Luxembourg', 1.79],
            ['Macedonia', 0.99],
            ['Malta', 1.03],
            ['Moldova', 1.12],
            ['Montenegro', 1.25],
            ['Netherlands', 1.77],
            ['Norway', 1.63],
            ['Poland', 1.67],
            ['Portugal', 1.71],
            ['Romania', 1.14],
            ['San Marino', 1.59],
            ['Serbia', 1.23],
            ['Slovakia', 1.56],
            ['Slovenia', 1.59],
            ['Spain', 1.89],
            ['Sweden', 1.69],
            ['Switzerland', 1.76],
            ['Ukraine', 1.23],
            ['United Kingdom', 1.68],
        ],
        'AFRICA': [
            ['Algeria', 1.79],
            ['Angola', 0.70],
            ['Benin', 1.13],
            ['Botswana', 0.65],
            ['Burkina Faso', 1.20],
            ['Burundi', 1.20],
            ['Cameroon', 1.05],
            ['Cape Verde', 0.72],
            ['Central African Republic', 1.06],
            ['Chad', 1.04],
            ['Comoros', 0.90],
            ['Congo', 0.88],
            ['Democratic Republic of Congo', 0.97],
            ['Djibouti', 1.2],
            ['Egypt', 0.7],
            ['Equatorial Guinea', 0.92],
            ['Eritrea', 1.22],
            ['Ethiopia', 1.35],
            ['Gabon', 0.86],
            ['Gambia', 1.43],
            ['Ghana', 1.08],
            ['Guinea', 1.34],
            ['Guinea-Bissau', 1.39],
            ['Ivory Coast', 1.22],
            ['Kenya', 1.14],
            ['Lesotho', 0.84],
            ['Liberia', 1.21],
            ['Libya', 0.94],
            ['Madagascar', 1.16],
            ['Malawi', 0.89],
            ['Mali', 1.32],
            ['Mauritania', 1.56],
            ['Mauritius', 1.16],
            ['Morocco', 1.86],
            ['Mozambique', 0.90],
            ['Namibia', 0.94],
            ['Niger', 0.90],
            ['Nigeria', 1.10],
            ['Rwanda', 1.23],
            ['Sao Tome and Principe', 0.86],
            ['Senegal', 1.41],
            ['Seychelles', 0.99],
            ['Sierra Leone', 1.29],
            ['Somalia', 1.19],
            ['South Africa', 0.91],
            ['South Sudan', 1.27],
            ['Sudan', 1.17],
            ['Swaziland', 0.69],
            ['Tanzania', 1.01],
            ['Togo', 1.20],
            ['Tunisia', 1.81],
            ['Uganda', 1.26],
            ['Zambia', 0.59],
            ['Zimbabwe', 0.58],
        ],
        'ASIA': [
            ['Afghanistan', 1.78],
            ['Bahrain', 1.48],
            ['Bangladesh', 0.52],
            ['Bhutan', 0.61],
            ['Brunei', 0.77],
            ['Burma (Myanmar)', 0.65],
            ['Cambodia', 0.84],
            ['China', 1.80],
            ['East Timor', 0.34],
            ['India', 0.96],
            ['Indonesia', 0.67],
            ['Iran', 1.48],
            ['Iraq', 0.68],
            ['Israel', 0.52],
            ['Japan', 1.03],
            ['Jordan', 0.56],
            ['Kazakhstan', 1.91],
            ['Kuwait', 1.24],
            ['Kyrgyzstan', 1.57],
            ['Laos', 0.87],
            ['Lebanon', 0.42],
            ['Malaysia', 0.79],
            ['Maldives', 0.70],
            ['Mongolia', 3.05],
            ['Nepal', 0.71],
            ['North Korea', 2.01],
            ['Oman', 1.53],
            ['Pakistan', 1.76],
            ['Philippines', 0.81],
            ['Qatar', 1.86],
            ['Russian Federation', 3.01],
            ['Saudi Arabia', 1.46],
            ['Singapore', 0.51],
            ['South Korea', 1.65],
            ['Sri Lanka', 0.90],
            ['Syria', 0.40],
            ['Tajikistan', 1.39],
            ['Thailand', 0.85],
            ['Turkey', 0.39],
            ['Turkmenistan', 1.50],
            ['United Arab Emirates', 2.08],
            ['Uzbekistan', 1.54],
            ['Vietnam', 0.72],
            ['Yemen', 1.37],
        ]
    }
    
    
    def rotText(areaText, defaultspacing, rotangleoffset, rText, fontname):
        angle = areaText[0][1]
        for ii, l in enumerate(areaText):
            if ii > 0:
                angle += defaultspacing + l[1]
            plt.text(
                (rText) * np.sin(np.deg2rad(angle)),
                (rText) * np.cos(np.deg2rad(angle)),
                '{}'.format(l[0]),
                {'ha': 'center', 'va': 'center'},
                rotation=-angle + rotangleoffset,
                fontsize=15,
                fontname=fontname,
            )
    
    
    plt.rcParams['axes.facecolor'] = backgroundcolor
    mpl.rcParams.update({'font.size': 22})
    
    cmap = plt.get_cmap('RdYlBu_r')
    norm = mpl.colors.Normalize(vmin=-2.0, vmax=2.0)
    
    Ncountries = 0
    Ncontinents = 0
    for countrylist in data2017.items():
        Ncountries += len(countrylist[1])
        Ncontinents += 1
    
    spaceBetweenContinents = 3.0  # degrees
    Nspaces = Ncontinents - 1
    anglePerCountry = (345.0 - Nspaces * spaceBetweenContinents) / (Ncountries - 1)
    
    
    fig, ax = plt.subplots(figsize=(12, 12))
    renderer = fig.canvas.get_renderer()
    transf = ax.transData.inverted()
    
    limitangles = np.linspace(np.deg2rad(5.0), np.deg2rad(355.0), 500)
    scaleRs = [
        [1.5, '-2.0', True, 0.25],
        [0.5 * (1.5 + 2.25), '-1.0', True, 0.25],
        [2.25, '0.0', True, 1.0],
        [0.5 * (3.0 + 2.25), '+1.0', True, 0.25],
        [3.0, '+2.0', True, 0.25],
        [3.3, '$^\\circ$C', False, 0.0]
    ]
    for r in scaleRs:
        if r[2]:
            ax.plot(r[0] * np.sin(limitangles), r[0] * np.cos(limitangles), linewidth=r[3], color='#888888', linestyle='-')
        plt.text(
            0.0,
            r[0],
            '{}'.format(r[1]),
            {'ha': 'center', 'va': 'center'},
            fontsize=12,
            fontname=fontname,
        )
    
    angle = 7.5
    rText = 3.96
    for continent in ['AFRICA', 'ASIA', 'EUROPE', 'AMERICA', 'OCEANIA']:
        for country in data2017[continent]:
    
            if angle < 185.0:
                rotangle = -angle + 90.0
            else:
                rotangle = -angle - 90.0
    
            plt.text(
                (rText) * np.sin(np.deg2rad(angle)),
                (rText) * np.cos(np.deg2rad(angle)),
                '{}'.format(country[0]),
                {'ha': 'center', 'va': 'center'},
                rotation=rotangle,
                fontsize=8,
                fontname=fontname,
                bbox={
                    'facecolor': backgroundcolor,
                    'linestyle': 'solid',
                    'linewidth': 0.0,
                    'boxstyle': 'square,pad=0.0'
                }
            )
    
            ax.plot(
                [1.3 * np.sin(np.deg2rad(angle)), 3.8 * np.sin(np.deg2rad(angle))],
                [1.3 * np.cos(np.deg2rad(angle)), 3.8 * np.cos(np.deg2rad(angle))],
                linewidth=0.6,
                linestyle='--',
                color='#DEDEDE'
            )
    
            lowerRoffset = 0.015
            temperatureAnomaly = country[1]
    
            rValue = 1.5 + (temperatureAnomaly + 2.0) / 4.0 * 1.5  # a lot more clever way for computing the radius should be used here...
            ax.plot(
                [(1.3 + lowerRoffset) * np.sin(np.deg2rad(angle)), rValue * np.sin(np.deg2rad(angle))],
                [(1.3 + lowerRoffset) * np.cos(np.deg2rad(angle)), rValue * np.cos(np.deg2rad(angle))],
                linewidth=4.3,
                linestyle='-',
                color='#202020'
            )
            ax.plot(
                [(1.3 + lowerRoffset) * np.sin(np.deg2rad(angle)), rValue * np.sin(np.deg2rad(angle))],
                [(1.3 + lowerRoffset) * np.cos(np.deg2rad(angle)), rValue * np.cos(np.deg2rad(angle))],
                linewidth=4.0,
                linestyle='-',
                color=cmap(norm(temperatureAnomaly))
            )
    
            angle += anglePerCountry
        angle += spaceBetweenContinents
    
    c = Circle((0.0, 0.0), radius=1.0, fill=True, color='#fff9f5')
    ax.add_patch(c)
    plt.text(
        0.0,
        -0.52,
        yearname,
        {'ha': 'center', 'va': 'bottom'},
        fontsize=40,
        fontname=fontname,
    )
    plt.text(
        0.0,
        0.27,
        'Year',
        {'ha': 'center', 'va': 'center'},
        fontsize=26,
        fontname=fontname,
    )
    
    angles = np.linspace(np.deg2rad(0.0), np.deg2rad(360.0), 1000)
    rs = [1.0, 1.3]
    for r in rs:
        ax.plot(r * np.sin(angles), r * np.cos(angles), linewidth=1.0, color='#666666', linestyle='-')
    
    plt.text(
        5.87,
        -4.67,
        'Antti Lipponen (@anttilip)',
        {'ha': 'right', 'va': 'center'},
        fontsize=10,
        fontname=fontname,
    )
    
    plt.text(
        -6.3 + 0.015,
        4.385 - 0.015,
        'Temperature anomalies',
        {'ha': 'left', 'va': 'center'},
        fontsize=27,
        fontname=fontname,
        color='#909090'
    )
    
    plt.text(
        -6.3,
        4.385,
        'Temperature anomalies',
        {'ha': 'left', 'va': 'center'},
        fontsize=27,
        fontname=fontname,
        color='#0D0D0D'
    )
    
    plt.text(
        -6.35,
        -4.35,
        'Data source:\nNASA GISS Surface Temperature Analysis (GISTEMP)\nLand-Ocean Temperature Index, ERSSTv4, 1200km smoothing\nhttps://data.giss.nasa.gov/gistemp/\nAverage of monthly temperature anomalies. GISTEMP base period 1951-1980.',
        {'ha': 'left', 'va': 'center'},
        fontsize=10,
        fontname=fontname,
    )
    
    areaText = [
        ['A', 46.0],
        ['f', 0.3],
        ['r', -0.05],
        ['i', -0.15],
        ['c', -0.15],
        ['a', 0.2],
    ]
    rText, defaultspacing, rotangleoffset = 1.13, 4.4, 0.0
    rotText(areaText, defaultspacing, rotangleoffset, rText, fontname)
    
    areaText = [
        ['E', 236.0],
        ['u', 0.0],
        ['r', 0.3],
        ['o', 0.7],
        ['p', 0.0],
        ['e', 0.0],
    ]
    rText, defaultspacing, rotangleoffset = 1.155, -5.5, 180.0
    rotText(areaText, defaultspacing, rotangleoffset, rText, fontname)
    
    areaText = [
        ['A', 147.0],
        ['s', -0.8],
        ['i', 0.0],
        ['a', 0.0],
    ]
    rText, defaultspacing, rotangleoffset = 1.155, -4.7, 180.0
    rotText(areaText, defaultspacing, rotangleoffset, rText, fontname)
    
    areaText = [
        ['A', 276.0],
        ['m', 2.5],
        ['e', 0.6],
        ['r', -0.15],
        ['i', -2.0],
        ['c', -2.0],
        ['a', -0.15],
    ]
    rText, defaultspacing, rotangleoffset = 1.13, 5.85, 0.0
    rotText(areaText, defaultspacing, rotangleoffset, rText, fontname)
    
    areaText = [
        ['O', 328.5],
        ['c', 1.0],
        ['e', 0.0],
        ['a', 0.2],
        ['n', 0.2],
        ['i', -0.3],
        ['a', -0.3],
    ]
    rText, defaultspacing, rotangleoffset = 1.125, 4.8, 0.0
    rotText(areaText, defaultspacing, rotangleoffset, rText, fontname)
    
    ax.set_xlim([-5.0, 5.0])
    ax.set_ylim([-5.0, 5.0])
    plt.axis('off')
    plt.savefig('temperatureCircle.png', facecolor=backgroundcolor, edgecolor='none', dpi=160)
    plt.close()
    
    # and finally I used imageMagick to crop the image for animation
    
    
    

    public by AbhishekGhosh modified Mar 6, 2017  304  0  3  0

    jupyter_notebook_config.py

    jupyter_notebook_config.py: jupyter_notebook_config.py
    c = get_config()
    c.IPKernelApp.pylab = 'inline'  
    c.NotebookApp.certfile = u'/path/to/cert.pem'
    c.NotebookApp.ip = '*'
    c.NotebookApp.open_browser = False
    c.NotebookApp.password = u'sha1:00000000000000000000000000000000000000'
    c.NotebookApp.port = 4334
    c.NotebookApp.base_url = '/pyspak/'
    c.NotebookApp.webapp_settings = {'static_url_prefix':'/pyspark/static/'}
    c.NotebookApp.notebook_dir = '/home/username/tutorials/pyspark/'
    
    

    public by Maher Malaeb modified Feb 24, 2017  322  0  3  0

    The easy guide for building python collaborative filtering recommendation system in 2017

    The easy guide for building python collaborative filtering recommendation system in 2017: surprise_tutorial.py
    import zipfile
    from surprise import Reader, Dataset, SVD, evaluate
    
    # Unzip ml-100k.zip
    zipfile = zipfile.ZipFile('ml-100k.zip', 'r')
    zipfile.extractall()
    zipfile.close()
    
    # Read data into an array of strings
    with open('./ml-100k/u.data') as f:
        all_lines = f.readlines()
    
    # Prepare the data to be used in Surprise
    reader = Reader(line_format='user item rating timestamp', sep='\t')
    data = Dataset.load_from_file('./ml-100k/u.data', reader=reader)
    
    # Split the dataset into 5 folds and choose the algorithm
    data.split(n_folds=5)
    algo = SVD()
    
    # Train and test reporting the RMSE and MAE scores
    evaluate(algo, data, measures=['RMSE', 'MAE'])
    
    # Retrieve the trainset.
    trainset = data.build_full_trainset()
    algo.train(trainset)
    
    # Predict a certain item
    userid = str(196)
    itemid = str(302)
    actual_rating = 4
    print algo.predict(userid, itemid, actual_rating)
    
    

    public by mmngreco modified Jan 15, 2017  12525  0  3  0

    hello_world

    #!/bin/python3
    # Test
    print("Hello, World!")

    public by ozmartian modified Dec 18, 2016  2332  9  4  0

    Python 3 docstring

    w/ UTF-8 encoding
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-                        
    • Public Snippets
    • Channels Snippets