text:
from utilities import to_column_vector, int_to_bits, bits_to_int

import numpy as np

class Constellation:
    """A mapping m: ℤ2^n → ℝ^K."""
    @classmethod
    def uniform(cls, n):
        "Equidistant points (K = 1)."

        # {-(2^n - 1), -(2^n - 3), ..., 2^n - 3, 2^n - 1} (2^n integers)
        ints = 2 * np.arange(2**n) - (2**n - 1)

        return cls(n, 1, [np.array([x]) for x in ints])

    @classmethod
    def cartesian_product(cls, *constellations, repeat=None):
        # Cartesian power
        if repeat is not None:
            (constellation,) = constellations
            return cls.cartesian_product(*(repeat * [constellation]))

        if len(constellations) == 1:
            return constellations[0]
        else:
            last = constellations[-1]
            init = constellations[:-1]
            inner = cls.cartesian_product(*init)

            points = [np.concatenate((p, q))
                    for p in inner.points for q in last.points]

            return cls(inner.n + last.n, inner.K + last.K, points)

    def __init__(self, n, K, points):
        for p in points:
            if type(p) != np.ndarray:
                raise ValueError(
                        "Point not of type numpy.ndarray: {}" .format(p))

        self.n = n
        self.K = K
        self.points = points

    def modulate(self, bits):
        return list(self.points[bits_to_int(bits)])

    def demodulate(self, point):
        index = min(range(2**self.n),
                key=lambda i: norm_sq(point - self.points[i]))
        return int_to_bits(index, self.n)

    def metric_increment(self, SNR, bias, received, codeword):
        # Real-valued codewords
        assert all(isinstance(z, float) for z in received.flatten())

        return (1 - bias) * self.n \
                - SNR / (2 * np.log(2)) \
                    * norm_sq(received -
                            to_column_vector(self.modulate(codeword))) \
                - np.log2(sum(np.exp(-SNR/2 * norm_sq(
                                    received - to_column_vector(point)))
                              for point in self.points))

    def normalize(self, new_power=1):
        """Normalize so that the average power is 1."""
        power = np.mean([norm_sq(p) for p in self.points])
        factor = np.sqrt(new_power / power)
        new_points = [factor * p for p in self.points]

        return self.__class__(self.n, self.K, new_points)

def norm_sq(x):
    return np.sum(x**2)


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Airy Ai' Function</title>
<link rel="stylesheet" href="../../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Math Toolkit 2.1.0">
<link rel="up" href="../airy.html" title="Airy Functions">
<link rel="prev" href="bi.html" title="Airy Bi Function">
<link rel="next" href="bip.html" title="Airy Bi' Function">

Home
Libraries
People
FAQ
More

Airy Ai' Function

        Synopsis

#include <boost/math/special_functions/airy.hpp>

namespace boost { namespace math {

 template <class T>
 calculated-result-type airy_ai_prime(T x);

 template <class T, class Policy>
 calculated-result-type airy_ai_prime(T x, const Policy&);

}} // namespaces

        Description

        The function airy_ai_prime calculates
        the Airy function Ai' which is the derivative of the first solution to the
        differential equation:

        The final Policy argument is optional and can
        be used to control the behaviour of the function: how it handles errors,
        what level of precision to use etc. Refer to the policy
        documentation for more details.

        The following graph illustrates how this function changes as x
        changes: for negative x the function is cyclic, while
        for positive x the value tends to zero:

        Accuracy

        This function is implemented entirely in terms of the Bessel functions cyl_bessel_j and cyl_bessel_k - refer to those
        functions for detailed accuracy information.

        In general though, the relative error is low (less than 100 ε) for x
        > 0 while only the absolute error is low for x <
        0.

        Testing

        Since this function is implemented in terms of other special functions, there
        are only a few basic sanity checks, using test values from functions.wolfram.com.

        Implementation

        This function is implemented in terms of the Bessel functions using the relations:

Copyright © 2006-2010, 2012-2014 Nikhar Agrawal,
      Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert
      Holin, Bruno Lalande, John Maddock, Johan Råde, Gautam Sewani, Benjamin Sobotta,
      Thijs van den Berg, Daryle Walker and Xiaogang Zhang

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

redpajama_set_name: RedPajamaGithub


text:
describe("CachedStrategy", function() {
  beforeEach(function() {
    jasmine.Clock.useMock();
  });

  describe("after calling isSupported", function() {
    it("should return true when the substrategy is supported", function() {
      var substrategy = Pusher.Mocks.getStrategy(true);
      var strategy = new Pusher.CachedStrategy(substrategy, {}, {});
      expect(strategy.isSupported()).toBe(true);
    });

    it("should return false when the substrategy is not supported", function() {
      var substrategy = Pusher.Mocks.getStrategy(false);
      var strategy = new Pusher.CachedStrategy(substrategy, {}, {});
      expect(strategy.isSupported()).toBe(false);
    });
  });

  describe("on browsers not supporting localStorage", function() {
    beforeEach(function() {
      spyOn(Pusher.Util, "getLocalStorage").andReturn(undefined);
    });

    it("should try the substrategy immediately", function() {
      var substrategy = Pusher.Mocks.getStrategy(false);
      var strategy = new Pusher.CachedStrategy(substrategy, {}, {});
      var callback = jasmine.createSpy("callback");
      strategy.connect(0, callback);
      expect(substrategy.connect).toHaveBeenCalled();
    });
  });

  describe("on browsers supporting localStorage", function() {
    var localStorage;

    beforeEach(function() {
      localStorage = {};
      spyOn(Pusher.Util, "getLocalStorage").andReturn(localStorage);
    });

    function buildCachedTransportTests(encrypted) {
      var ENCRYPTED_KEY = "pusherTransportEncrypted";
      var UNENCRYPTED_KEY = "pusherTransportUnencrypted";

      var usedKey = encrypted ? ENCRYPTED_KEY : UNENCRYPTED_KEY;
      var unusedKey = encrypted ? UNENCRYPTED_KEY : ENCRYPTED_KEY;

      var substrategy, transports, timeline;
      var strategy;
      var callback;

      beforeEach(function() {
        substrategy = Pusher.Mocks.getStrategy(true);
        transports = {
          test: Pusher.Mocks.getStrategy(true)
        };
        timeline = Pusher.Mocks.getTimeline();

        strategy = new Pusher.CachedStrategy(substrategy, transports, {
          encrypted: encrypted,
          timeline: timeline
        });
        callback = jasmine.createSpy("callback");
      });

      describe("without cached transport, encrypted=" + encrypted, function() {
        beforeEach(function() {
          delete localStorage[usedKey];
          localStorage[unusedKey] = "mock";
        });

        it("should not report anything to timeline", function() {
          strategy.connect(0, callback);
          expect(timeline.info).not.toHaveBeenCalled();
        });

        it("should try the substrategy immediately when cache is empty", function() {
          strategy.connect(0, callback);
          expect(substrategy.connect).toHaveBeenCalled();
        });

        it("should try the substrategy immediately when cache is stale", function() {
          localStorage[usedKey] = JSON.stringify({
            timestamp: Pusher.Util.now() - 1801*1000 // default ttl is 1800s
          });

          strategy.connect(0, callback);
          expect(substrategy.connect).toHaveBeenCalled();
        });

        it("should abort the substrategy when requested", function() {
          var runner = strategy.connect(0, callback);
          runner.abort();
          expect(substrategy._abort).toHaveBeenCalled();
        });

        describe("on forceMinPriority", function() {
          it("should force the new priority on the substrategy", function() {
            var runner = strategy.connect(0, callback);
            runner.forceMinPriority(10);
            expect(substrategy._forceMinPriority).toHaveBeenCalledWith(10);
          });
        });

        describe("after connecting successfully", function() {
          var transport;
          var startTimestamp;

          beforeEach(function() {
            startTimestamp = Pusher.Util.now();
            spyOn(Pusher.Util, "now").andReturn(startTimestamp);

            strategy.connect(0, callback);
            Pusher.Util.now.andReturn(startTimestamp + 1000);

            transport = Pusher.Mocks.getTransport(true);
            transport.name = "test";
            substrategy._callback(null, { transport: transport });
          });

          it("should call back with the transport", function() {
            expect(callback).toHaveBeenCalledWith(null, {
              transport: transport
            });
          });

          it("should cache the connected transport", function() {
            expect(JSON.parse(localStorage[usedKey])).toEqual({
              timestamp: Pusher.Util.now(),
              transport: "test",
              latency: 1000
            });
            expect(localStorage[unusedKey]).toEqual("mock");
          });
        });

        describe("after receiving an error", function() {
          beforeEach(function() {
            // set a very low timestamp to have something unused in the cache
            localStorage[usedKey] = JSON.stringify({
              timestamp: 0
            });
            strategy.connect(0, callback);
            substrategy._callback(1);
          });

          it("should call back after receiving an error from the substrategy", function() {
            expect(callback).toHaveBeenCalledWith(1);
          });

          it("should flush the appropriate transport cache", function() {
            expect(localStorage.pusherTransport).toBe(undefined);
            expect(localStorage[unusedKey]).toEqual("mock");
          });
        });
      });

      describe("with cached transport, encrypted=" + encrypted, function() {
        var t0 = Pusher.Util.now();

        beforeEach(function() {
          cachedStrategy = Pusher.Mocks.getStrategy(true);
          localStorage[usedKey] = JSON.stringify({
            timestamp: t0,
            transport: "test",
            latency: 1000
          });
          localStorage[unusedKey] = "mock";
        });

        it("should try the cached strategy first", function() {
          strategy.connect(0, callback);
          expect(transports.test.connect).toHaveBeenCalled();
        });

        it("should report to timeline when using cached strategy", function() {
          strategy.connect(0, callback);
          expect(timeline.info).toHaveBeenCalledWith({
            cached: true,
            transport: "test",
            latency: 1000
          });
        });

        it("should abort the cached transport and not call the substrategy", function() {
          var runner = strategy.connect(0, callback);
          runner.abort();
          expect(transports.test._abort).toHaveBeenCalled();
          expect(substrategy.connect).not.toHaveBeenCalled();
        });

        describe("on forceMinPriority", function() {
          it("should force the new priority on the cached strategy", function() {
            var runner = strategy.connect(0, callback);
            runner.forceMinPriority(1000);
            expect(transports.test._forceMinPriority).toHaveBeenCalledWith(1000);
          });
        });

        describe("after connecting successfully with the cached transport", function() {
          var transport;

          beforeEach(function() {
            startTimestamp = Pusher.Util.now();
            spyOn(Pusher.Util, "now").andReturn(startTimestamp);

            strategy.connect(0, callback);
            Pusher.Util.now.andReturn(startTimestamp + 2000);

            transport = Pusher.Mocks.getTransport(true);
            transport.name = "test";
            transport.options = { encrypted: false };
            transports.test._callback(null, { transport: transport });
          });

          it("should call back with the transport", function() {
            expect(callback).toHaveBeenCalledWith(null, { transport: transport });
          });

          it("should not try the substrategy", function() {
            expect(substrategy.connect).not.toHaveBeenCalled();
          });

          it("should cache the connected transport", function() {
            expect(JSON.parse(localStorage[usedKey])).toEqual({
              timestamp: Pusher.Util.now(),
              transport: "test",
              latency: 2000
            });
            expect(localStorage[unusedKey]).toEqual("mock");
          });
        });

        describe("after double the cached latency + 1s", function() {
          beforeEach(function() {
            startTimestamp = Pusher.Util.now();
            spyOn(Pusher.Util, "now").andReturn(startTimestamp);

            strategy.connect(0, callback);

            Pusher.Util.now.andReturn(startTimestamp + 3000);
            jasmine.Clock.tick(3000);
          });

          it("should abort the cached strategy", function() {
            expect(transports.test._abort).toHaveBeenCalled();
          });

          it("should fall back to the substrategy", function() {
            expect(substrategy.connect).toHaveBeenCalled();
          });

          it("should flush the appropriate transport cache", function() {
            expect(localStorage[usedKey]).toBe(undefined);
            expect(localStorage[unusedKey]).toEqual("mock");
          });
        });

        describe("after failing to connect with the cached transport", function() {
          var runner;

          beforeEach(function() {
            startTimestamp = Pusher.Util.now();
            spyOn(Pusher.Util, "now").andReturn(startTimestamp);

            runner = strategy.connect(0, callback);
            runner.forceMinPriority(666);
            Pusher.Util.now.andReturn(startTimestamp + 2000);
            transports.test._callback("error");
            Pusher.Util.now.andReturn(startTimestamp + 2500);
          });

          it("should fall back to the substrategy", function() {
            expect(substrategy.connect).toHaveBeenCalled();
          });

          it("should flush the appropriate transport cache", function() {
            expect(localStorage[usedKey]).toBe(undefined);
            expect(localStorage[unusedKey]).toEqual("mock");
          });

          it("should abort the substrategy when requested", function() {
            runner.abort();
            expect(cachedStrategy._abort).not.toHaveBeenCalled();
            expect(substrategy._abort).toHaveBeenCalled();
          });

          describe("on forceMinPriority", function() {
            it("should force the previously set priority on the substrategy", function() {
              // priority is forced in beforeEach
              expect(substrategy.connect)
                .toHaveBeenCalledWith(666, jasmine.any(Function));
            });

            it("should force the new priority on the substrategy", function() {
              runner.forceMinPriority(3);
              expect(substrategy._forceMinPriority).toHaveBeenCalledWith(3);
            });
          });

          describe("and connecting successfully using the substrategy", function() {
            var transport;

            beforeEach(function() {
              connection = {
                name: "test",
                options: { encrypted: true, "hostEncrypted": "example.net" }
              };

              transport = Pusher.Mocks.getTransport(true);
              transport.name = "test";
              substrategy._callback(null, { transport: transport });
            });

            it("should call back with the connection", function() {
              expect(callback).toHaveBeenCalledWith(null, {
                transport: transport
              });
            });

            it("should cache the connected transport", function() {
              expect(JSON.parse(localStorage[usedKey])).toEqual({
                timestamp: Pusher.Util.now(),
                transport: "test",
                latency: 500
              });
              expect(localStorage[unusedKey]).toEqual("mock");
            });
          });

          describe("and failing to connect using the substrategy", function() {
            beforeEach(function() {
              substrategy._callback("error again");
            });

            it("should call back with the error", function() {
              expect(callback).toHaveBeenCalledWith("error again");
            });

            it("should flush the appropriate transport cache", function() {
              expect(localStorage[usedKey]).toBe(undefined);
              expect(localStorage[unusedKey]).toEqual("mock");
            });
          });
        });
      });
    }

    buildCachedTransportTests(false);
    buildCachedTransportTests(true);
  });
});


text:
header {
  background-color: purple;
    padding: 10px;
}

.column-1 {
    background-color: green;
    float: left;
    box-sizing: border-box;
    width: 50%;
    padding: 10px;
}

.column-2 {
    background-color: magenta;
    float: left;
    box-sizing: border-box;
    width: 50%;
    padding: 10px;
    height: 100%;
}

footer {
    background-color: brown;
    clear: both;
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.ServiceModel.Channels
{
  internal partial interface IConnectionOrientedTransportFactorySettings : ITransportFactorySettings, System.ServiceModel.IDefaultCommunicationTimeouts, IConnectionOrientedConnectionSettings
  {
    #region Properties and indexers
    System.ServiceModel.Description.ServiceSecurityAuditBehavior AuditBehavior
    {
      get;
    }

    int MaxBufferSize
    {
      get;
    }

    System.ServiceModel.TransferMode TransferMode
    {
      get;
    }

    StreamUpgradeProvider Upgrade
    {
      get;
    }
    #endregion
  }
}


text:
import os, sys, glob, shutil, time
import _winreg as winreg

# Send output somewhere so it can be found if necessary...
import tempfile
tee_f = open(os.path.join(tempfile.gettempdir(), 'pywin32_postinstall.log'), "w")
class Tee:
    def __init__(self, file):
        self.f = file
    def write(self, what):
        if self.f is not None:
            try:
                self.f.write(what.replace("\n", "\r\n"))
            except IOError:
                pass
        tee_f.write(what)
    def flush(self):
        if self.f is not None:
            try:
                self.f.flush()
            except IOError:
                pass
        tee_f.flush()

# For some unknown reason, when running under bdist_wininst we will start up
# with sys.stdout as None but stderr is hooked up. This work-around allows
# bdist_wininst to see the output we write and display it at the end of
# the install.
if sys.stdout is None:
    sys.stdout = sys.stderr

sys.stderr = Tee(sys.stderr)
sys.stdout = Tee(sys.stdout)

com_modules = [
    # module_name,                      class_names
    ("win32com.servers.interp",         "Interpreter"),
    ("win32com.servers.dictionary",     "DictionaryPolicy"),
    ("win32com.axscript.client.pyscript","PyScript"),
]

# Is this a 'silent' install - ie, avoid all dialogs.
# Different than 'verbose'
silent = 0

# Verbosity of output messages.
verbose = 1

ver_string = "%d.%d" % (sys.version_info[0], sys.version_info[1])
root_key_name = "Software\\Python\\PythonCore\\" + ver_string

try:
    # When this script is run from inside the bdist_wininst installer,
    # file_created() and directory_created() are additional builtin
    # functions which write lines to Python23\pywin32-install.log. This is
    # a list of actions for the uninstaller, the format is inspired by what
    # the Wise installer also creates.
    file_created
    is_bdist_wininst = True
except NameError:
    is_bdist_wininst = False # we know what it is not - but not what it is :)
    def file_created(file):
        pass
    def directory_created(directory):
        pass
    def get_root_hkey():
        try:
            winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                           root_key_name, 0, winreg.KEY_CREATE_SUB_KEY)
            return winreg.HKEY_LOCAL_MACHINE
        except OSError, details:
            # Either not exist, or no permissions to create subkey means
            # must be HKCU
            return winreg.HKEY_CURRENT_USER

try:
    create_shortcut
except NameError:
    # Create a function with the same signature as create_shortcut provided
    # by bdist_wininst
    def create_shortcut(path, description, filename,
                        arguments="", workdir="", iconpath="", iconindex=0):
        import pythoncom
        from win32com.shell import shell, shellcon

        ilink = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
                                           pythoncom.CLSCTX_INPROC_SERVER,
                                           shell.IID_IShellLink)
        ilink.SetPath(path)
        ilink.SetDescription(description)
        if arguments:
            ilink.SetArguments(arguments)
        if workdir:
            ilink.SetWorkingDirectory(workdir)
        if iconpath or iconindex:
            ilink.SetIconLocation(iconpath, iconindex)
        # now save it.
        ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile)
        ipf.Save(filename, 0)

    # Support the same list of "path names" as bdist_wininst.
    def get_special_folder_path(path_name):
        import pythoncom
        from win32com.shell import shell, shellcon

        for maybe in """
            CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA
            CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY
            CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP
            CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON
            CSIDL_PROGRAM_FILES CSIDL_FONTS""".split():
            if maybe == path_name:
                csidl = getattr(shellcon, maybe)
                return shell.SHGetSpecialFolderPath(0, csidl, False)
        raise ValueError("%s is an unknown path ID" % (path_name,))

def CopyTo(desc, src, dest):
    import win32api, win32con
    while 1:
        try:
            win32api.CopyFile(src, dest, 0)
            return
        except win32api.error, details:
            if details.winerror==5: # access denied - user not admin.
                raise
            if silent:
                # Running silent mode - just re-raise the error.
                raise
            tb = None
            full_desc = "Error %s\n\n" \
                        "If you have any Python applications running, " \
                        "please close them now\nand select 'Retry'\n\n%s" \
                        % (desc, details.strerror)
            rc = win32api.MessageBox(0,
                                     full_desc,
                                     "Installation Error",
                                     win32con.MB_ABORTRETRYIGNORE)
            if rc == win32con.IDABORT:
                raise
            elif rc == win32con.IDIGNORE:
                return
            # else retry - around we go again.

# We need to import win32api to determine the Windows system directory,
# so we can copy our system files there - but importing win32api will
# load the pywintypes.dll already in the system directory preventing us
# from updating them!
# So, we pull the same trick pywintypes.py does, but it loads from
# our pywintypes_system32 directory.
def LoadSystemModule(lib_dir, modname):
    # See if this is a debug build.
    import imp
    for suffix_item in imp.get_suffixes():
        if suffix_item[0]=='_d.pyd':
            suffix = '_d'
            break
    else:
        suffix = ""
    filename = "%s%d%d%s.dll" % \
               (modname, sys.version_info[0], sys.version_info[1], suffix)
    filename = os.path.join(lib_dir, "pywin32_system32", filename)
    mod = imp.load_dynamic(modname, filename)

def SetPyKeyVal(key_name, value_name, value):
    root_hkey = get_root_hkey()
    root_key = winreg.OpenKey(root_hkey, root_key_name)
    try:
        my_key = winreg.CreateKey(root_key, key_name)
        try:
            winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value)
        finally:
            my_key.Close()
    finally:
        root_key.Close()
    if verbose:
        print "-> %s\\%s[%s]=%r" % (root_key_name, key_name, value_name, value)

def RegisterCOMObjects(register = 1):
    import win32com.server.register
    if register:
        func = win32com.server.register.RegisterClasses
    else:
        func = win32com.server.register.UnregisterClasses
    flags = {}
    if not verbose:
        flags['quiet']=1
    for module, klass_name in com_modules:
        __import__(module)
        mod = sys.modules[module]
        flags["finalize_register"] = getattr(mod, "DllRegisterServer", None)
        flags["finalize_unregister"] = getattr(mod, "DllUnregisterServer", None)
        klass = getattr(mod, klass_name)
        func(klass, **flags)

def RegisterPythonwin(register=True):
    """ Add (or remove) Pythonwin to context menu for python scripts.
        ??? Should probably also add Edit command for pys files also.
        Also need to remove these keys on uninstall, but there's no function
            like file_created to add registry entries to uninstall log ???
    """
    import os, distutils.sysconfig

    lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1)
    classes_root=get_root_hkey()
    ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build,
    pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe")
    pythonwin_edit_command=pythonwin_exe + ' /edit "%1"'

    keys_vals = [
        ('Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Pythonwin.exe', '', pythonwin_exe),
        ('Software\\Classes\\Python.File\\shell\\Edit with Pythonwin', 'command', pythonwin_edit_command),
        ('Software\\Classes\\Python.NoConFile\\shell\\Edit with Pythonwin', 'command', pythonwin_edit_command),
        ]

    try:
        if register:
            for key, sub_key, val in keys_vals:
                ## Since winreg only uses the character Api functions, this can fail if Python
                ##  is installed to a path containing non-ascii characters
                hkey = winreg.CreateKey(classes_root, key)
                if sub_key:
                    hkey = winreg.CreateKey(hkey, sub_key)
                winreg.SetValueEx(hkey, None, 0, winreg.REG_SZ, val)
                hkey.Close()
        else:
            for key, sub_key, val in keys_vals:
                try:
                    winreg.DeleteKey(classes_root, key)
                except OSError, why:
                    winerror = getattr(why, 'winerror', why.errno)
                    if winerror != 2: # file not found
                        raise
    finally:
        # tell windows about the change
        from win32com.shell import shell, shellcon
        shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None)

def get_shortcuts_folder():
    if get_root_hkey()==winreg.HKEY_LOCAL_MACHINE:
        try:
            fldr = get_special_folder_path("CSIDL_COMMON_PROGRAMS")
        except OSError:
            # No CSIDL_COMMON_PROGRAMS on this platform
            fldr = get_special_folder_path("CSIDL_PROGRAMS")
    else:
        # non-admin install - always goes in this user's start menu.
        fldr = get_special_folder_path("CSIDL_PROGRAMS")

    try:
        install_group = winreg.QueryValue(get_root_hkey(),
                                           root_key_name + "\\InstallPath\\InstallGroup")
    except OSError:
        vi = sys.version_info
        install_group = "Python %d.%d" % (vi[0], vi[1])
    return os.path.join(fldr, install_group)

# Get the system directory, which may be the Wow64 directory if we are a 32bit
# python on a 64bit OS.
def get_system_dir():
    import win32api # we assume this exists.
    try:
        import pythoncom
        import win32process
        from win32com.shell import shell, shellcon
        try:
            if win32process.IsWow64Process():
                return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEMX86)
            return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEM)
        except (pythoncom.com_error, win32process.error):
            return win32api.GetSystemDirectory()
    except ImportError:
        return win32api.GetSystemDirectory()

def fixup_dbi():
    # We used to have a dbi.pyd with our .pyd files, but now have a .py file.
    # If the user didn't uninstall, they will find the .pyd which will cause
    # problems - so handle that.
    import win32api, win32con
    pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd")
    pyd_d_name = os.path.join(os.path.dirname(win32api.__file__), "dbi_d.pyd")
    py_name = os.path.join(os.path.dirname(win32con.__file__), "dbi.py")
    for this_pyd in (pyd_name, pyd_d_name):
        this_dest = this_pyd + ".old"
        if os.path.isfile(this_pyd) and os.path.isfile(py_name):
            try:
                if os.path.isfile(this_dest):
                    print "Old dbi '%s' already exists - deleting '%s'" % (this_dest, this_pyd)
                    os.remove(this_pyd)
                else:
                    os.rename(this_pyd, this_dest)
                    print "renamed '%s'->'%s.old'" % (this_pyd, this_pyd)
                    file_created(this_pyd+".old")
            except os.error, exc:
                print "FAILED to rename '%s': %s" % (this_pyd, exc)

def install():
    import distutils.sysconfig
    import traceback
    # The .pth file is now installed as a regular file.
    # Create the .pth file in the site-packages dir, and use only relative paths
    lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1)
    # We used to write a .pth directly to sys.prefix - clobber it.
    if os.path.isfile(os.path.join(sys.prefix, "pywin32.pth")):
        os.unlink(os.path.join(sys.prefix, "pywin32.pth"))
    # The .pth may be new and therefore not loaded in this session.
    # Setup the paths just in case.
    for name in "win32 win32\\lib Pythonwin".split():
        sys.path.append(os.path.join(lib_dir, name))
    # It is possible people with old versions installed with still have
    # pywintypes and pythoncom registered.  We no longer need this, and stale
    # entries hurt us.
    for name in "pythoncom pywintypes".split():
        keyname = "Software\\Python\\PythonCore\\" + sys.winver + "\\Modules\\" + name
        for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER:
            try:
                winreg.DeleteKey(root, keyname + "\\Debug")
            except WindowsError:
                pass
            try:
                winreg.DeleteKey(root, keyname)
            except WindowsError:
                pass
    LoadSystemModule(lib_dir, "pywintypes")
    LoadSystemModule(lib_dir, "pythoncom")
    import win32api
    # and now we can get the system directory:
    files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*"))
    if not files:
        raise RuntimeError("No system files to copy!!")
    # Try the system32 directory first - if that fails due to "access denied",
    # it implies a non-admin user, and we use sys.prefix
    for dest_dir in [get_system_dir(), sys.prefix]:
        # and copy some files over there
        worked = 0
        try:
            for fname in files:
                base = os.path.basename(fname)
                dst = os.path.join(dest_dir, base)
                CopyTo("installing %s" % base, fname, dst)
                if verbose:
                    print "Copied %s to %s" % (base, dst)
                # Register the files with the uninstaller
                file_created(dst)
                worked = 1
                # If this isn't sys.prefix (ie, System32), then nuke
                # any versions that may exist in sys.prefix - having
                # duplicates causes major headaches.
                if dest_dir != sys.prefix:
                    bad_fname = os.path.join(sys.prefix, base)
                    if os.path.exists(bad_fname):
                        # let exceptions go here - delete must succeed
                        os.unlink(bad_fname)
            if worked:
                break
        except win32api.error, details:
            if details.winerror==5:
                # access denied - user not admin - try sys.prefix dir,
                # but first check that a version doesn't already exist
                # in that place - otherwise that one will still get used!
                if os.path.exists(dst):
                    msg = "The file '%s' exists, but can not be replaced " \
                          "due to insufficient permissions.  You must " \
                          "reinstall this software as an Administrator" \
                          % dst
                    print msg
                    raise RuntimeError(msg)
                continue
            raise
    else:
        raise RuntimeError(
              "You don't have enough permissions to install the system files")

    # Pythonwin 'compiles' config files - record them for uninstall.
    pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin")
    for fname in glob.glob(os.path.join(pywin_dir, "*.cfg")):
        file_created(fname[:-1] + "c") # .cfg->.cfc

    # Register our demo COM objects.
    try:
        try:
            RegisterCOMObjects()
        except win32api.error, details:
            if details.winerror!=5: # ERROR_ACCESS_DENIED
                raise
            print "You do not have the permissions to install COM objects."
            print "The sample COM objects were not registered."
    except:
        print "FAILED to register the Python COM objects"
        traceback.print_exc()

    # There may be no main Python key in HKCU if, eg, an admin installed
    # python itself.
    winreg.CreateKey(get_root_hkey(), root_key_name)

    # Register the .chm help file.
    chm_file = os.path.join(lib_dir, "PyWin32.chm")
    if os.path.isfile(chm_file):
        # This isn't recursive, so if 'Help' doesn't exist, we croak
        SetPyKeyVal("Help", None, None)
        SetPyKeyVal("Help\\Pythonwin Reference", None, chm_file)
    else:
        print "NOTE: PyWin32.chm can not be located, so has not " \
              "been registered"

    # misc other fixups.
    fixup_dbi()

    # Register Pythonwin in context menu
    try:
        RegisterPythonwin()
    except:
        print 'Failed to register pythonwin as editor'
        traceback.print_exc()
    else:
        if verbose:
            print 'Pythonwin has been registered in context menu'

    # Create the win32com\gen_py directory.
    make_dir = os.path.join(lib_dir, "win32com", "gen_py")
    if not os.path.isdir(make_dir):
        if verbose:
            print "Creating directory", make_dir
        directory_created(make_dir)
        os.mkdir(make_dir)

    try:
        # create shortcuts
        # CSIDL_COMMON_PROGRAMS only available works on NT/2000/XP, and
        # will fail there if the user has no admin rights.
        fldr = get_shortcuts_folder()
        # If the group doesn't exist, then we don't make shortcuts - its
        # possible that this isn't a "normal" install.
        if os.path.isdir(fldr):
            dst = os.path.join(fldr, "PythonWin.lnk")
            create_shortcut(os.path.join(lib_dir, "Pythonwin\\Pythonwin.exe"),
                            "The Pythonwin IDE", dst, "", sys.prefix)
            file_created(dst)
            if verbose:
                print "Shortcut for Pythonwin created"
            # And the docs.
            dst = os.path.join(fldr, "Python for Windows Documentation.lnk")
            doc = "Documentation for the PyWin32 extensions"
            create_shortcut(chm_file, doc, dst)
            file_created(dst)
            if verbose:
                print "Shortcut to documentation created"
        else:
            if verbose:
                print "Can't install shortcuts - %r is not a folder" % (fldr,)
    except Exception, details:
        print details

    # importing win32com.client ensures the gen_py dir created - not strictly
    # necessary to do now, but this makes the installation "complete"
    try:
        import win32com.client
    except ImportError:
        # Don't let this error sound fatal
        pass
    print "The pywin32 extensions were successfully installed."

def uninstall():
    import distutils.sysconfig
    lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1)
    # First ensure our system modules are loaded from pywin32_system, so
    # we can remove the ones we copied...
    LoadSystemModule(lib_dir, "pywintypes")
    LoadSystemModule(lib_dir, "pythoncom")

    try:
        RegisterCOMObjects(False)
    except Exception, why:
        print "Failed to unregister COM objects:", why

    try:
        RegisterPythonwin(False)
    except Exception, why:
        print "Failed to unregister Pythonwin:", why
    else:
        if verbose:
            print 'Unregistered Pythonwin'

    try:
        # remove gen_py directory.
        gen_dir = os.path.join(lib_dir, "win32com", "gen_py")
        if os.path.isdir(gen_dir):
            shutil.rmtree(gen_dir)
            if verbose:
                print "Removed directory", gen_dir

        # Remove pythonwin compiled "config" files.
        pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin")
        for fname in glob.glob(os.path.join(pywin_dir, "*.cfc")):
            os.remove(fname)

        # The dbi.pyd.old files we may have created.
        try:
            os.remove(os.path.join(lib_dir, "win32", "dbi.pyd.old"))
        except os.error:
            pass
        try:
            os.remove(os.path.join(lib_dir, "win32", "dbi_d.pyd.old"))
        except os.error:
            pass

    except Exception, why:
        print "Failed to remove misc files:", why

    try:
        fldr = get_shortcuts_folder()
        for link in ("PythonWin.lnk", "Python for Windows Documentation.lnk"):
            fqlink = os.path.join(fldr, link)
            if os.path.isfile(fqlink):
                os.remove(fqlink)
                if verbose:
                    print "Removed", link
    except Exception, why:
        print "Failed to remove shortcuts:", why
    # Now remove the system32 files.
    files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*"))
    # Try the system32 directory first - if that fails due to "access denied",
    # it implies a non-admin user, and we use sys.prefix
    try:
        for dest_dir in [get_system_dir(), sys.prefix]:
            # and copy some files over there
            worked = 0
            for fname in files:
                base = os.path.basename(fname)
                dst = os.path.join(dest_dir, base)
                if os.path.isfile(dst):
                    try:
                        os.remove(dst)
                        worked = 1
                        if verbose:
                            print "Removed file %s" % (dst)
                    except Exception:
                        print "FAILED to remove", dst
            if worked:
                break
    except Exception, why:
        print "FAILED to remove system files:", why

def usage():
    msg = \
"""%s: A post-install script for the pywin32 extensions.

This should be run automatically after installation, but if it fails you
can run it again with a '-install' parameter, to ensure the environment
is setup correctly.

Additional Options:
  -wait pid : Wait for the specified process to terminate before starting.
  -silent   : Don't display the "Abort/Retry/Ignore" dialog for files in use.
  -quiet    : Don't display progress messages.
"""
    print msg.strip() % os.path.basename(sys.argv[0])

# NOTE: If this script is run from inside the bdist_wininst created
# binary installer or uninstaller, the command line args are either
# '-install' or '-remove'.

# Important: From inside the binary installer this script MUST NOT
# call sys.exit() or raise SystemExit, otherwise not only this script
# but also the installer will terminate! (Is there a way to prevent
# this from the bdist_wininst C code?)

if __name__=='__main__':
    if len(sys.argv)==1:
        usage()
        sys.exit(1)

    arg_index = 1
    while arg_index < len(sys.argv):
        arg = sys.argv[arg_index]
        # Hack for installing while we are in use.  Just a simple wait so the
        # parent process can terminate.
        if arg == "-wait":
            arg_index += 1
            pid = int(sys.argv[arg_index])
            try:
                os.waitpid(pid, 0)
            except AttributeError:
                # Python 2.2 - no waitpid - just sleep.
                time.sleep(3)
            except os.error:
                # child already dead
                pass
        elif arg == "-install":
            install()
        elif arg == "-silent":
            silent = 1
        elif arg == "-quiet":
            verbose = 0
        elif arg == "-remove":
            # bdist_msi calls us before uninstall, so we can undo what we
            # previously did.  Sadly, bdist_wininst calls us *after*, so
            # we can't do much at all.
            if not is_bdist_wininst:
                uninstall()
        else:
            print "Unknown option:", arg
            usage()
            sys.exit(0)
        arg_index += 1


text:
require('dotenv').config();
const args = require('minimist')(process.argv.slice(2));
const queries = require('./graphQL/queries');
const mutations = require('./graphQL/mutations');

const city = args.city || process.env.DEFAULT_CITY;
const provider = args.provider;

if (!city) {
    console.error('Missing `city` argument');
    return;
}
if (!provider) {
    console.error('Missing `provider` argument');
    return;
}

queries.getApartments({
    city: city,
    provider: provider,
    first: 5000,
})
.then(apartments => {
    console.log(`Apartments fetched: ${apartments.length}`);
    console.log(`Proceeding with the truncation`);
    const ids = apartments.map(apartment => apartment.id);
    if (ids.length > 0) {
        return mutations.deleteApartments(ids);
    }
})
.catch(e => console.log(e));


text:
let testURL_click = chromeRoot + "browser_click_content.html";

let currentTab;
let element;
let clickPosition = { x: null, y: null};

//------------------------------------------------------------------------------
// Entry point (must be named "test")
function test() {
  // This test is async
  waitForExplicitFinish();

  // Add new tab
  currentTab = Browser.addTab(testURL_click, true);
  ok(currentTab, "Tab Opened");

  // Wait for the tab to load, then do the test
  messageManager.addMessageListener("pageshow", function() {
  if (currentTab.browser.currentURI.spec == testURL_click) {
    messageManager.removeMessageListener("pageshow", arguments.callee);
    testClickAndPosition();
  }});
}

function clickFired(aEvent) {
  let [x, y] = browserViewToClient(aEvent.clientX, aEvent.clientY);
  clickPosition.x = x;
  clickPosition.y = y;
}

function testClickAndPosition() {
  // Do sanity tests
  let uri = currentTab.browser.currentURI.spec;
  is(uri, testURL_click, "URL Matches newly created Tab");

  // Check click
  element = currentTab.browser.contentDocument.getElementById("iframe-1");
  element.addEventListener("click", function(aEvent) {
    element.removeEventListener("click", arguments.callee, true);
    clickFired(aEvent);
    is(aEvent.type, "click", "Click fired");
    checkClick();
  }, true);

  EventUtils.synthesizeMouseForContent(element, 1, 1, {}, window);
}

function checkClick() {
  // Check position
  element = currentTab.browser.contentDocument.documentElement;
  element.addEventListener("click", function(aEvent) {
    element.removeEventListener("click", arguments.callee, true);
    clickFired(aEvent);
    checkPosition();
  }, true);

  let rect = getBoundingContentRect(element);
  EventUtils.synthesizeMouse(element, 1, rect.height + 10, {}, window);
}

function checkPosition() {
  let rect = getBoundingContentRect(element);
  is(clickPosition.x, 1, "X position is correct");
  is(clickPosition.y, rect.height + 10, "Y position is correct");

  checkThickBorder();
}

function checkThickBorder() {
  let frame = currentTab.browser.contentDocument.getElementById("iframe-2");
  let element = frame.contentDocument.getElementsByTagName("input")[0];

  let frameRect = getBoundingContentRect(frame);
  let frameLeftBorder = window.getComputedStyle(frame, "").borderLeftWidth;
  let frameTopBorder = window.getComputedStyle(frame, "").borderTopWidth;

  let elementRect = getBoundingContentRect(element);
  ok((frameRect.left + parseInt(frameLeftBorder)) < elementRect.left, "X position of nested element ok");
  ok((frameRect.top + parseInt(frameTopBorder)) < elementRect.top, "Y position of nested element ok");

  close();
}

function close() {
  // Close the tab
  Browser.closeTab(currentTab);

  // We must finialize the tests
  finish();
}

// XXX copied from chrome/content/content.js
function getBoundingContentRect(aElement) {
  if (!aElement)
    return new Rect(0, 0, 0, 0);

  let document = aElement.ownerDocument;
  while(document.defaultView.frameElement)
    document = document.defaultView.frameElement.ownerDocument;

  let content = document.defaultView;
  let cwu = content.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
  let scrollX = {}, scrollY = {};
  cwu.getScrollXY(false, scrollX, scrollY);
  let offset = new Point(scrollX.value, scrollY.value);
  let r = aElement.getBoundingClientRect();

  // step out of iframes and frames, offsetting scroll values
  for (let frame = aElement.ownerDocument.defaultView; frame != content; frame = frame.parent) {
    // adjust client coordinates' origin to be top left of iframe viewport
    let rect = frame.frameElement.getBoundingClientRect();
    let left = frame.getComputedStyle(frame.frameElement, "").borderLeftWidth;
    let top = frame.getComputedStyle(frame.frameElement, "").borderTopWidth;
    offset.add(rect.left + parseInt(left), rect.top + parseInt(top));
  }

  return new Rect(r.left + offset.x, r.top + offset.y, r.width, r.height);
}

function browserViewToClient(x, y) {
  let container = document.getElementById("browsers");
  let containerBCR = container.getBoundingClientRect();

  let x0 = Math.round(-containerBCR.left);
  let y0 = Math.round(-containerBCR.top);

  return [x - x0, y - y0];
}


text:
@interface HCMatchingInAnyOrder : NSObject
{
    NSMutableArray *matchers;
    id<HCDescription, NSObject> mismatchDescription;
}
@end

@implementation HCMatchingInAnyOrder

- (id)initWithMatchers:(NSMutableArray *)itemMatchers
   mismatchDescription:(id<HCDescription, NSObject>)description
{
    self = [super init];
    if (self)
    {
        matchers = [itemMatchers retain];
        mismatchDescription = [description retain];
    }
    return self;
}

- (void)dealloc
{
    [matchers release];
    [mismatchDescription release];
    [super dealloc];
}

- (BOOL)matches:(id)item
{
    NSUInteger index = 0;
    for (id<HCMatcher> matcher in matchers)
    {
        if ([matcher matches:item])
        {
            [matchers removeObjectAtIndex:index];
            return YES;
        }
        ++index;
    }
    [[mismatchDescription appendText:@"not matched: "] appendDescriptionOf:item];
    return NO;
}

- (BOOL)isFinishedWith:(NSArray *)collection
{
    if ([matchers count] == 0)
        return YES;

    [[[[mismatchDescription appendText:@"no item matches: "]
                            appendList:matchers start:@"" separator:@", " end:@""]
                            appendText:@" in "]
                            appendList:collection start:@"[" separator:@", " end:@"]"];
    return NO;
}

@end

#pragma mark -

@implementation HCIsCollectionContainingInAnyOrder

+ (id)isCollectionContainingInAnyOrder:(NSMutableArray *)itemMatchers
{
    return [[[self alloc] initWithMatchers:itemMatchers] autorelease];
}

- (id)initWithMatchers:(NSMutableArray *)itemMatchers
{
    self = [super init];
    if (self)
        matchers = [itemMatchers retain];
    return self;
}

- (void)dealloc
{
    [matchers release];
    [super dealloc];
}

- (BOOL)matches:(id)collection
{
    return [self matches:collection describingMismatchTo:nil];
}

- (BOOL)matches:(id)collection describingMismatchTo:(id<HCDescription, NSObject>)mismatchDescription
{
    if (![collection conformsToProtocol:@protocol(NSFastEnumeration)])
    {
        [super describeMismatchOf:collection to:mismatchDescription];
        return NO;
    }

    HCMatchingInAnyOrder *matchSequence =
        [[[HCMatchingInAnyOrder alloc] initWithMatchers:matchers
                                    mismatchDescription:mismatchDescription] autorelease];
    for (id item in collection)
        if (![matchSequence matches:item])
            return NO;

    return [matchSequence isFinishedWith:collection];
}

- (void)describeMismatchOf:(id)item to:(id<HCDescription>)mismatchDescription
{
    [self matches:item describingMismatchTo:mismatchDescription];
}

- (void)describeTo:(id<HCDescription>)description
{
    [[[description appendText:@"a collection over "]
                   appendList:matchers start:@"[" separator:@", " end:@"]"]
                   appendText:@" in any order"];
}

@end

#pragma mark -

id<HCMatcher> HC_containsInAnyOrder(id itemMatch, ...)
{
    NSMutableArray *matchers = [NSMutableArray arrayWithObject:HCWrapInMatcher(itemMatch)];

    va_list args;
    va_start(args, itemMatch);
    itemMatch = va_arg(args, id);
    while (itemMatch != nil)
    {
        [matchers addObject:HCWrapInMatcher(itemMatch)];
        itemMatch = va_arg(args, id);
    }
    va_end(args);

    return [HCIsCollectionContainingInAnyOrder isCollectionContainingInAnyOrder:matchers];
}


text:
using namespace llvm;

STATISTIC(NumSimplified, "Number of redundant instructions simplified");

namespace {
  class LoopInstSimplify : public LoopPass {
  public:
    static char ID; // Pass ID, replacement for typeid
    LoopInstSimplify() : LoopPass(ID) {
      initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
    }

    bool runOnLoop(Loop*, LPPassManager&);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesCFG();
      AU.addRequired<LoopInfo>();
      AU.addRequiredID(LoopSimplifyID);
      AU.addPreservedID(LoopSimplifyID);
      AU.addPreservedID(LCSSAID);
      AU.addPreserved("scalar-evolution");
      AU.addRequired<TargetLibraryInfo>();
    }
  };
}

char LoopInstSimplify::ID = 0;
INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
                "Simplify instructions in loops", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
INITIALIZE_PASS_DEPENDENCY(LoopInfo)
INITIALIZE_PASS_DEPENDENCY(LCSSA)
INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
                "Simplify instructions in loops", false, false)

Pass *llvm::createLoopInstSimplifyPass() {
  return new LoopInstSimplify();
}

bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
  DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>();
  LoopInfo *LI = &getAnalysis<LoopInfo>();
  const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
  const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();

  SmallVector<BasicBlock*, 8> ExitBlocks;
  L->getUniqueExitBlocks(ExitBlocks);
  array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());

  SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;

  // The bit we are stealing from the pointer represents whether this basic
  // block is the header of a subloop, in which case we only process its phis.
  typedef PointerIntPair<BasicBlock*, 1> WorklistItem;
  SmallVector<WorklistItem, 16> VisitStack;
  SmallPtrSet<BasicBlock*, 32> Visited;

  bool Changed = false;
  bool LocalChanged;
  do {
    LocalChanged = false;

    VisitStack.clear();
    Visited.clear();

    VisitStack.push_back(WorklistItem(L->getHeader(), false));

    while (!VisitStack.empty()) {
      WorklistItem Item = VisitStack.pop_back_val();
      BasicBlock *BB = Item.getPointer();
      bool IsSubloopHeader = Item.getInt();

      // Simplify instructions in the current basic block.
      for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
        Instruction *I = BI++;

        // The first time through the loop ToSimplify is empty and we try to
        // simplify all instructions. On later iterations ToSimplify is not
        // empty and we only bother simplifying instructions that are in it.
        if (!ToSimplify->empty() && !ToSimplify->count(I))
          continue;

        // Don't bother simplifying unused instructions.
        if (!I->use_empty()) {
          Value *V = SimplifyInstruction(I, TD, TLI, DT);
          if (V && LI->replacementPreservesLCSSAForm(I, V)) {
            // Mark all uses for resimplification next time round the loop.
            for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
                 UI != UE; ++UI)
              Next->insert(cast<Instruction>(*UI));

            I->replaceAllUsesWith(V);
            LocalChanged = true;
            ++NumSimplified;
          }
        }
        LocalChanged |= RecursivelyDeleteTriviallyDeadInstructions(I, TLI);

        if (IsSubloopHeader && !isa<PHINode>(I))
          break;
      }

      // Add all successors to the worklist, except for loop exit blocks and the
      // bodies of subloops. We visit the headers of loops so that we can process
      // their phis, but we contract the rest of the subloop body and only follow
      // edges leading back to the original loop.
      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
           ++SI) {
        BasicBlock *SuccBB = *SI;
        if (!Visited.insert(SuccBB))
          continue;

        const Loop *SuccLoop = LI->getLoopFor(SuccBB);
        if (SuccLoop && SuccLoop->getHeader() == SuccBB
                     && L->contains(SuccLoop)) {
          VisitStack.push_back(WorklistItem(SuccBB, true));

          SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
          SuccLoop->getExitBlocks(SubLoopExitBlocks);

          for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
            BasicBlock *ExitBB = SubLoopExitBlocks[i];
            if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB))
              VisitStack.push_back(WorklistItem(ExitBB, false));
          }

          continue;
        }

        bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
                                              ExitBlocks.end(), SuccBB);
        if (IsExitBlock)
          continue;

        VisitStack.push_back(WorklistItem(SuccBB, false));
      }
    }

    // Place the list of instructions to simplify on the next loop iteration
    // into ToSimplify.
    std::swap(ToSimplify, Next);
    Next->clear();

    Changed |= LocalChanged;
  } while (LocalChanged);

  return Changed;
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using commercetools.Common;
using commercetools.Common.UpdateActions;
using commercetools.Carts;
using commercetools.Carts.UpdateActions;
using commercetools.Customers;
using commercetools.Messages;
using commercetools.Orders;
using commercetools.Orders.UpdateActions;
using commercetools.Products;
using commercetools.ProductTypes;
using commercetools.Project;
using commercetools.ShippingMethods;
using commercetools.TaxCategories;
using commercetools.Zones;

using Newtonsoft.Json.Linq;

using NUnit.Framework;

namespace commercetools.Tests
{
    /// <summary>
    /// Test the API methods in the OrderManager class.
    /// </summary>
    [TestFixture]
    public class OrderManagerTest
    {
        private Client _client;
        private Project.Project _project;
        private List<Cart> _testCarts;
        private List<Customer> _testCustomers;
        private Order _testOrder;
        private Product _testProduct;
        private ProductType _testProductType;
        private ShippingMethod _testShippingMethod;
        private TaxCategory _testTaxCategory;
        private Zone _testZone;
        private bool _createdTestZone = false;

        /// <summary>
        /// Test setup
        /// </summary>
        [OneTimeSetUp]
        public void Init()
        {
            _client = Helper.GetClient();

            Task<Response<Project.Project>> projectTask = _client.Project().GetProjectAsync();
            projectTask.Wait();
            Assert.IsTrue(projectTask.Result.Success);
            _project = projectTask.Result.Result;

            _testCustomers = new List<Customer>();

            for (int i = 0; i < 5; i++)
            {
                CustomerDraft customerDraft = Helper.GetTestCustomerDraft();
                Task<Response<CustomerCreatedMessage>> customerTask = _client.Customers().CreateCustomerAsync(customerDraft);
                customerTask.Wait();
                Assert.IsTrue(customerTask.Result.Success);

                CustomerCreatedMessage customerCreatedMessage = customerTask.Result.Result;
                Assert.NotNull(customerCreatedMessage.Customer);
                Assert.NotNull(customerCreatedMessage.Customer.Id);

                _testCustomers.Add(customerCreatedMessage.Customer);
            }

            _testCarts = new List<Cart>();
            Task<Response<Cart>> cartTask;

            for (int i = 0; i < 5; i++)
            {
                CartDraft cartDraft = Helper.GetTestCartDraft(_project, _testCustomers[i].Id);
                cartTask = _client.Carts().CreateCartAsync(cartDraft);
                cartTask.Wait();
                Assert.IsTrue(cartTask.Result.Success);

                Cart cart = cartTask.Result.Result;
                Assert.NotNull(cart.Id);

                _testCarts.Add(cart);
            }

            ProductTypeDraft productTypeDraft = Helper.GetTestProductTypeDraft();
            Task<Response<ProductType>> productTypeTask = _client.ProductTypes().CreateProductTypeAsync(productTypeDraft);
            productTypeTask.Wait();
            Assert.IsTrue(productTypeTask.Result.Success);

            _testProductType = productTypeTask.Result.Result;
            Assert.NotNull(_testProductType.Id);

            TaxCategoryDraft taxCategoryDraft = Helper.GetTestTaxCategoryDraft(_project);
            Task<Response<TaxCategory>> taxCategoryTask = _client.TaxCategories().CreateTaxCategoryAsync(taxCategoryDraft);
            taxCategoryTask.Wait();
            Assert.IsTrue(taxCategoryTask.Result.Success);

            _testTaxCategory = taxCategoryTask.Result.Result;
            Assert.NotNull(_testTaxCategory.Id);

            Task<Response<ZoneQueryResult>> zoneQueryResultTask = _client.Zones().QueryZonesAsync();
            zoneQueryResultTask.Wait();

            if (zoneQueryResultTask.Result.Success && zoneQueryResultTask.Result.Result.Results.Count > 0)
            {
                _testZone = zoneQueryResultTask.Result.Result.Results[0];
                _createdTestZone = false;
            }
            else
            {
                ZoneDraft zoneDraft = Helper.GetTestZoneDraft();
                Task<Response<Zone>> zoneTask = _client.Zones().CreateZoneAsync(zoneDraft);
                zoneTask.Wait();
                Assert.IsTrue(zoneTask.Result.Success);

                _testZone = zoneTask.Result.Result;
                _createdTestZone = true;
            }

            Assert.NotNull(_testZone.Id);

            ShippingMethodDraft shippingMethodDraft = Helper.GetTestShippingMethodDraft(_project, _testTaxCategory, _testZone);
            Task<Response<ShippingMethod>> shippingMethodTask = _client.ShippingMethods().CreateShippingMethodAsync(shippingMethodDraft);
            shippingMethodTask.Wait();
            Assert.IsTrue(shippingMethodTask.Result.Success);

            _testShippingMethod = shippingMethodTask.Result.Result;
            Assert.NotNull(_testShippingMethod.Id);

            ProductDraft productDraft = Helper.GetTestProductDraft(_project, _testProductType.Id, _testTaxCategory.Id);
            Task<Response<Product>> productTask = _client.Products().CreateProductAsync(productDraft);
            productTask.Wait();
            Assert.IsTrue(productTask.Result.Success);

            _testProduct = productTask.Result.Result;
            Assert.NotNull(_testProduct.Id);

            int quantity = 1;
            AddLineItemAction addLineItemAction = new AddLineItemAction(_testProduct.Id, _testProduct.MasterData.Current.MasterVariant.Id);
            addLineItemAction.Quantity = quantity;
            cartTask = _client.Carts().UpdateCartAsync(_testCarts[0], addLineItemAction);
            cartTask.Wait();
            Assert.IsTrue(cartTask.Result.Success);

            _testCarts[0] = cartTask.Result.Result;
            Assert.NotNull(_testCarts[0].Id);
            Assert.NotNull(_testCarts[0].LineItems);
            Assert.AreEqual(_testCarts[0].LineItems.Count, 1);
            Assert.AreEqual(_testCarts[0].LineItems[0].ProductId, _testProduct.Id);
            Assert.AreEqual(_testCarts[0].LineItems[0].Variant.Id, _testProduct.MasterData.Current.MasterVariant.Id);
            Assert.AreEqual(_testCarts[0].LineItems[0].Quantity, quantity);

            OrderFromCartDraft orderFromCartDraft = Helper.GetTestOrderFromCartDraft(_testCarts[0]);
            Task<Response<Order>> orderTask = _client.Orders().CreateOrderFromCartAsync(orderFromCartDraft);
            orderTask.Wait();
            Assert.IsTrue(orderTask.Result.Success);

            _testOrder = orderTask.Result.Result;
            Assert.NotNull(_testOrder.Id);

            cartTask = _client.Carts().GetCartByIdAsync(_testCarts[0].Id);
            cartTask.Wait();
            Assert.IsTrue(cartTask.Result.Success);

            _testCarts[0] = cartTask.Result.Result;
            Assert.NotNull(_testCarts[0].Id);
        }

        /// <summary>
        /// Test teardown
        /// </summary>
        [OneTimeTearDown]
        public void Dispose()
        {
            Task task = _client.Orders().DeleteOrderAsync(_testOrder);
            task.Wait();

            foreach (Cart cart in _testCarts)
            {
                task = _client.Carts().DeleteCartAsync(cart);
                task.Wait();
            }

            foreach (Customer customer in _testCustomers)
            {
                task = _client.Customers().DeleteCustomerAsync(customer);
                task.Wait();
            }

            task = _client.Products().DeleteProductAsync(_testProduct);
            task.Wait();

            task = _client.ProductTypes().DeleteProductTypeAsync(_testProductType);
            task.Wait();

            task = _client.ShippingMethods().DeleteShippingMethodAsync(_testShippingMethod);
            task.Wait();

            task = _client.TaxCategories().DeleteTaxCategoryAsync(_testTaxCategory);
            task.Wait();

            if (_createdTestZone)
            {
                task = _client.Zones().DeleteZoneAsync(_testZone);
                task.Wait();
            }
        }

        /// <summary>
        /// Tests the OrderManager.GetOrderByIdAsync method.
        /// </summary>
        /// <see cref="OrderManager.GetOrderByIdAsync"/>
        [Test]
        public async Task ShouldGetOrderByIdAsync()
        {
            Response<Order> response = await _client.Orders().GetOrderByIdAsync(_testOrder.Id);
            Assert.IsTrue(response.Success);

            Order order = response.Result;
            Assert.NotNull(order.Id);
            Assert.AreEqual(order.Id, _testOrder.Id);
        }

        /// <summary>
        /// Tests the OrderManager.QueryOrdersAsync method.
        /// </summary>
        /// <see cref="OrderManager.QueryOrdersAsync"/>
        [Test]
        public async Task ShouldQueryOrdersAsync()
        {
            Response<OrderQueryResult> response = await _client.Orders().QueryOrdersAsync();
            Assert.IsTrue(response.Success);

            OrderQueryResult orderQueryResult = response.Result;
            Assert.NotNull(orderQueryResult.Results);
            Assert.GreaterOrEqual(orderQueryResult.Results.Count, 1);

            int limit = 2;
            response = await _client.Orders().QueryOrdersAsync(limit: limit);
            Assert.IsTrue(response.Success);

            orderQueryResult = response.Result;
            Assert.NotNull(orderQueryResult.Results);
            Assert.LessOrEqual(orderQueryResult.Results.Count, limit);
        }

        /// <summary>
        /// Tests the OrderManager.CreateOrderFromCartAsync and DeleteOrderAsync methods.
        /// </summary>
        /// <see cref="OrderManager.CreateOrderFromCartAsync"/>
        /// <seealso cref="OrderManager.DeleteOrderAsync(commercetools.Orders.Order)"/>
        [Test]
        public async Task ShouldCreateOrderFromCartAndDeleteOrderAsync()
        {
            CartDraft cartDraft = Helper.GetTestCartDraft(_project, _testCustomers[0].Id);
            Response<Cart> cartResponse = await _client.Carts().CreateCartAsync(cartDraft);
            Assert.IsTrue(cartResponse.Success);

            Cart cart = cartResponse.Result;
            Assert.NotNull(cart.Id);

            int quantity = 3;
            AddLineItemAction addLineItemAction = new AddLineItemAction(_testProduct.Id, _testProduct.MasterData.Current.MasterVariant.Id);
            addLineItemAction.Quantity = quantity;
            cartResponse = await _client.Carts().UpdateCartAsync(cart, addLineItemAction);
            Assert.IsTrue(cartResponse.Success);

            cart = cartResponse.Result;
            Assert.NotNull(cart.Id);
            Assert.NotNull(cart.LineItems);
            Assert.AreEqual(cart.LineItems.Count, 1);
            Assert.AreEqual(cart.LineItems[0].ProductId, _testProduct.Id);
            Assert.AreEqual(cart.LineItems[0].Variant.Id, _testProduct.MasterData.Current.MasterVariant.Id);
            Assert.AreEqual(cart.LineItems[0].Quantity, quantity);

            OrderFromCartDraft orderFromCartDraft = Helper.GetTestOrderFromCartDraft(cart);
            Response<Order> orderResponse = await _client.Orders().CreateOrderFromCartAsync(orderFromCartDraft);
            Assert.IsTrue(orderResponse.Success);

            Order order = orderResponse.Result;
            Assert.NotNull(order.Id);

            // To get the new version number.
            cartResponse = await _client.Carts().GetCartByIdAsync(cart.Id);
            Assert.IsTrue(cartResponse.Success);
            cart = cartResponse.Result;

            string deletedOrderId = order.Id;

            Response<JObject> response = await _client.Orders().DeleteOrderAsync(order);
            Assert.IsTrue(response.Success);

            orderResponse = await _client.Orders().GetOrderByIdAsync(deletedOrderId);
            Assert.IsFalse(orderResponse.Success);

            await _client.Carts().DeleteCartAsync(cart);
        }

        /// <summary>
        /// Tests the OrderManager.UpdateOrderAsync method.
        /// </summary>
        /// <see cref="OrderManager.UpdateOrderAsync(commercetools.Orders.Order, System.Collections.Generic.List{commercetools.Common.UpdateAction})"/>
        [Test]
        public async Task ShouldUpdateOrderAsync()
        {
            OrderState newOrderState = OrderState.Confirmed;
            string newOrderNumber = Helper.GetRandomNumber(10000, 99999).ToString();

            ChangeOrderStateAction changeOrderStateAction = new ChangeOrderStateAction(newOrderState);

            GenericAction setOrderNumberAction = new GenericAction("setOrderNumber");
            setOrderNumberAction.SetProperty("orderNumber", newOrderNumber);

            List<UpdateAction> actions = new List<UpdateAction>();
            actions.Add(changeOrderStateAction);
            actions.Add(setOrderNumberAction);

            Response<Order> response = await _client.Orders().UpdateOrderAsync(_testOrder, actions);
            Assert.IsTrue(response.Success);

            _testOrder = response.Result;
            Assert.NotNull(_testOrder.Id);
            Assert.AreEqual(_testOrder.OrderState, newOrderState);
            Assert.AreEqual(_testOrder.OrderNumber, newOrderNumber);
        }
    }
}


text:
package com.amazonaws.services.elasticloadbalancing.model;

import java.io.Serializable;

/**
 *
 */
public class CreateLoadBalancerResult implements Serializable, Cloneable {

    /**
     *

     * The DNS name of the load balancer.
     *

     */
    private String dNSName;

    /**
     *

     * The DNS name of the load balancer.
     *

     *
     * @param dNSName
     *        The DNS name of the load balancer.
     */

    public void setDNSName(String dNSName) {
        this.dNSName = dNSName;
    }

    /**
     *

     * The DNS name of the load balancer.
     *

     *
     * @return The DNS name of the load balancer.
     */

    public String getDNSName() {
        return this.dNSName;
    }

    /**
     *

     * The DNS name of the load balancer.
     *

     *
     * @param dNSName
     *        The DNS name of the load balancer.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CreateLoadBalancerResult withDNSName(String dNSName) {
        setDNSName(dNSName);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDNSName() != null)
            sb.append("DNSName: " + getDNSName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateLoadBalancerResult == false)
            return false;
        CreateLoadBalancerResult other = (CreateLoadBalancerResult) obj;
        if (other.getDNSName() == null ^ this.getDNSName() == null)
            return false;
        if (other.getDNSName() != null
                && other.getDNSName().equals(this.getDNSName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getDNSName() == null) ? 0 : getDNSName().hashCode());
        return hashCode;
    }

    @Override
    public CreateLoadBalancerResult clone() {
        try {
            return (CreateLoadBalancerResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
<?php

final class PhabricatorMacroDatasource extends PhabricatorTypeaheadDatasource {

  public function getPlaceholderText() {
    return pht('Type a macro name...');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorMacroApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $results = array();

    $macros = id(new PhabricatorMacroQuery())
      ->setViewer($viewer)
      ->withStatus(PhabricatorMacroQuery::STATUS_ACTIVE)
      ->execute();

    foreach ($macros as $macro) {
      $results[] = id(new PhabricatorTypeaheadResult())
        ->setPHID($macro->getPHID())
        ->setName($macro->getName());
    }

    return $results;
  }

}


text:
cask 'jedit' do
  version '5.3.0'
  sha256 '9ef706449951c8904ed7504294c3d854aaaf73f3fd8059dd8d4803036829f9f7'

  # sourceforge.net is the official download host per the vendor homepage
  url "http://downloads.sourceforge.net/sourceforge/jedit/jedit#{version}install.dmg"
  name 'jEdit'
  homepage 'http://www.jedit.org'
  license :gpl

  app 'jEdit.app'
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;

namespace Skybrud.Umbraco.RssUtils {

    public class RssFeed {

        private DateTime? _pubDate;
        private List<RssItem> _items = new List<RssItem>();

        #region Properties

        ///
        /// Gets or sets the version of the RSS specification. Default is <c>2.0</c>.
        ///
        public string Version { get; set; }

        ///
        /// Gets or sets the title of the feed.
        ///
        public string Title { get; set; }

        ///
        /// Gets or sets the link of the feed. This link is usually an URL to
        /// where the feed can be downloaded or simply the URL to the index
        /// page of the website.
        ///
        public string Link { get; set; }

        ///
        /// Gets or sets the generator of the feed. If you're a good fellow,
        /// you will set this to <c>Skybrud.Umbraco.RssUtils</c>, but
        /// this is not a requirement.
        ///
        public string Generator { get; set; }

        ///
        /// Gets or sets the description of the feed.
        ///
        public string Description { get; set; }

        ///
        /// Gets or sets the language of the feed.
        ///
        public string Language { get; set; }

        ///
        /// Gets or sets the publication date of the feed. If no publication date has been explicitly
        /// set, the publication date of the most recent item will be used instead - or
        /// DateTime.Now if the feed is empty.
        ///
        public DateTime PubDate {
            get {
                if (_pubDate != null) return _pubDate.Value;
                return _items.Count == 0 ? DateTime.Now : _items[0].PubDate;
            }
            set { _pubDate = value; }
        }

        ///
        /// Gets or sets the list of RSS items of the feed.
        ///
        public List<RssItem> Items {
            get { return _items; }
            set { _items = value ?? new List<RssItem>(); }
        }

        public bool IncludeAtomLink { get; set; }

        #endregion

        #region Constructor

        public RssFeed() {
            Version = "2.0";
            IncludeAtomLink = true;
        }

        ///
        /// Adds the children of the specified IPublishedContent as RSS items.
        ///
        /// <param name="parent">The parent of the nodes to be added.</param>
        public RssFeed(IPublishedContent parent) : this() {
            AddRange(parent.Children);
        }

        ///
        /// Adds the children of the specified IPublishedContent as RSS items.
        ///
        /// <param name="parent">The parent of the nodes to be added.</param>
        /// <param name="func">Function to convert an IPublishedContent to RssItem.</param>
        public RssFeed(IPublishedContent parent, Func<IPublishedContent, RssItem> func) : this() {
            AddRange(parent.Children, func);
        }

        ///
        /// Adds the children of the specified IPublishedContent as RSS items.
        ///
        /// <param name="title">The title of the RSS feed.</param>
        /// <param name="link">A link to the RSS feed or relevant page.</param>
        /// <param name="parent">The parent of the nodes to be added.</param>
        public RssFeed(string title, string link, IPublishedContent parent) : this() {
            Title = title;
            Link = link;
            AddRange(parent.Children);
        }

        ///
        /// Adds the children of the specified IPublishedContent as RSS items.
        ///
        /// <param name="title">The title of the RSS feed.</param>
        /// <param name="link">A link to the RSS feed or relevant page.</param>
        /// <param name="parent">The parent of the nodes to be added.</param>
        /// <param name="func">Function to convert an IPublishedContent to RssItem.</param>
        public RssFeed(string title, string link, IPublishedContent parent, Func<IPublishedContent, RssItem> func) : this() {
            Title = title;
            Link = link;
            AddRange(parent.Children, func);
        }

        ///
        /// Adds the specified collection of IPublishedContent as RSS items.
        ///
        /// <param name="content">A collection of nodes to be added.</param>
        public RssFeed(IEnumerable<IPublishedContent> content) : this() {
            AddRange(content);
        }

        ///
        /// Adds the specified collection of IPublishedContent as RSS items.
        ///
        /// <param name="content">A collection of nodes to be added.</param>
        /// <param name="func">Function to convert an IPublishedContent to RssItem.</param>
        public RssFeed(IEnumerable<IPublishedContent> content, Func<IPublishedContent, RssItem> func) : this() {
            AddRange(content, func);
        }

        ///
        /// Adds the specified collection of IPublishedContent as RSS items.
        ///
        /// <param name="title">The title of the RSS feed.</param>
        /// <param name="link">A link to the RSS feed or relevant page.</param>
        /// <param name="content">A collection of nodes to be added.</param>
        public RssFeed(string title, string link, IEnumerable<IPublishedContent> content) : this() {
            Title = title;
            Link = link;
            AddRange(content);
        }

        ///
        /// Adds the specified collection of IPublishedContent as RSS items.
        ///
        /// <param name="title">The title of the RSS feed.</param>
        /// <param name="link">A link to the RSS feed or relevant page.</param>
        /// <param name="content">A collection of nodes to be added.</param>
        /// <param name="func">Function to convert an IPublishedContent to RssItem.</param>
        public RssFeed(string title, string link, IEnumerable<IPublishedContent> content, Func<IPublishedContent, RssItem> func) : this() {
            Title = title;
            Link = link;
            AddRange(content, func);
        }

        #endregion

        #region Member methods

        public void Add(RssItem item) {
            bool mustSort = (_items.Count > 1 && _items.Last().PubDate < item.PubDate);
            _items.Add(item);
            if (!mustSort) return;
            SortItems();
        }

        public void AddRange(IEnumerable<IPublishedContent> content) {
            AddRange(content, x => new RssItem {
                Title = x.Name,
                Guid = x.Id + "",
                PubDate = x.CreateDate,
                Link = x.Url(mode: UrlMode.Absolute)
            });
        }

        public void AddRange(IEnumerable<IPublishedContent> content, Func<IPublishedContent, RssItem> func) {
            _items.AddRange(from node in content let item = func(node) select item);
            SortItems();
        }

        private void SortItems() {
            _items = _items.OrderByDescending(x => x.PubDate).ToList();
        }

        public virtual XDocument ToXDocument() {

            // Initialize the root element of the feed
            XElement xRss = new XElement("rss");

            // Initialize the element for the channel
            XElement xChannel = new XElement(
                "channel",
                new XElement("title", Title ?? ""),
                new XElement("link", Link ?? ""),
                new XElement("pubDate", PubDate.ToUniversalTime().ToString("r"))
            );

            xRss.Add(xChannel);

            // Add extra elements to the channel (if specified)
            if (!string.IsNullOrWhiteSpace(Generator)) xChannel.Add(new XElement("generator", Generator));
            if (!string.IsNullOrWhiteSpace(Description)) xChannel.Add(new XElement("description", Description));
            if (!string.IsNullOrWhiteSpace(Language)) xChannel.Add(new XElement("language", Language));

            // Set the RSS version (if specified)
            if (!string.IsNullOrWhiteSpace(Version)) {
                xRss.Add(new XAttribute("version", Version));
            }

            // Append "atom:link" to the channel (if enabled)
            if (IncludeAtomLink) {
                XNamespace atom = "http://www.w3.org/2005/Atom";
                xRss.Add(new XAttribute(XNamespace.Xmlns + "atom", "http://www.w3.org/2005/Atom"));
                xChannel.Add(new XElement(
                    atom + "link",
                    new XAttribute("href", Link ?? ""),
                    new XAttribute("rel", "self"),
                    new XAttribute("type", "application/rss+xml")
                ));
            }

            // Add the items to the channel
            xChannel.Add(from item in Items orderby item.PubDate descending select item.ToXElement());

            // Add the content namespace only if necessary
            if (Items.Any(x => !string.IsNullOrWhiteSpace(x.Content))) {
                xRss.Add(new XAttribute(XNamespace.Xmlns + "content", "http://purl.org/rss/1.0/modules/content/"));
            }

            // Return the XDocument
            return new XDocument(
                new XDeclaration("1.0", "UTF-8", "true"),
                xRss
            );

        }

        ///
        /// Writes the feed to the current response stream as well as setting
        /// the correct mime type. Formatting will be disabled for the XML
        /// meaning no line breaks and indentation.
        ///
        public void Write() {
            Write(SaveOptions.DisableFormatting);
        }

        ///
        /// Writes the feed to the current response stream as well as setting
        /// the correct mime type. The XML is generated using the specified
        /// save options.
        ///
        /// <param name="options">The save options.</param>
        public void Write(SaveOptions options) {
            HttpContext.Current.Response.ContentType = "application/rss+xml";
            ToXDocument().Save(HttpContext.Current.Response.OutputStream, options);
            HttpContext.Current.Response.End();
        }

        #endregion

        #region Static methods

        public static void Write(string title, string link, IPublishedContent parent) {
            new RssFeed(title, link, parent).Write();
        }

        public static void Write(string title, string link, IPublishedContent parent, Func<IPublishedContent, RssItem> func) {
            new RssFeed(title, link, parent, func).Write();
        }

        public static void Write(string title, string link, IEnumerable<IPublishedContent> content) {
            new RssFeed(title, link, content).Write();
        }

        public static void Write(string title, string link, IEnumerable<IPublishedContent> content, Func<IPublishedContent, RssItem> func) {
            new RssFeed(title, link, content, func).Write();
        }

        #endregion

    }

}


text:
from setuptools import setup

VERSION = __import__('djenerator').__version__

install_requires = [
    'django>=1.10',
]

setup(name='djenerator',
      version=VERSION,
      description='A simple app for generating test data for a given django models description.',
      author='Mostafa M. Mohamed',
      author_email='mostafa.amin93@gmail.com',
      long_description=open('README.md', 'r').read(),
      url='https://github.com/mostafa-mahmoud/djenerator',
      download_url='https://github.com/mostafa-mahmoud/djenerator/archive/v' + VERSION + '.tar.gz',
      license='MIT',
      packages=['djenerator', 'djenerator.core', 'djenerator.management', 'djenerator.management.commands'],
      install_requires=install_requires,
      long_description_content_type="text/markdown",
      classifiers=[
            'Development Status :: 4 - Beta',
            'Environment :: Web Environment',
            'Framework :: Django :: 1.10',
            'Framework :: Django :: 1.11',
            'Framework :: Django :: 2',
            'Framework :: Django :: 2.0',
            'Framework :: Django :: 2.1',
            'Framework :: Django :: 2.2',
            'Framework :: Django :: 3',
            'Framework :: Django :: 3.0',
            'Framework :: Django :: 3.1',
            'Framework :: Django :: 3.2',
            'Framework :: Django :: 4',
            'Framework :: Django :: 4.0',
            'Framework :: Django :: 4.1',
            'Intended Audience :: Developers',
            'License :: OSI Approved :: MIT License',
            'Operating System :: OS Independent',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3 :: Only',
            'Programming Language :: Python :: 3.5',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
            'Topic :: Software Development :: Libraries :: Python Modules',
      ],
  )


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function () {
    sleep(hi,2000);
});

function hi(){
   var username = document.getElementById("username").innerHTML;
    alertify.success("Bienvenido al Sistema Rhythm "+username);
}

function sleep(nameFunction,val){setTimeout(nameFunction, val);}

function Mensajes(){
    cargarMensajes();
}

function cargarMensajes() {
    alertify.log("Cargando Mensajes...");
    $( "#mjsGru" ).empty();
    var user = $("#username").text();
    var opcion = '2';
    datos = {"user":user,"opcion":opcion};
    $.ajax({
        data: datos,
        type : 'POST',
        dataType: 'json',
        url  : 'php/lobby.php',
    })
    .done(function(response) {
            if(response != ''){
                Object.keys(response).forEach(function (key){
                    var Ms = response[key].split(";");
                    addMessage(Ms);
                });
            }else
                alertify.log("No hay nada q mostrar");
        })
    .fail(function (response) {
        alertify.error("Error de carga de datos y mensajes: "+response.msj)
     });
}

function addMessage(Ms){

    $.ajax({
        url: "php/Mensajes.php",
        type: 'POST',
        dataType: "json",
        data: {id:Ms[0].toString(), tipo: "GetUserEnvia"},
        beforeSend: function () {

        },

        success: function (respuesta) {
            var datosrespuesta = respuesta.resultados;
            $.each(datosrespuesta, function (i, item) {
                $( "#mjsGru" ).append( '
'+"De: "+datosrespuesta[i].USU_USUARIO+'
' );
                $( "#mjsGru" ).append( '
'+" Mensaje: "+Ms[1]+'
' );
                $( "#mjsGru" ).append( "
" );
                $("#mjsGru").scrollTop($("#mjsGru")[0].scrollHeight);
            });
        },
        error: function () {
            alertify.error("Error de eliminado")
        }
    });
}

$(document).ready(function () {
    var user = $("#username").val();
    var opcion = '1';
    datos = {"user":user,"opcion":opcion};
    $.ajax({
        data: datos,
        type: "POST",
        dataType: "json",
        url: "php/lobby.php",
    })
        .done(function (data) {

            if (data.estado == "ok") {
                $( "#opciones" ).append( "Opciones Avanzadas" );
            }

        })
        .fail(function () {
           alertify.error("Funcion no funciono. Error en el js: lobby.js funcion de ver panel de control.")
        });
});

var mensajesThead;
window.onload = function () {
    mensajesThead = setInterval(Mensajes, 60000);
    cargarMensajes();
};


text:
using GSDRequirementsCSharp.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GSDRequirementsCSharp.Domain.ViewModels
{
    public class IssueCommentContentViewModel
    {
        public Guid Id { get; set; }

        public string Locale { get; set; }

        public string Description { get; set; }

        public bool IsUpdated { get; set; }

        public static IssueCommentContentViewModel FromModel(IssueCommentContent model)
        {
            return new IssueCommentContentViewModel
            {
                Id = model.Id,
                Locale = model.Locale,
                Description = model.Description,
                IsUpdated = model.IsUpdated
            };
        }
    }
}


text:
import {AddReferenceComponent} from './add-reference.component';
import {ButtonComponent} from './button.component';
import {CheckboxComponent} from './checkbox.component';
import {CheckboxesComponent} from './checkboxes.component';
import {FileComponent} from './file.component';
import {HiddenComponent} from './hidden.component';
import {InputComponent} from './input.component';
import {MessageComponent} from './message.component';
import {NoneComponent} from './none.component';
import {NumberComponent} from './number.component';
import {RadiosComponent} from './radios.component';
import {RootComponent} from './root.component';
import {SectionComponent} from './section.component';
import {SelectComponent} from './select.component';
import {WidgetComponent} from './widget.component';
import {SubmitComponent} from './submit.component';
import {TabsComponent} from './tabs.component';
import {TextareaComponent} from './textarea.component';
import {ToolBarComponent} from "./toolbar.component";

export const BASIC_WIDGETS = [
    AddReferenceComponent
    , ButtonComponent
    , CheckboxComponent
    , CheckboxesComponent
    , FileComponent
    , HiddenComponent
    , InputComponent
    , MessageComponent
    , NoneComponent
    , NumberComponent
    , RadiosComponent
    , RootComponent
    , SectionComponent
    , SelectComponent
    , WidgetComponent
    , SubmitComponent
    , TabsComponent
    , TextareaComponent
    , ToolBarComponent
];

export {AddReferenceComponent} from './add-reference.component';
export {ButtonComponent} from './button.component';
export {CheckboxComponent} from './checkbox.component';
export {CheckboxesComponent} from './checkboxes.component';
export {FileComponent} from './file.component';
export {HiddenComponent} from './hidden.component';
export {InputComponent} from './input.component';
export {MessageComponent} from './message.component';
export {NoneComponent} from './none.component';
export {NumberComponent} from './number.component';
export {RadiosComponent} from './radios.component';
export {RootComponent} from './root.component';
export {SectionComponent} from './section.component';
export {SelectComponent} from './select.component';
export {WidgetComponent} from './widget.component';
export {SubmitComponent} from './submit.component';
export {TabsComponent} from './tabs.component';
export {TextareaComponent} from './textarea.component';
export {ToolBarComponent} from "./toolbar.component";


text:
package org.consulo.projectImport.model.library;

/**
 * @author VISTALL
 * @since 17:35/19.06.13
 */
public enum OrderRootTypeModel {
  BINARIES,
  SOURCES,
  DOCUMENTATION,
  ANNOTATION
}


text:
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.

module.exports = Duplex;
var util = require('util');
if (!util.isUndefined) {
  var utilIs = require('core-util-is');
  for (var f in utilIs) {
    util[f] = utilIs[f];
  }
}
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');

util.inherits(Duplex, Readable);

Object.keys(Writable.prototype).forEach(function(method) {
  if (!Duplex.prototype[method])
    Duplex.prototype[method] = Writable.prototype[method];
});

function Duplex(options) {
  if (!(this instanceof Duplex))
    return new Duplex(options);

  Readable.call(this, options);
  Writable.call(this, options);

  if (options && options.readable === false)
    this.readable = false;

  if (options && options.writable === false)
    this.writable = false;

  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false)
    this.allowHalfOpen = false;

  this.once('end', onend);
}

// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended)
    return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(this.end.bind(this));
}