Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oddly enough, I have continued experimenting on this, and expanded on the earlier work by replacing the ad-hoc data structure used previousl.y with a set of classes (including two types of exceptions) representing the data explicitly. There is a small test program at the end of the file to show how it can be used.

from tkinter import *
import tkinter as tk
from tkinter import ttk, Label


class TabSet(ttk.Notebook):
    def __init__(self, root, parent):
        super().__init__(root)
        self.root = root
        self.parent = parent
        self.tabEntries = dict()

    def add(self, title, **kwargs):
        if title not in self.tabEntries.keys():
            self.tabEntries[title] = TabEntry(title)
        if "tab" in kwargs.keys():
            if self.tabEntries[title].tab != None:
                raise TabSetDuplicateTabException(title)
            else:
                self.tabEntries[title].tab = kwargs["tab"]
                super().add(self.tabEntries[title].tab, text=title)
        if "subentry" in kwargs.keys():
            self.tabEntries[title].add(kwargs["subentry"])
            if "button_name" in kwargs.keys() and "json_request" in kwargs.keys() and "expected_response" in kwargs.keys():    
                self.tabEntries[title][kwargs["button_name"]] = TabSubentry(kwargs["button_name"], kwargs["json_request"], kwargs["expected_response"])



class TabEntry:
    def __init__(self, tab_title):
        self.tab_title = tab_title
        self.tab = None
        self.subentries = dict()

    def add(self, subentry):
        if subentry.button_name not in self.subentries.keys():
            self.subentries[subentry.button_name] = subentry
        else:
            raise TabEntryDuplicateSubentryException(self.tab_title, subentry.button_name)


class TabSubentry:
    def __init__(self, button_name, json_request, expected_response):
        self.button_name = button_name
        self.json_request = json_request
        self.expected_response = expected_response


class TabSetDuplicateTabException(Exception):
    def __init__(self, title):
        self.title = title


class TabEntryDuplicateSubentryException(Exception):
    def __init__(self, title, button):
        self.title = title
        self.button = button


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Tab Widget")
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w, h))
    frame = Label(root, text='')
    frame.pack(side='top', fill='x', expand=False)    
    tabControl = TabSet(root, frame)
    tabControl.add("Tab 1", 
                   tab = ttk.Frame(tabControl),  
                   button="Button 1", json_request="{}", expected_response="")
    ttk.Label(tabControl.tabEntries["Tab 1"].tab, text="Button 1")
    tabControl.add("Tab 2", subentry=TabSubentry("Button A", "{foo}", "foo"))
    ttk.Label(tabControl.tabEntries["Tab 2"].tab, text="Button …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It isn't that $winner_list_temp is null; it is that while it is declared as an array, you haven't populate that array yet. It is the lottery_draw_id member of $winner_list_temp[$i_key] that is null, as there is no actual entry for $winner_list_temp[$i_key] at that point.

At least, that is my impression; I haven't worked in PHP for a while, so I may be misreading this.

jai0007dev commented: Now how do I declare that member to rectify the issue? Can someone help please +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I am still looking into this, and while I haven't really made much progress, one thing that strikes me is that you could use a comprehensive data structure to hold the data in 'json_dumps.txt'. Also, the 'json_dumps.txt' file itself is a bit poorly normalized, since you don't really need both the index number of the tab, and the tab title; just the title should be sufficient.

I've written a function to destructure the file data into a dictionary keyed on the title, where each entry is a list which in turn contains one or more dictionaries representing that tab's button controls. However, using it effectively may require a lager restructing of the program as a whole, which I'd have to help you with later.

def packComparisonData(test_file):
    """Destructures a list of lines into a dictionary keyed on the title
    of the tab, each entry of which containing a list of sub-dictionaries
    holding the name of the button to be created, the corresponding
    JSON request to be performed, and the expected results of the 
    given request."""
    comp_entries = dict()
    for line in test_file:
        tab_title, button_name, json_request, expected_response = line.split('<->')
        if tab_title not in comp_entries.keys():
            comp_entries[tab_title] = list()
        comp_entries[tab_title].append({
                                    "button_name": button_name,
                                    "json_request": json_request,
                                    "expected_response": expected_response})
    return comp_entries
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To the best of my knowledge, there's no way to do that purely in HTML and CSS - HTML is a markup language, while CSS defines the styling of said markup. I am pretty sure you would need to use a JavaScript script to do anything dynamic like this.

Julia P. commented: 101 / 5000 Risultati della traduzione I do not know where to begin! Are there any editors that allow me to do this easily? thank you +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

These two lines

    if (strcmp (day,"Monday")|| (day, "Tuesday")|| (day, "Wednesday")|| (day, "Thursday")|| (day,"Friday"))

and

    else if (strcmp (day, "Saturday")|| (day,"Sunday"))

are both wrong. They should read

    if (strcmp (day,"Monday")|| strcmp (day, "Tuesday")|| strcmp (day, "Wednesday")|| strcmp (day, "Thursday")|| strcmp (day,"Friday"))

and

    else if (strcmp (day, "Saturday")|| strcmp (day,"Sunday"))

I'm surprised that it even compiled, to be honest. It seems likely that it worked only because of how the comma operator works, meaning it was interpreting it as:

    if (strcmp (day,"Monday")|| "Tuesday"|| "Wednesday"|| "Thursday"|| "Friday")

and since any non-empty string is equal to true, it would always use the first clause.

rproffitt commented: After this, should we reveal that strcmp is unsafe? +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, so I have some changes to the code, but they are still rather kludgey. I can keep working on it, but I think it should do what you want now, at least.

import os
import time
from tkinter import *
import tkinter as tk
from tkinter import ttk, PhotoImage, LabelFrame, Text, GROOVE, Button, Label, scrolledtext
from tkinter.scrolledtext import ScrolledText
import requests
import json


def runpost(resp_json,reqtxt,tiporeq):
    try:
        getconfval = reqtxt.get(1.0, "end-1c")
        if len(getconfval)>1:
            resp_json.delete('1.0', END)
            resp_json.insert(tk.INSERT, str(url_endpoint+tiporeq)+", headers="+str(headers)+", data=json.dumps("+str(getconfval)+"), timeout="+str(timeoutvar)+"\n\n\n")
            reqjson = requests.request("POST", str(url_endpoint+tiporeq), headers=headers, data=json.dumps(getconfval), timeout=int(timeoutvar))
            statReason = ("Request:\n\n" + getconfval + "\n\nStatus:\n\n" + str(reqjson.status_code) + " - " + str(reqjson.reason) + "\n\nResponse:\n\n" + str(reqjson.text))
            resp_json.insert(tk.INSERT, statReason)

    except Exception as e:
        from OCPP.main import log_error
        resp_json.insert(tk.INSERT, "\n\n"+str(e)+"\n\n")
        log_error(e, "runpost")


    def ChangConfWI(tipreq,reqtxt,lblexp):
    #try:
        reqtxt.delete('1.0', END)
        lblexp.delete('1.0', END)
        reqtxt.insert(tk.INSERT, lstjsonreq[tipreq])
        lblexp.insert(tk.INSERT, str(lstexpectresq[tipreq]))
    #except Exception as e:
     #   from OCPP.main import log_error
      #  log_error(e, "ChangConfWI")


def generateTabs(tabControl, tabMenus):
    tab = list()
    for i, key in enumerate(tabMenus.keys()):
        tab.append(ttk.Frame(tabControl))
        tabControl.add(tab[i], text=key)
        ttk.Label(tab[i], text=tabMenus[key])
    tabControl.pack(expand=1, fill="both")    
    return tab


###########################################nova janela####################################

def gera_forms(parent, get_inp_cond_id, get_inp_cond_endpoint):
    parent.pack_forget()

    nome_endpoint, timeoutvar, url_endpoint = get_inp_cond_endpoint.split('<:>')
    nome_endpoint = nome_endpoint.replace('  ', '').strip()
    url_endpoint = url_endpoint.replace(' ', '').strip()
    timeoutvar = timeoutvar.replace(' ', '').strip()

    photoRun = PhotoImage(file=r'img/run.png')
    photoOK = PhotoImage(file=r'img/ok.png')
    photoNot = PhotoImage(file=r'img/notok.png')

    headers = {'Content-Type': 'application/json', 'chargingstation':'stat1'}

    tiporeq = ""
    payload = json.dumps({})
    expResp = ""

    varconfbook = open("Confs/json_dumps.txt", "r").readlines()
    lsttiporeq = []
    lsttitreq = []
    lstjsonreq = []
    lstexpectresq = []

    tab = []

    def makesubmenu(tipo_de_conf, framename):

        frm_json_case_button = ttk.Frame(framename)
        frm_json_case_button.grid(column=0, row=0, rowspan=99)

        frm_txt_json_case = ttk.Frame(framename)
        frm_txt_json_case.grid(column=1, row=0)

        url_show=ttk.Label(frm_txt_json_case, text=nome_endpoint + " …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

So it is basically a program to test JSON queries? Or is there something more to it?

razstec commented: yes basicly that, but the querys are already defined in the txt +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Even seeing it run, I'm still not certain what the program is for. Could you elaborate on what it is meant to be used for, please?

razstec commented: . +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, thank you for those. I'll have to go over this to see what I can recommend.

razstec commented: thank you :) +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I have the whole program now, but there's still a problem. There are five different files which it reads from, three of which are PNG images.

  • img/run.png
  • img/ok.png
  • img/notok.png
  • Confs/json_dumps.txt
  • Confs/expectresult.txt

(In the code, these are actually all hard-coded absolute paths, though it seems straightforward enough to reset these as relative paths.)

It would be easy for me to replace the images with something suitable, but I would need the specific files for the other two. The easiest solution would be for you to attach all five of them in a post.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, that helps, though now I guess I would need an example of the input to gera_forms() in order to test the whole function. Sorry to keep hassling you about that, but I want to see what the function actually does in order to see if my advice has been what you need.

Again, this is a place where having an publicly accessible repo, on a site such as Github or Sourceforge, would help tremendously.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you explain what root does? im not getting it :( tabmain1 the the root i guess, its tabControl = ttk.Notebook(tabmain1)

Well, root is a commonly used name for the main window of a single-window application, which is what is returned by tkinter.Tk() (usually abbreviated to tk.Tk() by use of import renaming). Your own code does use it in this manner.

The parent , on the other hand, is the control which the new control is immediately a part of, in this case tabmain1 from the sounds of it.

I was assuming that the overall root would be needed by the function, but it looks as if parent (== tabmain1) might be the only value needed here.

I've had to work from some assumptions about how the actual code will work, since I can't see it running as things are. If you could provide a link to the xpto library so I could run the original code myself, and see exactly what it is suppose to do, that might help me help you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I believe this would be more readable as:

# class description
SemiDiode 
    +ForwardV {get; set; }: Double 
    +ReverseV (get; set; }: Double 
    +BreakdownV {get, set; }: Double 
    +SemiDiode()  # default c'tor
    +SemiDiode(forwardV: Double, reverseV: Double, breakdownV: Double) +ToString(): String 

# class description
LaserLED 
    -wavelength: Int32 
    -color: String 
    +Wavelength {get; set; } : Int32 
    +Laser() # default c'tor
    +Color (get; set; }: String 
    +LED() +GetCopy(): Object 

# collection class description
SemiDiodes 
    +this(Int32 index) {get; set; } : SemiDiodes 
    +Add(newSemiDiode: SemiDiode): Void
    +SemiDiodes()  # default c'tor
    +Remove(oldSemiDiode: SemiDiode): Void 
  • Void .ToString() must return a meaningful string with all the properties.
  • Valid values for color are: "RED", "GREEN", "BLUE", with "RED" being the default (recall from your first year the purpose of a public, non-automatic property)
  • Valid values for wavelength is the inclusive range from 405 to 3330 with 405 being the default (recall from your first year the purpose of a public, non-automatic property)
  • SemiDiodes is a collectionBase
  • Remember: Double, String and Int32 that you see in the UML are NOT the valid C# type names. You must convert the UML type names to the valid C# type names you started using in SOD1/SSD1.NO

The comment about Void .ToString() seems to be a requirement, that each of these classes should have a default ToString() method which returns a representation of the object. Presumably, "SOD1/SSD1.NO" is some previous assignment.

None of this really changes the answer I'd give, which is: please show us what you've done …

rproffitt commented: +1 for effort. +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, unfortunately, I can't find a copy of the library xpto.makeReport you are using for writing the report forms to, so I can't test the program as a whole. However, as I said before, using a list should work instad of tabN. I would start by populating a list or a dictionary, either by reading from a file as you've been doing:

varlist = open("vars.txt", "r").readlines()
tabMenus = dict()
for line in varlist:        
    title, data = line.split('<->')
    tabMenus[title] = data

or simply by reserving a Python configuration file, Confs/tab.py which may actually be the easier option if it is acceptable:

tabMenus = {
    'first': 'text a', 
    'GConfiguration': 'text b', 
    'Cache': 'text c', 
    'Get': 'text d', 
    'something ': 'text e', 
    'Get List': 'text f',
    'Remote Start': 'text g', 
    'Remote Stop': 'text h', 
    'Local List': 'text i', 
    'Unlock': 'text j', 
    'Update': 'text k'
}

which you would import thusly:

import Confs.tabs

Either way, you would have a function which walks through the dictionary

def generateTabs(root, parent, tabMenus):
    tabControl = ttk.Notebook(root)
    tab = list()
    for i, key in enumerate(tabMenus.keys()):
        tab.append(parent(tabControl))
        tabControl.add(tab[i], text=key)
    tabControl.pack(expand=1, fill="both")    
    return tab

... which you would use as so:

tab = generateTabs(root, tabmain1, tabMenus)

for i, key in enumerate(tabMenus.keys()):
    makesubmenu(tabMenus[key], tab[i])

I hope this helps.

razstec commented: Can you explain what root does? im not getting it :( tabmain1 the the root i guess, its tabControl = ttk.Notebook(tabmain1) +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Usually, with a class you would have the class in a separate file from the rest of the code, and import the class so you can use it. But that's up to you.

Right now, though, the way you are using it, you are creating several TextTabControl and assigning each to a local TextTabControl1, which I don't think would work as they would spanw several temporary TextTabControl objects and then overwrite them.

As for making a list of tabN names, well, that's sort of what a dictionary would be used for usually, but in this case, as I said earlier, it would make more sense to me to simply use a list of the tabs in the first place and access them as tab[]. If you really need to access them by their tab names, then a dictionary would be the way to go.

Maybe it would help if you showed us more of the code, so we could have more context for all of this. Do you have an offiste repo for you version control, where we could view the whole project? I highly recommend using version control for even the smallest of projects, and using an offsite repo such as GitHub or SourceForge to keep an online copy of it where it would be safer from crashes (though you still want to do local backups) and could easily be shared.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

this doesnt work still get error tab1 is missing

You would access it with tab[1] rather than tab1.

In my experience, most of the cases where you want to use var1, var2, ... varN, you are better off using an array or (in the case of Python) a list or dictionary.

Python lists are similar to arrays in many other languages, but are more flexible in that they are heterogeneous, that is to say, you can put different kinds of objects into them. Also, since they are linked lists rather than fixed arrays, you can add to them and remove things from them at very little cost.

Dictionaries are a bit more complex, being what in other languages is sometimes called a hash table or lookup table. They consist of a series of key/value pairs where the value can be found by using the key. As with lists, both the key and the value can be of almost any type, though the key has to be a value which can be compared uniquely to other possible keys.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I dont know iif it helps any, but this is the class (and a brief test program) I had initially come up with when I misconstrued your question; you may find it useful despite it not matching your actual immediate needs.

import tkinter as tk                    
from tkinter import ttk

class TextTabControl (ttk.Notebook):
    def __init__(self, rootWidget, parentWidget, tabData):
        """A TextTabControl consists of a Notebook and 
        a dictionary of tab names and tab data.
        In the current version, this cannot be added to later,
        but it should be possible to extend the class later to 
        make it more flexible."""
        super().__init__(rootWidget)
        self.__root__ = rootWidget
        self.__tabData__ = tabData
        # populate the tabs
        for key in self.__tabData__:
            tab = parentWidget(self) 
            ttk.Label(tab, text=self.__tabData__[key]).grid(column=0, row=0, padx=10, pady=10)
            super().add(tab, text = key)
        # pack the final set of tab widgets   
        self.pack(expand = 1, fill ="both")


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Tab Widget")
    textTabControl1 = TextTabControl(root, 
                                     ttk.Frame, 
                                     {"Welcome": "Welcome to the demo",
                                      "Tab 1": "tab data 1",
                                      "Tab 2": "tab data 2",
                                      "Tab 3": "tab data 3",
                                      "Tab 4": "tab data 4",
                                      "Tab 5": "tab data 5",
                                      "Tab 6": "tab data 6"})


    root.mainloop()  
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Overall, in Python (and nearly every other language) you generally want to use global variables as little as possible, and share variables between functions and methods by passing them as arguments. You can use globals, but you would be fighting the language's overall procedural/OOP design in doing so.

As a rule, you want to limit the scope of variables to the narrowest visbility that is usable, not the widest. Otherwise, you could end up with undesirable side effects where a change in a variable in one place causes its use elsewhere to be compromised. Ideally, when working on one function you don't need to pay any attention to the local variables in any other function - that's why they are local, you can't access them from anywhere outside of the local scope.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Why yes, yes I can. However, this sounds an awful lot like a homework assignment or, more likely, a test question.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It seems like a reasonably straightforward homework assignment. What are you stuck on?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

can i put my vars in a txt like this:

var1=something1
var2=something2

and access them from python?

Would it be acceptable to use a Python file with these as globals, and then import the data that way? It would leverage the Python package system to avoid having to explicitly read the data files. I don't know if this is something which would be feasible for your project, but it might be worth looking into.

razstec commented: the idea is to add remove change the content of the software without using the code, just fill the txt and your set for your needs +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Would a list of tab objects be suitable? Given the tabN format. using a list instead seems an obvious improvement (since you would be able to iterate through the list if needed), unless I am missing something.

    tab = list()
    for i, line in enumerate(varlist):
        title, data = line.split('<->')   
        tab.append(ttk.Frame(tabControl))
        tabControl.add(tab[i], text=title)
        ttk.Label(tab[i], text=data).grid(column=0, row=0, padx=10, pady=10)
    tabControl.pack(expand=1, fill='both')
razstec commented: this doesnt work still get error tab1 is missing +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I should add that, given the original problem, you probably could avoid the class implementation (which I've already tried before realizing this) by simply using the for: loop you already demonstrated earlier. Your original code ought to work with some modifications:

tabControl = ttk.Notebook(root)
varlist = open('Confs/vars.txt', 'r').readlines()
for line in varlist:
    title, data = line.split('<->')   
    tab = ttk.Frame(tabControl)
    tabControl.add(tab, text=title)
    ttk.Label(tab, text=data).grid(column=0, row=0, padx=10, pady=10)
tabControl.pack(expand=1, fill='both')

Note that you only need to pack the widget once, when it is fully populated.

I had misinterpreted the main question initially, which is why I went to down the rabbit hole of developing a class to wrap all of this in.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If a more compact format is the goal, It should be possible,and not especially difficult, to wrap the the tabmain1 in a class which takes a list or dictionary and destructures it into the above code. However, unless you are expecting to reuse this a lot - a good deal more than 10 entries in a single form - it may not be worth the effort.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While there is no tab control widget built into TKInter, there are a number of ways to implement one, with the best option probably being to use a Notebook widget as the parent for a TabControl class.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Even if we were willing to help you get caught cheating by providing you the code for this in a public, easily searched forum, you haven't told us nearly enough about the specifics of the assignment. Which version of VB are we talking about (since you tagged both VB.net and Visual Basic 6)? How is the data stored - in a list in the program, as a text file, in a SQL database, some other way? Is this a GUI program (a reasonable assumption for VB), and if so, how do you mean to display the output (e.g., in a textbox, as a listbox, whatever)? If this is an ASP.NET application (since you tagged that as well, and C++ too for some reason), then would you need to present this in the server-generated page?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As a side note: if you have any choice in the matter, never use void main() in C, or especially in C++. Always use int main(int argc, char argv[]), or at least int main().

The void main() form is a non-standard extension specific to some older, non-standard C compilers, most notably Turbo C++. No C or C++ compilers newer than 1992 will accept void main()) without at least a warning. Compiler extensions are an acceptable and often necessary thing, to be sure, but you need to be aware that this is what you are using.

I know that many professors - especially in India, Pakistan, and the Phillipines - still use Turbo C, and some will insist on you using void main(). In some cases, the compiler is mandated across the entire national university system, or at least it was in the past. Be aware that this is not going to be usable in most other contexts.

A similar note should be made regarding fflush(stdin), as the standard version of fflush() should not be applied to input buffers such as stdin - again, some older C compilers allow it, but it isn't standard, and trying to use it elsewhere will cause undefined behavior (compiler-specific results) or even an error message. There really isn't any standard way to flush stdin, though a sacrificial fgets() should at least drop any excess characters. Oh, and gets() is not exactly the safest function - you generally should replace it with fgets() to ensure …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Dumping an assignment to a post without at least saying that is what you are doing isn't the most polite way to start a conversation, especially if you don't show any of your own effort to solve the problem.

It also isn't the safest approach, since plenty of professors regularly search the web to catch students doing things such as this (or more often, they get their TAs and grad students to do it for them).

There are websites where they will do your homework for you, at least for a fee. This isn't one of those sites.

So, try to solve it yourself, and if you get stuck, let us know what you've tried and we'll see if we can help you then.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Dumping an assignment to a post without at least saying that is what you are doing isn't the most polite way to start a conversation, especially if you don't show any of your own effort to solve the problem.

It also isn't the safest approach, since plenty of professors regularly search the web to catch students doing things such as this (or more often, they get their TAs and grad students to do it for them).

There are websites where they will do your homework for you, at least for a fee. This isn't one of those sites.

In any case, there are a lot of details missing from the assignment, so there would be no way to solve it for you as it is. Addressing this specific problem, let me ask a few questions:

  • What have you done to solve this so far?
  • Do you have a table of students and grades, and how is it stored - in list of lists, in a Dictionary, in a database which you would need to query, or something else?
  • The same regarding a table of parents and teachers, and their email addresses?
  • Given the necessary data, how would you determine a student's average?
  • Do you know how to send email from a Python application?
rproffitt commented: +1 +16
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, why did you need to translate this particular piece of code? Keep in mind that, if this is an assignment, we can only give advice, not do the problem for you.

Just to make sure we're all on the same page, the code section in question prints a set of four arrows pointed towards the corners. Having seen this, the logic of the code should be a bit clearer, even if you don't know Python. The equivalent Java code is fairly straightforward; the logic is the same, just in a slightly different syntax (and I do mean 'slightly' - if you treat the Python code as if it were pseudocode, you should be able to translate it directly into a Java method).

If you replace the or operators with || operators, use else if instead of elif, and re-write the for: conditions like so:

 for (int i=0; i <= size; i++) {
     for (int j=0; j <= size; j++) {
         // body goes here
     }
 }

The rest is mostly just using System.out.print() for the printout (with the last one a System.out.println() instead).

Oh, and you'd have to make a class for it to be in, of course.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
  1. Please format your code by indenting each line by four characters.
  2. What is your question?
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You don't. The algorithm (or rather, the elaborate set of algorithms and heuristics, though most people mistakenly refer to it as just 'the algorithm') is a tightly kept corporate secret (which in any case is so complex that no one individual can understand more than a small part of it), and is changed frequently to prevent SEO abusers from trying to game it. This doesn't stop anyone from trying, of course, and sometimes successfully for at least a while.

rproffitt commented: ? +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

This is basically a variation on Conway's Game of Life, which is a pretty well-known cellular automata ruleset and a common student problem.

As RProffitt said, the post as it is isn't formatted in a way which help us to help you.

So, what have you tried so far?

Zead_1 commented: i can send a photo for the question +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

ASP.NET code runs on the server, and is never sent to the browser. You can't see the code because it is not part of the web page itself - rather, it is the code which generates the web page's HTML and Javascript code before it is even sent to the client side.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Try declaring a boolean variable initialized to true, and use that instead of true in the while() condition. Then, at the end of the loop, add a call to reader.NextChar(), then use a comparison against 'y' to set the boolean's value.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you clarify what you are trying to do? The title sounds as if yoiu are trying to convert from C++ to C, and were specfically asking how to use the standard C I/O functions... except you are using both puts() and printf() already, which are exactly the functions you'd want to use. Could you please elaborate on the problem you are having?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Dumping an assignment to a post without at least saying that is what you are doing isn't the most polite way to start a conversation, especially if you don't show any of your own effort to solve the problem.

It also isn't the safest approach, since plenty of professors regularly search the web to catch students doing things such as this (or more often, they get their TAs and grad students to do it for them).

There are websites where they will do your homework for you, at least for a fee. This isn't one of those sites.

So, let's try this: what have you done to solve this problem already, and what part are you stuck on? Do you know how you would reverse a whole array, and could you write a function for it which could be applied to an arbitrary array when given a pointer to an element in said array? Do you know how to find the midpoint of an array, and have a rule for determining which side would get the trailing/leading chracter when the array size is odd (meaning that the midpoint is right on a character)?

One hint I will give you: keep in mind the differences between a plain array of characters, C-style strings of characters, and C++ style string objects. Specificially, when working with C-strings, don't forget to account for the NULL delimiter at the end of the character string, and make sure that you don't move it from the end …

rproffitt commented: Let's also add UNICODE strings to the heap. (pun intended.) +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Dumping an assignment to a post without at least saying that is what you are doing isn't the most polite way to start a conversation, especially if you don't show any of your own effort to solve the problem.

It also isn't the safest approach, since plenty of professors regularly search the web to catch students doing things such as this (or more often, they get their TAs and grad students to do it for them).

There are websites where they will do your homework for you, at least for a fee. This isn't one of those sites.

So, let's try this: what have you done to solve this problem already, and what part are you stuck on? Are you expected to use a specific search algorithm for finding the keywords? Does the assignment involve any specific technique, such as parsing the text down into a weighted tree or a set of buckets? What topics covered in your lectures and textbook are you expected to apply? Are there any other restrictions on how the problem is to be solved?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

TBH, the assignment is pretty sparse as given; just what the program is supposed to be doing isn't entirely clear, but it seems to be a seating assignment chart, where each seat is a value in a two-dimentional array. The program starts by setting the values of the seats in the array as some arbitrary integer, presumably the count of the seat. Then each assignee (student, employee, whatever) requests a seat location, which the program checks against existing assignments. If the seat is available, its value in the replaced with a zero. If that seat is already assigned, then the program prints out a statement that there's no available seat. If the value requested isn't valid, then an error message is printed. The program continues looping on this data entry until the program is killed.

This having been said, the first step is clear: write a skeleton main() function and declare a 7x5 array of integers. That will at least get some code started.

For the rest, you would write a nested loop which populates the array, followed by a separate loop which gets the input from the user, checks for validity, iterates through the array for the requested seating and either sets that seat to zero or returns the message that it was already assigned.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Looking at this again, I note that you are using the WooCommerce plugin for WordPress. This is relevant information for anyone trying to help, as the solution is going to require some knowledge of WoodCommerce and WordPress itself.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you post the JavaScript/AJAX code that goes together with this? PHP code runs entirely server-side, and thus can only affect the browser-side rendering on a refresh. Any AJAX code has to run browser side, which effectively means JavaScript (or a language which translates into either JavaScript or WebAssembly). It is even in the acronym: AJAX stands for "Asynchronous JavaScript and XML", which was what it is used for (e.g., communicating between the browser and the server so the page could be updated without a refresh).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

This problem most likely is from some textbook, unless I am misreading things, as shows up on CourseHero under two different courses by separate professors.

rproffitt commented: That's good to know. My answer would change to review your coursework leading up to this assignment. +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Are there any other contraints on the assignment (which I am presuming is for a compiler course, since it is basically a parsing problem)? Are you allowed to use a lexical analyzer generator (e.g., flex) and/or a parser generator (e.g., bison)? Are there any requirements for the method used?

Note that professors can use Google to find students' posts, and often do. Just something to keep in mind.

rproffitt commented: That makes me recall the Trinity of Flex, Bison and YACC. Yup, you can make source code with that! +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In my experience, most LGBT+ groups are local to a specific city or region, and are usually formed around private/hidden FB groups and/or Discord channels. Most of the more national and global groups are formed around web forums (or, in the distant past of the 1990s, Usenet groups), and generally these are focused on some specific sub-set of LGBT+ interests (e.g., trans folk, bisexuality, particular subclutures, political activism, support for trauma or other mental health problems common among LGBT+ people, etc.).

An app that isn't focused on a particular topic or area is likely to grow beyond any reasonably sized moderation team.

There are a number of LGBT+ focused apps around, some of which at least started out as the sort of thing you seem to have in mind, but sad to say a lot of them end up focusing on dating and hookups despite the intentions of the developers and moderators. The ones which don't fall into that trap seem to be support-focused apps (e.g., Pride Counseling), which doesn't sound like your aim.

All this is to say that you may need to focus the app a bit more than you seem to have, at least based on what you've told us so far. Also, moderation is going to be a primary concern with any community-focused app, regardless of the topic.

dado.d commented: Thanks, that's helpful +3
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In JavaScript, the operator == tests for object identity, i.e., that they are the same object. This is the same as value equality for primitives such as integers and floats, but for objects such as strings, it only tests if they are the same object, not if they have the same value.

To test for string equality in JavaScript, you use the === (three equals signs) operator.

Note also that this value equality only really works correctly for single character (atomic) graphemes, so combining characters in Unicode may not be equal to an atomic equivalent even if they are displayed the same way. That doesn't seem to apply here, but it is something to watch for in the future.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think you've misunderstood how message boards work. Just posting a link tells us nothing about what problems you are having, and no one - no one - here is going to be daft enough to follow a blind link like that, anyway.

I should add that it is also a banning offense to do this, as it looks an awful lot like attempted link spam.

Could you start by telling us what help you need?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

@JamesCherrill : The standard Python implementation doesn't do TCO by default - Guido had doctrinal problems with it because he felt it makes stack traces effectively impossible - but there are several implementations of decorators which will force tail calls to be optimized in various ways. The most widely used on appears to the one maintained by ActiveState (though it isn't specific to their implementation of Python). This simple one seems easy to find as well. This blog post discusses the development of such a decorator in detail.

JamesCherrill commented: Thanks for clarifying that. +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

And what makes you think a single answer is going to be possible, or that it would even be relevant in a development forum? Is your intention to try to clone it or something?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

This rather old post of mine discusses the use of recursion in general terms; the discussion following it in that thread might prove of value as well. While it is presented vis a vis C++, it applies to Python just as well, IMAO.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The question is very muddled, as it seems to be mixing unrelated topics - the technologies for developing a coupon system (whatever you mean by that, as it isn't entirely clear if you are talking about transferrable discounts or something else; also, note the spelling of 'coupon'), the legal requirements for a coupon system, and the tax code in your local jurisdiction, just to name a few.

As rproffit stated, the best person to discuss the legalities of such a system would be legal counsel (presumably one specializing in contract law as it applies to transferrable discount coupons), not a technical forum. Similarly, the issues of tax codes would be better referred to a CPA, or more likely, a lawyer specializing in tax law (which is a very different topic from contract law vis a vis discounting, which means you'd need to talk to two lawyers at minimum).

None of which relates to the technical side of how to compute the tax applied to these discounts, though you won't be able to write your code for that without speaking to those experts first.

The statements and questions regarding the technology used are, to be blunt, baffling to me. They are so general and uninformative that there simply isn't any substance to what you've said which I can comment on. Could you please explain your intended design in greater detail (without revealing any proprietary information, of course)?

rproffitt commented: To me the tax angles are not muddled as we know to get with our tax attorney. The rest? Muddy. Coupon sites are free here. +15