Esempio n. 1
0
    def __init__(self, parent=None):
        super(TelepatManager, self).__init__(parent)
        self.applications = []

        uic.loadUi('telepatmanager.ui', self)
        console.set_widget(self.loggerWidget)

        self.actionConnect.triggered.connect(self.openConnection)
        self.actionRefresh.triggered.connect(self.refreshContexts)
        self.actionEditApp.triggered.connect(self.editApplication)
        self.actionShowNameId.toggled.connect(self.showNameId)
        self.contextsTreeView.clicked.connect(self.itemSelected)
        self.filterLineEdit.textChanged.connect(self.filterChanged)

        # Set up the UI
        self.actionRefresh.setEnabled(False)
        self.loggerWidget.setFont(QtGui.QFont(QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)))
        self.setupHistoryMenu()
        self.setupSplitters()
        self.setupAppsCombobox()
        self.treeViewLayout.setContentsMargins(0, 0, 0, 0)
        self.stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.setUnifiedTitleAndToolBarOnMac(True)

        self.contexts_model = QtGui.QStandardItemModel()
        self.proxy = QtCore.QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.contexts_model)
        self.proxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.contextsTreeView.setModel(self.proxy)

        console.log("Application started")
def clonar_repositorio(directorio, url):
    if os.path.exists(os.path.join('..', directorio)):
        console.log("  Evitando clonar %s porque ya existe." %(directorio))
        os.system('cd ..; git pull ')
    else:
        console.success("Clonando %s ..." %(directorio))
        os.system('cd ..; git clone ' + url + " " + directorio)
Esempio n. 3
0
def __generate_bundle_pom(bundle, packaging):
    """
    Generate the pom.xml file for the given bundle and given packaging
    :param bundle: The bundle to generate the pom for
    :param packaging: The type of packaging (feature or plugin)
    :return: True if the operation succeeded, False otherwise
    """
    if len(bundle.targets) == 0:
        console.log("Bundle " + bundle.name + " has no target => skipped", "WARNING")
        return True
    if len(bundle.targets) >= 2:
        console.log("Bundle " + bundle.name + " has more than one target:", "ERROR")
        for target in bundle.targets:
            console.log("\t" + target, "ERROR")
        return False
    if os.path.isfile(os.path.join(bundle.location, "pom.xml")):
        console.log("Bundle " + bundle.name + " already has pom.xml => skipped")
        return True
    relative = os.path.relpath(".", bundle.location)
    relative = os.path.join(relative, bundle.targets[0].pom)
    impl = xml.dom.minidom.getDOMImplementation()
    doc = impl.createDocument(None, "project", None)
    project = doc.documentElement
    __xml_append_text(doc, project, "modelVersion", MAVEN_MODEL_VERSION)
    parent = doc.createElement("parent")
    project.appendChild(parent)
    __xml_append_tycho_ref(doc, parent, PRODUCT_GROUP)
    __xml_append_text(doc, parent, "relativePath", relative)
    __xml_append_tycho_ref(doc, project, bundle.name)
    __xml_append_text(doc, project, "packaging", packaging)
    xmlutils.output(doc, os.path.join(bundle.location, "pom.xml"))
    console.log("Bundle " + bundle.name + " POM generated for target " + bundle.targets[0].name)
    return True
Esempio n. 4
0
def __cleanup_classpath(bundle):
    """
    Cleanup the classpath of the specified Eclipse bundle
    :param bundle: An Eclipse bundle
    :return: None
    """
    subs = os.listdir(bundle.location)
    if not ".classpath" in subs:
        return
    doc = xml.dom.minidom.parse(os.path.join(bundle.location, ".classpath"))
    dirty = False
    for entry in doc.getElementsByTagName("classpathentry"):
        data = entry.getAttribute("excluding")
        folder = entry.getAttribute("path")
        if data is not None and len(data) > 0:
            files = data.split("|")
            for file in files:
                if file is not None and len(file) > 0:
                    dirty = True
                    full = os.path.join(bundle.location, os.path.join(folder, os.path.join(file)))
                    print("Found " + full)
                    if full.endswith("/"):
                        subprocess.call(["git", "rm", "-r", full])
                    else:
                        subprocess.call(["git", "rm", full])
            entry.parentNode.removeChild(entry)
    if dirty:
        xmlutils.output(doc, os.path.join(bundle.location, ".classpath"))
        console.log("Bundle " + bundle.name + " => Fixed .classpath to remove excluded sources")
Esempio n. 5
0
    def gen_segments(x, y, old_w, old_d):
        new_segments = []
        d = old_d % 360

        target = (90, 270)[d > 180]
        upper = target - d
        lower = random.randint(-10, 10)
        if lower > upper:
            lower, upper = upper, lower
        d += random.randint(lower, upper)

        dx = int(10*sin(radians(d)))
        dy = int(10*cos(radians(d)))
        width = min(3, max(1, old_w + random.randint(-1, 1)))
        log(d, dx, dy, m='cave')

        if (x+dx in range(chunk_pos - world_gen['max_cave_radius'],
                          chunk_pos + world_gen['max_cave_radius'] + world_gen['chunk_size']) and
           0 < y+dy < ground_heights[x+dx]):

            new_segments.append(((x, y), (dx, dy), width))
            new_segments += gen_segments(x + dx, y + dy, width, d)
            if random.random() < 0.1:
                new_segments += gen_segments(x + dx, y + dy, width, random.choice([-90, 90]) + d)

        return new_segments
Esempio n. 6
0
def isValidRepo(path):
	try:
		repo = git.Repo(path)
		console.log('Valid Repo!', 'info')
		return True
	except:
		console.log('is Not Valid Repo!', 'error')
		return False
Esempio n. 7
0
def create_lighting_buffer(width, height, x, y, map_, slice_heights, bk_objects, sky_colour, day, lights):
    if settings_ref['render_c']:
        return render_c.create_lighting_buffer(width, height, x, y, map_, slice_heights, bk_objects, sky_colour, day, lights, settings_ref)
    else:
        global day_global
        day_global = day

        log('Not implemented: Python create_lighting_buffer function', m='warning')
Esempio n. 8
0
    def _event_set_players(self, players):
        self.current_players.update(players)
        self.redraw = True

        # TODO: Move the login checks out of this method
        if self._name in players and not self.finished_login.is_set():
            log('FINISHED LOGIN')
            self.finished_login.set()
Esempio n. 9
0
def get_light_level(*args):
    if settings_ref['render_c']:
        result = render_c.get_world_light_level(*args)
    else:
        result = day_global
        log('Not implemented: Python get_light_level function', m='warning')

    log('{}'.format(result), m='lighting')
    return result
Esempio n. 10
0
    def local_interface_kill_server(self):
        log('Server stopped')

        self.serving = False
        self._update_clients({'event': 'logout', 'args': ['Server Closed']}, exclude=self.local_player)
        self.current_players = {}

        self._stop_server()
        self.port, self._stop_server = None, None
Esempio n. 11
0
    def __init__(self, name, ip, port):
        self.map_ = {}
        self.slice_heights = {}
        self.current_players = {}
        self.game = True
        self.error = None
        self._name = name

        # We cannot serve, we are connected to a server.
        # TODO: Maybe we can do this better...?
        self.serving = None

        try:
            self._sock = network.connect(ip, int(port))
        except (ConnectionRefusedError, ValueError):
            self.error = 'Cannot connect to server'
            return

        self._sock.setblocking(True)

        self.finished_login = Event()

        self._listener_t = Thread(target=self._listener)
        self._listener_t.daemon = True
        self._listener_t.start()

        # Login
        self._send('login', [self._name])

        # Server doesn't respond
        if not self.finished_login.wait(3):
            self.error = 'No response from server on login'
            log(self.error)

            self._sock.close()
            return

        # Server responds with error
        if self.error is not None:
            log('Error response from server on login:'******'tick']
        self._dt = False
        self._last_tick = time()

        self._chunks_requested = set()

        self._send('get_players')
        self._send('get_time')

        self.redraw = False
        self.view_change = False
Esempio n. 12
0
def execute(arguments):
    """
    Executes the update process
    :return: None
    """
    # Checks the arguments
    nb = len(arguments)
    if nb <= 1:
        print_usage()
        sys.exit(1)

    # Initializes the local data
    local = False
    simrel = SIMREL_PATH
    targets = []

    # Parse the arguments
    expect_local = False
    for arg in arguments[1:]:
        if arg == "-h" or arg == "--help":
            print_usage()
            sys.exit(0)
        elif arg == console.CLI_COLOR:
            console.USE_COLOR = True
        elif arg == "--simrel":
            expect_local = True
        elif expect_local:
            local = True
            simrel = arg
            expect_local = False
        else:
            targets.append(arg)

    # Checks the data
    if expect_local:
        console.log("Expected path the local SIMREL repo", "ERROR")
        print_usage()
        sys.exit(1)
    if len(targets) == 0:
        console.log("No target given", "ERROR")
        print_usage()
        sys.exit(1)

    # Clone the SIMREL repo if needed
    if local:
        console.log("Using local simrel at " + simrel)
    else:
        console.log("Cloning the simrel repository from Eclipse")
        subprocess.call(["git", "clone", SIMREL_GIT, simrel])
    # Do the updates
    for target in targets:
        update(simrel, target)
    # Cleanup if required
    if not local:
        console.log("Cleaning up ...")
        shutil.rmtree(simrel)
Esempio n. 13
0
    def collision_system(self):
        map_width = self.game.settings['width']
        map_height = self.game.settings['height']
        
        for bullet in self.bullets:
            # Bullet-wall collision
            if (bullet.x < 0 or bullet.x > map_width or
                    bullet.y < 0 or bullet.y > map_height):
                self.bullets.remove(bullet)
                continue
            
            # Bullet-enemy
            for enemy in self.enemies:
                force_break = 0
                if circle_collision(bullet, enemy):
                    if random.randint(0, 100) <= self.config['powerup_chance']:
                        powerup = PowerupFactory.create_random()
                        powerup.x, powerup.y = enemy.x, enemy.y
                        self.powerups.append(powerup)

                    points = enemy.move_speed * 2
                    self.add_score(points)
                    self.enemies.remove(enemy)
                    self.bullets.remove(bullet)
                    force_break = 1
                    
                # NOTE: Workaround to prevent nonexistent bullets (bullets that
                # were already killed) from being tested against
                if force_break: break
                    
        for enemy in self.enemies:
            # Enemy-wall
            if not 0 < enemy.x < map_width or not 0 < enemy.y < map_height:
                self.enemies.remove(enemy)
                continue
                
            # Enemy-tank
            if circle_collision(enemy, self.tank):
                self.tank.health -= enemy.impact * self.tank.get('damage_modifier')
                self.enemies.remove(enemy)
                continue
                
            # Enemy-enemy
            for enemy2 in self.enemies:
                if circle_collision(enemy, enemy2) and enemy != enemy2:
                    self.enemies.remove(enemy)
                    self.enemies.remove(enemy2)
                    break # Stop iterating because `enemy` has been deleted
            
        for powerup in self.powerups:
            # Powerup-tank
            if circle_collision(powerup, self.tank):
                self.tank.apply_powerup(powerup)
                powerup.health = 0
                console.log("Picked up powerup: " + powerup.name)
Esempio n. 14
0
    def event_logout(self, sock=None):
        # Re-add all players which aren't the sock
        players = {}
        for name, conn in self.current_players.items():
            if conn == sock:
                log('Logging out', name, sock)
                self._update_clients({'event': 'remove_player', 'args': [name]}, name)
            else:
                players[name] = sock

        self.current_players = players
Esempio n. 15
0
 def create_ui(self):
     """Create the HUD"""
     ui_path = 'resources/ui/play_ui.ini'
     w, h = self.game.settings['width'], self.game.settings['height']
 
     self.ui = load_ui(ui_path, (w, h))
     
     try:
         self.ui['score_label'].x = w-self.ui['score_label'].width-10
     except ValueError:
         console.log("Score label not found in `" + ui_path + "`.")
    def _create_xpi(self, files_map=None):
        if not files_map:
            files_map = self.result_files

        xpi = zipfile.ZipFile(self.xpi_file, "w", compression=zipfile.ZIP_DEFLATED)
        if not self.config["verbose"]:
            console.log("building xpi", self.xpi_file)
        for i in files_map:
            if self.config["verbose"]:
                console.log("archiving", "%s to @%s@/%s" % (i[0], self.xpi_file, i[1]))
            xpi.write(i[0], i[1])  # source, path_inside_xpi
        xpi.close()
Esempio n. 17
0
    def event_login(self, name, sock):
        if name not in self.current_players.keys() and not name == self.local_player:
            log('Logging in: ' + name)

            if not name == self.local_player:
                # local_player already contains the local_player name
                self.current_players[name] = sock

            self._update_clients({'event': 'set_players', 'args': [{name: self.game.get_player(name)}]})
        else:
            log('Not Logging in: ' + name)
            return {'event': 'error', 'args': [{'event': 'login', 'message': 'Username in use'}]}
    def _preprocess(self, source, target, app_version=None):
        source_full = os.path.join(self.src_dir, source)
        target_full = os.path.join(self.build_dir, target)
        if not self.config["verbose"]:
            console.log("preprocessor.py", "... %s" % target_full)
        else:
            console.log("preprocessor.py", "... %s from %s" % (target_full, source_full))

        deps_tmp_file = os.path.join(self.build_dir, "deps.tmp")

        if not os.path.isdir(os.path.dirname(deps_tmp_file)):
            os.makedirs(os.path.dirname(deps_tmp_file)) # exist_ok=True

        if not os.path.isdir(os.path.dirname(target_full)):
            os.makedirs(os.path.dirname(target_full)) # exist_ok=True

        variables = []
        if app_version:
            variables = ["-D", "APP_VERSION="+str(app_version)]

        python2 = "python2"
        if "PYTHON2PATH" in os.environ:
            python2 = os.environ.get("PYTHON2PATH")
            if not (os.path.isfile(python2) or os.access(python2, os.X_OK)):
                print("Error: can't execute %s" % python2)
                print("Please check your PYTHON2PATH environment variable")
                sys.exit(1)

        cmd = []
        cmd = cmd + [python2, "build/preprocessor.py", "--marker=%"]
        cmd = cmd + ["--depend="+deps_tmp_file]
        cmd = cmd + variables
        cmd = cmd + ["--output="+target_full, source_full]

        try:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT,
                                    universal_newlines=True)
        except subprocess.CalledProcessError as e:
            print("BuildError: preprocessor.py returned no zero code (%i)" % e.returncode)
            print("Command: \"%s\"" % " ".join(str(a) for a in cmd))
            print(e.output, end="")
            os.remove(target_full)
            sys.exit(2)

        line = open(deps_tmp_file, "r").readline()
        line = re.sub(r"^[^:]*:", "", line)
        line = line.replace(os.path.abspath(self.src_dir)+"/", "")
        line = line.replace(source_full, "")
        line = line.strip()

        if line:
            deps = line.split(" ")
            self._update_dependencies(target, deps)
Esempio n. 19
0
def import_render_c():
    render_c = None

    sys.path += glob.glob('build/lib.*')
    try:
        import render_c
    except ImportError:
        log('Cannot import C renderer: disabling option.', m='warning')
        settings_ref['render_c'] = False

    saves.save_settings(settings_ref)

    return render_c
Esempio n. 20
0
def import_render_c():
    render_c = None

    sys.path += glob.glob('build/lib.*')
    try:
        import render_c
    except ImportError:
        log('Cannot import C renderer: disabling option.', m='warning')
        settings_ref['render_c'] = False

    saves.save_settings(settings_ref)

    return render_c
Esempio n. 21
0
def create_lighting_buffer(width, height, x, y, map_, slice_heights,
                           bk_objects, sky_colour, day, lights):
    if settings_ref['render_c']:
        return render_c.create_lighting_buffer(width, height, x, y, map_,
                                               slice_heights, bk_objects,
                                               sky_colour, day, lights,
                                               settings_ref)
    else:
        global day_global
        day_global = day

        log('Not implemented: Python create_lighting_buffer function',
            m='warning')
Esempio n. 22
0
 def process_input(self):
     """Process events and input such as keypresses, mouse button presses,
     and PyGame Events."""
     for event in pygame.event.get():
         if event.type == QUIT:
             console.log("Thanks for playing " + self.settings['title'] + "!")
             pygame.quit()
             sys.exit()
         elif event.type == KEYDOWN:
             if event.key == K_ESCAPE: # If ESC is pressed, QUIT the game
                 pygame.event.post(pygame.event.Event(QUIT))
                 
         self.screen.handle_input(event)
Esempio n. 23
0
    def local_interface_kill_server(self):
        log('Server stopped')

        self.serving = False
        self._update_clients({
            'event': 'logout',
            'args': ['Server Closed']
        },
                             exclude=self.local_player)
        self.current_players = {}

        self._stop_server()
        self.port, self._stop_server = None, None
Esempio n. 24
0
def saveSpectrogram(spectrogram, filePath):
    spectrum = spectrogram
    console.info("Range of spectrum is " + str(np.min(spectrum)) + " -> " +
                 str(np.max(spectrum)))
    image = np.clip(
        (spectrum - np.min(spectrum)) / (np.max(spectrum) - np.min(spectrum)),
        0, 1)
    console.info("Shape of spectrum is", image.shape)
    # Low-contrast image warnings are not helpful, tyvm
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        io.imsave(filePath, image)
    console.log("Saved image to", filePath)
Esempio n. 25
0
        def handle(self):
            while True:
                data = receive(self.request)

                if data:
                    response = self.data_handler(self.request, data)

                    if response:
                        send(self.request, response)
                else:
                    break

            log('Handler Exiting')
Esempio n. 26
0
def gen_cave_features(features, ground_heights, slices_biome, chunk_pos, meta):

    def gen_segments(x, y, old_w, old_d):
        new_segments = []
        d = old_d % 360

        target = (90, 270)[d > 180]
        upper = target - d
        lower = random.randint(-10, 10)
        if lower > upper:
            lower, upper = upper, lower
        d += random.randint(lower, upper)

        dx = int(10*sin(radians(d)))
        dy = int(10*cos(radians(d)))
        width = min(3, max(1, old_w + random.randint(-1, 1)))
        log(d, dx, dy, m='cave')

        if (x+dx in range(chunk_pos - world_gen['max_cave_radius'],
                          chunk_pos + world_gen['max_cave_radius'] + world_gen['chunk_size']) and
           0 < y+dy < ground_heights[x+dx]):

            new_segments.append(((x, y), (dx, dy), width))
            new_segments += gen_segments(x + dx, y + dy, width, d)
            if random.random() < 0.1:
                new_segments += gen_segments(x + dx, y + dy, width, random.choice([-90, 90]) + d)

        return new_segments

    for x in range(chunk_pos, chunk_pos + world_gen['chunk_size']):

        # TODO: Each of these `if` blocks should be abstracted into a function
        #         which just returns the `attrs` object.

        if features.get(x) is None:
            # Init to empty, so 'no features' is cached.
            features[x] = {}

        # If it is not None, it has all ready been generated.
        if features[x].get('cave') is None:

            random.seed(str(meta['seed']) + str(x) + 'cave')
            if random.random() <= world_gen['cave_chance']:

                attrs = {}
                attrs['y'] = random.randint(0, ground_heights[x] + 1)

                attrs['segments'] = gen_segments(x, attrs['y'], 2, 180)

                features[x]['cave'] = attrs
                log('got a cave', features[x]['cave'], m='cave')
def generate_data_arrs(file_path, slice_size_t=1536):
    audio, sr = conversion.file_to_audio(file_path)
    amplitude, phase = conversion.audio_to_spectrogram(audio,
                                                       fft_window_size=1536)
    amplitude = amplitude[:, :2 * slice_size_t]

    # clipping only the first part to minimize "easy" repeated audio
    content = amplitude[:, :slice_size_t]
    style = amplitude[:, slice_size_t:2 * slice_size_t]
    freq_rang = [np.min(content, 1), np.max(content, 1)]

    console.log("Content shape", content.shape)
    console.log("Style shape", style.shape)
    # it's a lot of work to compute the x...
    fundamental_mask = sst.extract_fundamental(amplitude)
    #console.stats(fundamental_mask, "fundamental_mask")
    #console.stats(amplitude, "amplitude")
    fundamental_freqs, fundamental_amps = sst.extract_fundamental_freqs_amps(
        fundamental_mask, amplitude)
    content_fundamental_freqs = fundamental_freqs[:slice_size_t]
    content_fundamental_amps = fundamental_amps[:slice_size_t]
    style_fundamental_freqs = fundamental_freqs[slice_size_t:2 * slice_size_t]
    # features are computed directly and then sliced
    features = sst.get_feature_array(file_path) / 5
    features = sst.resize(features, (2048, amplitude.shape[1]))
    content_features = features[:, :slice_size_t]
    style_features = features[:, slice_size_t:2 * slice_size_t]
    stylized = sst.audio_patch_match(content,
                                     style,
                                     content_fundamental_freqs,
                                     style_fundamental_freqs,
                                     content_features,
                                     style_features,
                                     iterations=10)  # Harmonic recovery
    content_harmonics = sst.fundamental_to_harmonics(content_fundamental_freqs,
                                                     content_fundamental_amps,
                                                     content)
    content_harmonics = sst.grey_dilation(content_harmonics, size=3)
    content_harmonics *= content.max() / content_harmonics.max()
    # Sibilant recovery
    content_sibilants = sst.get_sibilants(content, content_fundamental_amps)
    content_sibilants *= content.max() / content_sibilants.max()

    x_arr = np.dstack([
        np.mean(stylized, axis=2),
        np.mean(content_harmonics, axis=2),
        np.mean(content_sibilants, axis=2)
    ])
    y_arr = np.mean(content, axis=2)
    style_arr = np.mean(style, axis=2)
    return 0, 0, style_arr
Esempio n. 28
0
def main():
    while True:
        if check_connection() is False:
            log('No internet connection!')
            break

        worker = WorkerThread()
        progress = ProgressThread(worker)
        worker.start()
        progress.start()
        progress.join()

        delay = args.delay
        time.sleep(delay)
Esempio n. 29
0
    def event_logout(self, sock=None):
        # Re-add all players which aren't the sock
        players = {}
        for name, conn in self.current_players.items():
            if conn == sock:
                log('Logging out', name, sock)
                self._update_clients({
                    'event': 'remove_player',
                    'args': [name]
                }, name)
            else:
                players[name] = sock

        self.current_players = players
Esempio n. 30
0
def calculate_attack(entity, ax, ay, radius, strength):
    dist_from_attack_sq = (ax - entity['x'])**2 + (ay - entity['y'])**2
    success = False

    if dist_from_attack_sq <= radius**2:
        dist_from_attack = sqrt(dist_from_attack_sq)

        affected_strength = (1 - (dist_from_attack / radius)) * strength
        log(dist_from_attack, affected_strength, m='mobs')

        entity['health'] -= affected_strength

        success = True
    return success
Esempio n. 31
0
def generate(inputs, targets, include_pattern, exclude_pattern):
    """
    Generate the Tycho data and files
    :param inputs: Array of input directories to load Eclipse plugins and features from
    :param targets: Array of build targets
    :param include_pattern: Pattern matching Eclipse bundle to include into a build target
    :param exclude_pattern: Pattern matching Eclipse bundle to exclude from any build target
    :return: The error code, or 0 if all went well
    """
    # Build repo
    console.log("== Preparing the repository ...")
    repo = __build_repository(inputs, include_pattern, exclude_pattern)
    if repo is None:
        return 1
    # Setup the bundles' target data
    for target in targets:
        __add_target(repo, target.feature, target)
    # Generate all bundles POM
    console.log("== Generating POM for features ...")
    for name in iter(sorted(repo.features)):
        if not __generate_bundle_pom(repo.features[name], "eclipse-feature"):
            return 2
    console.log("== Generating POM for plugins ...")
    for name in iter(sorted(repo.plugins)):
        if not __generate_bundle_pom(repo.plugins[name], "eclipse-plugin"):
            return 2
    # Update the targets' top pom.xml
    console.log("== Updating the module references in top POMs ...")
    for target in targets:
        __update_modules(repo, target)
    return 0
Esempio n. 32
0
def generate(inputs, targets, include_pattern, exclude_pattern):
    """
    Generate the Tycho data and files
    :param inputs: Array of input directories to load Eclipse plugins and features from
    :param targets: Array of build targets
    :param include_pattern: Pattern matching Eclipse bundle to include into a build target
    :param exclude_pattern: Pattern matching Eclipse bundle to exclude from any build target
    :return: The error code, or 0 if all went well
    """
    # Build repo
    console.log("== Preparing the repository ...")
    repo = __build_repository(inputs, include_pattern, exclude_pattern)
    if repo is None:
        return 1
    # Setup the bundles' target data
    for target in targets:
        __add_target(repo, target.feature, target)
    # Generate all bundles POM
    console.log("== Generating POM for features ...")
    for name in iter(sorted(repo.features)):
        if not __generate_bundle_pom(repo.features[name], "eclipse-feature"):
            return 2
    console.log("== Generating POM for plugins ...")
    for name in iter(sorted(repo.plugins)):
        if not __generate_bundle_pom(repo.plugins[name], "eclipse-plugin"):
            return 2
    # Update the targets' top pom.xml
    console.log("== Updating the module references in top POMs ...")
    for target in targets:
        __update_modules(repo, target)
    return 0
def list_configs(opt):
    config = utils.get_config()

    def to_str(value, key):
        return "[%s] %s %s" % (value, "-", key)

    if opt == 'disk':
        disks = config[utils.DISK_SECTION]
        console.info('Disks list...', True)
        console.log('\n'.join([to_str(value, key) for key, value in disks.iteritems()]))
    if opt == 'inet':
        inet = config[utils.INET_SECTION]
        console.info('Net Interface list...', True)
        console.log('\n'.join([to_str(value, key) for key, value in inet.iteritems()]))
Esempio n. 34
0
    def __init__(self):
        mashup = Input(shape=(None, None, 1), name='input')
        convA = Conv2D(64, 3, activation='relu', padding='same')(mashup)
        conv = Conv2D(64,
                      4,
                      strides=2,
                      activation='relu',
                      padding='same',
                      use_bias=False)(convA)
        conv = BatchNormalization()(conv)

        convB = Conv2D(64, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(64,
                      4,
                      strides=2,
                      activation='relu',
                      padding='same',
                      use_bias=False)(convB)
        conv = BatchNormalization()(conv)

        conv = Conv2D(128, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(128,
                      3,
                      activation='relu',
                      padding='same',
                      use_bias=False)(conv)
        conv = BatchNormalization()(conv)
        conv = UpSampling2D((2, 2))(conv)

        conv = Concatenate()([conv, convB])
        conv = Conv2D(64, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(64, 3, activation='relu', padding='same',
                      use_bias=False)(conv)
        conv = BatchNormalization()(conv)
        conv = UpSampling2D((2, 2))(conv)

        conv = Concatenate()([conv, convA])
        conv = Conv2D(64, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(64, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(32, 3, activation='relu', padding='same')(conv)
        conv = Conv2D(1, 3, activation='relu', padding='same')(conv)
        acapella = conv
        m = Model(inputs=mashup, outputs=acapella)
        console.log("Model has", m.count_params(), "params")
        m.compile(loss='mean_squared_error', optimizer='adam')
        self.model = m
        # need to know so that we can avoid rounding errors with spectrogram
        # this should represent how much the input gets downscaled
        # in the middle of the network
        self.peak_downscale_factor = 4
 def __init__(self, config):
     self.config = config
     metrics = Metrics().get()
     m = Modeler().get()
     loss = Loss().get()
     optimizer = Optimizer().get()
     console.log("Model has", m.count_params(), "params")
     m.compile(loss=loss, optimizer=optimizer, metrics=metrics)
     m.summary(line_length=150)
     self.model = m
     # need to know so that we can avoid rounding errors with spectrogram
     # this should represent how much the input gets downscaled
     # in the middle of the network
     self.peakDownscaleFactor = 4
Esempio n. 36
0
def 命令_显示附件宠物信息():
    "显示在附近已被加载出来的宠物信息,未加载出来的无法显示"
    cs = GameObject.FindObjectsOfType(Character)
    for c in cs:
        if not c.IsPlayer and c.AnimalData != None:
            if c.AnimalData.OnwerType == 1:
                type = Config.GetLangText(c.Name)
                if c.AnimalData.SelfAnimalData != None:
                    name = c.AnimalData.SelfAnimalData.Name
                else:
                    name = ""
                console.log(
                    "种类:%s\t\t 名字:<color=#66CD00>%s</color>\t\t ID:%s" %
                    (type, name, c.gameObject.name.Replace("(Character)", "")))
Esempio n. 37
0
def 命令_自动回血():
    "当血量低于50%时,自动加满血量"

    def autoHealth():
        if Config.PlayerCharacter:
            if Config.PlayerCharacter.Hp < Config.PlayerCharacter.MaxHp / 2:
                Config.PlayerCharacter.Hp = Config.PlayerCharacter.MaxHp

    if not core.isContainsUpdateCallback(keplerth_commands, autoHealth):
        core.registerUpdateCallback(keplerth_commands, autoHealth)
        console.log("开启自动回血")
    else:
        core.unRegisterUpdateCallback(keplerth_commands, autoHealth)
        console.log("关闭自动回血")
Esempio n. 38
0
def calculate_attack(entity, ax, ay, radius, strength):
    dist_from_attack_sq = (ax - entity['x'])**2 + (ay - entity['y'])**2
    success = False

    if dist_from_attack_sq <= radius**2:
        dist_from_attack = sqrt(dist_from_attack_sq)

        affected_strength = (1 - (dist_from_attack / radius)) * strength
        log(dist_from_attack, affected_strength, m='mobs')

        entity['health'] -= affected_strength

        success = True
    return success
Esempio n. 39
0
    def _create_xpi(self, files_map=None):
        if not files_map:
            files_map = self.result_files

        xpi = zipfile.ZipFile(self.xpi_file,
                              "w",
                              compression=zipfile.ZIP_DEFLATED)
        if not self.config["verbose"]:
            console.log("building xpi", self.xpi_file)
        for i in files_map:
            if self.config["verbose"]:
                console.log("archiving",
                            "%s to @%s@/%s" % (i[0], self.xpi_file, i[1]))
            xpi.write(i[0], i[1])  # source, path_inside_xpi
        xpi.close()
Esempio n. 40
0
def 命令_杀死周围生物(*可选_排除中立):
    "消灭范围内的生物,例: <color=#FF4500>杀死周围生物 是</color> 或 <color=#FF4500>杀死周围生物</color>"
    justMonster = False
    if len(可选_排除中立) > 0:
        justMonster = True

    cs = GameObject.FindObjectsOfType(Character)
    for c in cs:
        if not c.IsPlayer:
            if c.type == CharacterType.Monster or c.type == CharacterType.Humanoid or (
                    not justMonster and c.type == CharacterType.Animal):
                console.log(
                    "杀死 <color=red>%s</color> <color=yellow>%s</color>" %
                    (c.type, Config.GetLangText(c.Name)))
                c.Hp = 0
Esempio n. 41
0
def spawn(mobs, players, map_, x_start_range, y_start_range, x_end_range,
          y_end_range):
    log("spawning", x_start_range, x_end_range, m='mobs')

    n_mobs_to_spawn = random.randint(0, 5) if random.random() < mob_rate else 0
    new_mobs = {}

    max_attempts = 100 * n_mobs_to_spawn
    attempts = 0

    while (len(mobs) + len(new_mobs) < mob_limit
           and len(new_mobs) < n_mobs_to_spawn and attempts < max_attempts):

        attempts += 1

        mx = random.randint(x_start_range, x_end_range - 1)
        my = random.randint(y_start_range, y_end_range - 1)

        if mx not in map_ or my < 1 or my > len(map_[mx]) - 2: continue

        feet = map_[mx][my]
        head = map_[mx][my - 1]
        floor = map_[mx][my + 1]

        closest_player_dist = min(
            map(lambda p: abs(p['x'] - mx), players.values()))

        spot_found = (not terrain.is_solid(feet) and not terrain.is_solid(head)
                      and terrain.is_solid(floor)
                      and render_interface.get_light_level(
                          mx, my) < max_spawn_light_level
                      and render_interface.get_light_level(
                          mx, my - 1) < max_spawn_light_level
                      and not closest_player_dist < spawn_player_range_min)

        if spot_found:
            new_mobs[str(uuid4())] = {
                'x': mx,
                'y': my,
                'x_vel': 0,
                'health': max_mob_health,
                'type': 'mob',
                'last_attack': 0
            }

    mobs.update(new_mobs)

    return new_mobs
Esempio n. 42
0
def setup():
    log('Start\n')

    meta = saves.get_global_meta()
    settings = saves.get_settings()

    profile = c.getenv_b('PYCRAFT_PROFILE')

    name = c.getenv('PYCRAFT_NAME') or settings.get('name') or ui.name(settings)
    port = c.getenv('PYCRAFT_PORT') or meta.get('port') or 0

    init_colours(settings)
    saves.check_map_dir()

    print(HIDE_CUR + CLS)
    return meta, settings, profile, name, port
Esempio n. 43
0
def list_configs(opt):
    config = utils.get_config()

    def to_str(value, key):
        return "[%s] %s %s" % (value, "-", key)

    if opt == 'disk':
        disks = config[utils.DISK_SECTION]
        console.info('Disks list...', True)
        console.log('\n'.join(
            [to_str(value, key) for key, value in disks.iteritems()]))
    if opt == 'inet':
        inet = config[utils.INET_SECTION]
        console.info('Net Interface list...', True)
        console.log('\n'.join(
            [to_str(value, key) for key, value in inet.iteritems()]))
Esempio n. 44
0
class Main(object):

    def __init__(self):
        self._behaviorGos = {}
        self._load()
        self.debug_go = None
        file_mgr.load(None) #load mod save


    def Update(self):
        #debug
        if Input.GetKeyDown(KeyCode.F12):
            if not self.debug_go:
                path2 = "C:/Users/Administrator/Desktop/New Unity Project 2/AssetBundles/StandaloneWindows/debug_hierarchy";
                asset2 = AssetBundle.LoadFromFile(path2);
                go = asset2.LoadAsset("Canvas");
                self.debug_go = GameObject.Instantiate(go);
                GameObject.DontDestroyOnLoad(self.debug_go);
                asset2.Unload(False);
            else:
                self.debug_go.SetActive(not self.debug_go.active);

        if Input.GetKeyDown(KeyCode.R) and Input.GetKey(KeyCode.LeftControl):
            self._reload()
        for mod in self._behaviorGos:
            if config.ModList[mod].Count <= 0 or config.ModList[mod].Contains(config.CurrentScene):
                self._behaviorGos[mod].SetActive(True);
            else:
                self._behaviorGos[mod].SetActive(False);
        for module, funs in updateCallback.iteritems():
            for fun in funs:
                fun()
       

    def _load(self):
        for mod, scenes in config.ModList.iteritems():
            if not self._behaviorGos.ContainsKey(mod):
                console.log(Text.getText(Text.LOAD_MOD, mod.__name__))
                go = behavior_creator(mod.__name__, mod.MonoBehaviour, True)
                go.SetActive(False)
                self._behaviorGos.Add(mod, go)
            else:
                console.error(Text.getText(Text.MOD_ALREADY_EXIT, mod.__name__))


    def _reload(self):
        try:
            for mod in self._behaviorGos.Keys:
                GameObject.DestroyImmediate(self._behaviorGos[mod])
                reload(mod)
                self._behaviorGos.Remove(mod)
                console.log(Text.getText(Text.UNLOAD_MOD, mod.__name__))
        except StandardError, e:
            print 'except:', e

        for module in config.CommandModules:
            console.log(Text.getText(Text.UNLOAD_CMD_SCRIPT, mod.__name__))
        updateCallback.Clear()
        self._load()
Esempio n. 45
0
    def recieve(self):

        year = self.year.get('1.0', tk.END).strip('\n')
        month = self.month.get('1.0', tk.END).strip('\n')
        day = self.day.get('1.0', tk.END).strip('\n')
        id_ = self.search.get('1.0', tk.END).strip('\n')

        if id_ == '':
            messagebox.showerror('Fatal Error', 'Please enter an ID')
            console.log(console.E, 'Invalid ID entered')

        else:
            try:
                id_ = int(id_)
            except ValueError:
                messagebox.showerror('Fatal Error', 'ID must be an integer')
                console.log(console.E, 'ID not an integer')

        if day != '' and month != '' and year != '' and id_ != '':
            try:
                day = int(day)
            except ValueError:
                messagebox.showerror('Fatal Error',
                                     'Day must be an integer between 1 and 7')
                console.log(console.E, 'Day not an integer')

            try:
                month = int(month)
            except ValueError:
                messagebox.showerror(
                    'Fatal Error',
                    'Month must be an integer between 1 and 31/30/29')
                console.log(console.E, 'Month not an integer')

            try:
                year = int(year)
            except ValueError:
                messagebox.showerror('Fatal Error', 'Year must be an integer')
                console.log(console.E, 'Year not an integer')

            room_request = ts.Room(id_, year=year, month=month, day=day)
            self.process(room_request)

        else:
            room_request = ts.Room(id_)
            self.process(room_request)
Esempio n. 46
0
def spawn(mobs, players, map_, x_start_range, y_start_range, x_end_range, y_end_range):
    log("spawning", x_start_range, x_end_range, m='mobs');

    n_mobs_to_spawn = random.randint(0, 5) if random.random() < mob_rate else 0
    new_mobs = {}

    max_attempts = 100 * n_mobs_to_spawn
    attempts = 0

    while (len(mobs) + len(new_mobs) < mob_limit and
           len(new_mobs) < n_mobs_to_spawn and
           attempts < max_attempts):

        attempts += 1

        mx = random.randint(x_start_range, x_end_range-1)
        my = random.randint(y_start_range, y_end_range-1)

        if mx not in map_ or my < 1 or my > len(map_[mx]) - 2: continue

        feet = map_[mx][my]
        head = map_[mx][my - 1]
        floor = map_[mx][my + 1]

        closest_player_dist = min(map(lambda p: abs(p['x'] - mx), players.values()))

        spot_found = (not terrain.is_solid(feet) and
                      not terrain.is_solid(head) and
                      terrain.is_solid(floor) and
                      render_interface.get_light_level(mx, my) < max_spawn_light_level and
                      render_interface.get_light_level(mx, my - 1) < max_spawn_light_level and
                      not closest_player_dist < spawn_player_range_min)

        if spot_found:
            new_mobs[str(uuid4())] = {
                'x': mx,
                'y': my,
                'x_vel': 0,
                'health': max_mob_health,
                'type': 'mob',
                'last_attack': 0
            }

    mobs.update(new_mobs)

    return new_mobs
Esempio n. 47
0
def cleanupBuildProperties(bundle):
	subs = os.listdir(bundle.location)
	if not "build.properties" in subs:
		return
	properties = open(os.path.join(bundle.location, "build.properties"), "r")
	found = False
	for line in properties:
		if line.find("src.includes") != -1:
			found = True
			break
	properties.close()
	if not found:
		if not "about.html" in subs:
			shutil.copy("about.html", os.path.join(bundle.location, "about.html"))
		properties = open(os.path.join(bundle.location, "build.properties"), "a")
		properties.write("src.includes = about.html\n")
		properties.close()
		console.log("Bundle " + bundle.name + " => Fixed build.properties to add src.includes")
Esempio n. 48
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('key',
                        help='key name to be fetched ("." to fetch all)')
    parser.add_argument('conf', help='path to a config file')

    ns = parser.parse_args()

    try:
        val = fetch_value_from_file(ns.key, ns.conf)
    except KeyError:
        log('no such key: ' + ns.key)
        sys.exit(1)

    if isinstance(val, dict) or isinstance(val, list):
        print yaml.dump(val)
    else:
        print val
    def _generate_install_manifest(self, source, target):
        source = os.path.join(self.src_dir, source)
        target = os.path.join(self.build_dir, target)
        if not self.config["verbose"]:
            console.log("generating", target)
        else:
            console.log("generating", "%s from %s" % (target, source))

        if not os.path.isdir(os.path.dirname(target)):
            os.makedirs(os.path.dirname(target))  # exist_ok=True

        with open(source, "rt") as source_file:
            with open(target, "wt") as target_file:
                for l in source_file:
                    l = l.replace("@VERSION@", str(self.config["version"]))
                    l = l.replace("@MIN_VERSION@", str(self.config["min-version"]))
                    l = l.replace("@MAX_VERSION@", str(self.config["max-version"]))
                    target_file.write(l)
Esempio n. 50
0
def main():
    stylized_img = np.load("stylized_img.npy")
    content_phase = np.load("content_phase.npy")
    for radius in [0.2, 0.5, 1, 1.5]:
        # stylized_image_sharp = unsharp_mask(stylized_img, radius=radius, amount=1)
        stylized_img_blur = cv2.GaussianBlur(stylized_img, (9, 9), radius)
        stylized_img_sharp = cv2.addWeighted(stylized_img, 1.5,
                                             stylized_img_blur, -0.5, 0,
                                             stylized_img)
        stylized_audio = conversion.amplitude_to_audio(stylized_img_sharp,
                                                       fft_window_size=1536,
                                                       phase_iterations=15,
                                                       phase=content_phase)
        conversion.audio_to_file(
            stylized_audio,
            "/Users/ollin/Desktop/stylized_random_phase.sharpened." +
            str(radius) + ".mp3")
        console.log("Tested radius", radius)
Esempio n. 51
0
def save_slices(save, new_slices, slice_heights):
    """ Updates slices anywhere in the world. """

    # Group slices by chunk
    chunks = {}
    for pos, slice_ in new_slices.items():
        chunk_pos = chunk_num(pos)

        try:
            chunks[chunk_pos].update({pos: slice_})
        except KeyError:
            chunks[chunk_pos] = {pos: slice_}

    log('saving slices', new_slices.keys())
    log('saving chunks', chunks.keys())

    # Update chunk files
    for chunk_pos, chunk in chunks.items():
        save_chunk(save, chunk_pos, chunk, slice_heights)
Esempio n. 52
0
def receive(sock):
    data = None
    error = False
    bufsize = 1024

    try:
        d = sock.recv(4)
    except OSError:
        error = True
    else:
        if not d:
            error = True

    if not error:
        length = struct.unpack('I', d)[0]
        log('data length', length)
        d = bytes()

        try:
            for i in range(length // bufsize):
                d += sock.recv(bufsize)
                time.sleep(0.001)
            d += sock.recv(length % bufsize)
        except OSError:
            error = True
        else:
            if not len(d):
                error = True

        if not error:
            data = str(d, 'ascii')
            log('real length', len(d))

    if error:
        log('Socket closing')
        sock.close()

    else:
        log('Received:', repr(data), trunc=False)
        try:
            return json.loads(data)
        except ValueError as e:
            log('JSON Error:', e)
Esempio n. 53
0
def build_cave(chunk, chunk_pos, x, cave_feature, ground_heights):
    """ Adds caves at x to the chunk. """

    for segment in cave_feature['segments']:
        (sx, sy), (dx, dy), r = segment

        x_quad = abs(dx) >= abs(dy)
        r -= (r/2) * abs(cos(atan2(dy, dx)))
        log(r, x_quad, m='cave')

        if x_quad:
            if dx < 0:
                sx = sx + dx
                dx *= -1
                sy = sy + dy
                dy *= -1

            ry = int(r * cos(atan2(dy, dx)))
            for u in range(sx, sx + dx):
                if in_chunk(u, chunk_pos):
                    y_intercept = int(world_gen['height'] - (sy + dy * (u - sx) / dx))

                    for zy in range(y_intercept-ry, y_intercept+ry+1):
                        if zy < world_gen['height'] and chunk[u][zy] is not '_':
                            chunk[u][zy] = ' '

        else:
            if dy < 0:
                sy = sy + dy
                dy *= -1
                sx = sx + dx
                dx *= -1

            rx = int(r * cos(atan2(dx, dy)))
            for v in range(sy, sy + dy):
                x_intercept = int((sx + dx * (v - sy) / dy))

                world_y = world_gen['height'] - v
                if world_y < world_gen['height']:

                    for zx in range(x_intercept-rx, x_intercept+rx):
                        if in_chunk(zx, chunk_pos) and chunk[zx][world_y] is not '_':
                            chunk[zx][world_y] = ' '
Esempio n. 54
0
 def train(self, data, epochs, batch=8):
     xTrain, yTrain = data.train()
     xValid, yValid = data.valid()
     while epochs > 0:
         console.log("Training for", epochs, "epochs on", len(xTrain), "examples")
         self.model.fit(xTrain, yTrain, batch_size=batch, epochs=epochs, validation_data=(xValid, yValid))
         console.notify(str(epochs) + " Epochs Complete!", "Training on", data.inPath, "with size", batch)
         while True:
             try:
                 epochs = int(input("How many more epochs should we train for? "))
                 break
             except ValueError:
                 console.warn("Oops, number parse failed. Try again, I guess?")
         if epochs > 0:
             save = input("Should we save intermediate weights [y/n]? ")
             if not save.lower().startswith("n"):
                 weightPath = ''.join(random.choice(string.digits) for _ in range(16)) + ".h5"
                 console.log("Saving intermediate weights to", weightPath)
                 self.saveWeights(weightPath)
def save_spectrogram(spectrogram, file_path, learn_phase=False):
    if learn_phase:
        spectrogram = stft_to_amplitude(
            real_and_imag_to_stft(spectrogram))

    spectrogram = spectrogram[:, :, 0]

    cm_hot = get_cmap('magma')
    spectrum = spectrogram
    console.info("Range of spectrum is " +
                 str(np.min(spectrum)) + " -> " + str(np.max(spectrum)))
    image = np.clip((spectrum - np.min(spectrum)) /
                    (np.max(spectrum) - np.min(spectrum)), 0, 1)
    console.info("Shape of spectrum is", image.shape)
    # Low-contrast image warnings are not helpful, tyvm
    with warnings.catch_warnings():
        image = cm_hot(image)
        warnings.simplefilter("ignore")
        io.imsave(file_path, image)
    console.log("Saved image to", file_path)
Esempio n. 56
0
    def _generate_install_manifest(self, source, target):
        source = os.path.join(self.src_dir, source)
        target = os.path.join(self.build_dir, target)
        if not self.config["verbose"]:
            console.log("generating", target)
        else:
            console.log("generating", "%s from %s" % (target, source))

        if not os.path.isdir(os.path.dirname(target)):
            os.makedirs(os.path.dirname(target))  # exist_ok=True

        with open(source, "rt") as source_file:
            with open(target, "wt") as target_file:
                for l in source_file:
                    l = l.replace("@VERSION@", str(self.config["version"]))
                    l = l.replace("@MIN_VERSION@",
                                  str(self.config["min-version"]))
                    l = l.replace("@MAX_VERSION@",
                                  str(self.config["max-version"]))
                    target_file.write(l)
Esempio n. 57
0
File: run.py Progetto: ovaaq/chess
def chess():
    token = None
    if 'x-access-tokens' in request.headers:
        token = request.headers['x-access-tokens']

    if request.method == 'GET':
        if not token:
            plain_text = str(datetime.datetime.now())
            new_key = jwt.encode({
                'key': plain_text
            }, app.config['SECRET_KEY']).decode('UTF-8')
            document = loads(dumps(({'_id': plain_text, 'game': 'whippii'})))
            collection.insert_one(document)
            console.log('inserting this key: ' + plain_text)
            tmp = collection.find_one({'_id': plain_text})
            if tmp is not None:
                return loads(dumps({
                    'game': tmp.get('game'),
                    'token': new_key
                }))
            return jsonify({'error': 'something went wrong'})

        try:
            jwt_dict = jwt.decode(token, app.config['SECRET_KEY'])
            key = jwt_dict.get('key')
            console.log('trying this key: ' + key)
            tmp = collection.find_one({'_id': key})
            if tmp is not None:
                return loads(dumps({'game': tmp.get('game')}))
            else:
                return jsonify({'message': 'token was not in the database'})
        except:
            return jsonify({'message': 'token is invalid'})

    if request.method == 'POST':
        if not token:
            return jsonify({'message': 'there was no token'})
        json_document = request.json
        return jsonify({'message': 'ei vittu'})
Esempio n. 58
0
    def isolateVocals(self, path, fftWindowSize, phaseIterations=10):
        console.log("Attempting to isolate vocals from", path)
        audio, sampleRate = conversion.loadAudioFile(path, sr=22100)
        spectrogram, phase = conversion.audioFileToSpectrogram(
            audio, fftWindowSize=fftWindowSize)
        console.log("Retrieved spectrogram; processing...")

        expandedSpectrogram = conversion.expandToGrid(spectrogram,
                                                      self.peakDownscaleFactor)
        expandedSpectrogramWithBatchAndChannels = expandedSpectrogram[
            np.newaxis, :, :, np.newaxis]
        print(expandedSpectrogramWithBatchAndChannels.shape)
        # 预测
        predictedSpectrogramWithBatchAndChannels = self.model.predict(
            expandedSpectrogramWithBatchAndChannels)

        predictedSpectrogram = predictedSpectrogramWithBatchAndChannels[
            0, :, :, 0]  # o /// o
        newSpectrogram = predictedSpectrogram[:spectrogram.
                                              shape[0], :spectrogram.shape[1]]
        console.log("Processed spectrogram; reconverting to audio")
        newAudio = conversion.spectrogramToAudioFile(
            newSpectrogram,
            sampleRate,
            fftWindowSize=fftWindowSize,
            phaseIterations=phaseIterations)

        # file information
        pathParts = os.path.split(path)
        fileNameParts = os.path.splitext(pathParts[1])
        outputFileNameBase = os.path.join(pathParts[0],
                                          fileNameParts[0] + "_densenet")
        console.log("Converted to audio; writing to", outputFileNameBase)

        conversion.saveAudioFile(newAudio, outputFileNameBase + ".wav",
                                 sampleRate)
        # conversion.saveSpectrogram(newSpectrogram, outputFileNameBase + ".png")
        # conversion.saveSpectrogram(spectrogram, os.path.join(pathParts[0], fileNameParts[0]) + ".png")
        console.log("Vocal isolation complete")
    def process_spectrogram(self, spectrogram, channels=1):
        chopper = Chopper()
        chopper.name = "infer"
        chopper.params = "{'scale': %d}" % self.config.inference_slice
        chop = chopper.get(both=False)

        slices = chop(spectrogram)

        normalizer = Normalizer()
        normalize = normalizer.get(both=False)
        denormalize = normalizer.get_reverse()

        new_spectrogram = np.zeros((spectrogram.shape[0], 0, channels))
        for slice in slices:
            # normalize
            slice, norm = normalize(slice)

            epanded_spectrogram = conversion.expand_to_grid(
                slice, self.peakDownscaleFactor, channels)
            epanded_spectrogram_with_batch_and_channels = \
                epanded_spectrogram[np.newaxis, :, :]

            predicted_spectrogram_with_batch_and_channels = self.model.predict(
                epanded_spectrogram_with_batch_and_channels)
            # o /// o
            predicted_spectrogram = \
                predicted_spectrogram_with_batch_and_channels[0, :, :, :]
            local_spectrogram = predicted_spectrogram[:slice.shape[0], :slice.
                                                      shape[1], :]

            # de-normalize
            local_spectrogram = denormalize(local_spectrogram, norm)

            new_spectrogram = np.concatenate(
                (new_spectrogram, local_spectrogram), axis=1)
        console.log("Processed spectrogram")
        return spectrogram, new_spectrogram