scipy stats.foldcauchy () | python

| | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

scipy.stats.foldcauchy () is a folded continuous Cauchy random variable that is defined in a standard format and with some shape parameters to complete its specification.

- & gt; q: lower and upper tail probability
- & gt; a: shape parameters
- & gt; x: quantiles
- & gt; loc: [optional] location parameter. Default = 0
- & gt; scale: [optional] scale parameter. Default = 1
- & gt; size: [tuple of ints, optional] shape or random variates.
- & gt; moments: [optional] composed of letters [’mvsk’]; ’m’ = mean, ’v’ = variance, ’s’ = Fisher’s skew and ’k’ = Fisher’s kurtosis. (default = ’mv’).

Results: folded Cauchy continuous random variable

Code # 1: Create a folded Cauchy continuous random variable Cauchy random variable

from scipy.stats import foldcauchy

numargs = foldcauchy.numargs

[a] = [ 0.7 ,] * numargs

rv = foldcauchy (a)

< p> print ( "RV:" , rv)


 RV: & lt; scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D55D8E160 & gt; 

Code # 2: the folded Cauchy random variables and the probability distribution function.

import numpy as np

quantile = np.arange ( 0.01 , 1 , 0.1 )

# Random Variants

R = foldcauchy.rvs (a, scale = 2 , size = 10 )

print ( "Random Variates:" , R)


R = foldcauchy.pdf (a, quantile, loc = 0 , scale = 1 )

print ( "Probability Distribution:" , R)


 Random Variates: [1.7445128 2.82630984 0.81871044 5.19668279 7.81537565 1.67855736 3.35417067 0.13838753 1.29145462 1.90601065] Probability Distribution: [0.42727064 0.42832192 0.43080143 0.43385803 0.43622229 0.43639823 0.4 3294602 0.42480391 0.41154712 0.3934792] 

Code # 3: Graphic representation.

import numpy as np

import matplotlib.pyplot as plt

distribution = np.linspace ( 0 , np.minimum (rv.dist. b, 3 ))

print ( "Distribution:" , distribution)

plot = plt.plot (distributio n, rv.pdf (distribution))


 Distribution: [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102 2.93877551 3. ] 


Code # 4: Various Positional Arguments

import matplotlib. pyplot as plt

import numpy as np

x = np.linspace ( 0 , 5 , 100 )

# Various positional arguments

y1 = foldcauchy.pdf (x, 1 , 3 )

y2 = foldcauchy.pdf (x, 1 , 4 )

plt.plot (x, y1, "*" , x, y2, "r--" )


👻 Read also: what is the best laptop for engineering students?

scipy stats.foldcauchy () | python iat: Questions


InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

3 answers

Tried to perform REST GET through python requests with the following code and I got error.

Code snip:

import requests
header = {"Authorization": "Bearer..."}
url = az_base_url + az_subscription_id + "/resourcegroups/Default-Networking/resources?" + az_api_version
r = requests.get(url, headers=header)


          InsecurePlatformWarning: A true SSLContext object is not available. 
          This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. 
          For more information, see

My python version is 2.7.3. I tried to install urllib3 and requests[security] as some other thread suggests, I still got the same error.

Wonder if anyone can provide some tips?


Answer #1

The docs give a fair indicator of what"s required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3

If you"re on ubuntu, you may run into trouble installing pyopenssl, you"ll need these dependencies:

$ apt-get install libffi-dev libssl-dev

scipy stats.foldcauchy () | python iat: Questions


Dynamic instantiation from string name of a class in dynamically imported module?

3 answers

In python, I have to instantiate certain class, knowing its name in a string, but this class "lives" in a dynamically imported module. An example follows:

loader-class script:

import sys
class loader:
  def __init__(self, module_name, class_name): # both args are strings
      modul = sys.modules[module_name]
      instance = modul.class_name() # obviously this doesn"t works, here is my main problem!
    except ImportError:
       # manage import error

some-dynamically-loaded-module script:

class myName:
  # etc...

I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...


Answer #1

You can use getattr

getattr(module, class_name)

to access the class. More complete code:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()

As mentioned below, we may use importlib

import importlib
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
instance = class_()

scipy stats.foldcauchy () | python iat: Questions


How to get all of the immediate subdirectories in Python

3 answers

I"m trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).

I"m getting bogged down by trying to get the list of subdirectories.


Answer #1

import os
def get_immediate_subdirectories(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isdir(os.path.join(a_dir, name))]

Meaning of @classmethod and @staticmethod for beginner?

5 answers

user1632861 By user1632861

Could someone explain to me the meaning of @classmethod and @staticmethod in python? I need to know the difference and the meaning.

As far as I understand, @classmethod tells a class that it"s a method which should be inherited into subclasses, or... something. However, what"s the point of that? Why not just define the class method without adding @classmethod or @staticmethod or any @ definitions?

tl;dr: when should I use them, why should I use them, and how should I use them?


Answer #1

Though classmethod and staticmethod are quite similar, there"s a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.


class Date(object):

    def __init__(self, day=0, month=0, year=0): = day
        self.month = month
        self.year = year

    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split("-"))
        date1 = cls(day, month, year)
        return date1

    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split("-"))
        return day <= 31 and month <= 12 and year <= 3999

date2 = Date.from_string("11-09-2012")
is_date = Date.is_date_valid("11-09-2012")


Let"s assume an example of a class, dealing with date information (this will be our boilerplate):

class Date(object):

    def __init__(self, day=0, month=0, year=0): = day
        self.month = month
        self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let"s assume all dates are presented in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds a reference to a newly created instance.

Class Method

We have some tasks that can be nicely done using classmethods.

Let"s assume that we want to create a lot of Date class instances having date information coming from an outer source encoded as a string with format "dd-mm-yyyy". Suppose we have to do this in different places in the source code of our project.

So what we must do here is:

  1. Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
  2. Instantiate Date by passing those values to the initialization call.

This will look like:

day, month, year = map(int, string_date.split("-"))
date1 = Date(day, month, year)

For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod. Let"s create another "constructor".

    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split("-"))
        date1 = cls(day, month, year)
        return date1

date2 = Date.from_string("11-09-2012")

Let"s look more carefully at the above implementation, and review what advantages we have here:

  1. We"ve implemented date string parsing in one place and it"s reusable now.
  2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
  3. cls is an object that holds the class itself, not an instance of the class. It"s pretty cool because if we inherit our Date class, all children will have from_string defined also.

Static method

What about staticmethod? It"s pretty similar to classmethod but doesn"t take any obligatory parameters (like a class method or instance method does).

Let"s look at the next use case.

We have a date string that we want to validate somehow. This task is also logically bound to the Date class we"ve used so far, but doesn"t require instantiation of it.

Here is where staticmethod can be useful. Let"s look at the next piece of code:

    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split("-"))
        return day <= 31 and month <= 12 and year <= 3999

    # usage:
    is_date = Date.is_date_valid("11-09-2012")

So, as we can see from usage of staticmethod, we don"t have any access to what the class is---it"s basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.


Answer #2

Rostyslav Dzinko"s answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor.

In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below:

class Date:
  def __init__(self, month, day, year):
    self.month = month   = day
    self.year  = year

  def display(self):
    return "{0}-{1}-{2}".format(self.month,, self.year)

  def millenium(month, day):
    return Date(month, day, 2000)

new_year = Date(1, 1, 2013)               # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object. 

# Proof:
new_year.display()           # "1-1-2013"
millenium_new_year.display() # "1-1-2000"

isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True

Thus both new_year and millenium_new_year are instances of the Date class.

But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below:

class DateTime(Date):
  def display(self):
      return "{0}-{1}-{2} - 00:00:00PM".format(self.month,, self.year)

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False

datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it"s not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.

datetime2 is not an instance of DateTime? WTF? Well, that"s because of the @staticmethod decorator used.

In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need.

Rewriting Date.millenium as (that"s the only part of the above code that changes):

def millenium(cls, month, day):
    return cls(month, day, 2000)

ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls.
Let"s test that out:

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True

datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"

The reason is, as you know by now, that @classmethod was used instead of @staticmethod


Answer #3

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don"t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can"t access the instance of that class (this is useful when your method does not use the instance).


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method