def get_hrg_production_rules(fname):
    import graph_sampler as gs
    G = load_edgelist(fname)
    G.remove_edges_from(G.selfloop_edges())
    giant_nodes = max(nx.connected_component_subgraphs(G), key=len)
    G = nx.subgraph(G, giant_nodes)
    Info(str(G.number_of_nodes()))
    if G.number_of_nodes() >= 500:
        Info('Grande')
        for Gprime in gs.rwr_sample(G, 2, 300):
            td([Gprime])
Ejemplo n.º 2
0
    def widget(self):
        Info(
            self.frame,
            text=f"Version {self.version}",
        )._pack()
        Header(self.frame, text="General Information")._pack()
        general_info = f"PyAdSkipper is a tool used to skip Spotify ads. It functions by detecting when an ad is being played, restarting Spotify, and resuming music. View the README included in the local directory for the most information."
        Info(
            self.frame,
            text=general_info,
        )._pack()
        Link(
            self.frame,
            "Developed by Ethanol",
            "https://github.com/3than0ls",
        )._pack()
        Link(
            self.frame,
            "Visit this project's GitHub repo for more information.",
            "https://github.com/3than0ls/PyAdSkipper",
        )._pack()

        Header(self.frame, text="FAQs and Common Issues")._pack()
        Header(
            self.frame,
            text=
            "The tool seems to be having some effect, but doesn't seem to be working correctly.",
        )._pack()
        not_working = "The script has certain intervals in which it executes commands such as restarting Spotify and playing the music. If a computer is under heavy load or is slow, some timed processes and events may be skipped."
        Info(
            self.frame,
            text=not_working,
        )._pack()

        Header(
            self.frame,
            text="The script does not seem to be skipping some ads.",
        )._pack()
        not_skipping = 'The script relies on the Spotify window name to recognize if an ad is playing, meaning there is no need to use the Spotify API (which woud require additional bothersome credentials.) The downside, however, is that while for most ads, the window name is "Advertisement," some ads (usually those from Spotify artist/songs) are not named this, and so the script does not detect that they are ads. Unfortunately, there is no current way to solve this.'
        Info(
            self.frame,
            text=not_skipping,
        )._pack()

        Header(
            self.frame,
            text="The script is skipping my local file songs.",
        )._pack()
        skipping_local = 'Again, the script relies on the Spotify window name to recognize if an ad is playing. The window name of Spotify when playing a local file is the name of that local file. If you name your local file "Advertisement", it will automatically be considered an advertisement.'
        Info(
            self.frame,
            text=skipping_local,
        )._pack()
def edgelist_in_dimacs_out(ifname):
    '''
		args: graph is the input nx graph
		returns: output filename
	'''
    g = nx.read_edgelist(ifname, data=False)
    g.name = graph_name(ifname)
    ofname = '../datasets/{}.dimacs'.format(g.name)
    if path.exists(ofname):
        return None
    n = g.number_of_nodes()
    m = g.number_of_edges()
    edges = g.edges()
    edges = [(int(e[0]), int(e[1])) for e in edges]
    df = pd.DataFrame(edges)
    df.sort_values(by=[0], inplace=True)
    with open(ofname, 'w') as f:
        f.write('c {}\n'.format(g.name))
        f.write('p edge\t{}\t{}\n'.format(n + 1, m))
        output_edges = lambda x: f.write("e\t{}\t{}\n".format(
            x[0] + 1, x[1] + 1))
        df.apply(output_edges, axis=1)
    if path.exists(ofname):
        Info("Wrote: %s" % ofname)
    # ToDo: a few extra checks could be added
    return ofname
Ejemplo n.º 4
0
def recompute_probabilities(pd_data_frame):
	'''
	recompute probabilities
	:param pd_data_frame: pd.DataFrame
	:return: df
	'''
	Info("recompute_probabilities")
	df = pd_data_frame
	df = df.reset_index(drop=True)
	if df.columns[0]=='rnbr':
		df['rnogrp'] = df["rnbr"].apply(lambda x: x.split(".")[0])
	else:
		df['rnogrp'] = df[0].apply(lambda x: x.split(".")[0])


	gb = df.groupby(['rnogrp']).groups
	for k,v in gb.items():
		kcntr = 0
		# print k, v
		# print
		for r in v:
			prob_f = df["prob"].loc[r]/sum([df["prob"].loc[x] for x in v])
			# df.loc[r] = pd.Series(["{}.{}".format(k, kcntr), list(df["lhs"].loc[r]), \
			# 	df["rhs"].loc[r], prob_f])
			df.set_value(v, 'prob', prob_f)
			kcntr += 1
	df.drop('rnogrp', axis=1, inplace=True)
	return df
Ejemplo n.º 5
0
    def OnStartDateChanged(self, event):
        date_val = event.GetDate()
        if date_val.IsLaterThan(wx.DateTime.Now()):
            color = wx.Colour(255, 0, 0)
            warningDateDialog = wx.MessageDialog(
                self,
                "Data de start selectata depaseste ziua curenta.",
                style=wx.OK)
            warningDateDialog.ShowModal()
            self.DisableReportButtons()
        elif date_val.IsLaterThan(self._wx_stop_date):
            color = wx.Colour(255, 0, 0)
            warningDateDialog = wx.MessageDialog(
                self,
                "Data de start selectata depaseste data de stop.",
                style=wx.OK)
            warningDateDialog.ShowModal()
            self.DisableReportButtons()
        else:
            self.EnableReportButtons()

        self._wx_start_date = date_val
        self._pd_start_date = pd.to_datetime(
            self._wx_start_date.Format("%Y%m%d"))
        Info("Start date: {}.".format(self._pd_start_date))
Ejemplo n.º 6
0
 def OnManagementButton(self, event):
     ManagementGenerator.Instance().Generate(self._pd_start_date,
                                             self._pd_stop_date)
     Info("Generated management report.")
     infoDialog = wx.MessageDialog(self,
                                   "Raportul de gestiune a fost generat.",
                                   style=wx.OK)
     infoDialog.ShowModal()
Ejemplo n.º 7
0
 def GetDataFromKey(self, section, ini_key):
     if section not in self._config:
         Error("Section {} does not exist.".format(section))
     if ini_key not in self._config[section]:
         Error("Key {} does not exist in section {}.".format(ini_key, section))
     value = self._config[section].get(ini_key)
     Info("Reading {}/{} from .ini file: {}".format(section, ini_key, value))
     return value
Ejemplo n.º 8
0
 def OnJournalButton(self, event):
     start_date = pd.to_datetime(self._wx_start_date.Format("%Y%m%d"))
     stop_date = pd.to_datetime(self._wx_stop_date.Format("%Y%m%d"))
     JournalGenerator.Instance().Generate(self._pd_start_date,
                                          self._pd_stop_date)
     Info("Generated input/output journal.")
     infoDialog = wx.MessageDialog(
         self, "Jurnalul de incasari si plati a fost generat.", style=wx.OK)
     infoDialog.ShowModal()
Ejemplo n.º 9
0
    def _read(self):
        if not os.path.isfile(CONFIG_PATH):
            Error("{} file not present.".format(CONFIG_PATH))
            return

        Info("Reading {} data.".format(CONFIG_PATH))
        self._config.read(CONFIG_PATH)

        for section in ConfigModule.SECTIONS:
            if section not in self._config:
                Error("Section {} does not exist.".format(section))
Ejemplo n.º 10
0
def probe_stacked_prs_likelihood_tofire(df, fname="", nbr_nodes=0):
    Info("probe stacked prs likelihood tofire")
    g = pcfg.Grammar('S')
    df = df[['rnbr', 'lhs', 'rhs',
             'prob']]  # ToDo: need to drop the gname column
    for (id, lhs, rhs, prob) in df.values.tolist():  # 21Nov17
        g.add_rule(pcfg.Rule(id, lhs, rhs, float(prob)))
    num_nodes = int(nbr_nodes)
    g.set_max_size(num_nodes)
    try:
        g.set_max_size(num_nodes)
    except Exception, e:  # print "Done with max size"
        print "\t:", e
        # return False
        os._exit(1)
Ejemplo n.º 11
0
 def plot(self):
     markers = ['o', 'D']
     color = ['firebrick', 'teal']
     i = 0
     x_offsets = {}
     for s in EXECUTABLES:
         x_offsets = {}
         xs = []
         ys = []
         lower_error = []
         upper_error = []
         for k, v in self.data[s].iteritems():
             info = Info(**v['info'])
             data = []
             for t in v['time']:
                 data.append(t)
             if info.variables not in x_offsets:
                 x_offsets[info.variables] = -2.5
             x_offsets[info.variables] = x_offsets[info.variables] + 0.5
             xs.append(info.variables + x_offsets[info.variables])
             data1 = []
             for d in data:
                 data1.append(np.mean(d))
             mean = np.mean(data1)
             ys.append(mean)
             lower, upper = conf_95_mean(data1)
             lower_error.append(mean - lower)
             upper_error.append(upper - mean)
         plt.errorbar(xs,
                      ys,
                      yerr=[lower_error, upper_error],
                      label=s,
                      fmt=markers[i],
                      color=color[i],
                      markerfacecolor='none')
         i = i + 1
     plt.xticks(x_offsets.keys(), x_offsets.keys())
     plt.title(
         'Stealing vs Master-Worker, mean runtime with 95% confidence interval'
     )
     plt.xlabel(
         'Approximate formula difficulty [formula size: number of variables]'
     )
     plt.ylabel('Runtime [ms]')
     plt.legend(loc=2)
     plt.show()
Ejemplo n.º 12
0
    def widget(self):
        Info(
            self,
            text="Updates to settings require the script to be restarted.",
            center=True,
        )._pack(pady=5)

        settings_frame = tk.Frame(self)
        settings_frame.grid_columnconfigure(1, weight=1)
        inputs = []  # may be better known as entries

        def on_change(_):
            if list(self.settings.values()) == [
                    _entry.sv.get() for _entry in inputs
            ]:
                save["state"] = "disabled"
            else:
                save["state"] = "normal"

        ## CREATE INPUT WIDGETS
        for i, (name, setting) in enumerate(self.settings.items()):
            ### CREATE LABEL WIDGET
            label = tk.Label(settings_frame, text=name)
            label.grid(row=i, column=0, padx=10)
            CreateToolTip(label, self.tooltips[name])

            ### CREATE ENTRY WIDGET
            if (name == "Pause When Locked" or name == "Push To Back"
                    or name == "Create Shortcut"):
                entry = Dropdown(
                    settings_frame,
                    name,
                    self.yes_no_options,
                    self.yes_no_options.index(setting),
                )
            elif name == "Spotify Path":
                entry = FileSelector(settings_frame,
                                     name,
                                     setting,
                                     on_change=on_change)

            else:
                entry = Input(settings_frame, name=name, value=setting)
            CreateToolTip(entry, self.tooltips[name])
            entry.grid(
                row=i,
                column=1,
                padx=15,
                sticky=tk.W + tk.E,
                pady=2 if name == "Spotify Path" else 0,
            )
            inputs.append(entry)
            entry.on_change = on_change

        ### CREATE SAVE BUTTON WIDGET
        def on_click():
            settings = {}
            for input in inputs:
                value = input.sv.get()
                if value:
                    settings[input.name] = value
                else:
                    settings[input.name] = self.settings[input.name]

            self.settings = settings
            save_settings(settings)
            save["state"] = "disabled"
            self.master.focus()

        save = tk.Button(
            settings_frame,
            text="Save Settings",
            command=on_click,
            state="disabled",
        )
        save.grid(row=i + 1,
                  column=0,
                  columnspan=2,
                  pady=10,
                  padx=40,
                  sticky=tk.W + tk.E)

        settings_frame.pack(fill="x")
Ejemplo n.º 13
0
from utils import Info, graph_name
import sys, os
import pprint as pp

from glob import glob
from isomorph_overlap_hl import stack_prod_rules_bygroup_into_list
from prs import proc_prod_rules_orig

results = []


def prs_count_per(prs_lst):
    for f in prs_lst:
        pp.pprint([os.path.basename(f), len(open(f).readlines())])


if __name__ == '__main__':
    if len(sys.argv) < 2:
        Info("add an out.* dataset with its full path")
        exit()

    f = sys.argv[1]
    gn = graph_name(f)

    f = "../ProdRules/" + gn + "*.prs"
    files = glob(f)

    prs_cnt_per = prs_count_per(files)
    # prs_stack = stack_prod_rules_bygroup_into_list(files)

    sys.exit(0)