Python math.fmod() Examples

The following are code examples for showing how to use math.fmod(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10,1)', math.fmod(10,1), 0)
        self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
        self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
        self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
        self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
        self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 2
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def MapToMinusPiToPi(angles):
  """Maps a list of angles to [-pi, pi].

  Args:
    angles: A list of angles in rad.
  Returns:
    A list of angle mapped to [-pi, pi].
  """
  mapped_angles = copy.deepcopy(angles)
  for i in range(len(angles)):
    mapped_angles[i] = math.fmod(angles[i], TWO_PI)
    if mapped_angles[i] >= math.pi:
      mapped_angles[i] -= TWO_PI
    elif mapped_angles[i] < -math.pi:
      mapped_angles[i] += TWO_PI
  return mapped_angles 
Example 3
Project: RouteOptimization   Author: andre-le   File: geomath.py    MIT License 6 votes vote down vote up
def sincosd(x):
    """Compute sine and cosine of x in degrees."""

    r = math.fmod(x, 360)
    q = Math.nan if Math.isnan(r) else int(math.floor(r / 90 + 0.5))
    r -= 90 * q; r = math.radians(r)
    s = math.sin(r); c = math.cos(r)
    q = q % 4
    if q == 1:
      s, c =  c, -s
    elif q == 2:
      s, c = -s, -c
    elif q == 3:
      s, c = -c,  s
    # Remove the minus sign on -0.0 except for sin(-0.0).
    # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360) = +0.0
    # (x, c) here fixes this bug.  See also Math::sincosd in the C++ library.
    # AngNormalize has a similar fix.
    s, c = (x, c) if x == 0 else (0.0+s, 0.0+c)
    return s, c 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
        self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
        self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
        self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
        self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
        self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 5
Project: JupiKD_Discord_Python   Author: IsaacAKAJupiter   File: functions.py    GNU General Public License v3.0 6 votes vote down vote up
def TotalSecondsToDHMS(total_seconds):
    total_minutes = total_seconds / 60
    seconds = math.fmod(total_seconds, 60)
    total_hours = total_minutes / 60
    minutes = math.fmod(total_minutes, 60)
    days = total_hours / 24
    hours = math.fmod(total_hours, 24)

    days = int(days)
    hours = int(hours)
    minutes = int(minutes)
    seconds = int(seconds)

    return_string = ""
    return_string += f"{days} days, " if days > 1 or days < 1 and not days == 0 else f"{days} day, " if days == 1 else ""
    return_string += f"{hours} hours, " if hours > 1 or hours < 1 and not hours == 0 else f"{hours} hour, " if hours == 1 else ""
    return_string += f"{minutes} minutes, " if minutes > 1 or minutes < 1 and not minutes == 0 else f"{minutes} minute, " if minutes == 1 else ""
    return_string += f"{seconds} seconds." if seconds > 1 or seconds < 1 and not seconds == 0 else f"{seconds} second." if seconds == 1 else ""
    return return_string

#This function is a central hub for post requests with aiohttp. (json response only) 
Example 6
Project: grabba_grabba_hey   Author: multiply-org   File: landsat_downloader.py    GNU General Public License v2.0 6 votes vote down vote up
def next_overpass (date1, path, sat):
    """ provides the next overpass for path after date1
    """
    date0_L5 = datetime.datetime(1985,5,4)
    date0_L7 = datetime.datetime(1999,1,11)
    date0_L8 = datetime.datetime(2013,5,1)
    if sat == 'LT5':
        date0 = date0_L5
    elif sat == 'LE7':
        date0 = date0_L7
    elif sat == 'LC8':
        date0 = date0_L8
    next_day=math.fmod((date1-date0).days-cycle_day(path)+1,16)
    if next_day != 0:
        date_overpass = date1+datetime.timedelta(16-next_day)
    else:
        date_overpass = date1
    
    return date_overpass 
Example 7
Project: NiaPy   Author: NiaOrg   File: schwefel.py    MIT License 6 votes vote down vote up
def function(self):
		r"""Return benchmark evaluation function.

		Returns:
			Callable[[int, Union[int, float, List[int, float], numpy.ndarray]], float]: Fitness function
		"""
		def g(z, D):
			if z > 500: return (500 - fmod(z, 500)) * sin(sqrt(fabs(500 - fmod(z, 500)))) - (z - 500) ** 2 / (10000 * D)
			elif z < -500: return (fmod(z, 500) - 500) * sin(sqrt(fabs(fmod(z, 500) - 500))) + (z - 500) ** 2 / (10000 * D)
			return z * sin(fabs(z) ** (1 / 2))
		def h(x, D): return g(x + 420.9687462275036, D)
		def f(D, sol):
			r"""Fitness function.

			Args:
				D (int): Dimensionality of the problem
				sol (Union[int, float, List[int, float], numpy.ndarray]): Solution to check.

			Returns:
				float: Fitness value for the solution.
			"""
			val = 0.0
			for i in range(D): val += h(sol[i], D)
			return 418.9829 * D - val
		return f 
Example 8
Project: rpython-lang-scheme   Author: tomoh1r   File: rfloat.py    MIT License 6 votes vote down vote up
def _sinpi(x):
    y = math.fmod(abs(x), 2.)
    n = int(round_away(2. * y))
    if n == 0:
        r = math.sin(math.pi * y)
    elif n == 1:
        r = math.cos(math.pi * (y - .5))
    elif n == 2:
        r = math.sin(math.pi * (1. - y))
    elif n == 3:
        r = -math.cos(math.pi * (y - 1.5))
    elif n == 4:
        r = math.sin(math.pi * (y - 2.))
    else:
        raise AssertionError("should not reach")
    return copysign(1., x) * r 
Example 9
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10,1)', math.fmod(10,1), 0)
        self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
        self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
        self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
        self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
        self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 10
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_math.py    GNU General Public License v3.0 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
        self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
        self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
        self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
        self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
        self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 11
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_math.py    GNU General Public License v2.0 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
        self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
        self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
        self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
        self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
        self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 12
Project: oss-ftp   Author: aliyun   File: test_math.py    MIT License 6 votes vote down vote up
def testFmod(self):
        self.assertRaises(TypeError, math.fmod)
        self.ftest('fmod(10,1)', math.fmod(10,1), 0)
        self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
        self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
        self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
        self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
        self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
        self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
        self.assertTrue(math.isnan(math.fmod(1., NAN)))
        self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
        self.assertRaises(ValueError, math.fmod, 1., 0.)
        self.assertRaises(ValueError, math.fmod, INF, 1.)
        self.assertRaises(ValueError, math.fmod, NINF, 1.)
        self.assertRaises(ValueError, math.fmod, INF, 0.)
        self.assertEqual(math.fmod(3.0, INF), 3.0)
        self.assertEqual(math.fmod(-3.0, INF), -3.0)
        self.assertEqual(math.fmod(3.0, NINF), 3.0)
        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
        self.assertEqual(math.fmod(0.0, NINF), 0.0) 
Example 13
Project: SapPy   Author: SomeShrug   File: interface.py    MIT License 6 votes vote down vote up
def update(self, track: M4ATrack):
        self.redraw_volume = track.out_vol != self.volume
        self.redraw_panning = track.panning != self.panning
        self.redraw_voice = track.voice != self.voice
        self.volume = track.out_vol
        self.ticks = f'{track.ticks:>2}'
        self.panning = track.panning
        self.voice = track.voice
        if self.redraw_voice:
            self.voice_type = track.type.name
            self.current_voice = track.voice
        if self.redraw_volume:
            bars = self.volume / (255 / self.WIDTH)
            vol_interval = fmod(self.volume, 255 / self.WIDTH)

            block_id = NUM_BLOCKS - int(vol_interval) // int(self.INTERVAL)
            end_bar = H_BLOCK_TABLE.get(block_id, '')
            self.bars = int(bars)
            self.vol_output = f'{FULL_BLOCK * self.bars + end_bar:{self.WIDTH}}'
            self.vol_percent = f'{self.volume / 255:6.1%}'
        if self.redraw_panning:
            self.pan_pos = round(self.panning * (self.WIDTH - 1) / 254) + 1 
Example 14
Project: s2sphere   Author: sidewalklabs   File: sphere.py    MIT License 6 votes vote down vote up
def advance_wrap(self, steps):
        assert self.is_valid()
        if steps == 0:
            return self

        step_shift = 2 * (self.__class__.MAX_LEVEL - self.level()) + 1
        if steps < 0:
            min_steps = -(self.id() >> step_shift)
            if steps < min_steps:
                step_wrap = self.__class__.WRAP_OFFSET >> step_shift
                # cannot use steps %= step_wrap as Python % different to C++
                steps = int(math.fmod(steps, step_wrap))
                if steps < min_steps:
                    steps += step_wrap
        else:
            max_steps = (self.__class__.WRAP_OFFSET - self.id()) >> step_shift
            if steps > max_steps:
                step_wrap = self.__class__.WRAP_OFFSET >> step_shift
                # cannot use steps %= step_wrap as Python % different to C++
                steps = int(math.fmod(steps, step_wrap))
                if steps > max_steps:
                    steps -= step_wrap

        return self.__class__(self.id() + (steps << step_shift)) 
Example 15
Project: Adafruit_CircuitPython_LIS3DH   Author: adafruit   File: lis3dh_spinner_advanced.py    MIT License 6 votes vote down vote up
def get_position(self, delta):
        """Update the spinner position after the specified delta (in seconds)
        has elapsed.  Will return the new spinner position, a continuous value
        from 0...<10.
        """
        # Increment elapsed time and compute the current velocity after a
        # decay of the initial velocity.
        self._elapsed += delta
        current_velocity = self._velocity*math.pow(self._decay, self._elapsed)
        # Update position based on the current_velocity and elapsed time.
        self._position += current_velocity*delta
        # Make sure the position stays within values that range from 0 to <10.
        self._position = math.fmod(self._position, 10.0)
        if self._position < 0.0:
            self._position += 10.0
        return self._position


# Define animation classes.  Each animation needs to have an update function
# which takes in the current spinner position and a selected primary and
# secondary color (3-tuple of RGB bytes) and will render a frame of spinner
# animation. 
Example 16
Project: yWaves   Author: drjod   File: yOutput.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_timeseries(self, network, timemarching, gs):
        plt.subplot(gs[self.__id, 0])
        plt.xlabel("Time")
        
        if self.__grid_id == 0:
            plt.title("Node " + str(self.__connectors_id[0]))
        else:
            plt.title("Link " + str(self.__connectors_id[0]))  

        self.series_times.append(timemarching.current)

        for i in range(len(self.__variables)):
            self.series_values.append(
                network.grids[self.__grid_id].connectors[self.__connectors_id[0]].get_variable_value(
                    self.__variables[i]))
            output_values = list()

            for j in range(0, len(self.series_values), 1):
                if math.fmod(j, len(self.__variables)) == i:
                    output_values.append(self.series_values[j])
                                    
            plt.ylabel(self.__variables[i])
            linecolor = select_linecolor(self.__variables[i])
            plt.plot(self.series_times, output_values, color=linecolor, linewidth=2.5, linestyle="-") 
Example 17
Project: deep_image_model   Author: tobegit3hub   File: image_ops_test.py    Apache License 2.0 6 votes vote down vote up
def _adjustHueNp(self, x_np, delta_h):
    self.assertEqual(x_np.shape[-1], 3)
    x_v = x_np.reshape([-1, 3])
    y_v = np.ndarray(x_v.shape, dtype=x_v.dtype)
    channel_count = x_v.shape[0]
    for i in xrange(channel_count):
      r = x_v[i][0]
      g = x_v[i][1]
      b = x_v[i][2]
      h, s, v = colorsys.rgb_to_hsv(r, g, b)
      h += delta_h
      h = math.fmod(h + 10.0, 1.0)
      r, g, b = colorsys.hsv_to_rgb(h, s, v)
      y_v[i][0] = r
      y_v[i][1] = g
      y_v[i][2] = b
    return y_v.reshape(x_np.shape) 
Example 18
Project: hippie-trap   Author: mayhem   File: color.py    MIT License 6 votes vote down vote up
def random_color_pair(self, offset):
        while True:
            hue = random()
            bad = False 
            for old_hue in self.last_hues:
                if math.fabs(hue - old_hue) < .10:
                    bad = True
                    break

            if bad:
                continue
            else:
                break

        rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
        rgb2 = colorsys.hsv_to_rgb(math.fmod(hue + offset, 1.0), 1.0, 1.0)
        self.last_hues.append(hue)
        if len(self.last_hues) > 5:
            self.last_hues = self.last_hues[1:]

        return (Color(int(255 * rgb[0]), int(255 * rgb[1]), int(255 * rgb[2])), 
                Color(int(255 * rgb2[0]), int(255 * rgb2[1]), int(255 * rgb2[2]))) 
Example 19
Project: kepler_laws   Author: agarciamontoro   File: planet.py    GNU General Public License v2.0 6 votes vote down vote up
def getDate(self, u):
        """Retrieves the date from the eccentric anomaly

        Obtains the date in which the eccentric anomaly of the planet is the
        given one.''

        Args:
            u: Eccentric anomaly, in radians.

        Returns:
            The (first after self.t0) date -codified as a datetime object- in
            which the planet had the given u.
        """
        p = self.period
        e = self.eccentricity
        u = math.fmod(u,2*math.pi)

        u = math.fmod(u,2*math.pi)

        delta = p * (u - e*math.sin(u)) / (2*math.pi)

        return self.t0 + timedelta(days=delta), delta 
Example 20
Project: GPflow-Slim   Author: ssydasheng   File: neural_kernel_network_wrapper_v2.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, input_dim, step, name='Product'):
        super(Product, self).__init__(input_dim, name=name)
        assert isinstance(step, int) and step > 1, 'step must be number greater than 1'
        assert int(math.fmod(input_dim, step)) == 0, 'input dim must be multiples of step'
        self.step = step 
Example 21
Project: GPflow-Slim   Author: ssydasheng   File: neural_kernel_network_wrapper.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, input_dim, step, name='Product'):
        super(Product, self).__init__(input_dim, name=name)
        assert isinstance(step, int) and step > 1, 'step must be number greater than 1'
        assert int(math.fmod(input_dim, step)) == 0, 'input dim must be multiples of step'
        self.step = step 
Example 22
Project: RouteOptimization   Author: andre-le   File: polygonarea.py    MIT License 5 votes vote down vote up
def _transitdirect(lon1, lon2):
    """Count crossings of prime meridian for AddEdge."""
    # We want to compute exactly
    #   int(floor(lon2 / 360)) - int(floor(lon1 / 360))
    # Since we only need the parity of the result we can use std::remquo but
    # this is buggy with g++ 4.8.3 and requires C++11.  So instead we do
    lon1 = math.fmod(lon1, 720.0); lon2 = math.fmod(lon2, 720.0)
    return ( (0 if ((lon2 >= 0 and lon2 < 360) or lon2 < -360) else 1) -
             (0 if ((lon1 >= 0 and lon1 < 360) or lon1 < -360) else 1) ) 
Example 23
Project: RouteOptimization   Author: andre-le   File: geomath.py    MIT License 5 votes vote down vote up
def AngNormalize(x):
    """reduce angle to (-180,180]"""

    y = math.fmod(x, 360)
    # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360) = +0.0
    # This fixes this bug.  See also Math::AngNormalize in the C++ library.
    # sincosd has a similar fix.
    y = x if x == 0 else y
    return (y + 360 if y <= -180 else
            (y if y <= 180 else y - 360)) 
Example 24
Project: RouteOptimization   Author: andre-le   File: point.py    MIT License 5 votes vote down vote up
def _normalize_angle(x, limit):
    """
    Normalize angle `x` to be within `[-limit; limit)` range.
    """
    double_limit = limit * 2.0
    modulo = fmod(x, double_limit) or 0.0  # `or 0` is to turn -0 to +0.
    if modulo < -limit:
        return modulo + double_limit
    if modulo >= limit:
        return modulo - double_limit
    return modulo 
Example 25
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bmath.py    MIT License 5 votes vote down vote up
def d2s(ang, fmt=""):
	"""degrees to string
	D2S(angle[,"H"|"M"|"D"|"N"])
	"""
	fmt.capitalize()
	if ang<0.0:
		neg = "-"
		ang = -ang
	else:
		neg = ""

	ang = round(ang*360000)/100
	SS  = "%05.2f" % (fmod(ang,60))
	ang = int(ang / 60.0)
	MM  = "%02d" % (ang % 60)
	HH  = neg + str(ang / 60)

	if fmt=="H":
		return HH+"h"+MM+"m"+SS+"s"
	if fmt=="M":
		return HH+"h"+MM+"m"
	if fmt=="D":
		return HH+" "+MM+"'"+SS+'"'
	if fmt=="N":
		return HH+":"+MM
	return HH+":"+MM+":"+SS

#------------------------------------------------------------------------------- 
Example 26
Project: grabba_grabba_hey   Author: multiply-org   File: landsat_downloader.py    GNU General Public License v2.0 5 votes vote down vote up
def cycle_day (path):
    """ provides the day in cycle given the path number
    """
    cycle_day_path1  = 5
    cycle_day_increment = 7
    nb_days_after_day1 = cycle_day_path1 + cycle_day_increment*(path-1)
 
    cycle_day_path = math.fmod(nb_days_after_day1,16)
    if path >= 98: #change date line
        cycle_day_path += 1

    return cycle_day_path 
Example 27
Project: rpython-lang-scheme   Author: tomoh1r   File: ll_time.py    MIT License 5 votes vote down vote up
def register_time_sleep(self):
        if sys.platform == 'win32':
            Sleep = self.llexternal('Sleep', [rffi.ULONG], lltype.Void)
            def time_sleep_llimpl(secs):
                millisecs = secs * 1000.0
                while millisecs > UINT_MAX:
                    Sleep(UINT_MAX)
                    millisecs -= UINT_MAX
                Sleep(rffi.cast(rffi.ULONG, int(millisecs)))
        else:
            c_select = self.llexternal('select', [rffi.INT, rffi.VOIDP,
                                                  rffi.VOIDP, rffi.VOIDP,
                                                  self.TIMEVALP], rffi.INT,
                                       save_err=rffi.RFFI_SAVE_ERRNO)
            def time_sleep_llimpl(secs):
                void = lltype.nullptr(rffi.VOIDP.TO)
                t = lltype.malloc(self.TIMEVAL, flavor='raw')
                try:
                    frac = math.fmod(secs, 1.0)
                    rffi.setintfield(t, 'c_tv_sec', int(secs))
                    rffi.setintfield(t, 'c_tv_usec', int(frac*1000000.0))

                    if rffi.cast(rffi.LONG, c_select(0, void, void, void, t)) != 0:
                        errno = rposix.get_saved_errno()
                        if errno != EINTR:
                            raise OSError(errno, "Select failed")
                finally:
                    lltype.free(t, flavor='raw')

        return extdef([float], None, llimpl=time_sleep_llimpl,
                      export_name='ll_time.ll_time_sleep') 
Example 28
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rbuiltin.py    MIT License 5 votes vote down vote up
def test_builtin_math_fmod(self):
        def fn(f,y):
            return math.fmod(f,y)

        for i in range(10):
            for j in range(10):
                rv = 1000 * float(i-10)
                ry = 100 * float(i-10) +0.1
                assert self.float_eq(fn(rv,ry), self.interpret(fn, (rv, ry))) 
Example 29
Project: rpython-lang-scheme   Author: tomoh1r   File: test_typed.py    MIT License 5 votes vote down vote up
def test_float_operations(self):
        def func(x, y):
            z = x + y / 2.1 * x
            z = math.fmod(z, 60.0)
            z = math.pow(z, 2)
            z = -z
            return int(z)

        fn = self.getcompiled(func, [float, float])
        assert fn(5.0, 6.0) == func(5.0, 6.0) 
Example 30
Project: vnpy_crypto   Author: birforce   File: jdcal.py    MIT License 5 votes vote down vote up
def is_leap(year):
    """Leap year or not in the Gregorian calendar."""
    x = math.fmod(year, 4)
    y = math.fmod(year, 100)
    z = math.fmod(year, 400)

    # Divisible by 4 and,
    # either not divisible by 100 or divisible by 400.
    return not x and (y or not z) 
Example 31
Project: IronHydra   Author: microdee   File: PerlinAtPoint.py    MIT License 5 votes vote down vote up
def n1(p):
    tempv = p
    for i in range(0, 3):
        tempv[i] = math.sin(p[i] * (3.3 ** 0.5) + math.fmod(math.sin(p[2-i] * (5.0 ** 0.5) + Options.Content["RandomSeed"][0]) * (8.0 ** 0.5), 1.0) * 8.0)
    return math.cos(veclength(tempv)) 
Example 32
Project: IronHydra   Author: microdee   File: PerlinAtPoint.py    MIT License 5 votes vote down vote up
def octave(n):
    ii = VVVVContext.InvokationCount % Options.Content["Rows"][0]
    ti = VVVVContext.ThreadID
    x = [PosList.Content["X"][ii], PosListY.Content["Y"][ti]]
    z = Options.Content["Z"][0] / ((2.0 ** MorphBalance) ** n - 6.0)
    p = [(x[0] + 3.0) * (1111.0 ** 0.5), (x[0] + 3.0) * (1111.0 ** 0.5), math.floor(z)]
    c = lerp(n1(p), n1([p[0], p[1], p[2] + 1.0]), math.fmod(z, 1.0)) 
Example 33
Project: ted-editor   Author: tarnheld   File: ted-editor.py    The Unlicense 5 votes vote down vote up
def addHandles(self):
        self.removeHandles()
        self.cp_cidmap = {}
        print(len(self.cc.road))
        for r in self.cc.road:
            print(len(r))
            cids = self.addMoveHandle(r)
            for cid in cids:
                self.r_cidmap[cid] = r
            self.imap[r] = cids
        self.canvas.tag_lower("rail","segment")
        sys.stdout.flush()

        minslotlen = 50
        #tex = m.fmod(self.cc.length(),minslotlen)
        #numslots = int((self.cc.length() - tex)/minslotlen + 2)
        numslots = int(self.cc.length()/minslotlen + 2)
        ex = (self.cc.length() - numslots*minslotlen)/numslots
        slotlen = minslotlen + ex

        
        try:
            self.canvas.delete("slots")
        except tk.TclError:
            pass

        for i in range(numslots):
            s = i*slotlen
            op, ot = self.cc.pointAndTangentAt(s)
            on = la.perp2ccw(ot)
            p1 = op + 30*la.unit(on)
            p2 = op - 30*la.unit(on)
            self.canvas.create_polygon([(p1[0],p1[1]),(p2[0],p2[1])],outline="black",tags="slots") 
Example 34
Project: ted-editor   Author: tarnheld   File: ted-editor.py    The Unlicense 5 votes vote down vote up
def drawContours(self, path):
        # print("load contours",path)
        try:
            self.canvas.delete("contour")
        except tk.TclError:
            pass

        import re
        self.contours = np.load(path)
        ex = self.scene["ex"]
        lf = len(self.contours.files)
        for a in self.contours.files:
            cs = self.contours[a]
            h = int(re.findall('\d+', a)[0])
            h /= lf
            # print("file",a,h)
            # print("contours",len(cs))
            col = colorsys.rgb_to_hsv(0.7, 0.9, 0.85)
            hue = col[0] - h / 2
            hue = m.fmod(hue, 1)
            col = (hue, max(0, min(col[1], 1)), max(0, min(col[2], 1)))
            col = colorsys.hsv_to_rgb(*col)
            hexcol = rgb2hex(col)
            for c in cs:
                if len(c):
                    cc = [((x[1] - 512) / 1024 * ex * 2, (x[0] - 512) / 1024 * ex * 2) for x in c]
                    if la.norm(c[-1] - c[0]) < 0.01:
                        self.canvas.create_polygon(cc, fill="", outline=hexcol, width=7, tag="contour")
                    else:
                        self.canvas.create_line(cc, fill=hexcol, width=7, tag="contour")
        try:
            self.canvas.tag_lower("contour")
        except tk.TclError:
            pass

        sys.stdout.flush() 
Example 35
Project: Dallinger   Author: Dallinger   File: models.py    MIT License 5 votes vote down vote up
def _func(self, x):
        return 75 if (math.fmod(x, 50) <= 25) else 25 
Example 36
Project: efficientmc   Author: latour-a   File: generators.py    MIT License 5 votes vote down vote up
def halton2(dim, nsims):
    """
    la fonction ne crash plus.
    Version 2 de la suite d'halton sans la librairie Python existante.
    """
    h = np.empty(nsims * dim)
    h.fill(np.nan)
    p = np.empty(nsims)
    p.fill(np.nan)
    Base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
    lognsims = log(nsims + 1)
    for i in range(dim):
        base = Base[i]
        n = int(ceil(lognsims / log(base)))
        for t in range(n):
            p[t] = pow(base, -(t + 1) )
        for j in range(nsims):
            d = j + 1
            somme = fmod(d, base) * p[0]
            for t in range(1, n):
                d = floor(d / base)
                somme += fmod(d, base) * p[t]

            h[j*dim + i] = somme

    return norm.ppf(h.reshape(dim, nsims)) 
Example 37
Project: tq   Author: cdluminate   File: __init__.py    MIT License 5 votes vote down vote up
def sec2hms(s: float) -> str:
    '''
    Convert X seconds into A hour B minute C seconds as a string.
    '''
    sec = math.fmod(s, 60.0)
    mm  = (int(s) // 60) % 60
    hh  = (int(s) // 60) // 60
    return f'{hh}h{mm}m{sec:.3f}s' 
Example 38
Project: perceptron-benchmark   Author: advboxes   File: motion_blur.py    Apache License 2.0 5 votes vote down vote up
def motion_Kernel(dim, angle):

        if isinstance(dim, int):
            dim = (dim, dim)
        dim = np.array(dim).astype(int)
        center = (dim - 1) / 2
        kernel = np.zeros(dim)
        angle = math.fmod(angle, 180.0)
        if angle == 90:
            kernel[:, int(center[1])] = 1
            return kernel

        delta_x = 0
        delta_y = 0
        while True:
            if (center[1] + delta_x).is_integer():
                if int(round(center[0] + delta_y)) < 0 or int(round(center[0] + delta_y)) >= dim[0] or int(
                        center[1] + delta_x) < 0 or int(center[1] + delta_x) >= dim[1]:
                    break

                kernel[int(round(center[0] - delta_y)),
                       int(center[1] + delta_x)] = 1
                kernel[int(round(center[0] + delta_y)),
                       int(center[1] - delta_x)] = 1
            delta_x += 0.5
            delta_y = delta_x * math.tan(angle / 180 * np.pi)
        normalizationFactor = np.count_nonzero(kernel)
        kernel /= normalizationFactor
        return kernel 
Example 39
Project: s2sphere   Author: sidewalklabs   File: sphere.py    MIT License 5 votes vote down vote up
def drem(x, y):
    """Like fmod but rounds to nearest integer instead of floor."""
    xd = decimal.Decimal(x)
    yd = decimal.Decimal(y)
    return float(xd.remainder_near(yd)) 
Example 40
Project: ufora   Author: ufora   File: pure_math.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, x):
        remainder = math.fmod(x, 1)

        if x >= 0:
            return float(x - remainder)

        if remainder == 0:
            return float(x)

        return float(x - remainder - 1) 
Example 41
Project: ufora   Author: ufora   File: pure_math.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, x, y):
        if not isinstance(x, float):
            x = float(x)
        if not isinstance(y, float):
            y = float(y)

        return __inline_fora(
            """fun(@unnamed_args:(x, y), *args) {
                   return PyFloat(`fmod([email protected], [email protected]))
                   }"""
            )(x, y) 
Example 42
Project: mgrspy   Author: planetfederal   File: mgrs.py    GNU General Public License v2.0 5 votes vote down vote up
def _mgrsString(zone, letters, easting, northing, precision):
    """ Constructs an MGRS string from its component parts
    @param zone - UTM zone
    @param letters - MGRS coordinate string letters
    @param easting - easting value
    @param northing - northing value
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """
    if zone:
        tmp = str(zone)
        mgrs = tmp.zfill(3 - len(tmp))
    else:
        mgrs = '  '

    for i in range(3):
        mgrs += list(ALPHABET.keys())[
            list(ALPHABET.values()).index(letters[i])
        ]

    easting = math.fmod(easting + 1e-8, 100000.0)
    if easting >= 99999.5:
        easting = 99999.0
    mgrs += str(int(easting)).rjust(5, '0')[:precision]

    northing = math.fmod(northing + 1e-8, 100000.0)
    if northing >= 99999.5:
        northing = 99999.0
    mgrs += str(int(northing)).rjust(5, '0')[:precision]

    log.debug('mgrs: {0}'.format(mgrs))

    return mgrs 
Example 43
Project: Adafruit_CircuitPython_LIS3DH   Author: adafruit   File: lis3dh_spinner.py    MIT License 5 votes vote down vote up
def get_position(self, delta):
        # Increment elapsed time and compute the current velocity after a
        # decay of the initial velocity.
        self._elapsed += delta
        current_velocity = self._velocity*math.pow(self._decay, self._elapsed)
        self._position += current_velocity*delta
        # Make sure the position stays within values that range from 0 to <10.
        self._position = math.fmod(self._position, 10.0)
        if self._position < 0.0:
            self._position += 10.0
        return self._position


# pylint: disable=no-member
# Initialize NeoPixels and accelerometer. 
Example 44
Project: true-random   Author: hathix   File: testrands.py    MIT License 5 votes vote down vote up
def prng():
    global x
    x = math.fmod((x + math.pi) ** 2.0, 1.0)
    return x

# combination by recursive method 
Example 45
Project: astrolabe   Author: dcf21   File: calendar.py    GNU General Public License v2.0 5 votes vote down vote up
def inv_julian_day(jd):
    """
    Convert a Julian date into a calendar date.

    :param jd:
        Julian date

    :type jd:
        float

    :return:
        Calendar date
    """
    day_fraction = (jd + 0.5) - floor(jd + 0.5)
    hour = int(floor(24 * day_fraction))
    minute = int(floor(fmod(1440 * day_fraction, 60)))
    sec = fmod(86400 * day_fraction, 60)

    # Number of whole Julian days. b = Number of centuries since the Council of Nicaea.
    # c = Julian Day number as if century leap years happened.
    a = int(jd + 0.5)
    if a < 2361222.0:
        c = int(a + 1524)  # Julian calendar
    else:
        b = int((a - 1867216.25) / 36524.25)
        c = int(a + b - (b / 4) + 1525)  # Gregorian calendar
    d = int((c - 122.1) / 365.25)  # Number of 365.25 periods, starting the year at the end of February
    e_ = int(365 * d + d / 4)  # Number of days accounted for by these
    f = int((c - e_) / 30.6001)  # Number of 30.6001 days periods (a.k.a. months) in remainder
    day = int(floor(c - e_ - int(30.6001 * f)))
    month = int(floor(f - 1 - 12 * (f >= 14)))
    year = int(floor(d - 4715 - int(month >= 3)))
    return [year, month, day, hour, minute, sec] 
Example 46
Project: rl_games   Author: Denys88   File: robot.py    MIT License 5 votes vote down vote up
def angleDiff(self,a,b):
        dif = math.fmod(b - a + glm.pi(), 2.0 * glm.pi())
        if dif < 0:
            dif += 2.0 *glm.pi()
        return dif - glm.pi() 
Example 47
Project: mrcrowbar   Author: moralrecordings   File: colour.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mix_line( points, alpha ):
    count = len( points ) - 1
    if alpha == 1:
        return points[-1]
    return mix(
        points[math.floor( alpha*count )],
        points[math.floor( alpha*count )+1],
        math.fmod( alpha*count, 1 )
    ) 
Example 48
Project: mrcrowbar   Author: moralrecordings   File: colour.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mix_colour_line( points, alpha ):
    count = len( points ) - 1
    if alpha == 1:
        return points[-1]
    return mix_colour(
        points[math.floor( alpha*count )],
        points[math.floor( alpha*count )+1],
        math.fmod( alpha*count, 1 )
    ) 
Example 49
Project: hippie-trap   Author: mayhem   File: sweep_two_color_shift.py    MIT License 5 votes vote down vote up
def pattern(self):
        self.trap.send_decay(ALL, 90)
        self.trap.start_pattern(ALL)

        index = 0
        hue_offset = 0.0
        stop = False

        color_rings = [ random_color(), random_color(), random_color() , random_color() ]
        while not stop:
            for bottle, angle in self.geo.enumerate_all_bottles(index % 2 == 0):
                self.trap.set_color(bottle, color_rings[self.geo.get_ring_from_bottle(bottle)])
                sleep(.01)
                if self.stop_thread:
                    stop = True
                    break

            index += 1
            hue_offset = math.fmod(hue_offset + .02, 1.0)
            shift = math.sin(index / self.color_shift_between_rings) / 2.0 + .50
            new_offset = math.fmod(shift, 1.0)
            color_rings.pop()
            color_rings.insert(0, hue_to_color(new_offset))

        self.trap.stop_pattern(ALL)
        if self.transition:
            sleep(.02)
            transition_sweep_in(self.trap) 
Example 50
Project: hippie-trap   Author: mayhem   File: sweep_two_color_shift.py    MIT License 5 votes vote down vote up
def pattern(self):
        self.trap.send_decay(ALL, 90)
        self.trap.start_pattern(ALL)

        index = 0
        hue_offset = 0.0
        stop = False

        color_rings = [ random_color(), random_color(), random_color() , random_color() ]
        while not stop:
            for bottle, angle in self.geo.enumerate_all_bottles(index % 2 == 0):
                self.trap.set_color(bottle, color_rings[self.geo.get_ring_from_bottle(bottle)])
                sleep(.01)
                if self.stop_thread:
                    stop = True
                    break

            index += 1
            hue_offset = math.fmod(hue_offset + .02, 1.0)
            shift = math.sin(index / self.color_shift_between_rings) / 2.0 + .50
            new_offset = math.fmod(shift, 1.0)
            color_rings.pop()
            color_rings.insert(0, hue_to_color(new_offset))

        self.trap.stop_pattern(ALL)
        if self.transition:
            sleep(.02)
            transition_sweep_in(self.trap) 
Example 51
Project: qgis-latlontools-plugin   Author: NationalSecurityAgency   File: mgrs.py    GNU General Public License v2.0 5 votes vote down vote up
def _mgrsString(zone, letters, easting, northing, precision):
    """ Constructs an MGRS string from its component parts
    @param zone - UTM zone
    @param letters - MGRS coordinate string letters
    @param easting - easting value
    @param northing - northing value
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """
    if zone:
        tmp = str(zone)
        mgrs = tmp.zfill(3 - len(tmp))
    else:
        mgrs = '  '

    for i in range(3):
        mgrs += list(ALPHABET.keys())[
            list(ALPHABET.values()).index(letters[i])
        ]

    easting = math.fmod(easting + 1e-8, 100000.0)
    if easting >= 99999.5:
        easting = 99999.0
    mgrs += str(int(easting)).rjust(5, '0')[:precision]

    northing = math.fmod(northing + 1e-8, 100000.0)
    if northing >= 99999.5:
        northing = 99999.0
    mgrs += str(int(northing)).rjust(5, '0')[:precision]

    log.debug('mgrs: {0}'.format(mgrs))

    return mgrs 
Example 52
Project: campy   Author: sredmond   File: gobjects.py    MIT License 5 votes vote down vote up
def containsAngle(self, theta):
        '''
        Internal method
        '''
        start = min(self.start, self.start + self.sweep)
        sweep = abs(self.sweep)
        if(sweep >= 360): return True
        if(theta < 0): theta = 360 - math.fmod(-theta, 360)
        else: theta = math.fmod(theta, 360)
        if(start < 0): start = 360 - math.fmod(-start, 360)
        else: start = math.fmod(start, 360)
        if(start + sweep > 360):
            return (theta >= start or theta <= start + sweep - 360)
        else:
            return (theta >= start and theta <= start + sweep) 
Example 53
Project: QuakeMigrate   Author: QuakeMigrate   File: model.py    MIT License 5 votes vote down vote up
def _utm_zone(longitude):
    return (int(1 + math.fmod((longitude + 180.0) / 6.0, 60)))


# def _proj_nlloc_simple(latOrg,lonOrg,rotAngle):
#     x = (long - longOrig) * 111.111 * cos(lat_radians)
#     y = (lat - latOrig) * 111.111
#     lat = latOrig + y / 111.111
#     long = longOrig + x / (111.111 * cos(lat_radians))
#     x=(lon) 
Example 54
Project: PyMove   Author: InsightLab   File: gridutils.py    MIT License 5 votes vote down vote up
def create_virtual_grid(cell_size, bbox, meters_by_degree = lat_meters(-3.8162973555)):
    print('\nCreating a virtual grid without polygons')
    
    # Latitude in Fortaleza: -3.8162973555
    cell_size_by_degree = cell_size/meters_by_degree
    print('...cell size by degree: {}'.format(cell_size_by_degree))

    lat_min_y = bbox[0]
    lon_min_x = bbox[1]
    lat_max_y = bbox[2] 
    lon_max_x = bbox[3]

    #If cell size does not fit in the grid area, an expansion is made
    if math.fmod((lat_max_y - lat_min_y), cell_size_by_degree) != 0:
        lat_max_y = lat_min_y + cell_size_by_degree * (math.floor((lat_max_y - lat_min_y) / cell_size_by_degree) + 1)

    if math.fmod((lon_max_x - lon_min_x), cell_size_by_degree) != 0:
        lon_max_x = lon_min_x + cell_size_by_degree * (math.floor((lon_max_x - lon_min_x) / cell_size_by_degree) + 1)

    
    # adjust grid size to lat and lon
    grid_size_lat_y = int(round((lat_max_y - lat_min_y) / cell_size_by_degree))
    grid_size_lon_x = int(round((lon_max_x - lon_min_x) / cell_size_by_degree))
    
    print('...grid_size_lat_y:{}\ngrid_size_lon_x:{}'.format(grid_size_lat_y, grid_size_lon_x))

    # Return a dicionary virtual grid 
    my_dict = dict()
    
    my_dict['lon_min_x'] = lon_min_x
    my_dict['lat_min_y'] = lat_min_y
    my_dict['grid_size_lat_y'] = grid_size_lat_y
    my_dict['grid_size_lon_x'] = grid_size_lon_x
    my_dict['cell_size_by_degree'] = cell_size_by_degree
    print('\n..A virtual grid was created')
    return my_dict 
Example 55
Project: Pirates-Online-Rewritten   Author: PiratesOnlineRewritten   File: WaterPanel.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mod(self, numerator, denominator):
        return math.fmod(numerator, denominator) 
Example 56
Project: ultimate_osu_analyzer   Author: abraker95   File: math_utils.py    MIT License 5 votes vote down vote up
def triangle(val, amplitude):
    return abs((math.fmod(val + (amplitude / 2.0), amplitude)) - (amplitude / 2.0)) 
Example 57
Project: osmo.sessdsa   Author: chbpku   File: F-Tango.py    GNU General Public License v3.0 5 votes vote down vote up
def regularization(self, rad):
        """角度正规化"""
        return math.fmod((rad + 3 * math.pi * 2) / math.pi * 180, 360) 
Example 58
Project: kepler_laws   Author: agarciamontoro   File: planet.py    GNU General Public License v2.0 5 votes vote down vote up
def getPos(self, delta):
        """Retrieves the position and eccentric anomaly values.

        Retrieves the planet position at the day `delta` after the self.t_0
        date. Along with the plane coordinates -returned as a list- the
        eccentric anomaly is returned.

        Args:
            delta: Number of days after self.t_0 date; i.e., the number of days
                after the first perihelium of the planet after 31st December,
                1899. Integer or float.
        Returns:
            A two-positions list [x,y] giving the XY plane coordinates and the
            eccentric anomaly measured in radians in the interval [0,2*pi[
        """
        current_xi = self.xi(delta)
        phi = self.build_phi(self.eccentricity, current_xi)

        u = self.NR(phi)

        sin_u = math.sin(u)
        cos_u = math.cos(u)

        x_coord = self.semi_major_axis*(cos_u-self.eccentricity)
        y_coord = self.semi_major_axis*math.sqrt(1-self.eccentricity**2)*sin_u

        return [x_coord, y_coord], math.fmod(u, 2*math.pi) 
Example 59
Project: pyCreate2   Author: USC-ACTLab   File: tracker.py    MIT License 5 votes vote down vote up
def query(self):
    t = self.time.time()
    if t > self.queried_time + 1.0 / self.rate:
      # if np.random.random() < 0.05: # 5% chance of not detecting the tag
      #   return None
      rc, xyz = vrep.simxGetObjectPosition(
        self._clientID,
        self._create,
        -1,
        vrep.simx_opmode_oneshot)

      if rc != 0:
        return None

      x, y, z = xyz
      x += np.random.normal(0, self.sd_x)
      y += np.random.normal(0, self.sd_y)

      rc, rpy = vrep.simxGetObjectOrientation(
        self._clientID,
        self._create,
        -1,
        vrep.simx_opmode_oneshot)
      
      if rc != 0:
        return None

      roll, pitch, yaw = rpy
      yaw = math.fmod(yaw + np.random.normal(0, self.sd_theta), 2 * math.pi)

      self.queried_time = t

      return {
        'id': self.tag_id,
        'time': t,
        'position': dict(zip('xyz', (x, y, z))),
        'orientation': dict(zip('rpy', (roll, pitch, yaw)))
      }

    return None 
Example 60
Project: gxpy   Author: GeosoftInc   File: jdcal.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_leap(year):
    """Leap year or not in the Gregorian calendar."""
    x = math.fmod(year, 4)
    y = math.fmod(year, 100)
    z = math.fmod(year, 400)

    # Divisible by 4 and,
    # either not divisible by 100 or divisible by 400.
    return not x and (y or not z) 
Example 61
Project: MotionBlur   Author: young666   File: MotionBlur.py    GNU General Public License v3.0 5 votes vote down vote up
def SanitizeAngleValue(kernelCenter, angle):
    numDistinctLines = kernelCenter * 4
    angle = math.fmod(angle, 180.0)
    validLineAngles = np.linspace(0, 180, numDistinctLines, endpoint=False)
    angle = nearestValue(angle, validLineAngles)
    return angle 
Example 62
Project: Panda3DCraft   Author: kengleason   File: perlin.py    MIT License 5 votes vote down vote up
def noise3(self, x, y, z, repeat, base=0.0):
		"""Tileable 3D noise.
		
		repeat specifies the integer interval in each dimension 
		when the noise pattern repeats.
		
		base allows a different texture to be generated for
		the same repeat interval.
		"""
		i = int(fmod(floor(x), repeat))
		j = int(fmod(floor(y), repeat))
		k = int(fmod(floor(z), repeat))
		ii = (i + 1) % repeat
		jj = (j + 1) % repeat
		kk = (k + 1) % repeat
		if base:
			i += base; j += base; k += base
			ii += base; jj += base; kk += base

		x -= floor(x); y -= floor(y); z -= floor(z)
		fx = x**3 * (x * (x * 6 - 15) + 10)
		fy = y**3 * (y * (y * 6 - 15) + 10)
		fz = z**3 * (z * (z * 6 - 15) + 10)

		perm = self.permutation
		A = perm[i]
		AA = perm[A + j]
		AB = perm[A + jj]
		B = perm[ii]
		BA = perm[B + j]
		BB = perm[B + jj]
		
		return lerp(fz, lerp(fy, lerp(fx, grad3(perm[AA + k], x, y, z),
										  grad3(perm[BA + k], x - 1, y, z)),
								 lerp(fx, grad3(perm[AB + k], x, y - 1, z),
										  grad3(perm[BB + k], x - 1, y - 1, z))),
						lerp(fy, lerp(fx, grad3(perm[AA + kk], x, y, z - 1),
										  grad3(perm[BA + kk], x - 1, y, z - 1)),
								 lerp(fx, grad3(perm[AB + kk], x, y - 1, z - 1),
										  grad3(perm[BB + kk], x - 1, y - 1, z - 1)))) 
Example 63
Project: InteractiveHtmlBom   Author: openscopeproject   File: config.py    MIT License 5 votes vote down vote up
def set_from_args(self, args):
        # type: (argparse.Namespace) -> None
        import math

        # Html
        self.dark_mode = args.dark_mode
        self.show_pads = not args.hide_pads
        self.show_fabrication = args.show_fabrication
        self.show_silkscreen = not args.hide_silkscreen
        self.highlight_pin1 = args.highlight_pin1
        self.redraw_on_drag = not args.no_redraw_on_drag
        self.board_rotation = math.fmod(args.board_rotation // 5, 37)
        self.checkboxes = args.checkboxes
        self.bom_view = args.bom_view
        self.layer_view = args.layer_view
        self.open_browser = not args.no_browser

        # General
        self.bom_dest_dir = args.dest_dir
        self.bom_name_format = args.name_format
        self.component_sort_order = self._split(args.sort_order)
        self.component_blacklist = self._split(args.blacklist)
        self.blacklist_virtual = not args.no_blacklist_virtual
        self.blacklist_empty_val = args.blacklist_empty_val
        self.include_tracks = args.include_tracks
        self.include_nets = args.include_nets

        # Extra
        self.netlist_file = args.netlist_file
        self.extra_fields = self._split(args.extra_fields)
        self.normalize_field_case = args.normalize_field_case
        self.board_variant_field = args.variant_field
        self.board_variant_whitelist = self._split(args.variants_whitelist)
        self.board_variant_blacklist = self._split(args.variants_blacklist)
        self.dnp_field = args.dnp_field 
Example 64
Project: BL-Bot   Author: IOIIIO   File: bounding_box.py    GNU General Public License v3.0 5 votes vote down vote up
def angle(bx, by):
    """Get the angle between vector (1,0) and vector (bx,by)."""
    return fmod(
        2 * pi + (1 if by > 0 else -1) * acos(bx / sqrt(bx * bx + by * by)),
        2 * pi) 
Example 65
Project: QGISFMV   Author: All4Gis   File: mgrs.py    GNU General Public License v3.0 5 votes vote down vote up
def _mgrsString(zone, letters, easting, northing, precision):
    """ Constructs an MGRS string from its component parts
    @param zone - UTM zone
    @param letters - MGRS coordinate string letters
    @param easting - easting value
    @param northing - northing value
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """
    if zone:
        tmp = str(zone)
        mgrs = tmp.zfill(3 - len(tmp))
    else:
        mgrs = '  '

    for i in range(3):
        mgrs += list(ALPHABET.keys())[list(ALPHABET.values()).index(letters[i])]

    mgrs += '  '
    easting = math.fmod(easting + 1e-8, 100000.0)
    if easting >= 99999.5:
        easting = 99999.0
    mgrs += str(int(easting)).rjust(5, '0')[:precision]

    mgrs += '  '
    northing = math.fmod(northing + 1e-8, 100000.0)
    if northing >= 99999.5:
        northing = 99999.0
    mgrs += str(int(northing)).rjust(5, '0')[:precision]

    return mgrs 
Example 66
Project: pyblur   Author: lospooky   File: LinearMotionBlur.py    MIT License 5 votes vote down vote up
def SanitizeAngleValue(kernelCenter, angle):
    numDistinctLines = kernelCenter * 4
    angle = math.fmod(angle, 180.0)
    validLineAngles = np.linspace(0,180, numDistinctLines, endpoint = False)
    angle = nearestValue(angle, validLineAngles)
    return angle 
Example 67
Project: addon_common   Author: CGCookie   File: debug.py    GNU General Public License v3.0 5 votes vote down vote up
def point_inside_loop2d(loop, point):
    '''
    args:
    loop: list of vertices representing loop
        type-tuple or type-Vector
    point: location of point to be tested
        type-tuple or type-Vector

    return:
        True if point is inside loop
    '''
    #test arguments type
    if any(not v for v in loop): return False

    ptype = str(type(point))
    ltype = str(type(loop[0]))
    nverts = len(loop)

    if 'Vector' not in ptype:
        point = Vector(point)

    if 'Vector' not in ltype:
        for i in range(0,nverts):
            loop[i] = Vector(loop[i])

    #find a point outside the loop and count intersections
    out = Vector(outside_loop_2d(loop))
    intersections = 0
    for i in range(0,nverts):
        a = Vector(loop[i-1])
        b = Vector(loop[i])
        if intersect_line_line_2d(point,out,a,b):
            intersections += 1

    inside = False
    if math.fmod(intersections,2):
        inside = True

    return inside 
Example 68
Project: moving-symbols   Author: rszeto   File: moving_symbols_utils.py    MIT License 5 votes vote down vote up
def create_triangle_fn(period, amplitude, x_offset, y_offset):
    p = float(period)
    a = float(amplitude)
    x_offset = float(x_offset)
    y_offset = float(y_offset)
    def ret(x):
        in_ = math.fmod(x - x_offset, p) + 7*p/4
        return 4*a/p * (math.fabs(math.fmod(in_, p) - p/2) - p/4) + y_offset
    return ret 
Example 69
Project: manticore   Author: trailofbits   File: operators.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def SMOD(a, b):
    if isinstance(a, BitVec):
        return a.smod(b)
    elif isinstance(b, BitVec):
        return b.rsmod(a)
    return int(math.fmod(a, b)) 
Example 70
Project: eddy   Author: obdasystems   File: ontology_consistency_check.py    GNU General Public License v3.0 4 votes vote down vote up
def doWork(self):

        total_no_of_buttons = len(self.project.explanations_for_inconsistency)
        #total_no_of_buttons = 44

        sb = math.sqrt(total_no_of_buttons)
        total_number_of_rows = math.ceil(sb)
        total_no_of_columns = math.ceil(sb)

        if (total_number_of_rows>15) | (total_no_of_buttons > 45):
            total_number_of_rows = 15
            total_no_of_columns = math.ceil(total_no_of_buttons/15)

        if total_no_of_buttons <=45:
            total_no_of_columns = 3
            total_number_of_rows = math.ceil(total_no_of_buttons/3)

        total_number_of_extra_spaces = (total_number_of_rows*total_no_of_columns) - total_no_of_buttons
        extra_space_dec = math.floor(total_number_of_extra_spaces / total_no_of_columns)
        extra_extra_space = int(math.fmod(total_number_of_extra_spaces,total_no_of_columns))

        sp = 1
        ep = sp+total_number_of_rows-1

        for c in range(1,total_no_of_columns+1):

            if extra_extra_space > 0:
                ep = ep - 1
                extra_extra_space = extra_extra_space - 1

            if total_number_of_extra_spaces>0:

                ep = ep-extra_space_dec
                total_number_of_extra_spaces=total_number_of_extra_spaces-extra_space_dec

            self.addAColumnOfButtons(sp, ep)

            new_sp = ep+1
            new_ep = new_sp+total_number_of_rows-1

            sp = new_sp
            ep = new_ep

        self.explanationButtonsArea.setLayout(self.explanationButtonsLayout)
        self.mainLayout.addWidget(self.explanationButtonsArea)
        self.setLayout(self.mainLayout) 
Example 71
Project: ted-editor   Author: tarnheld   File: ted-editor.py    The Unlicense 4 votes vote down vote up
def redrawSegments(self, affected=None, except_seg=None):
        if except_seg is None: except_seg = []
        if affected is None:
            for seg, cids in self.jointimap.items():
                for cid in cids:
                    self.canvas.delete(cid)
            # TODO: remove nonexisting segments from imap
            self.canvas.delete(self.segtag)

            seg2cid = self.cc.draw(self.canvas, **self.segstyle)
            self.seg_cidmap = {}
            for s, cids in seg2cid.items():
                self.imap[s] = cids
                for cid in cids:
                    self.seg_cidmap[cid] = s
        else:
            for i, a in enumerate(affected):
                if a in self.imap:
                    cids = self.imap[a]
                    for cid in cids:
                        self.canvas.delete(cid)
                ncids = self.cc.drawSegment(a, self.canvas, **self.segstyle)
                if ncids is None:
                    self.imap.pop(a)
                    for cid in cids:
                        self.seg_cidmap.pop(cid)
                else:
                    self.imap[a] = ncids
                    for cid in ncids:
                        self.seg_cidmap[cid] = a
        self.addJointHandles(except_seg)
        self.canvas.tag_raise(self.segtag, "contour")
        try:
            self.canvas.tag_raise(self.segtag, "image")
        except tk.TclError:
            pass

        # minslotlen = 50
        # tex = m.fmod(self.cc.length(),minslotlen)
        # numslots = int((self.cc.length() - tex)/minslotlen + 2)
        # ex = (self.cc.length() - numslots*minslotlen)/numslots
        # slotlen = minslotlen + ex
        
        # try:
        #     self.canvas.delete("slots")
        # except tk.TclError:
        #     pass

        # for i in range(numslots):
        #     s = i*slotlen
        #     op, ot = self.cc.pointAndTangentAt(s)
        #     on = la.perp2ccw(ot)
        #     p1 = op + 30*la.unit(on)
        #     p2 = op - 30*la.unit(on)
        #     self.canvas.create_polygon([(p1[0],p1[1]),(p2[0],p2[1])],outline="black",tags="slots")

        self.canvas.itemconfigure(self.lengthdisplay,
                                  text="Length: {:.2f}m".format(self.cc.length())) 
Example 72
Project: news_proj   Author: TheoElia   File: base.py    MIT License 4 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.create_function("django_date_extract", 2, _sqlite_datetime_extract)
        conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
        conn.create_function("django_datetime_cast_date", 2, _sqlite_datetime_cast_date)
        conn.create_function("django_datetime_cast_time", 2, _sqlite_datetime_cast_time)
        conn.create_function("django_datetime_extract", 3, _sqlite_datetime_extract)
        conn.create_function("django_datetime_trunc", 3, _sqlite_datetime_trunc)
        conn.create_function("django_time_extract", 2, _sqlite_time_extract)
        conn.create_function("django_time_trunc", 2, _sqlite_time_trunc)
        conn.create_function("django_time_diff", 2, _sqlite_time_diff)
        conn.create_function("django_timestamp_diff", 2, _sqlite_timestamp_diff)
        conn.create_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
        conn.create_function('regexp', 2, _sqlite_regexp)
        conn.create_function('ACOS', 1, none_guard(math.acos))
        conn.create_function('ASIN', 1, none_guard(math.asin))
        conn.create_function('ATAN', 1, none_guard(math.atan))
        conn.create_function('ATAN2', 2, none_guard(math.atan2))
        conn.create_function('CEILING', 1, none_guard(math.ceil))
        conn.create_function('COS', 1, none_guard(math.cos))
        conn.create_function('COT', 1, none_guard(lambda x: 1 / math.tan(x)))
        conn.create_function('DEGREES', 1, none_guard(math.degrees))
        conn.create_function('EXP', 1, none_guard(math.exp))
        conn.create_function('FLOOR', 1, none_guard(math.floor))
        conn.create_function('LN', 1, none_guard(math.log))
        conn.create_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))
        conn.create_function('LPAD', 3, _sqlite_lpad)
        conn.create_function('MOD', 2, none_guard(math.fmod))
        conn.create_function('PI', 0, lambda: math.pi)
        conn.create_function('POWER', 2, none_guard(operator.pow))
        conn.create_function('RADIANS', 1, none_guard(math.radians))
        conn.create_function('REPEAT', 2, none_guard(operator.mul))
        conn.create_function('REVERSE', 1, none_guard(lambda x: x[::-1]))
        conn.create_function('RPAD', 3, _sqlite_rpad)
        conn.create_function('SIN', 1, none_guard(math.sin))
        conn.create_function('SQRT', 1, none_guard(math.sqrt))
        conn.create_function('TAN', 1, none_guard(math.tan))
        conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev))
        conn.create_aggregate('STDDEV_SAMP', 1, list_aggregate(statistics.stdev))
        conn.create_aggregate('VAR_POP', 1, list_aggregate(statistics.pvariance))
        conn.create_aggregate('VAR_SAMP', 1, list_aggregate(statistics.variance))
        conn.execute('PRAGMA foreign_keys = ON')
        return conn 
Example 73
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 74
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 75
Project: eperpus   Author: HilmiZul   File: base.py    MIT License 4 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.create_function("django_date_extract", 2, _sqlite_datetime_extract)
        conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
        conn.create_function("django_datetime_cast_date", 2, _sqlite_datetime_cast_date)
        conn.create_function("django_datetime_cast_time", 2, _sqlite_datetime_cast_time)
        conn.create_function("django_datetime_extract", 3, _sqlite_datetime_extract)
        conn.create_function("django_datetime_trunc", 3, _sqlite_datetime_trunc)
        conn.create_function("django_time_extract", 2, _sqlite_time_extract)
        conn.create_function("django_time_trunc", 2, _sqlite_time_trunc)
        conn.create_function("django_time_diff", 2, _sqlite_time_diff)
        conn.create_function("django_timestamp_diff", 2, _sqlite_timestamp_diff)
        conn.create_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
        conn.create_function('regexp', 2, _sqlite_regexp)
        conn.create_function('ACOS', 1, none_guard(math.acos))
        conn.create_function('ASIN', 1, none_guard(math.asin))
        conn.create_function('ATAN', 1, none_guard(math.atan))
        conn.create_function('ATAN2', 2, none_guard(math.atan2))
        conn.create_function('CEILING', 1, none_guard(math.ceil))
        conn.create_function('COS', 1, none_guard(math.cos))
        conn.create_function('COT', 1, none_guard(lambda x: 1 / math.tan(x)))
        conn.create_function('DEGREES', 1, none_guard(math.degrees))
        conn.create_function('EXP', 1, none_guard(math.exp))
        conn.create_function('FLOOR', 1, none_guard(math.floor))
        conn.create_function('LN', 1, none_guard(math.log))
        conn.create_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))
        conn.create_function('LPAD', 3, _sqlite_lpad)
        conn.create_function('MOD', 2, none_guard(math.fmod))
        conn.create_function('PI', 0, lambda: math.pi)
        conn.create_function('POWER', 2, none_guard(operator.pow))
        conn.create_function('RADIANS', 1, none_guard(math.radians))
        conn.create_function('REPEAT', 2, none_guard(operator.mul))
        conn.create_function('REVERSE', 1, none_guard(lambda x: x[::-1]))
        conn.create_function('RPAD', 3, _sqlite_rpad)
        conn.create_function('SIN', 1, none_guard(math.sin))
        conn.create_function('SQRT', 1, none_guard(math.sqrt))
        conn.create_function('TAN', 1, none_guard(math.tan))
        conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev))
        conn.create_aggregate('STDDEV_SAMP', 1, list_aggregate(statistics.stdev))
        conn.create_aggregate('VAR_POP', 1, list_aggregate(statistics.pvariance))
        conn.create_aggregate('VAR_SAMP', 1, list_aggregate(statistics.variance))
        conn.execute('PRAGMA foreign_keys = ON')
        return conn 
Example 76
Project: mrcrowbar   Author: moralrecordings   File: sound.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def resample_audio_iter( source, format_type, field_size, signedness, endian, channels, sample_rate, start=None, end=None, length=None, interpolation=AudioInterpolation.LINEAR, output_rate=RESAMPLE_RATE ):
    if sample_rate == 0:
        yield array( 'f' )
        return

    assert is_bytes( source )
    start, end = bounds( start, end, length, len( source ) )

    mixer = mix_linear
    if interpolation == AudioInterpolation.STEP:
        mixer = mix_step

    new_len = (end-start)*output_rate//sample_rate

    src_inc = NORMALIZE_BUFFER
    chunk_size=src_inc*channels
    src_iter = normalise_audio_iter( source, format_type, field_size, signedness, endian, start, end, overlap=channels, chunk_size=chunk_size )
    src = next( src_iter, None )
    src_bound = src_inc

    for index_base in range( 0, new_len, RESAMPLE_BUFFER ):
        buffer = array( 'f', (0.0 for i in range( RESAMPLE_BUFFER )))

        for index in range( RESAMPLE_BUFFER ):
            tgt_pos = index_base + index
            src_pos = sample_rate*tgt_pos/output_rate
            samp_index = math.floor( src_pos ) % src_inc
            alpha = math.fmod( src_pos, 1.0 )

            if src_pos > src_bound:
                src = next( src_iter, None )
                src_bound += src_inc

            if src is None:
                break

            a = 0.0 if samp_index >= len( src ) else src[samp_index]
            b = 0.0 if samp_index+channels >= len( src ) else src[samp_index+channels]

            buffer[index] = mixer( a, b, alpha )

        yield buffer 
Example 77
Project: hippie-trap   Author: mayhem   File: fire_ice_circles.py    MIT License 4 votes vote down vote up
def pattern(self):

        color_shift = 0.0
        color_offset = 0.0
        stop = False

        while True:
            bottle_base = 1
            for i, ring in enumerate(BOTTLES_PER_RING):
                if i == len(BOTTLES_PER_RING):
                    break

                for bottle in range(bottle_base, bottle_base + BOTTLES_PER_RING[i] + 1):
                    array = []

                    #                                   This last part makes each ring distinct
                    hue = color_shift + (random() / 4) + color_offset  + (i * .1)
                    array.append(hue_to_color(min(1.0, math.fmod(hue, 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + self.angle, 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + (self.angle * 2), 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + (self.angle * 3), 1.0))))

                    self.trap.stop_pattern(bottle)
                    self.trap.send_fade(bottle, self.PERIOD, array)
                    sleep(.035)

                    if self.stop_thread:
                        stop = True
                        break

                    self.trap.start_pattern(bottle)

                if self.stop_thread:
                    stop = True
                    break
                bottle_base += BOTTLES_PER_RING[i]
                color_offset += .1

            if self.stop_thread:
                stop = True
                break
            color_shift += .01

        self.trap.stop_pattern(ALL)
        if self.transition:
            sleep(.02)
            transition_sweep_in(self.trap) 
Example 78
Project: hippie-trap   Author: mayhem   File: fire_ice_circles.py    MIT License 4 votes vote down vote up
def pattern(self):

        color_shift = 0.0
        color_offset = 0.0
        stop = False

        while True:
            bottle_base = 1
            for i, ring in enumerate(BOTTLES_PER_RING):
                if i == len(BOTTLES_PER_RING):
                    break

                for bottle in range(bottle_base, bottle_base + BOTTLES_PER_RING[i] + 1):
                    array = []

                    #                                   This last part makes each ring distinct
                    hue = color_shift + (random() / 4) + color_offset  + (i * .1)
                    array.append(hue_to_color(min(1.0, math.fmod(hue, 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + self.angle, 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + (self.angle * 2), 1.0))))
                    array.append(hue_to_color(min(1.0, math.fmod(hue + (self.angle * 3), 1.0))))

                    self.trap.stop_pattern(bottle)
                    self.trap.send_fade(bottle, self.PERIOD, array)
                    sleep(.035)

                    if self.stop_thread:
                        stop = True
                        break

                    self.trap.start_pattern(bottle)

                if self.stop_thread:
                    stop = True
                    break
                bottle_base += BOTTLES_PER_RING[i]
                color_offset += .1

            if self.stop_thread:
                stop = True
                break
            color_shift += .01

        self.trap.stop_pattern(ALL)
        if self.transition:
            sleep(.02)
            transition_sweep_in(self.trap) 
Example 79
Project: pyCreate2   Author: USC-ACTLab   File: create2_vrep.py    MIT License 4 votes vote down vote up
def update(self):
        state = State()
        vrep.simxSynchronousTrigger(self._clientID)

        # Simulate wheel encoders
        rc, pos_right = vrep.simxGetJointPosition(self._clientID, self._rightWheelJoint, vrep.simx_opmode_oneshot_wait)
        rc, pos_left = vrep.simxGetJointPosition(self._clientID, self._leftWheelJoint, vrep.simx_opmode_oneshot_wait)

        if self._lastPosRight is not None:
            dr = pos_right - self._lastPosRight
            dl = pos_left - self._lastPosLeft

            if dr >= 0:
                dr = math.fmod(dr+math.pi, 2*math.pi) - math.pi
            else:
                dr = math.fmod(dr-math.pi, 2*math.pi) + math.pi

            if dl >= 0:
                dl = math.fmod(dl+math.pi, 2*math.pi) - math.pi
            else:
                dl = math.fmod(dl-math.pi, 2*math.pi) + math.pi

            self._rightEncoderCount += dr * Specs.CountsPerRev / 2 / math.pi
            self._leftEncoderCount += dl * Specs.CountsPerRev / 2 / math.pi

            if self._rightEncoderCount > 32768:
                self._rightEncoderCount -= 65547
            if self._rightEncoderCount < -32768:
                self._rightEncoderCount += 65547
            if self._leftEncoderCount > 32768:
                self._leftEncoderCount -= 65547
            if self._leftEncoderCount < -32768:
                self._leftEncoderCount += 65547

        self._lastPosRight = pos_right
        self._lastPosLeft = pos_left

        if Sensor.LeftEncoderCounts in self._sensorIDs:
            state.leftEncoderCounts = int(self._leftEncoderCount)
        if Sensor.RightEncoderCounts in self._sensorIDs:
            state.rightEncoderCounts = int(self._rightEncoderCount)

        # mode
        if Sensor.OIMode in self._sensorIDs:
            state.mode = self._mode

        # battery
        if Sensor.BatteryCharge in self._sensorIDs:
            state.batteryChargeInMAH = 980
        if Sensor.BatteryCapacity in self._sensorIDs:
            state.batteryCapacityInMAH = 1348

        return state 
Example 80
Project: Django_To_Do   Author: IEEE-VIT   File: base.py    MIT License 4 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.create_function("django_date_extract", 2, _sqlite_datetime_extract)
        conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
        conn.create_function("django_datetime_cast_date", 2, _sqlite_datetime_cast_date)
        conn.create_function("django_datetime_cast_time", 2, _sqlite_datetime_cast_time)
        conn.create_function("django_datetime_extract", 3, _sqlite_datetime_extract)
        conn.create_function("django_datetime_trunc", 3, _sqlite_datetime_trunc)
        conn.create_function("django_time_extract", 2, _sqlite_time_extract)
        conn.create_function("django_time_trunc", 2, _sqlite_time_trunc)
        conn.create_function("django_time_diff", 2, _sqlite_time_diff)
        conn.create_function("django_timestamp_diff", 2, _sqlite_timestamp_diff)
        conn.create_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
        conn.create_function('regexp', 2, _sqlite_regexp)
        conn.create_function('ACOS', 1, none_guard(math.acos))
        conn.create_function('ASIN', 1, none_guard(math.asin))
        conn.create_function('ATAN', 1, none_guard(math.atan))
        conn.create_function('ATAN2', 2, none_guard(math.atan2))
        conn.create_function('CEILING', 1, none_guard(math.ceil))
        conn.create_function('COS', 1, none_guard(math.cos))
        conn.create_function('COT', 1, none_guard(lambda x: 1 / math.tan(x)))
        conn.create_function('DEGREES', 1, none_guard(math.degrees))
        conn.create_function('EXP', 1, none_guard(math.exp))
        conn.create_function('FLOOR', 1, none_guard(math.floor))
        conn.create_function('LN', 1, none_guard(math.log))
        conn.create_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))
        conn.create_function('LPAD', 3, _sqlite_lpad)
        conn.create_function('MOD', 2, none_guard(math.fmod))
        conn.create_function('PI', 0, lambda: math.pi)
        conn.create_function('POWER', 2, none_guard(operator.pow))
        conn.create_function('RADIANS', 1, none_guard(math.radians))
        conn.create_function('REPEAT', 2, none_guard(operator.mul))
        conn.create_function('REVERSE', 1, none_guard(lambda x: x[::-1]))
        conn.create_function('RPAD', 3, _sqlite_rpad)
        conn.create_function('SIN', 1, none_guard(math.sin))
        conn.create_function('SQRT', 1, none_guard(math.sqrt))
        conn.create_function('TAN', 1, none_guard(math.tan))
        conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev))
        conn.create_aggregate('STDDEV_SAMP', 1, list_aggregate(statistics.stdev))
        conn.create_aggregate('VAR_POP', 1, list_aggregate(statistics.pvariance))
        conn.create_aggregate('VAR_SAMP', 1, list_aggregate(statistics.variance))
        conn.execute('PRAGMA foreign_keys = ON')
        return conn