Mirrors of the object found on other sites
516311
def mirrors
      return [] unless self.site.is_mirrored?
      (Cms::Site.mirrored - [self.site]).collect do |site|
        case self
          when Cms::Layout  then site.layouts.find_by_identifier(self.identifier)
          when Cms::Page    then site.pages.find_by_full_path(self.full_path)
          when Cms::Snippet then site.snippets.find_by_identifier(self.identifier)
        end
      end.compact
    end
6145
def have_equivalent_surfaces(self):
        

        # tag the sites as either surface sites or not
        surf_sites_dict = self.get_surface_sites(tag=True)

        a = SpacegroupAnalyzer(self)
        symm_structure = a.get_symmetrized_structure()

        # ensure each site on one surface has a
        # corresponding equivalent site on the other
        equal_surf_sites = []
        for equ in symm_structure.equivalent_sites:
            # Top and bottom are arbitrary, we will just determine
            # if one site is on one side of the slab or the other
            top, bottom = 0, 0
            for s in equ:
                if s.is_surf_site:
                    if s.frac_coords[2] > self.center_of_mass[2]:
                        top += 1
                    else:
                        bottom += 1
            # Check to see if the number of equivalent sites
            # on one side of the slab are equal to the other
            equal_surf_sites.append(top == bottom)

        return all(equal_surf_sites)
1374199
def similarity(self, other):
        """"""
        if self.magnitude == 0 or other.magnitude == 0:
            return 0

        return self.dot(other) / self.magnitude
622339
def hidden(self):
        """"""
        members = [self.member_info(item["_id"]) for item in self.members()]
        result = []
        for member in members:
            if member['rsInfo'].get('hidden'):
                server_id = member['server_id']
                result.append({
                    '_id': member['_id'],
                    'host': self._servers.hostname(server_id),
                    'server_id': server_id})
        return result
282375
void mirror() {
    for (int x = 0; x < bitMatrix.getWidth(); x++) {
      for (int y = x + 1; y < bitMatrix.getHeight(); y++) {
        if (bitMatrix.get(x, y) != bitMatrix.get(y, x)) {
          bitMatrix.flip(y, x);
          bitMatrix.flip(x, y);
        }
      }
    }
  }
182872
def find_base_images(self):
        """"""

        for mountpoint, _ in self.mountpoints.items():
            if re.match(self.orig_re_pattern, mountpoint):
                yield mountpoint
498044
def view_on_site(self, request, content_type_id, object_id):
        
        # Look up the object, making sure it's got a get_absolute_url() function.
        try:
            content_type = ContentType.objects.get(pk=content_type_id)
            if not content_type.model_class():
                raise Http404(_("Content type %(ct_id)s object has no associated model") % {
                    'ct_id': content_type_id,
                })
            obj = content_type.get_object_for_this_type(pk=object_id)
        except (ObjectDoesNotExist, ValueError):
            raise Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {
                'ct_id': content_type_id,
                'obj_id': object_id,
            })

        try:
            get_absolute_url = obj.get_absolute_url
        except AttributeError:
            raise Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") % {
                'ct_name': content_type.name,
            })
        absurl = get_absolute_url()

        return HttpResponseRedirect(absurl)
894837
def _sanity_check_fold_scope_locations_are_unique(ir_blocks):
    """"""
    observed_locations = dict()
    for block in ir_blocks:
        if isinstance(block, Fold):
            alternate = observed_locations.get(block.fold_scope_location, None)
            if alternate is not None:
                raise AssertionError(u'Found two Fold blocks with identical FoldScopeLocations: '
                                     u'{} {} {}'.format(alternate, block, ir_blocks))
            observed_locations[block.fold_scope_location] = block
772271
def cross_correlate(observed, template_dispersion, template_fluxes,
    rebin="template", wavelength_range=None, continuum_degree=-1,
    apodize=0.10, rescale=False, z_limits=None, full_output=False):
    

    template_fluxes = np.atleast_2d(template_fluxes)
    template_dispersion = np.array(template_dispersion)
    if template_dispersion.shape[0] != template_fluxes.shape[1]:
        raise ValueError("template dispersion must have size (N_pixels,) and "\
            "template fluxes must have size (N_models, N_pixels)")

    try:
        continuum_degree = int(continuum_degree)
    except (TypeError, ValueError):
        raise TypeError("continuum order must be an integer-like object")

    if not (1 > apodize >= 0):
        raise ValueError("apodize fraction must be between 0 and 1")

    if rebin.lower() == "template":
        # Put the template fluxes onto the observed dispersion map.
        dispersion = observed.disp
        template_flux = template_fluxes \
            * resample(template_dispersion, observed.disp)
        observed_flux = observed.flux.copy()
        observed_ivar = observed.ivariance.copy()

    elif rebin.lower() == "observed":
        # Put the observed fluxes onto the template dispersion map.
        dispersion = template_dispersion
        template_flux = template_fluxes
        mat = resample(observed.disp, template_dispersion)
        observed_flux = observed.flux.copy() * mat
        observed_ivar = observed.ivariance.copy() * mat
        
    else:
        raise ValueError("rebin must be either `template` or `observed`")

    if wavelength_range is not None:
        if not isinstance(wavelength_range, (tuple, list, np.ndarray)) \
        or len(wavelength_range) != 2:
            raise TypeError("wavelength range must be a two length tuple")

        indices = np.clip(
            template_dispersion.searchsorted(wavelength_range) + [0, 1],
            0, template_dispersion.size)
        template_dispersion = template_dispersion[indices[0]:indices[1]]
        template_flux = template_flux[indices[0]:indices[1]]
        observed_flux = observed_flux[indices[0]:indices[1]]

    N_templates = template_fluxes.shape[0]

    # Clip out the non-finite edges, if they exist.
    _ = np.where(np.isfinite(template_flux[0] * observed_flux))[0]
    l_idx, u_idx = _[0], _[-1]

    dispersion = dispersion[l_idx:u_idx]
    observed_flux = observed_flux[l_idx:u_idx]
    observed_ivar = observed_ivar[l_idx:u_idx]
    template_flux = template_flux[:, l_idx:u_idx]

    # Ensure an even number of points.
    N = u_idx - l_idx
    N = N - 1 if N % 2 > 0 else N
    dispersion = dispersion[:N]
    observed_flux = observed_flux[:N]
    observed_ivar = observed_ivar[:N]
    template_flux = template_flux[:, :N]

    finite = np.isfinite(observed_flux * observed_ivar) * (observed_flux > 1e-3)
    
    # Continuum.
    if continuum_degree >= 0:
        coefficients = np.polyfit(dispersion[finite], observed_flux[finite],
            continuum_degree)
        observed_flux /= np.polyval(coefficients, dispersion)

    # Interpolate over non-finite pixels.
    observed_flux[~finite] = np.interp(dispersion[~finite], dispersion[finite],
        observed_flux[finite], left=1, right=1)

    # Scale the flux level to that the template intensities
    if rescale:
        observed_flux = (observed_flux * template_flux.ptp()) \
            + template_flux.min()

    # Apodize edges.
    edge_buffer = apodize * (dispersion[-1] - dispersion[0])
    low_w_indices = np.nonzero(dispersion < dispersion[0] + edge_buffer)[0]
    high_w_indices = np.nonzero(dispersion > dispersion[-1] - edge_buffer)[0]

    apod_curve = np.ones(N, dtype='d')
    apod_curve[low_w_indices] = (1.0 + np.cos(np.pi*(
        1.0 - (dispersion[low_w_indices] - dispersion[0])/edge_buffer)))/2.
    apod_curve[high_w_indices] = (1.0 + np.cos(np.pi*(
        1.0 - (dispersion[-1] - dispersion[high_w_indices])/edge_buffer)))/2.

    apod_observed_flux = observed_flux * apod_curve
    apod_template_flux = template_flux * apod_curve

    fft_observed_flux = np.fft.fft(apod_observed_flux)
    fft_template_flux = np.fft.fft(apod_template_flux)
    template_flux_corr = (fft_observed_flux * fft_template_flux.conjugate())
    template_flux_corr /= np.sqrt(
        np.inner(apod_observed_flux, apod_observed_flux))

    z_array = np.array(dispersion.copy())/dispersion[N/2] - 1.0

    z = np.ones(N_templates) * np.nan
    z_err = np.ones(N_templates) * np.nan
    R = np.ones(N_templates) * np.nan
    for i in range(N_templates):

        denominator = np.sqrt(
            np.inner(apod_template_flux[i, :], apod_template_flux[i, :]))
        flux_correlation = template_flux_corr[i, :] / denominator 
        correlation = np.fft.ifft(flux_correlation).real

        # Reflect about zero
        ccf = np.zeros(N)
        ccf[:N/2] = correlation[N/2:]
        ccf[N/2:] = correlation[:N/2]

        # Get height and redshift of best peak
        h = ccf.max()

        # Scale the CCF
        #ccf -= ccf.min()
        #ccf *= (h/ccf.max())
        
        R[i] = h
        z[i] = z_array[ccf.argmax()]
        try:
            z_err[i] = (np.ptp(z_array[np.where(ccf >= 0.5*h)])/2.35482)**2
        except ValueError:
            continue

    # Limits:
    if z_limits is not None:
        R[~((z_limits[1] >= z) * (z >= z_limits[0]))] = np.nan

    # Re-measure the velocity at the best peak.
    index = np.nanargmax(R)

    denominator = np.sqrt(
        np.inner(apod_template_flux[index, :], apod_template_flux[index, :]))

    flux_correlation = template_flux_corr[index, :] / denominator
    correlation = np.fft.ifft(flux_correlation).real

    # FReflect about zero.
    ccf = np.zeros(N)
    ccf[:N/2] = correlation[N/2:]
    ccf[N/2:] = correlation[:N/2]

    h = ccf.max()
    ccf -= ccf.min()
    ccf *= h/ccf.max()

    # Fit +/- 5 pixels
    idx = np.argmax(ccf) - 3, np.argmax(ccf) + 3

    coeffs = np.polyfit(z_array[idx[0]:idx[1]], ccf[idx[0]:idx[1]], 2)
    x_i = np.linspace(z_array[idx[0]], z_array[idx[1]], 1000)
    y_i = np.polyval(coeffs, x_i)

    # Update the value
    z[index] = x_i[y_i.argmax()]

    """
    # Fit the profile peak.
    fwhm = np.ptp(z_array[np.where(ccf >= 0.5)])
    p0 = np.array([z[index], fwhm/2.355, 1.0]) # mu, sigma, peak.
    use = (z_array > (p0[0] - 3 * p0[1])) * ((p0[0] + 3*p0[1]) > z_array)
    x, y = z_array[use], ccf[use]

    # Fit profile:
    f = lambda x, mu, sigma, peak: peak * np.exp(-(mu - x)**2/(2*sigma**2)) 
    
    import matplotlib.pyplot as plt
    plt.plot(z_array, ccf, c='k')
    plt.plot(x, y, c='b')
    plt.plot(x, f(x, *p0), c='r')

    p1 = curve_fit(f, x, y, p0=p0)
    plt.plot(x, f(x, *p1[0]), c='m')

    plt.gca().set_ylim(0,1)
    raise a

    p1 = curve_fit(f, x, y, p0=p0)
    """

    return (z * c, z_err * c, R)
1110923
def reflect(src, roffset, rpercent, rstrength)
      tmp_cc = Cairo::Context.new(Cairo::ImageSurface.new(src.width, src.height * (1.0 + rpercent) + roffset))
      tmp_cc.set_source(src, 0, 0)
      tmp_cc.paint
      # Flip affine magic from: http://cairographics.org/matrix_transform/
      matrix = Cairo::Matrix.new(1, 0, 0, -1, 0, 2 * src.height + roffset)
      tmp_cc.transform(matrix) # flips the coordinate system
      top_y    = src.height    # top of the reflection
      bottom_y = src.height * (1.0 - rpercent) + roffset # bottom of the reflection
      gradient = Cairo::LinearPattern.new(0, top_y, 0, bottom_y)
      gradient.add_color_stop_rgba(0.0, 0, 0, 0, rstrength) # start a little reflected
      gradient.add_color_stop_rgba(1.0, 0, 0, 0, 0.0)       # fade to nothing
      tmp_cc.set_source(src, 0, 0)
      tmp_cc.mask(gradient)
      return tmp_cc.target
    end
833747
def detect_images_and_galleries(generators):
    """"""
    for generator in generators:
        if isinstance(generator, ArticlesGenerator):
            for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
                detect_image(generator, article)
                detect_gallery(generator, article)
        elif isinstance(generator, PagesGenerator):
            for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):
                detect_image(generator, page)
                detect_gallery(generator, page)
1279630
def get_organized_repos(repos)
      forks = []
      publics = []
      mirrors = []
      privates = []
      repos.each do |r|
        repo_name = r[:full_name]
        forks << repo_name if r[:fork]

        if r[:private]
          privates << repo_name
        else
          publics << repo_name
        end

        mirrors << repo_name unless r[:mirror_url].nil?
      end

      {
        public: publics,
        forks: forks,
        mirrors: mirrors,
        privates: privates
      }
    end
8073
function mirrorProperties(src, dest = {}) {
  function set(name) { dest[name] = src[name]; }
  function _delete(name) { delete dest[name]; }

  var handlers = { add: set, update: set, delete: _delete};

  assign(dest, src);
  observe(src, makeObserver(handlers));
  return dest;
}
932416
def fixations(self):
        ''' '''
        if not self._fixations:
            raise RuntimeError('This Images object does not have'
                +' an associated fixmat')
        if len(list(self._categories.keys())) == 0:
            return None
        else:
            idx = np.zeros(self._fixations.x.shape, dtype='bool')
            for (cat, _) in list(self._categories.items()):
                idx = idx | ((self._fixations.category == cat))
            return self._fixations[idx]
245812
function detectIntersection(a, b) {
  if (a instanceof Sphere) {
    if (b instanceof Sphere) {
      return sphereCollisionDetection.sphereVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return sphereCollisionDetection.sphereVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return sphereCollisionDetection.sphereVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return sphereCollisionDetection.sphereVsObb(a, b);
    } else {
      return sphereCollisionDetection.sphereVsPoint(a, b);
    }
  } else if (a instanceof Aabb) {
    if (b instanceof Sphere) {
      return aabbCollisionDetection.aabbVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return aabbCollisionDetection.aabbVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return aabbCollisionDetection.aabbVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return aabbCollisionDetection.aabbVsObb(a, b);
    } else {
      return aabbCollisionDetection.aabbVsPoint(a, b);
    }
  } else if (a instanceof Capsule) {
    if (b instanceof Sphere) {
      return capsuleCollisionDetection.capsuleVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return capsuleCollisionDetection.capsuleVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return capsuleCollisionDetection.capsuleVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return capsuleCollisionDetection.capsuleVsObb(a, b);
    } else {
      return capsuleCollisionDetection.capsuleVsPoint(a, b);
    }
  } else if (a instanceof Obb) {
    if (b instanceof Sphere) {
      return obbCollisionDetection.obbVsSphere(a, b);
    } else if (b instanceof Aabb) {
      return obbCollisionDetection.obbVsAabb(a, b);
    } else if (b instanceof Capsule) {
      return obbCollisionDetection.obbVsCapsule(a, b);
    } else if (b instanceof Obb) {
      return obbCollisionDetection.obbVsObb(a, b);
    } else {
      return obbCollisionDetection.obbVsPoint(a, b);
    }
  } else {
    if (b instanceof Sphere) {
      return sphereCollisionDetection.sphereVsPoint(b, a);
    } else if (b instanceof Aabb) {
      return aabbCollisionDetection.aabbVsPoint(b, a);
    } else if (b instanceof Capsule) {
      return capsuleCollisionDetection.capsuleVsPoint(b, a);
    } else if (b instanceof Obb) {
      return obbCollisionDetection.obbVsPoint(b, a);
    } else {
      return false;
    }
  }
}
1198864
function () {
      var doUniqueSlotIdsCheck = function (elementary) {
        var duplicateSlotIds = [];
        elementary.slots.forEach(function (slot) {
          var slotId = slot.slotId;

          function filterBySlotId (slot) {
            return slot.slotId === slotId;
          }

          var arrayByUniqueSlotIds = elementary.slots.filter(filterBySlotId);
          if (arrayByUniqueSlotIds.length > 1 && duplicateSlotIds.indexOf(slotId) < 0) {
            duplicateSlotIds.push(slotId);
          }
        });
        duplicateSlotIds.forEach(function (slotId) {
          errors.push('RuleViolation identified: Artifact \'' + elementary.artifactId +
            '\' contains multiple slots with \'slotId\'=\'' + slotId + '\'');
        });
      };
      //
      if (doc.artifacts && doc.artifacts.elementaryComponents) {
        doc.artifacts.elementaryComponents.forEach(function (elementary) {
          if (elementary.slots) {
            doUniqueSlotIdsCheck(elementary);
          }
        });
      }
    }
913634
function(obj) {
        var key;
        var mirrored = {};

        if ( obj && typeof obj === 'object' ) {
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    mirrored[key] = key;
                }
            }
        }
        return mirrored;
    }