how to setText() from adapterclass

Question: i have created a custom alertbar on context menu, which is on the list viewed from json parsing. what i want is to get a details(name of the specific person on which the context menu is opened). i want to set Text in the on the alertbar.
Thank you very much for help.
enter code here

public class MyConnectionAsyncTask extends AsyncTask> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("Connecting...");
        progressDialog.show();
    }

    @Override
    protected List<MyconnectionManager> doInBackground(String... params) {

        try {
            URL url = new URL(params[0]);// taking params from execute method
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();//opening connection
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));//putting data into buffer from input stream

            String result = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;

            }
            String json_str = result.toString();

            JSONObject parentObject = new JSONObject(json_str);
            JSONArray parentArray = parentObject.getJSONArray("result_array");//ARRAY name from API will come here

            ArrayList<MyconnectionManager> connectionManagerList = new ArrayList<MyconnectionManager>();//created a list bc we have list of connections

            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                MyconnectionManager myconnectionManager = new MyconnectionManager(getActivity());
                myconnectionManager.setFullname_myConnection(finalObject.getString("fullname"));
                myconnectionManager.setProfilePic_myConnection(finalObject.getString("profile_pic"));
                myconnectionManager.setPosition_myconnection(finalObject.getString("position"));
                myconnectionManager.setCompany_myConnection(finalObject.getString("company"));
                myconnectionManager.setLocation_myConnection(finalObject.getString("location"));
                connectionManagerList.add(myconnectionManager);//adding to list

            }
            return connectionManagerList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(List<MyconnectionManager> result) {
        super.onPostExecute(result);
        progressDialog.dismiss();
        MyConnectionAdapter adapter = new MyConnectionAdapter(getActivity(), R.layout.single_row_my_connections, result);//creating adpater here
        connectionList.setAdapter(adapter);
    }
}

adpater Class is below
public class MyConnectionAdapter extends ArrayAdapter {

    private List<MyconnectionManager> myconnectionManagerList;
    private int resource;
    LayoutInflater inflater;

    public MyConnectionAdapter(Context context, int resource, List objects) {
        super(context, resource, objects);
        this.resource = resource;// resource has the layout view so we can also give resource below instead of layout
        myconnectionManagerList = objects;
        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.single_row_my_connections, null);//we can give resource here
        }
        ImageView imageView;
        TextView name, company, location, position_company;

        imageView = (ImageView) convertView.findViewById(R.id.iv_profile_pic_myconnection);
        name = (TextView) convertView.findViewById(R.id.tvname_myconncetion);
        company = (TextView) convertView.findViewById(R.id.tvCompany_myconnection);
        location = (TextView) convertView.findViewById(R.id.tvlocation_myconnections);
        position_company = (TextView) convertView.findViewById(R.id.tvPosition_myconnection);

        ImageLoader.getInstance().displayImage(myconnectionManagerList.get(position).getProfilePic_myConnection(), imageView);

        name.setText(myconnectionManagerList.get(position).getFullname_myConnection());
        company.setText(myconnectionManagerList.get(position).getCompany_myConnection());
        location.setText(myconnectionManagerList.get(position).getLocation_myConnection());
        position_company.setText(myconnectionManagerList.get(position).getPosition_myconnection());
        return convertView;
    }

}

context menu is below
 @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    menu.setHeaderIcon(R.drawable.small_logo);
    menu.setHeaderTitle("Choose Action");
    menu.add(0, 1, 0, "Send Message");
    menu.add(0,2,1,"Remove Connection");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getItemId()==1){
        Toast.makeText(getActivity(),"Send Message",Toast.LENGTH_SHORT).show();
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.send_message_layout,null,false);
        final EditText et_sub= (EditText) view.findViewById(R.id.et_sub_send_Message);
        final EditText et_msg= (EditText) view.findViewById(R.id.etMessage_send_Message);
        TextView name= (TextView) view.findViewById(R.id.tv_name_send_message);

        name.setText("To: ");//name of user will come here

        AlertDialog.Builder ab=new AlertDialog.Builder(getActivity());
        ab.setTitle("Send Message");
        ab.setView(view);
        ab.setNegativeButton("Cancel", null);
        ab.setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String sub = et_sub.getText().toString();
                String msg = et_msg.getText().toString();
                Toast.makeText(getActivity(), sub + "  " + msg, Toast.LENGTH_SHORT).show();
            }
        });
        ab.show();

    }else {
        Toast.makeText(getActivity(),"Remove Connection",Toast.LENGTH_SHORT).show();
    }
    return true;
}

Comment: Bro  i edited my code please try that and let me know result
Answer: You can use
  @Override
        public boolean onContextItemSelected(MenuItem item) {
             AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
             int listPosition = info.position;
            String  nameoOfUser = ((TextView)info.targetView.findViewById(R.id.YOUR_TEXTVIEW_ID)).getText().toString();

  name.setText("To: " + nameoOfUser );
    }

Comment: what i want is to get the name from the list, which is shown on activity after json parsing. Thank You :-)
Comment: it looks like it will work, can you please write the rest of the code.
Comment: trying to do it. not getting results.
Answer: TextView textViewItem = (TextView)convertView.findViewById(R.id.textViewItem);
    textViewItem.setText("your text");

Comment: name.setText("To: "); //this is where i want the name of user on which i

how to setText() from adapterclass


Problema com o Tomcat!

Question: Oi!
Estou estou tentando ativar o apache tomcat v7.0 no eclipse, porem quando vou ativa-lo acontece esse erro:
"-Djava.endorsed.dirs=\apache-tomcat-7.0.94\endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules."
Como eu resolvo esse problema?
Eu ate pensei em por o tomcat 8.5, porém no meu eclipse só aparece até a versão 8.0 do apache e não quer aceitar a 8.5.
Answer: Olá,
Se estiver usando o Java 10 para rodar o Eclipse, recomendo o downgrade para a versão 8.
Alguns problemas que eu tinha visto em relação a incompatibilidade do Tomcat com o Eclipse (por exemplo neste tópico aqui https://cursos.alura.com.br/forum/topico-tomcat-nao-funciona-61602), muitos problemas estão sendo causados porque estão sendo executados com a versão muito recente do Java/JDK, que possuem diversas mudanças em relação as anteriores.

Problema com o Tomcat!


Assert Equal an Object which has an Array within it

Question: My goal is to check the similarity of an object using unittesting in python. I have this kind of object
class ImageModel(object):

    def __init__(self):
        self.data = data #this an array
        self.name = name
        self.path = path

I have read that if you want to do test the similarity of an array self.assertEqual(arr1,arr2) you have to put .all() after each array. But I have to check the similarity of an object which has an array within it. For my case, it would be:
self.assertEqual(ImageObj1, ImageObj2)

But it always show that those object isn't similar, i assume the problem is at the ImageObj.data
so, is there any way to assert equal an array within an object?
Comment: what kind of `array` - python has `list`s( and `(frozen)set`, `dict`, `tuple`, ...). "Array"s are from other packages like array or numpy or ... which might have convenience functions to compare value equality
Comment: Unless you define `__eq__` in your class, equality is based on identity, that is, `ImageObj1 == ImageObj2` if and only if `id(ImageObj1) == id(ImageObj2)`. Python won't automatically compare two objects attribute by attribute.
Comment: @PatrickArtner the array is from reading an image with OpenCV library
Answer: One possibility is to override the __eq__ method of your class. Basically, this is the method that is called when you're using the == operator on an ImageModel instance.
Here is an example:
def __eq__(self, other):
    return (
        # the two instances must be of the same class
        isinstance(other, self.__class__) and
        # compare name and path, that's straightforward
        self.name == other.name and
        self.path == other.path and
        # and compare data
        len(self.data) == len(other.data) and
        all(a == b for a, b in zip(self.data, other.data))
    )


Find the MGF of difference in Chi-Squared Random Variables: When is it legal to divide by an MGF?

Question: Can someone please explain why the following two scenarios lead to different distributions?
1) $X\sim\chi^2(m)$ and $Y\sim\chi^2(n)$. Using moment-generating functions, show that $Y-X$ does not have a $\chi^2(n-m)$ distribution, for $n>m$ with $X$ and $Y$ independent.
Refer to the following for a derivation of this: Distribution of Difference of Chi-squared Variables
2) Show using MGF's that if $X\sim\chi^2(m)$ and $S = Y+X \sim\chi^2(n-m)$, then $S-X\sim\chi^2(n)$.
Here is my derivation:
$$
E[e^{(S-X)t}]=E[e^{St}]E[e^{-Xt}]\\
=\frac{M_S(t)}{M_X(t)}\\
= (1-2t)^{-(m+n)/2}(1-2t)^{m/2}\\
= (1-2t)^{-n/2}
$$
My question is: why can't we use this type of derivation (putting $M_X(t)$ in the denominator instead of using $M_X(-t)$) in (1)? Or alternatively, is there another way to show this using $M_X(-t)$ in the derivation?
Thanks!
Comment: What are you asked to prove in (2), exactly? The hypotheses are unclear, you might want to restate.
Answer: Your mistake is that you want $E[1/Z]$ to be  $1/E[Z]$ for a random variable $Z$ (in fact, when $Z > 0$ they are never equal unless $Z$ is almost surely constant).
Comment: Interesting... my professor definitely recommended this approach. Is there an alternative way to show (2)?
Answer: there is another mistake that X and S are not independent, so the first equation is wrong.(E(XY)~=E(X)E(Y))


How to look ahead one element (peek) in a Python generator?

Question: I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
gen = iter([1,2,3])
next_value = gen.next()  # okay, I looked forward and see that next_value = 1
# but now:
list(gen)  # is [2, 3]  -- the first value is gone!

Here is a more real example:
gen = element_generator()
if gen.next_value() == 'STOP':
  quit_application()
else:
  process(gen.next())

Can anyone help me write a generator that you can look one element forward?

See also: Resetting generator object in Python
Comment: Can you describe in more detail what you want to do? Code sample perhaps?
Comment: if you have an existing list, what else do you need? Also, it seems that you saving the first value as `next_value`, no?
Comment: SilentGhost, it was an example to illustrate what `gone` means. I don't have a list and I don't have next_value. It was just an example to show what it means for an element to disappear from a generator.
Comment: @bodacydo: I still don't understand. **How** is it gone then? Why don't you have access to that value?
Comment: Tim, updated the question with a better example.
Comment: SilentGhost, I didn't look into generator - I took the value out of it, looked at it, but didn't put back. So it's gone from generator. I just want to look in it. See updated post. :)
Comment: I still don't see what that's supposed to be good for. You want to avoid calling `gen.next()` if the generator is "exhausted". That's what the exception `StopIteration` is for. What is in the generator after this element "STOP"? Why isn't the generator simply exhausted at this point? Or, if that's not possible, why not have the generator `raise StopIteration` if the current element is "Stop"?
Comment: -1: "I don't have a list and I don't have next_value." "I don't know". It's very hard to answer a question like this.
Comment: I've come around to thinking that the correct approach is to modify your algorithm to use the 'current' and 'previous' value from the generator, rather than trying to use the 'next' and 'current'. I don't believe there is any algorithm that can't be recast this way, which is much simpler than any of the solutions offered (including both of mine.)
Comment: I consider it a limitation of Python if it forces you to change a perfectly reasonable algorithm in order for it to work. But hey, that falls out of the philosophy of the language itself.
Comment: @StevenLu That's crazy! It's not the language, it's the OP's bad idea of having two different readers of an unseekable stream, then compensating for this bad design by trying to make them not tread on each other's toes. Have a single reader from the generator, rather than two, and all these problems melt away into zero required code.
Answer: For sake of completeness, the more-itertools package (which should probably be part of any Python programmer's toolbox) includes a peekable wrapper that implements this behavior. As the code example in the documentation shows:
>>> p = peekable(['a', 'b'])
>>> p.peek()
'a'
>>> next(p)
'a'

However, it's often possible to rewrite code that would use this functionality so that it doesn't actually need it. For example, your realistic code sample from the question could be written like this:
gen = element_generator()
command = gen.next_value()
if command == 'STOP':
  quit_application()
else:
  process(command)

(reader's note: I've preserved the syntax in the example from the question as of when I'm writing this, even though it refers to an outdated version of Python)
Answer: The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the itertools module and prepend the element:
import itertools

gen = iter([1,2,3])
peek = gen.next()
print list(itertools.chain([peek], gen))

Comment: I've used this solution many times, but I think it probably should be pointed out that you basically call `itertools.chain.__next__` `n` times for each element that you get out of the iterable (where `n` is the number of times you've peeked).  This works great for one or two peeks, but if you need to peek at every element, this isn't the best solution :-)
Comment: I'd mention that this is implemented in the `more-itertools` package as [`spy`](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.spy). Not to say it's worth bringing in a whole new package for just this one piece of functionality, but some people may find an existing implementation useful.
Comment: You can use [`send`](http://docs.python.org/2/reference/expressions.html#generator) to push a previously yielded value back into a generator as it yields the next value.
Comment: @dansalmo: Yes, but you need to modify the generator code for this. See the answer by Andrew Hare.
Comment: @mgilson Yeah, this should definitely come with a warning. People might very well try to do this in a loop, peeking at each element, and then the whole iteration takes quadratic time.
Comment: @EricAuld If you want to use this, i.e., use `chain` to prepend a peeked value back to the iterable, you'd build a stack of chains and every value would go through the whole stack. [Demo](https://tio.run/##VVBBjsIwDLznFT6mUg@wXFClPmDPuze0WgVwqUXjRMbVwutLkkJh5xJ5xh5PHG/aB95so0xTJ8GDkkdSIB@D6KMyRSFF0RCGy1M89I7YmCN2EBHPF8tVYyAhzbel3YrjEya@KvxfTwPCt4w492Wo3F5FRrZK44xXtaTVouH1gFHhS0P8TNZOKfD/SUEdhReqpCgZ7S6b/tTw7rcsMF0Q@AVimNNuHr/INGd6vUqo4SM/b8GT@3weOzi/P7pmuUINPPo9Srt@rYtCrJZr0Gqa7g) where doubling the length indeed quadruples the time.
Comment: @KellyBundy Why would it be quadratic time to peek at each element? `itertools.chain` runs in constant time, no?
Comment: You may want to wrap that with a try-except StopIteration to cover the case where the iterator is empty - otherwise this will raise
Answer: Ok - two years too late - but I came across this question, and did not find any of the answers to my satisfaction. Came up with this meta generator:
class Peekorator(object):

    def __init__(self, generator):
        self.empty = False
        self.peek = None
        self.generator = generator
        try:
            self.peek = self.generator.next()
        except StopIteration:
            self.empty = True

    def __iter__(self):
        return self

    def next(self):
        """
        Return the self.peek element, or raise StopIteration
        if empty
        """
        if self.empty:
            raise StopIteration()
        to_return = self.peek
        try:
            self.peek = self.generator.next()
        except StopIteration:
            self.peek = None
            self.empty = True
        return to_return

def simple_iterator():
    for x in range(10):
        yield x*3

pkr = Peekorator(simple_iterator())
for i in pkr:
    print i, pkr.peek, pkr.empty

results in:
0 3 False
3 6 False
6 9 False
9 12 False
...
24 27 False
27 None False

i.e. you have at any moment during iteration access to the next item in the list.
Comment: @Jonathan this may not always be possible in non-trivial examples, eg when the iterator gets passed into a function.
Comment: I feel a bit mean saying this but I find this solution horrendous & quite error-prone. At any moment in time, you need access to two items from the generator: the 'i' and 'i+1' elements. Why not code your algorithm to use the current and the previous value, instead of the next and the current value? It seems absolutely identical, and much simpler than this.
Comment: Someone should point out that from python2.6 onward, the preferred way to get the next value of a generator is `next(generator)` rather than `generator.next()`.  IIRC, `generator.next()` goes away in python3.x.  Similarly, for best forward compatibility, add `__next__ = next` into the body of the class so that it continues to work in python3.x.  That said, great answer.
Comment: by all means - be as mean as you need to :)
Comment: Echoing @mgilson, this doesn't work in Python 3 if the generator is a string iterator. For that you absolutely need to use `next()`
Answer: Using itertools.tee will produce a lightweight copy of the generator; then peeking ahead at one copy will not affect the second copy. Thus:
import itertools

def process(seq):
    peeker, items = itertools.tee(seq)

    # initial peek ahead
    # so that peeker is one ahead of items
    if next(peeker) == 'STOP':
        return

    for item in items:

        # peek ahead
        if next(peeker) == "STOP":
            return

        # process items
        print(item)

The items generator is unaffected by modifications to peeker. However, modifying seq after the call to tee may cause problems.
That said: any algorithm that requires looking an item ahead in a generator could instead be written to use the current generator item and the previous item. This will result in simpler code - see my other answer to this question.
Comment: "Any algorithm that requires you to look 1 item ahead in a generator could alternatively be written to use the current generator item and the previous item." Mangling your use of generators can sometimes lead to more elegant and readable code, especially in parsers that require lookahead.
Comment: FWIW, code is now fixed, @Eric\ May's comment that the whole iterator is buffered is no longer true.
Comment: Hey there Rufflewind. I understand the point about parsing requiring lookahead, but I don't see why you can't achieve that by simply storing the previous item out of your generator, and using the most recent item out of your generator as the lookahead. Then you get the best of both worlds: unmangled generator, and simple parser.
Comment: Well, that's why you wrap the generator in a custom class to automatically do this.
Comment: Hey Ruffelwind. I'm no longer sure that I understand what you're advocating. Sorry to have lost the plot.
Comment: This is bad idea - the existance of `copy1` causes you to buffer the entire iterator.
Comment: @Eric Hey Eric. you're right insomuch as I wrote the demo code wrong - my intention was that the call to 'copy1.next()' would happen within the loop that processes copy2, hence both copies move through the sequence together, so only one item is buffered at any time. I'll fix the code, thanks for pointing out it was wrong.
Answer: An iterator that allows peeking at the next element and also further ahead. It reads ahead as needed and remembers the values in a deque.
from collections import deque

class PeekIterator:

    def __init__(self, iterable):
        self.iterator = iter(iterable)
        self.peeked = deque()

    def __iter__(self):
        return self

    def __next__(self):
        if self.peeked:
            return self.peeked.popleft()
        return next(self.iterator)

    def peek(self, ahead=0):
        while len(self.peeked) <= ahead:
            self.peeked.append(next(self.iterator))
        return self.peeked[ahead]

Demo:
>>> it = PeekIterator(range(10))
>>> it.peek()
0
>>> it.peek(5)
5
>>> it.peek(13)
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    it.peek(13)
  File "[...]", line 15, in peek
    self.peeked.append(next(self.iterator))
StopIteration
>>> it.peek(2)
2
>>> next(it)
0
>>> it.peek(2)
3
>>> list(it)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Answer: A simple solution is to use a function like this:
def peek(it):
    first = next(it)
    return first, itertools.chain([first], it)

Then you can do:
>>> it = iter(range(10))
>>> x, it = peek(it)
>>> x
0
>>> next(it)
0
>>> next(it)
1

Answer: >>> gen = iter(range(10))
>>> peek = next(gen)
>>> peek
0
>>> gen = (value for g in ([peek], gen) for value in g)
>>> list(gen)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Comment: This is the same, but more explicit than the itertools.chain solution.
Comment: do you mind providing an explanation about what is happening here
Comment: We take peek off gen. We then create an iterable [peek] and combine it with the rest of gen to create a new gen. This is done by iterating through the flattening of the two generators which combine to give the original. See flatting: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
Answer: Just for fun, I created an implementation of a lookahead class based on the suggestion by
Aaron:
import itertools

class lookahead_chain(object):
    def __init__(self, it):
        self._it = iter(it)

    def __iter__(self):
        return self

    def next(self):
        return next(self._it)

    def peek(self, default=None, _chain=itertools.chain):
        it = self._it
        try:
            v = self._it.next()
            self._it = _chain((v,), it)
            return v
        except StopIteration:
            return default

lookahead = lookahead_chain

With this, the following will work:
>>> t = lookahead(xrange(8))
>>> list(itertools.islice(t, 3))
[0, 1, 2]
>>> t.peek()
3
>>> list(itertools.islice(t, 3))
[3, 4, 5]

With this implementation it is a bad idea to call peek many times in a row...
While looking at the CPython source code I just found a better way which is both shorter and more efficient:
class lookahead_tee(object):
    def __init__(self, it):
        self._it, = itertools.tee(it, 1)

    def __iter__(self):
        return self._it

    def peek(self, default=None):
        try:
            return self._it.__copy__().next()
        except StopIteration:
            return default

lookahead = lookahead_tee

Usage is the same as above but you won't pay a price here to use peek many times in a row. With a few more lines you can also look ahead more than one item in the iterator (up to available RAM).
Answer: This will work -- it buffers an item and calls a function with each item and the next item in the sequence.
Your requirements are murky on what happens at the end of the sequence.  What does "look ahead" mean when you're at the last one?
def process_with_lookahead( iterable, aFunction ):
    prev= iterable.next()
    for item in iterable:
        aFunction( prev, item )
        prev= item
    aFunction( item, None )

def someLookaheadFunction( item, next_item ):
    print item, next_item

Answer: If anybody is interested, and please correct me if I am wrong, but I believe it is pretty easy to add some push back functionality to any iterator.
class Back_pushable_iterator:
    """Class whose constructor takes an iterator as its only parameter, and
    returns an iterator that behaves in the same way, with added push back
    functionality.

    The idea is to be able to push back elements that need to be retrieved once
    more with the iterator semantics. This is particularly useful to implement
    LL(k) parsers that need k tokens of lookahead. Lookahead or push back is
    really a matter of perspective. The pushing back strategy allows a clean
    parser implementation based on recursive parser functions.

    The invoker of this class takes care of storing the elements that should be
    pushed back. A consequence of this is that any elements can be "pushed
    back", even elements that have never been retrieved from the iterator.
    The elements that are pushed back are then retrieved through the iterator
    interface in a LIFO-manner (as should logically be expected).

    This class works for any iterator but is especially meaningful for a
    generator iterator, which offers no obvious push back ability.

    In the LL(k) case mentioned above, the tokenizer can be implemented by a
    standard generator function (clean and simple), that is completed by this
    class for the needs of the actual parser.
    """
    def __init__(self, iterator):
        self.iterator = iterator
        self.pushed_back = []

    def __iter__(self):
        return self

    def __next__(self):
        if self.pushed_back:
            return self.pushed_back.pop()
        else:
            return next(self.iterator)

    def push_back(self, element):
        self.pushed_back.append(element)

it = Back_pushable_iterator(x for x in range(10))

x = next(it) # 0
print(x)
it.push_back(x)
x = next(it) # 0
print(x)
x = next(it) # 1
print(x)
x = next(it) # 2
y = next(it) # 3
print(x)
print(y)
it.push_back(y)
it.push_back(x)
x = next(it) # 2
y = next(it) # 3
print(x)
print(y)

for x in it:
    print(x) # 4-9

Answer: Instead of using items (i, i+1), where 'i' is the current item and i+1 is the 'peek ahead' version, you should be using (i-1, i), where 'i-1' is the previous version from the generator.
Tweaking your algorithm this way will produce something that is identical to what you currently have, apart from the extra needless complexity of trying to 'peek ahead'.
Peeking ahead is a mistake, and you should not be doing it.
Comment: You need to take an item out of a generator before you know if you want it. Say a function takes an item from a generator, upon inspection decides it doesn't want it. The next user of the generator won't see that item unless you can push it back. Peeking removes to need to push items back.
Comment: @IsaacTurner No, you don't need to do that. For example, you could have two nested generators. The inner one takes an item, decides it doesn't want to do anything with it, then yields it regardless. The outer one still sees everything in the sequence. There are equivalent, very simple, ways to do the same thing without nested generators. Just remember the 'previous item' in a variable and you can do anything that is requested by this question. MUCH simpler than trying to push things back.
Answer: Although itertools.chain() is the natural tool for the job here, beware of loops like this:
for elem in gen:
    ...
    peek = next(gen)
    gen = itertools.chain([peek], gen)

...Because this will consume a linearly growing amount of memory, and eventually grind to a halt.  (This code essentially seems to create a linked list, one node per chain() call.)  I know this not because I inspected the libs but because this just resulted in a major slowdown of my program - getting rid of the gen = itertools.chain([peek], gen) line sped it up again.  (Python 3.3)
Answer: Python3 snippet for @jonathan-hartley answer:
def peek(iterator, eoi=None):
    iterator = iter(iterator)

    try:
        prev = next(iterator)
    except StopIteration:
        return iterator

    for elm in iterator:
        yield prev, elm
        prev = elm

    yield prev, eoi

for curr, nxt in peek(range(10)):
    print((curr, nxt))

# (0, 1)
# (1, 2)
# (2, 3)
# (3, 4)
# (4, 5)
# (5, 6)
# (6, 7)
# (7, 8)
# (8, 9)
# (9, None)

It'd be straightforward to create a class that does this on __iter__ and yields just the prev item and put the elm in some attribute.
Comment: An issue with this approach is that you fetch the next element one step ahead of time, which might be undesirable. For instance if fetching an element is slow or has side effects.
Comment: @Maëlan that's going to be an issue regardless. There's no way to find out what an element's value is, without in some sense fetching it.
Comment: @KarlKnechtel there are situations where you decide to stop the iteration based on the value of the last fetched element, or on other context. You don't need and don't want to fetch another one.
Comment: In that case, write the corresponding logic so that it occurs in the previous loop iteration? Though in some special cases that might require special-casing to check the first element before starting a loop...
Answer: w.r.t @David Z's post, the newer seekable tool can reset a wrapped iterator to a prior position.
>>> s = mit.seekable(range(3))
>>> s.next()
# 0

>>> s.seek(0)                                              # reset iterator
>>> s.next()
# 0

>>> s.next()
# 1

>>> s.seek(1)
>>> s.next()
# 1

>>> next(s)
# 2

Answer: cytoolz has a peek function.
>> from cytoolz import peek
>> gen = iter([1,2,3])
>> first, continuation = peek(gen)
>> first
1
>> list(continuation)
[1, 2, 3]

Answer: In my case, I need a generator where I could queue back to generator the data I have just got via next() call.
The way I handle this problem, is to create a queue. In the implementation of the generator, I would first check the queue: if queue is not empty, the "yield" will return the values in queue, or otherwise the values in normal way.
import queue

def gen1(n, q):
    i = 0
    while True:
        if not q.empty():
            yield q.get()
        else:
            yield i
            i = i + 1
            if i >= n:
                if not q.empty():
                    yield q.get()
                break

q = queue.Queue()

f = gen1(2, q)

i = next(f)
print(i)
i = next(f)
print(i)
q.put(i) # put back the value I have just got for following 'next' call
i = next(f)
print(i)

running
python3 gen_test.py

0
1
1

This concept is very useful when I was writing a parser, which needs to look the file line by line, if the line appears to belong to next phase of parsing, I could just queue back to the generator so that the next phase of code could parse it correctly without handling complex state.
Answer: An algorithm that works by "peeking" at the next element in a generator could equivalently be one that works by remembering the previous element, treating that element as the one to operate upon, and treating the "current" element as simply "peeked at".
Either way, what is really happening is that the algorithm considers overlapping pairs from the generator. The itertools.tee recipe will work fine - and it is not hard to see that it is essentially a refactored version of Jonathan Hartley's approach:
from itertools import tee
# From https://docs.python.org/3/library/itertools.html#itertools.pairwise
# In 3.10 and up, this is directly supplied by the `itertools` module.
def pairwise(iterable):
    # pairwise('ABCDEFG') --> AB BC CD DE EF FG
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def process(seq):
    for to_process, lookahead in pairwise(seq):
        # peek ahead
        if lookahead == "STOP":
            return
        # process items
        print(to_process)

Comment: counter proof of equivalence may be as simple as enforcing no side effects on a type check?
Answer: For those of you who embrace frugality and one-liners, I present to you a one-liner that allows one to look ahead in an iterable (this only works in Python 3.8 and above):
>>> import itertools as it
>>> peek = lambda iterable, n=1: it.islice(zip(it.chain((t := it.tee(iterable))[0], [None] * n), it.chain([None] * n, t[1])), n, None)
>>> for lookahead, element in peek(range(10)):
...     print(lookahead, element)
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
None 9
>>> for lookahead, element in peek(range(10), 2):
...     print(lookahead, element)
2 0
3 1
4 2
5 3
6 4
7 5
8 6
9 7
None 8
None 9

This method is space-efficient by avoiding copying the iterator multiple times. It is also fast due to how it lazily generates elements. Finally, as a cherry on top, you can look ahead an arbitrary number of elements.
Answer: Many use cases for iter.peek() can also be achieved using an iterator of current-value, next-value.
This has an advantage over the currently-accepted answer because it doesn't involve calling itertools.chain repeatedly, wrapping the iterator in a new iterator each time.
This is just a few lines of code by hand:
>>> def cur_next(iterator):
...     cur = None
...     for num, next_val in enumerate(iterator):
...         if num != 0:
...             yield cur, next_val
...         cur = next_val
...     yield cur, None
...
>>> list(cur_next(range(10)))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, None)]

It can also be done using itertools, although that doesn't save much code in this case.
>>> import itertools
>>> def cur_next_2(iterator):
...     cur, next = itertools.tee(iterator)
...     cur = itertools.chain([None], cur)
...     result = itertools.zip_longest(cur, next)
...     # Advance so the first element is (0, 1)
...     for discarded in result:
...         break
...     return result
...
>>> list(cur_next_2(range(10)))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, None)]

Comment: Why not use just `return itertools.pairwise(itertools.chain(iterator, [None]))`


Sonar failing to get pylint results

Question: I am trying to use pylint with the python plugin in sonar and a jenkins job. However, even though my pylint results are created and available in the workspace, sonar is not picking it up.
Execute shell step: generate pylint report file
cd $WORKSPACE
export TERM="linux"
pylint --rcfile=.pylintrc $(find . -iname "*.py" -print) -r n --msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" > pylint-report.txt || exit 0

Execute SonarQube Scanner: scan project and send to sonar server
sonar.projectKey=python:python-project
sonar.projectName=python-project
sonar.projectVersion=dev
sonar.projectDescription=python project

sonar.language=py
sonar.projectBaseDir=$WORKSPACE
sonar.sources=$WORKSPACE

sonar.python.pylint.reportPath=pylint-report.txt
sonar.python.pylint=/bin/pylint
sonar.python.pylint_config=.pylintrc

sonar.exclusions=**/venv/**
sonar.sourceEncoding=UTF-8

This job succeeds and data is populated into sonar, but I don't see any pylint data. I tried running the sonar-scanner manually directly in the workspace using the same flags the job is using (plus debug enabled) and I don't even see it looking for a pylint report file:
09:08:42.040 INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
09:08:42.044 INFO: Project root configuration file: /var/lib/jenkins/workspace/redacted-sonar/sonar-project.properties
09:08:42.066 INFO: SonarQube Scanner 2.8
09:08:42.066 INFO: Java 1.8.0_121 Oracle Corporation (64-bit)
09:08:42.066 INFO: Linux 3.10.0-514.6.1.el7.x86_64 amd64
09:08:42.262 DEBUG: keyStore is :
09:08:42.262 DEBUG: keyStore type is : jks
09:08:42.262 DEBUG: keyStore provider is :
09:08:42.262 DEBUG: init keystore
09:08:42.263 DEBUG: init keymanager of type SunX509
09:08:42.332 INFO: User cache: /root/.sonar/cache
09:08:42.332 DEBUG: Extract sonar-scanner-api-batch in temp...
09:08:42.339 DEBUG: Get bootstrap index...
09:08:42.340 DEBUG: Download: http://redacted.com/batch_bootstrap/index
09:08:42.401 DEBUG: Get bootstrap completed
09:08:42.402 DEBUG: Create isolated classloader...
09:08:42.417 DEBUG: Start temp cleaning...
09:08:42.429 DEBUG: Temp cleaning done
09:08:42.429 DEBUG: Execution getVersion
09:08:42.433 DEBUG: Execution start
09:08:42.637 DEBUG: Publish global mode
09:08:42.741 INFO: Load global repositories
09:08:42.813 DEBUG: GET 200 http://redacted.com/batch/global | time=68ms
09:08:42.872 INFO: Load global repositories (done) | time=132ms
09:08:42.888 INFO: User cache: /root/.sonar/cache
09:08:43.094 INFO: Load plugins index
09:08:43.100 DEBUG: GET 200 http://redacted.com/deploy/plugins/index.txt | time=5ms
09:08:43.100 INFO: Load plugins index (done) | time=6ms
09:08:43.101 DEBUG: Load plugins
09:08:43.113 DEBUG: Load plugins (done) | time=12ms
09:08:43.123 DEBUG: API compatibility mode is enabled on plugin Git [scmgit] (built with API lower than 5.2)
09:08:43.201 DEBUG: Plugins:
09:08:43.201 DEBUG:   * Python 126.96.36.1995 (python)
09:08:43.201 DEBUG:   * CSS / SCSS / Less 3.1 (css)
09:08:43.201 DEBUG:   * Web 18.104.22.1686 (web)
09:08:43.201 DEBUG:   * Git 1.2 (scmgit)
09:08:43.201 DEBUG:   * JSON 2.2 (JSON)
09:08:43.201 DEBUG:   * SonarJS 126.96.36.19907 (javascript)
09:08:43.219 DEBUG: Execution getVersion
09:08:43.219 INFO: SonarQube server 6.2
09:08:43.220 INFO: Default locale: "en_US", source code encoding: "UTF-8"
09:08:43.220 DEBUG: Work directory: /var/lib/jenkins/workspace/redacted-sonar/.sonar
09:08:43.220 DEBUG: Execution getVersion
09:08:43.221 DEBUG: Execution execute
09:08:43.491 INFO: Process project properties
09:08:43.493 DEBUG: Process project properties (done) | time=2ms
09:08:43.622 INFO: Load project repositories
09:08:43.640 DEBUG: GET 200 http://redacted.com/batch/project.protobuf?key=redacted%3Aredacted | time=17ms
09:08:43.707 INFO: Load project repositories (done) | time=85ms
09:08:43.775 DEBUG: Available languages:
09:08:43.775 DEBUG:   * Python => "py"
09:08:43.775 DEBUG:   * CSS => "css"
09:08:43.775 DEBUG:   * SCSS => "scss"
09:08:43.775 DEBUG:   * Less => "less"
09:08:43.775 DEBUG:   * Web => "web"
09:08:43.775 DEBUG:   * JSON => "json"
09:08:43.775 DEBUG:   * JavaScript => "js"
09:08:43.779 INFO: Load quality profiles
09:08:43.799 DEBUG: GET 200 http://redacted.com/api/qualityprofiles/search.protobuf?projectKey=redacted%3Aredacted | time=20ms
09:08:43.804 INFO: Load quality profiles (done) | time=25ms
09:08:43.810 INFO: Load active rules
09:08:43.853 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=css-sonarqube-way-71134&p=1&ps=500 | time=43ms
09:08:43.938 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=js-sonar-way-27675&p=1&ps=500 | time=46ms
09:08:43.961 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=json-sonarqube-way-96571&p=1&ps=500 | time=19ms
09:08:44.005 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=less-sonarqube-way-34273&p=1&ps=500 | time=43ms
09:08:44.039 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=py-sonar-way-66789&p=1&ps=500 | time=28ms
09:08:44.090 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=scss-sonarqube-way-58162&p=1&ps=500 | time=49ms
09:08:44.114 DEBUG: GET 200 http://redacted.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives&activation=true&qprofile=web-sonar-way-97604&p=1&ps=500 | time=20ms
09:08:44.125 INFO: Load active rules (done) | time=315ms
09:08:44.160 INFO: Publish mode
09:08:44.160 DEBUG: Start recursive analysis of project modules
09:08:44.161 INFO: -------------  Scan redacted
09:08:44.250 INFO: Language is forced to py
09:08:44.259 INFO: Load server rules
09:08:44.375 DEBUG: GET 200 http://redacted.com/api/rules/list.protobuf | time=116ms
09:08:44.384 INFO: Load server rules (done) | time=125ms
09:08:44.433 DEBUG: Initializers : GenericCoverageSensor
09:08:44.434 INFO: Initializer GenericCoverageSensor
09:08:44.434 INFO: Initializer GenericCoverageSensor (done) | time=0ms
09:08:44.434 INFO: Base dir: /var/lib/jenkins/workspace/redacted-sonar
09:08:44.434 INFO: Working dir: /var/lib/jenkins/workspace/redacted-sonar/.sonar
09:08:44.436 INFO: Source paths: .
09:08:44.436 INFO: Source encoding: UTF-8, default locale: en_US
09:08:44.436 INFO: Index files
09:08:44.439 INFO: Excluded sources:
09:08:44.439 INFO:   **/flask/**
09:08:44.441 DEBUG: Declared extensions of language Python were converted to sonar.lang.patterns.py : **/*.py
09:08:44.441 DEBUG: Declared extensions of language CSS were converted to sonar.lang.patterns.css : **/*.css
09:08:44.441 DEBUG: Declared extensions of language SCSS were converted to sonar.lang.patterns.scss : **/*.scss
09:08:44.441 DEBUG: Declared extensions of language Less were converted to sonar.lang.patterns.less : **/*.less
09:08:44.441 DEBUG: Declared extensions of language Web were converted to sonar.lang.patterns.web : **/*.html,**/*.xhtml,**/*.rhtml,**/*.shtml
09:08:44.441 DEBUG: Declared extensions of language JSON were converted to sonar.lang.patterns.json : **/*.json
09:08:44.442 DEBUG: Declared extensions of language JavaScript were converted to sonar.lang.patterns.js : **/*.js
09:08:44.446 DEBUG: Language of file 'app/__init__.py' is detected to be 'py'
09:08:44.446 DEBUG: Language of file 'app/app.py' is detected to be 'py'
09:08:44.447 DEBUG: Language of file 'checks_queue_runner.py' is detected to be 'py'
09:08:44.457 DEBUG: Language of file 'clear_queue.py' is detected to be 'py'
09:08:44.457 DEBUG: Language of file 'config.py' is detected to be 'py'
09:08:44.459 DEBUG: Language of file 'delete_queue_runner.py' is detected to be 'py'
09:08:44.468 DEBUG: Language of file 'get_auth_token.py' is detected to be 'py'
09:08:44.470 DEBUG: Language of file 'osclient.py' is detected to be 'py'
09:08:44.471 DEBUG: Language of file 'queue_runner.py' is detected to be 'py'
09:08:44.477 DEBUG: Language of file 'run.py' is detected to be 'py'
09:08:44.478 DEBUG: Language of file 'tq.py' is detected to be 'py'
09:08:44.490 INFO: 11 files indexed
09:08:44.492 INFO: 0 files ignored because of inclusion/exclusion patterns
09:08:44.507 INFO: Quality profile for py: Sonar way
09:08:44.519 DEBUG: Code colorizer, supported languages:
09:08:45.813 DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing
09:08:45.813 DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing
09:08:45.814 DEBUG: 'CSS Analyzer Sensor' skipped because there is no related file in current project
09:08:45.814 DEBUG: 'SCSS Analyzer Sensor' skipped because there is no related file in current project
09:08:45.815 DEBUG: 'Less Analyzer Sensor' skipped because there is no related file in current project
09:08:45.815 DEBUG: 'Web' skipped because there is no related file in current project
09:08:45.815 DEBUG: 'JSON Squid Sensor' skipped because there is no related file in current project
09:08:45.815 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
09:08:45.820 DEBUG: Sensors : Lines Sensor -> PythonXUnitSensor -> SCM Sensor -> Python Squid Sensor -> Embedded CSS Analyzer Sensor -> Zero Coverage Sensor -> Code Colorizer Sensor -> CPD Block Indexer
09:08:45.820 INFO: Sensor Lines Sensor
09:08:45.830 INFO: Sensor Lines Sensor (done) | time=10ms
09:08:45.830 INFO: Sensor PythonXUnitSensor
09:08:45.830 DEBUG: Using pattern 'xunit-reports/xunit-result-*.xml' to find reports
09:08:45.842 DEBUG: No report was found for sonar.python.xunit.reportPath using default pattern xunit-reports/xunit-result-*.xml
09:08:45.842 INFO: Sensor PythonXUnitSensor (done) | time=12ms
09:08:45.842 INFO: Sensor SCM Sensor
09:08:45.850 INFO: Sensor SCM Sensor (done) | time=8ms
09:08:45.851 INFO: Sensor Python Squid Sensor
09:08:46.315 INFO: Python unit test coverage
09:08:46.315 DEBUG: Using pattern 'coverage-reports/coverage-*.xml' to find reports
09:08:46.317 DEBUG: No report was found for sonar.python.coverage.reportPath using default pattern coverage-reports/coverage-*.xml
09:08:46.318 INFO: Python integration test coverage
09:08:46.318 DEBUG: Using pattern 'coverage-reports/it-coverage-*.xml' to find reports
09:08:46.319 DEBUG: No report was found for sonar.python.coverage.itReportPath using default pattern coverage-reports/it-coverage-*.xml
09:08:46.319 INFO: Python overall test coverage
09:08:46.319 DEBUG: Using pattern 'coverage-reports/overall-coverage-*.xml' to find reports
09:08:46.321 DEBUG: No report was found for sonar.python.coverage.overallReportPath using default pattern coverage-reports/overall-coverage-*.xml
09:08:46.321 INFO: Sensor Python Squid Sensor (done) | time=470ms
09:08:46.321 INFO: Sensor Embedded CSS Analyzer Sensor
09:08:46.382 INFO: 0 source files to be analyzed
09:08:46.383 INFO: Sensor Embedded CSS Analyzer Sensor (done) | time=62ms
09:08:46.383 INFO: Sensor Zero Coverage Sensor
09:08:46.387 INFO: 0/0 source files have been analyzed
09:08:46.399 INFO: Sensor Zero Coverage Sensor (done) | time=16ms
09:08:46.399 INFO: Sensor Code Colorizer Sensor
09:08:46.400 INFO: Sensor Code Colorizer Sensor (done) | time=1ms
09:08:46.400 INFO: Sensor CPD Block Indexer
09:08:46.400 INFO: DefaultCpdBlockIndexer is used for py
09:08:46.402 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/app/__init__.py
09:08:46.405 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/app/app.py
09:08:46.429 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/checks_queue_runner.py
09:08:46.431 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/clear_queue.py
09:08:46.432 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/config.py
09:08:46.434 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/delete_queue_runner.py
09:08:46.440 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/get_auth_token.py
09:08:46.442 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/osclient.py
09:08:46.446 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/queue_runner.py
09:08:46.449 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/run.py
09:08:46.450 DEBUG: Populating index from /var/lib/jenkins/workspace/redacted-sonar/tq.py
09:08:46.451 INFO: Sensor CPD Block Indexer (done) | time=51ms
09:08:46.456 INFO: Calculating CPD for 9 files
09:08:46.457 DEBUG: Detection of duplications for redacted:redacted:config.py
09:08:46.464 DEBUG: Detection of duplications for redacted:redacted:tq.py
09:08:46.465 DEBUG: Detection of duplications for redacted:redacted:checks_queue_runner.py
09:08:46.471 DEBUG: Detection of duplications for redacted:redacted:queue_runner.py
09:08:46.474 DEBUG: Detection of duplications for redacted:redacted:app/app.py
09:08:46.476 DEBUG: Detection of duplications for redacted:redacted:osclient.py
09:08:46.477 DEBUG: Detection of duplications for redacted:redacted:clear_queue.py
09:08:46.478 DEBUG: Detection of duplications for redacted:redacted:get_auth_token.py
09:08:46.478 DEBUG: Detection of duplications for redacted:redacted:delete_queue_runner.py
09:08:46.479 INFO: CPD calculation finished
09:08:46.557 INFO: Analysis report generated in 74ms, dir size=104 KB
09:08:46.583 INFO: Analysis reports compressed in 25ms, zip size=43 KB
09:08:46.583 INFO: Analysis report generated in /var/lib/jenkins/workspace/redacted-sonar/.sonar/batch-report
09:08:46.583 DEBUG: Upload report
09:08:46.612 DEBUG: POST 200 http://redacted.com/api/ce/submit?projectKey=redacted:redacted&projectName=redacted | time=27ms
09:08:46.614 INFO: Analysis report uploaded in 31ms
09:08:46.614 INFO: ANALYSIS SUCCESSFUL, you can browse http://redacted.com/dashboard/index/redacted:redacted
09:08:46.614 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
09:08:46.614 INFO: More about the report processing at http://redacted.com/api/ce/task?id=redacted
09:08:46.619 DEBUG: Report metadata written to /var/lib/jenkins/workspace/redacted-sonar/.sonar/report-task.txt
09:08:46.620 DEBUG: Post-jobs :
09:08:46.622 INFO: Task total time: 3.396 s
09:08:46.622 INFO: ------------------------------------------------------------------------
09:08:46.622 INFO: EXECUTION SUCCESS
09:08:46.622 INFO: ------------------------------------------------------------------------
09:08:46.622 INFO: Total time: 4.610s
09:08:46.715 INFO: Final Memory: 45M/163M
09:08:46.715 INFO: ------------------------------------------------------------------------
09:08:46.716 DEBUG: Execution getVersion
09:08:46.716 DEBUG: Execution stop

Versions:
Java 1.8.0_121 Oracle Corporation
Linux 3.10.0-514.6.1.el7.x86_64 amd64
SonarQube server 6.2
pylint 1.6.5,
astroid 1.4.9
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
Plugins:
  * Python 22.214.171.1245 (python)
  * CSS / SCSS / Less 3.1 (css)
  * Web 220.127.116.116 (web)
  * Git 1.2 (scmgit)
  * JSON 2.2 (JSON)
  * SonarJS 18.104.22.16807 (javascript)

example pylint output:
************* Module tq
tq.py:1: [R0801(duplicate-code), ] Similar lines in 2 files
==app.app:246
==get_auth_token:13
***REDACTED RAW CODE***

tq.py:1: [R0801(duplicate-code), ] Similar lines in 2 files
==checks_queue_runner:1
==queue_runner:1
***REDACTED RAW CODE***

# connect to consul
tq.py:1: [R0801(duplicate-code), ] Similar lines in 3 files
==checks_queue_runner:1
==clear_queue:1
==queue_runner:1
***REDACTED RAW CODE***

tq.py:1: [R0801(duplicate-code), ] Similar lines in 2 files
==app.app:40
==tq:11
***REDACTED RAW CODE***

tq.py:1: [R0801(duplicate-code), ] Similar lines in 4 files
==checks_queue_runner:1
==clear_queue:1
==delete_queue_runner:2
==queue_runner:1
***REDACTED RAW CODE***

Report
======
774 statements analysed.

Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |12     |12         |=          |25.00       |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|method   |16     |16         |=          |93.75       |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|function |25     |25         |=          |8.00        |0.00     |
+---------+-------+-----------+-----------+------------+---------+

External dependencies
---------------------
::

    app
      \-app (run)
        \-app (app)
    osclient (clear_queue,app.app,queue_runner,checks_queue_runner,delete_queue_runner)
    six (osclient)

Raw metrics
-----------

+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |895    |66.59 |895      |=          |
+----------+-------+------+---------+-----------+
|docstring |102    |7.59  |102      |=          |
+----------+-------+------+---------+-----------+
|comment   |141    |10.49 |141      |=          |
+----------+-------+------+---------+-----------+
|empty     |206    |15.33 |206      |=          |
+----------+-------+------+---------+-----------+

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |97    |97       |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |7.282 |7.282    |=          |
+-------------------------+------+---------+-----------+

Messages by category
--------------------

+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |238    |238      |=          |
+-----------+-------+---------+-----------+
|refactor   |16     |16       |=          |
+-----------+-------+---------+-----------+
|warning    |681    |681      |=          |
+-----------+-------+---------+-----------+
|error      |41     |41       |=          |
+-----------+-------+---------+-----------+

% errors / warnings by module
-----------------------------

+--------------------+------+--------+---------+-----------+
|module              |error |warning |refactor |convention |
+====================+======+========+=========+===========+
|app.app             |21.95 |56.09   |25.00    |43.28      |
+--------------------+------+--------+---------+-----------+
|delete_queue_runner |19.51 |4.99    |25.00    |7.98       |
+--------------------+------+--------+---------+-----------+
|queue_runner        |14.63 |14.39   |12.50    |15.97      |
+--------------------+------+--------+---------+-----------+
|checks_queue_runner |14.63 |8.22    |0.00     |7.56       |
+--------------------+------+--------+---------+-----------+
|clear_queue         |14.63 |7.05    |0.00     |6.30       |
+--------------------+------+--------+---------+-----------+
|get_auth_token      |4.88  |7.78    |0.00     |4.62       |
+--------------------+------+--------+---------+-----------+
|osclient            |4.88  |0.88    |6.25     |7.56       |
+--------------------+------+--------+---------+-----------+
|app.__init__        |2.44  |0.15    |0.00     |1.26       |
+--------------------+------+--------+---------+-----------+
|tq                  |2.44  |0.00    |31.25    |3.78       |
+--------------------+------+--------+---------+-----------+
|config              |0.00  |0.29    |0.00     |1.26       |
+--------------------+------+--------+---------+-----------+
|run                 |0.00  |0.15    |0.00     |0.42       |
+--------------------+------+--------+---------+-----------+

Messages
--------

+------------------------------+------------+
|message id                    |occurrences |
+==============================+============+
|mixed-indentation             |233         |
+------------------------------+------------+
|bad-indentation               |204         |
+------------------------------+------------+
|unused-wildcard-import        |149         |
+------------------------------+------------+
|invalid-name                  |75          |
+------------------------------+------------+
|bad-whitespace                |49          |
+------------------------------+------------+
|line-too-long                 |44          |
+------------------------------+------------+
|import-error                  |38          |
+------------------------------+------------+
|unused-variable               |33          |
+------------------------------+------------+
|missing-docstring             |33          |
+------------------------------+------------+
|unused-import                 |32          |
+------------------------------+------------+
|bad-continuation              |18          |
+------------------------------+------------+
|wrong-import-order            |11          |
+------------------------------+------------+
|unnecessary-semicolon         |8           |
+------------------------------+------------+
|wildcard-import               |6           |
+------------------------------+------------+
|unused-argument               |5           |
+------------------------------+------------+
|duplicate-code                |5           |
+------------------------------+------------+
|redefined-outer-name          |4           |
+------------------------------+------------+
|bare-except                   |4           |
+------------------------------+------------+
|too-many-statements           |3           |
+------------------------------+------------+
|too-many-locals               |3           |
+------------------------------+------------+
|too-many-arguments            |3           |
+------------------------------+------------+
|superfluous-parens            |3           |
+------------------------------+------------+
|undefined-variable            |2           |
+------------------------------+------------+
|trailing-whitespace           |2           |
+------------------------------+------------+
|wrong-import-position         |1           |
+------------------------------+------------+
|too-many-nested-blocks        |1           |
+------------------------------+------------+
|too-many-format-args          |1           |
+------------------------------+------------+
|too-many-branches             |1           |
+------------------------------+------------+
|singleton-comparison          |1           |
+------------------------------+------------+
|relative-import               |1           |
+------------------------------+------------+
|old-style-class               |1           |
+------------------------------+------------+
|broad-except                  |1           |
+------------------------------+------------+
|anomalous-backslash-in-string |1           |
+------------------------------+------------+

Global evaluation
-----------------
Your code has been rated at -4.73/10 (previous run: -4.73/10, +0.00)

EDIT
I was able to get this working by chowning the pylint-report.txt to jenkins:jenkins as a part of my exec shell step and that seems to have made it work.
Comment: Did you activate Pylint rules in SonarQube profile?
Comment: @ElenaVilchik I have all rules enabled except for deprecated rules. However, I chowned the pylint-report.txt to `jenkins:jenkins` as a part of my exec shell step and that seems to have made `PylintImportSensor` kick in (complains alot about `Pylint rule is unknown in Sonar` though). It's not picking up duplications though and there are definitely some when I run pylint manually. Not sure how to make that work.
Comment: What kind of duplications are you talking about? Could you provide pylint report?
Comment: @ElenaVilchik Added. Redacted the raw code pylint outputs for showing what code is duplicated.
Comment: @ElenaVilchik for now I have my jenkins instance using clonedigger for duplicate code reports until sonar has it working.
Comment: @ElenaVilchik how do you activate the pylint rules???
Comment: In your report I only issues for R0801 (duplicate-code), this rule is deprecated. To activate the rule, open it in SQ UI and activate in the profile you use in your project.
Answer: I had the same problem, but the solution was different: activate pylint rules on sonarqube. I activated one by one in my Python quality profile, jotting down the code of the pylint rules for which the description (on sonarqube) said it was deprecated.
In general, the pylint rule is deemed deprecated on sonarqube when the "built-in" SonarAnalyzer for Python already has the same rule. (We don't want the same issue reported by two rules.)
These are the pylint rules that I found as deprecated on sonarqube. I disabled them on my pylint.cfg file.
 C0103,C0111,C0112,C0301,C0302,C0303,C0304,C0321,C0325,C1001,E0100,E0101,E0103,E0104,E0105,E0106,E0107,E0235,R0201,R0801,R0911,R0912,R0913,W0101,W0107,W0122,W0331,W0333,W1401
When activating a rule, you specify the severity, so doing one by one allows you to configure how "offensive" each type of violation is for your projects.

Sonar failing to get pylint results


Cannot install Ruby 1.9.3 on Mountain Lion w/ RVM: Error running make

Question: I'm trying to install Ruby so I can do the "Learn Ruby the Hard Way" course, and I've just been having tons of trouble installing the newest version of Ruby
Here's the relevant part of my log:
compiling md5ossl.c
linking shared-object digest/md5.bundle
ld: in /usr/local/lib/libz.1.dylib, file was built for unsupported file format ( 0xce 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 0 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (x86_64): /usr/local/lib/libz.1.dylib for architecture x86_64
collect2: ld returned 1 exit status
make[2]: *** [../../../.ext/x86_64-darwin12.1.0/digest/md5.bundle] Error 1
make[1]: *** [ext/digest/md5/all] Error 2
make: *** [build-ext] Error 2

I googled around and found this post looking like the exact same problem: Cannot install Ruby 1.9.3 on Mountain Lion w/ Jewlery Box: Error running make -j4 (have current readline, gcc)
But the answer there is an ambiguous "update libz lib". I don't know what that means, I googled around and found zlib but I don't know if these are the same thing as libz? I also found another post indicating libz is libtool, my libtool version is Apple Inc. version cctools-829, but is libtool the same thing as libz? I've never seen any of these terms before or used Ruby before and am just totally confused.
I have gcc 4.2.1 and xcode 4.4.1. Thanks for any help, this is my first post on here so please kindly let me know if I did anything incorrectly or need to provide more information. I basically stole my title from the title I linked to because I wasn't sure about how to format titles, I hope that's okay.
Comment: Yes, zlib and libz are the same thing.
Answer: As a note, OS X does not put anything in /usr/local/lib or /usr/local/bin so you must've installed something there yourself, perhaps even inadvertently.
If you're using a Ruby manager like rvm or rbenv then they have special build tools to help with this process. It's a lot easier than installing from source since the correct patches are applied not only to Ruby but the dependencies like libz.
What you might have is libraries compiled for the wrong architecture on your machine. These may have been rolled over from an old PowerPC install or even Intel 32-bit one from a version of OS X prior to 10.5.
Your best bet might be to simply remove /usr/local/lib/libz* and use the ones that come bundled with your OS instead. You should have a set of the required files in /usr/lib/libz* that can work.
Comment: You can also easily check what architecture it's compiled for by running the file command in a shell "file /usr/local/lib/libz.1.dylib"


Updating all HierarchyID nodes in SQL Server 2008

Question: I am importing data from one database to another. The hierarchyid column must also be ported over with the relationships intact.
If the target table is empty, it's easy. When the target contains rows, the hierarchy as it is in the source table will not be valid in the target table
The easiest would be to increment all values in the hierarchy field with the value of the first ported row's primary key.
So if a source row's hierarchyid was '/1/12/13/' and the next available id in target before importing was 101, the hierarchy should change so each value is incremented by 100:  '/101/112/113/'
I have read Updating "Hierarchyid" in SQL Server, but do not see how it can be applied to my problem.
How would I go about incrementing each number in each hierarchyid of each row by 1 set value, i.e. increment all numbers in the hierarchy field by 100?
Comment: When you transfer data from source table to target table (1) then you, always, transfer also the first level or (2) there are some cases when you import only inferior levels (ex. you start importing data from the second level => you import /101/1/ without importing /101/) ? So, /101/ and /101/1/, /101/2/, .../101/5/, /101/2/1/ (first case) or /101/2/, /101/2/1/ ?
Answer: Look at this solution (explanations can be found bellow):
DECLARE @Source TABLE
(
    ID HIERARCHYID PRIMARY KEY
    ,Name NVARCHAR(50) NOT NULL
);

DECLARE @Target TABLE
(
    ID HIERARCHYID PRIMARY KEY
    ,Name NVARCHAR(50) NOT NULL
    ,OldID HIERARCHYID
);

INSERT  @Source
VALUES
        ('/1/','a'), ('/1/1/','aa'), ('/1/2/','ab'), ('/1/3/','ac')
        ,('/2/','b')
        ,('/3/','c'), ('/3/3/','cc')
        ,('/4/','d'), ('/4/1/','da'), ('/4/2/','db'), ('/4/2/1/','dba'), ('/4/2/1/5/','dbaf');

DECLARE @LastTargetRootNodeAsInteger INT;
SELECT  @LastTargetRootNodeAsInteger = REPLACE( MAX( a.ID.GetAncestor( a.ID.GetLevel()-1 ) ).ToString(), '/', '')
FROM    @Target a;

WITH CteUpdate
AS
(
SELECT  a.ID
        ,a.Name
        ,a.ID.GetAncestor( a.ID.GetLevel()-1 ) AS OldRootID
        ,CONVERT(HIERARCHYID,'/'+CONVERT(VARCHAR(256),@LastTargetRootNodeAsInteger+DENSE_RANK()OVER(ORDER BY a.ID.GetAncestor( a.ID.GetLevel()-1 )))+'/') NewRootID
FROM    @Source a
)
INSERT  @Target(ID, Name, OldID)
SELECT  a.ID.GetReparentedValue(a.OldRootID, a.NewRootID), a.Name, a.ID
FROM    CteUpdate a;

SELECT  *
        ,t.ID.ToString() AS CurrentNodeToString
        ,t.OldID.ToString() AS OldNodeToString
FROM    @Target t
ORDER BY t.ID;

Explanation:

First step suppose to find last root node (@LastTargetRootNodeAsInteger) from the target table.
Then, for every ID from source table we get the root node (old root node: a.ID.GetAncestor( a.ID.GetLevel()-1 ) ).
For every old root node we get the new root node ('/'+...+@LastTargetRootNodeAsInteger+DENSE_RANK()OVER(ORDER BY old_root_node)+'/').
And finally, we will insert the rows with the new root node (a.ID.GetReparentedValue(old_root,new_root)).

To see how we get the new IDs, you can execute this query:
SELECT  *
        ,c.ID.GetReparentedValue(c.OldRootNode,c.NewRootNode).ToString() AS NewCurrentNode
FROM
(
        SELECT  *
                ,'/'+CONVERT(VARCHAR(256),@LastTargetRootNodeAsInteger+DENSE_RANK() OVER(ORDER BY b.OldRootNode))+'/' AS NewRootNode
        FROM
        (
                SELECT  *
                        ,a.ID.ToString() AS OldCurrentNode
                        ,a.ID.GetAncestor( a.ID.GetLevel()-1 ).ToString() AS OldRootNode
                FROM    @Source a
        ) b
) c

Results:


Understanding 'newtype' keyword

Question: For a uni assignment, we have been given a line of Haskell code which shows:
newtype TC a = TC ([Id] -> Either TypeError ([Id], a))

Firstly, TypeError is something which needs to be implemented by us for the assignment so I can't post the data declaration here, but my question is this. How do I read the code above? What is the a right after the newtype TC? I also don't understand how TC is being reused to the right of the equals sign.
I think a here is a type variable since newtype works similarly to data. I don't know how knowing this will help my understanding.
Answer:
What is the a right after the newtype TC?

The a in the newtype declaration
newtype TC a = ...

expresses much the same as the x in a function declaration
f x = ...

a is a type parameter. So you'll be able to use TC as, for example, TC Int or TC Bool, similar to how you're able to use f like f 1 or f "bla bla" (depending on its type).
The case TC Int is equivalent to the following alternative:
newtype TCInt = TCInt ([Id] -> Either TypeError ([Id], Int))

I also don't understand how TC is being reused to the right of the equals sign.

That is a bit of a confusing quirk in Haskell. Actually TC is not reused, rather you're declaring two separate entities which are both called TC. You could also call them differently:
newtype TC_T a = TC_V ([Id] -> Either TypeError ([Id], a))

TC_T is a type constructor. This is the thing that will appear in type signatures, i.e. TC_T Int or TC_T Bool.
TC_V is a value constructor. You use this when, well, generating values of type TC_T Int or TC_T Bool.

So for example, you might write these:
tci :: TC_T Int
tci = TC_V (\ids -> Right (ids, 37))

tcb :: TC_T Bool
tcb = TC_V (\ids -> Right (reverse ids, False))

With your original version it looks like this:
tci :: TC Int
tci = TC (\ids -> Right (ids, 37))

tcb :: TC Bool
tcb = TC (\ids -> Right (reverse ids, False))

...but it's still two separate things both called TV here. Most newtypes in Haskell call the type- and value constructors the same, but often only the type constructor is exported from a module and the value constructor left as an implementation detail.
Most of this is the same for data as for newtype. You could as well have
data TC a = TC ([Id] -> Either TypeError ([Id], a))

... the only difference to the newtype version is a subtle indirection: if it's data, then the compiler inserts an indirection which allows a bit more lazyness, but in this case there's hardly a point to doing that.
In practice, you generally use data only when you need multiple constructors and/or a constructor with multiple fields, which newtype does not support.
Comment: @mraya99 `a` can be any arbitrary type: `TC (Int, String)`, `TC [Bool]`, `TC (Maybe Bool`, `TC (Bool -> [(Int, String)])` are all valid. Note that in `TC (Int, String)` we are not passing a pair-of-types (i.e., two type arguments), but we are applying `TC` to the type of the tuples (AKA product type) which is written `(Int, String)` in Haskell. So, to be pedantic, `a` can not be a tuple-of-types, but it can be the (single) type of tuples.
Comment: The difference between type and value constructors is more understandable when there is more than one of them: e.g. `data Tree = Leaf | Branch Tree Tree`
Comment: Thank you, this is a very detailed answer. I will have to let it sit for a while but I can already understand the difference between the TC's and the fact that "a" is a type paramater. Follow up question, can the "a" be a tuple then?
Answer: The benefit of newtype over data is that you can derive via the type that underlies it:
{-# Language DerivingVia              #-}
{-# Language StandaloneKindSignatures #-}

import Control.Applicative   (Alternative)
import Control.Monad         (MonadPlus)
import Control.Monad.Except  (ExceptT(..), Except)
import Control.Monad.Fix     (MonadFix)
import Control.Monad.State   (StateT(..), MonadState)
import Data.Functor.Identity (Identity(..))
import Data.Kind             (Type)

type    TC :: Type -> Type
newtype TC a = MkTC ([Id] -> Either TypeError (a, [Id]))
  deriving
    ( Functor, Applicative, Alterantive
    , Monad, MonadPlus, MonadState [Id], MonadFix
    )
  via StateT [Id] (Except TypeError)

-- Alternative and MonadPlus rely on these
instance Semigroup TypeError ..
instance Monoid    TypeError ..

I had to swap the tuple but this works because of three newtypes: TC a, StateT s m a and ExceptT. The compiler generates an instance for each newtype witnessing that it has the same runtime representation as the underlying type.
This is called representational equality and is witnessed by Coercible.
-- instance Coercible (StateT s m a) (s -> m (a, s))
type    StateT :: Type -> (Type -> Type) -> (Type -> Type)
newtype StateT s m a = MkStateT (s -> m (a, s))

-- instance Coercible (ExceptT e m a) (m (Either e a))
type    ExceptT :: Type -> (Type -> Type) -> (Type -> Type)
newtype ExceptT e m a = MkExceptT (m (Either e a))

This entails that TC a is coercible to StateT [Id] (Except TypeError) a and thus we can use coerce-based deriving strategies to carry instances between them (like GeneralizedNewtypeDeriving or DerivingVia).
  TC a
={Coercible}
  [Id] -> Either TypeError (a, [Id])
={Coercible}
  [Id] -> ExceptT TypeError Identity (a, [Id])
={Except e = ExceptT e Identity}
  [Id] -> Except TypeError (a, [Id])
={Coercible}
  StateT [Id] (Except TypeError) a

GeneralizedNewtypeDeriving only works on newtypes but this does not mean that DerivingVia only works on newtypes. You can dervive many instances for data, for example by Applicative lifting methods over TC (Ap TC a).
Making it a newtype does simplify things, the Applicative can be derived through the state transformer so we don't need to write any instance by hand.
data TC a = MkTC ..
  ..

  deriving (Semigroup, Monoid, Num, Bounded)
  via Ap TC a

The TC name serves two purposes in your code ('punning'). I separate them into two different names, for TC and the transformers.
The left-hand side is the type constructor:
>> :k TC
TC :: Type -> Type
>> :k StateT
StateT :: Type -> (Type -> Type) -> (Type -> Type)
>> :k ExceptT
ExceptT :: Type -> (Type -> Type) -> (Type -> Type)

and the right-hand side is the value constructor, which I added a Mk for disambiguation:
>> :t MkTC
MkTC :: ([Id] -> Either TypeError (a, [Id])) -> TC a
>> :t MkStateT
MkStateT :: (s -> m (a, s)) -> StateT s m a
>> :t MkExceptT
MkExceptT :: m (Either e a) -> ExceptT e m a

The a :: Type is an argument to the type constructor:
TC   :: Type -> Type
TC a :: Type

Without a type argument none of those instaces would kind-check because all of those instances require an "unary type constructor" (Type -> Type) as an argument. That is to say, a type parameterised by a type:
Functor         :: (Type -> Type) -> Constraint
Applicative     :: (Type -> Type) -> Constraint
Alternative     :: (Type -> Type) -> Constraint
Monad           :: (Type -> Type) -> Constraint
MonadPlus       :: (Type -> Type) -> Constraint
MonadState [Id] :: (Type -> Type) -> Constraint
MonadFix        :: (Type -> Type) -> Constraint

Understanding 'newtype' keyword


Parcelamento para mysql

Question: Estou fazendo um sistema de vendas no qual 1 venda gera 12 parcelas para 3 usuários, sendo eles o vendedor, o gerente e o supervisor, gostaria de saber qual o melhor método para o armazenamento destas parcelas.
Seria criar 1 tabela para cada usuário e quando fizesse a venda gerasse as 36 linhas, um cronjob que gerasse as parcelas a cada mês ou outra coisa?
É um sistema para mais ou menos 100 usuários.
Comment: Está um pouco confuso, pode explicar melhor? Afinal, são 12 parcelas ou 36? Seja como for, criar uma tabela por usuário é uma péssima ideia, crie uma tabela só com uma coluna indicando qual é o usuário.
Comment: @bfavaretto são 3 tipos de usuários sendo eles (vendedor, gerente e supervisor) cada venda gera 12 parcelas para cada 1 deles com valores diferentes. por ex: 1 vendedor faz uma venda, desta venda 1.7% é comissão do vendedor, 0.3% é comissão do supervisor e 1.5 é comissão do gerente. e caso esta venda seja por indicação de algum cliente tem mais a comissão do cliente
Comment: @KelvinPrimo isso são duas coisas distintas, tipo de usuário tem de ser uma tabela "tipo" com id na tabela de usuários: `tipo_id` ou assim. depois cada id de usuário tem de estar na tabela de vendas: `usuario_id`
Answer: Não precisa muito longe. No caso você pode usar 3 tabelas simples, como ver nesse diagrama ER bem porco que acabei de fazer.
Comment: então, esta ideia era o que eu estava tentando evitar, pois em 1 ano nas melhores hipóteses já teria 360000 rows a tabela de comissionamento. entre eles as inadimplentes.
Comment: Até ai tudo bem. Mysql dá conta sem problemas desse número de registros. O que vc poderia fazer ai é criar 2 views. Uma para parcela casas e outra para inadimplentes se vc quer uma forma fácil de separa-las.
Comment: Se seguir com esse modelo você também pode particionar a tablea. Aqui tem um exemplo de como fazer isso: http://www.w3resource.com/mysql/mysql-partition.php  Com ele faz separações lógicas e fisicas dos registros, de acordo com a forma com a qual vc quiser odernar (ano por exempo).
Comment: eu tive a seguinte ideia a pouco, gostaria da sua opinião, quando o usuário confirmasse o pagamento da 1 parcela, o sistema geraria a segunda. e isso sucessivamente.
Comment: Entendi, vc quer gerar conforme é paga. Funciona, mas dificultaria na hora que vc por exemplo precisasse procurar por inadimplentes por exemplo. Mas tudo depende das operações que você pretende fazer. Mas lembre-se o numero de registros da tabela não é importante desde que você use corretamente indices e chavs. Normalmente tabelas que tendem a crescer muito, eu também evito usar INT ou BIGINT como chave primária, preferindo um GUID.
Comment: huum, entendi. vou seguir seu conselho e caso o banco fique muito grande ai tem que partir para partição. muito obrigado.

Parcelamento para mysql


how to add dynamic options using jquery with same class?

Question: I am trying to learn to add category and subcategory dynamically in a dropdown menu with the same class, however when i click the first dropdown all inputs gets effected
html :
form action="" method="post">

 <select class="category"> <option value="">Select
Category</option>

 </select>

Sub Category <select class="sub_category">

</select>>

 <input type="button" id="add" value="Add another">
    </form>

Jquery:

Comment: okay, sure.. problem with the code is when i press add another it adds fresh sets of dropdown, but they are getting affected with any change that i make to the first dropdown
Comment: the each() function isn't workin
Comment: I got you a fiddle started - (https://jsfiddle.net/hk59b4d1/), you can modify the code at the jsfiddle until you get the desired results. I can tell you one thing that is wrong is that each time you click on the dropdown for category, you re-add the same options again, I think you only want to add them once. Same goes for the sub_category. I also combined your code into one `$(document).ready()`
Comment: @RyanWilson thanks very much, could you pls. tell me where an i goin wrong?
Comment: Please see provided answer and link to working fiddle below.
Answer: I decided to help you out and hopefully teach you a few things along the way:
$(document).ready(function()  {
    const wrapper = $("#tmp"); //Fields wrapper
    const add_button = $("#add"); //Add button ID
    const pfield = "Category"+
    "<select class=\"category\">"+
    "<option value=\"\">Select Category</option></select>"+
    "Sub Category"+
    "<select class=\"sub_category\"></select>
"

    $(add_button).click(function(){ //on add input button click
        $(wrapper).append(pfield); //add input box
    });

    //***START of updated code***
    //We use Event Delegation in this scenario -
    //learn more here: (https://learn.jquery.com/events/event-delegation/)
    //We attach the click/change events to the parent div, but delegate it
    //to children of class .category

    //Use delegate event handler
    $(wrapper).on('click', '.category', function(){
        //Check to see if the drop down has more than 1 option
        //if not, perform the append of the desired options
        if($(this).find('option').length < 2){
            for (var i = 0; i < 5; i++) {
                $(this).append($("<option></option>").attr("value",i).text("something"+i));
            }
        }
    });
     //Use delegate event handler
     $(wrapper).on('change', '.category', function(){
         //This one is a little tricky, we only want to check and append
         //to the closest drop down of className .sub_category
         //We can get the closest .sub_category drop down by using
         //.nextAll() - passing a selector of .sub_category and specifying the first match using :first
         //So we check to see if the sibling .sub_category has any options
         //If not, we add them
         if($(this).nextAll('.sub_category:first').find('option').length < 1){
            for (var j = 0; j < 5; j++) {
                $(this).nextAll('.sub_category:first').append($("<option></option>").attr("value",j).text("somethingelse"+j));
            }
         }
     });

});
//***END of updated code***

Here is a working jsfiddle - (https://jsfiddle.net/jty0716k/2/)
Comment: you're awesome.. works like magic!! thanks very much..
Comment: @John You're welcome. Please take the time to read through the code and my comments as it may help you in your future coding efforts.
Comment: especially for the learning :), thanks for your efforts!!
Comment: @John No problem. We all are learning. That's what it is all about. :)