text:
Q: Which Regular Expression could I use to find an email address inside tags? My problem
I have a string with an email address between tags, and I need to extract that email. For example, from here:
var myString = "This email for John <john@mail.com> needs to be extracted"

I would like to extract john@mail.com
My attempt to fix
I came up with this regular expression to extract an email address from a string (it doesn't need to validate the email, just a simple regex):
/<\S*@\S*>/gi

It works fine if my string doesn't have other tags, like the previous one. But this regex fails when it finds this scenario:
var myString = "This bold email for John <b><john@mail.com><b/> needs to be extracted"

How can I improve my regex to match only the email, ignoring other tags?
P.S.: My end goal is to strip those tags out of the string (only the email tags), so I am open to other suggestions on how to do that as well.
Thanks!

A: It would be difficult to get a perfect regular expression for matching all email addresses and only email addresses, but this should work for your case:
/<[^<\s]*\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b[^>\s]*>/gi

A: You can exclude matching the brackets, @ and whitespace chars before and after matching the @ using a negated character class [^<>\s@]
If you want to match 0 or more times, you could use * instead of +
<[^<>\s@]+@[^<>\s@]+>

Regex demo

A: "This bold email for John <b><john@mail.com><b/> needs to be extracted".match(/<\w+@\w+\.\w+/>)[0];
// <john@mail.com>

\w matches letters, numbers, and the underscore. Followed by a +, it matches an unbroken string of such characters.
. is a special character in regex so it has to be escaped.
So in the regex \w+@\w+\.\w+, the first \w+ matches john, then @ matches @ of course.  The next \w+ matches mail, the \. matches ., and the last \w+ matches com.


text:
Q: Windows 10 Universal App Navigating between pages VB.NET Looking at various sources across the internet I have found that
Frame.Navigate(typeof (SecondaryPage))

Seems to be the method of switching pages. However, I get an error on 'SecondaryPage' Saying: SecondaryPage is a class type and cannot be used in this expression. Any Ideas?
I need navigation between a few pages

A: I have found that inspecting the App.vb provided the answer. I looked into how the app automatically loaded the first page.
In VB.NET it is
Frame.Navigate(GetType(SecondaryPage))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I generate UUID in C++11? Is there any build-in facility that allows to generate UUID in C++11 without using any adidtional libraries?

A: Reposted from comment:
Built-in facility, no. But if you use a third party library (as opposed to OS functionality), I strongly recommend Boost.UUID.

A: I know this is an old thread, but another option is Poco's UUIDGenerator.
auto uuid_str = Poco::UUIDGenerator().createRandom().toString();


text:
Q: Does the apache httpclient fluent API support gzip encoding? The recommended API for apache httpclient seems to be the HC Fluent API these days.  I cannot find an example using gzip encoding for the request or response however.
The tutorial https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html doesn't mention how to add interceptors which seem to be one way of adding this functionality
I'm happy to use the 'old' HttpPost style API if written against the latest httpclient version (currently 4.5) but these APIs appear to get rewritten and the previous one deprecated frequently meaning previous answers based on these APIs are out of date e.g.
Does Apache Commons HttpClient support GZIP?


text:
Q: Login database issues I am trying to fill a database with records so that when you login it will either accept you or not. For now I just have one to test it out but it doesn't seem to work. When I put in the info for ID and password and click the Button, nothing happens. Can anyone tell me what I'm missing or doing wrong? Sorry if it's obvious, but I'm just stuck right now.
https://github.com/liliycode/Login/blob/master/login%20java

A: Your click listener is not correct. You should define click listener for button in onCreate method. When you click button you get data from edittext and invoke method which inserts data to DB.

A: First of all your are comparing EditTexts to strings which is wrong
if ( loginET.equals("Liliy") && login2ET.equals("1234"))

change this to
 if ( loginET.getText().toString().equals("Liliy") && login2ET.getText().toString().equals("1234"))

And make your buttonListener in onCreate(), and at click of button call your method populateData()
pressBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //reading the inputs
                String idET = loginET.getText().toString();
                Double passET = Double.parseDouble(login2ET.getText().toString());
            populateData();
            }
        });

Which checks for data and populates it.


text:
Q: Tablesorter filter works, but from second attempt I'm using jQuery tablesorter (last version) and having an interesting issue with filter widget. It works, but only from second attempt. First time when i filter any column it does not filtering at all, but if i clear filter field (backscape or delete) and print something again it work just fine (Until i reload the page of course). Debug not showing any signs of problem.
Any thoughts?

A: Issue was solved by updating jQuery library to latest version.


text:
Q: Phase space measure in positron-electron annihilation calculation I'm still trying to calculate the cross-section of the $e^- e^+ \rightarrow \mu^- \mu^+$ interaction in first order. This time I'm struggling with the phase space measure. Note that I have two questions, which are not exactly related but since they deal with the same equation I'll post them both at once.
1) So generally one has to integrate over the unknown momenta, i.e. the momenta of the outgoing muons, while keeping in mind that energy and momentum conservation needs to hold:
$$d\Phi_{12 \rightarrow 34} = [dp_3][dp_4] (2 \pi)^4 \delta(p_1 + p_2 - p_3 - p_4) = \frac{d^4p_3}{(2 \pi )^3}\delta(p_3^2 - m_{\mu}^2)\frac{d^4p_4}{(2\pi)^3}\delta(p_4^2 - m_{\mu}^2)(2\pi)^4\delta(p_1 + p_2 - p_3 - p_4)$$
In my script they jump from this point to this expression:
$$\frac{d^4p_3}{(2\pi)^2}\delta(p_3^2 - m_{\mu}^2)\delta((p_1 + p_2 - p_3)^2 - m_{\mu}^2)$$
Can somebody explain to me what happened here? Where did the integration over $p_4$ vanish to?
2) In the expression below:
$$\frac{|\vec{p_3}|^2 d|\vec{p_3}| d(\cos\theta) d\phi}{(2\pi)^2} \frac{1}{4E} \delta(E_3^2 - |\vec{p_3}|^2 - m_{\mu}^2) = \frac{|\vec{p_3}|d(\cos\theta)d\phi}{(2\pi)^2}\frac{1}{8E}$$
How was the Delta function manipulated here to give make the two terms equal? I have trouble seeing this.

A: Generally, a Dirac delta function is there to ensure conservation of momentum. In the first case where you have:
$$\delta(p_1 + p_2 - p_3 - p_4)$$
This is telling you that the momentum of the incoming particles must necessarily be equal to the momentum of the outgoing particles. Hence from the delta function above, we know that
$$p_1 + p_2 = p_3 + p_4$$
From this it follows that $p_4 = p_1 + p_2 - p_3$. All you do next is perform some cancellations of factors of $2\pi$ and replace everywhere you see $p_4$ with the expression above.
Its the same with the second expression but its a bit trickier because of the $d|\vec{p_3}|$. To remove the delta function, you need
$$|\vec{p_3}| = \sqrt{E_3^2 - m_{\mu}^2}$$
Performing the differential:
$$d|\vec{p_3}| = d(\sqrt{E_3^2 - m_{\mu}^2}) = \frac{1}{2}(E_3^2 - m_{\mu}^2)^{-1/2} = \frac{1}{2}(|\vec{p_3}|^2)^{-1/2} = \frac{1}{2}(|\vec{p_3}|)^{-1}$$
Perform the cancellations and you are done.


text:
Q: Blender + Python import bpy
    positions = (0,3,2) , (4,1,6) , (3,-5,1) , (3,10,1) , (1,8,1)
    start_pos =(0,0,0)
    ob = bpy.data.objects ["Sphere"]
    frame_num = 0
     for position in positions:
         bpy.context.scene.frame_set(frame_num)
         ob.location = position
         ob.keyframe_insert(data_path="location", index =-1)
         frame_num +=20

Can anyone help me realize the error and what part of the code is wrong I can't understand what is wrong
This is the error
'Python script failed, check the message in the system console'

A: The formatting used in a python script affects the way it is interpreted. You need to make sure that each block of code has matching indentation, which is normally set at four spaces per indentation.
There is a formal specification of how to format a python script, often referred to as PEP 8
The correctly formatted version of your script should look like :-
import bpy
positions = (0,3,2) , (4,1,6) , (3,-5,1) , (3,10,1) , (1,8,1)
start_pos =(0,0,0)
ob = bpy.data.objects ["Sphere"]
frame_num = 0
for position in positions:
    bpy.context.scene.frame_set(frame_num)
    ob.location = position
    ob.keyframe_insert(data_path="location", index =-1)
    frame_num +=20


text:
Q: html not parsing as php in wamp I am  using this snippet in my .htaccess file to parse html as php:
<FilesMatch "\.(html|htm|txt)$">
 SetHandler application/x-httpd-php5
</FilesMatch>

this is working fine in my website(online) but not in my localhost (using WAMP latest version)..
but if I change the above code to:
<FilesMatch "\.(html|htm|txt)$">
 SetHandler application/x-httpd-php
</FilesMatch>

then, this is working fine in my localhost but not in my website..
I have to add/remove the 5 in SetHandler application/x-httpd-php to work in either one side.
Please, help me..

A: You can edit your local httpd.conf file, and add the mime modules you need:
<IfModule mime_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php .html
AddType application/x-httpd-php .htm
AddType application/x-httpd-php .txt
</IfModule>

This should work for your local host. If you can't configure your server this way, and since your .htaccess works there, use the .htaccess config for your server only.


text:
Q: Passing php variable to window.location I use the following code for my sumbit to reddit button.
onclick="window.location = 'http://www.reddit.com/submit?url=<?php echo $url?>';

but the above won't work for cases where there a ' in $url
onclick="window.location = 'http://www.reddit.com/submit?url=http://vinejar.com/96-Don't-be-this-guy.html';

It is necessary to get $url there so the following won't help.
onclick="window.location = 'http://www.reddit.com/submit?url=' + encodeURIComponent(window.location);

A: You could encode your $url,for example:
onclick="window.location = 'http://www.reddit.com/submit?url=<?php echo urlencode($url) ?>';


text:
Q: Reverse the order of pairs I am trying to write a function in Racket that will reverse the order of pairs.  For example, given the list '(1 2) the function should produce '(2 1).  Here is my code so far:
(define (reverse aList)
    (cons (second aList)
        (first aList))

This is not producing the correct answer, however.  When I test with '(a b) it returns '(b . a) instead of '(b a).  How do I get rid of the period between the b and a?

A: You should have:
(define (reverse-pair lst)
  (cons (second lst) (cons (first lst) empty)))

As stated in Racket's docs:

The cons function actually accepts any two values, not just a list for the second argument. When the second argument is not empty and not itself produced by cons, the result prints in a special way. The two values joined with cons are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between.

So,
> (cons 1 2)
'(1 . 2)
> (cons 1 (cons 2 empty))     ; equivalent to (list 1 2)
'(1 2)


text:
Q: How to disable touch screen with a broken screen? I have a lenovo yoga pro 2. I´ve closed it badly and now i have the screen broken. It has one crack at the bottom which does imitates clicks on the screen. I did not found any hot keys to disable touch on screen. The only solution i found is to go to the device manager and disable it there. But because of the crack which does like 6 touches per second i can't open it and do something there.
Is there any easy solution to disable it in this situation?


text:
Q: Looking for tables/columns that contain specific substring Is there any way to query an entire Oracle database using sql or plsql to return a list of all tables/columns that contain the specific substring? Note that I want to look for the substring within the data (not within the table/column names themselves).
I have an issue where a character looks like a space, but is actually a different character.  I have proven this out by taking the substring text and putting it through a hexadecimal converter.  I need to be able to locate everywhere in the database this character exists, so I can replace it with an actual space.
Any thoughts?

A: If you're just looking for table and column names, you can use the view: ALL_TAB_COLUMNS:
SELECT owner, table_name, column_name FROM all_tab_columns
WHERE table_name LIKE UPPER('%search_string%')
OR column_name LIKE UPPER('%search_string%');

If you want to search additional places for names, you could use the ALL_OBJECTS view:
SELECT owner, object_name, object_type
FROM all_objects WHERE object_name LIKE UPPER('%search_string%') ;

A: You can use ALL_TAB_COLUMNS table to search in column and tables using like.


text:
Q: PDFtk throws a Java Exception when attempting to use 'fill_form' function I have a PHP application that fills out a form from a database call. At present I am putting this together using PDFtk, I am able to run a number of PDFtk commands with no issue and I am currently working out the desired command at command line.
My call is currently this:
pdftk /var/www/html/CSR/template/job_card.pdf fill_form /var/www/html/CSR/template/wwwwu7mMH.fdf output /var/www/html/CSR/template/filled4.pdf

This exact call run multiple times generates this error sometimes:
    Unhandled Java Exception in create_output():
java.lang.ClassCastException: pdftk.com.lowagie.text.pdf.PdfNull cannot be cast to pdftk.com.lowagie.text.pdf.PdfDictionary
   at pdftk.com.lowagie.text.pdf.FdfReader.readFields(pdftk)
   at pdftk.com.lowagie.text.pdf.FdfReader.readPdf(pdftk)
   at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.FdfReader.<init>(pdftk)

and this error sometimes:
Unhandled Java Exception in create_output():
Unhandled Java Exception in main():
java.lang.NullPointerException
   at gnu.gcj.runtime.NameFinder.lookup(libgcj.so.10)
   at java.lang.Throwable.getStackTrace(libgcj.so.10)
   at java.lang.Throwable.stackTraceString(libgcj.so.10)
   at java.lang.Throwable.printStackTrace(libgcj.so.10)
   at java.lang.Throwable.printStackTrace(libgcj.so.10)

The error message alternates but the command never works and the form is never filled. As I say though, the PDFtk works with other commands, I have been able to generate encrypted PDFs and run the fixed commands succesfully.
My question is what is causing this error and how do I fix it?

A: It looks like PDF TK was not able to process stings that had char ( and ) I replaced them with \) and \( to escape them, and it worked well.

A: I see my name in the StackTrace. That's not a coincidence: PdfTk is based on a mighty old version of iText. iText is a Java PDF library that was originally written by me, but used by a third party to create PdfTk.
The error tells you that iText is parsing a PDF that has either an error, or an unexpected feature.
A PDF consists of PDF objects such as PDF string objects, PDF number objects, PDF array objects, PDF dictionary objects, PDF stream objects, and so on. iText is able to retrieve these objects and to reuse them to create a new PDF. In your case, a new PDF with some form fields that are filled out is created based on the objects of the original PDF.
It is impossible to answer your question without seeing the PDF that causes the problem, but let's say that your PDF contains an /AcroForm entry with a /Fields array. In this fields array, there is a reference to a field dictionary. Suppose that one of the field dictionaries in your PDF isn't a dictionary, but a PDF null object. The form shows up perfectly in Adobe Reader, but internally, there is a flaw that prevents proper processing of the form.
In that case, iText will loop over the entries in the fields array, and one of those entries won't return a field dictionary, but a PdfNull object. In that case, you'll get a ClassCastException, because you can't cast PdfNull to PdfDictionary.
This being said:

*

*If I see my name in your stack trace, this triggers an alarm, because it means that you're using an iText version that predates iText 5. Such a version should no longer be used. You should use a more recent version of iText. There is a high chance that a more recent version of iText gives you either a better error message, or tolerates (and maybe even fixes) the error in the PDF.

*If you find a PdfTk version that uses a more recent version of iText, that would surprise me, because as far as I know, PdfTk isn't available under the AGPL, nor is PDF Labs (the owner of PdfTk) a customer of iText Software.

*If you want to keep on using PdfTk, you shouldn't expect an answer as long as you don't share the PDF document that you're trying to fill.

One thing you could try: open the form in Adobe Acrobat. Save the form in Adobe Acrobat. There is a chance that the saved form no longer has the problem. Adobe Acrobat is very tolerant towards errors in PDFs. It tries to fix as many as it can. Then when you save the form, the error is gone.

A: As it turns out the issue was not as Bruno Lowagie suggested regarding the consistency of the PDF.
I had run out of ideas and just thought I would try generating the FDF a different way. By running the command:
pdftk /full/path/to/template.pdf generate_fdf output /full/path/to/output.fdf

And then inspecting the resulting file, I was able to get a more accurate FDF and then when I ran the fill_form command:
pdftk /full/path/to/template.pdf fill_form /full/path/to/output.fdf output /full/path/to/output.pdf

I got a proper response and everything worked. So the problem I was getting was in fact caused by the FDF being malformed in some way.
My final solution was this if anyone is interested. It takes a template PDF with fields, generates an FDF to fill it, creates a new PDF by adding the data from FDF with the template PDF, redirects the browser to the PDFs location.
Big thanks to Bruno Lowagie for helping understand the system better and rule out a few things.

A: I had the same problem. In my case changing the string encoding solved it.
Previously I was encoding it in utf-8 then I changed it to utf_16_be.
Root cause is that form fields data are stored in fdf form where values are stored inside brackets so if your data has brackets then it throws error.

A: Font issue:
https://stackoverflow.com/a/44442957/2150220
The link above is a better solution than just changing your font.
I was receiving the same error, however, none of the above solutions worked for me.
As I was testing:
pdftk a.pdf fill_form a.fdf output b.pdf

I was able to generate a pdf if my original pdf had not been altered, IE: all of the acrobat settings where default.
Only when I changed the font to "Arial" for a fill_form element did I receive the error.
I changed the font, and it was working again.

A: I just wanted to follow up for anyone else who encounters this. In our case, the problem was in the contents of the FDF file. Specifically, we were automating the process of filling in PDFs and user-generated content sometimes includes an unclosed ( [ or { character. These cause this same exception. If this is happening to you, verify that the contents of your FDF file do not contain "unclosed" parens, brackets, or curly braces.


text:
Q: Como recuperar dados usando FirebaseRecyclerAdapter que possui IDs gerados automaticamente? estou com um erro usando FirebaseRecyclerAdapter, na hora de recuperar os dados do firebase apresenta esse erro: "com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap"
Vi que é algo relacionado a leitura do ID criado para cada clínica, estou gerando uma chave automaticamente para cada clínica. Alguém pode me ajudar com isso? Como recupero as ids e mostro todas as clínicas cadastradas no firebase?

   mFirebaseDatabase = FirebaseDatabase.getInstance();

    rootReference = mFirebaseDatabase.getReference().child("clinicas");

    listaClinicas = new ArrayList<>();

}

@Override
protected void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<Clinicas, ViewHolder> firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<Clinicas, ViewHolder>(
                    Clinicas.class,
                    R.layout.adapter_lista_clinicas,
                    ViewHolder.class,
                    rootReference

            ) {
                @Override
                protected void populateViewHolder(final ViewHolder viewHolder, final Clinicas clinicas, int position) {

                    final String clinicasIds = getRef(position).getKey();

                    rootReference.child(clinicasIds).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            viewHolder.setDetails(getApplicationContext(), clinicas.getNomeClinica(), clinicas.getEnderecoClinica(),
                                    clinicas.getBairroClinica(), clinicas.getEstadoCidadeClinica(), clinicas.getTelefoneClinica(), clinicas.getWhatsappClinica(),
                                    clinicas.getFoto2());
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });

                }
            };

    mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}

A: Sou novato em Firebase, mas acho que é porque você precisa criar um addListenerForSingleValueEvent para poder recuperar essas informações. Como no meu exemplo abaixo:
private void getUsuarioTecnicoId() {

    DatabaseReference tecnicoDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Clientes").child(usuarioAtualID).child("conexoes").child("tecnicos");
    tecnicoDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for (DataSnapshot tecnico: dataSnapshot.getChildren()){
                    FetchtecnicoInformation(tecnico.getKey());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

private void FetchtecnicoInformation(final String key) {
    DatabaseReference usuarioDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Tecnicos").child(key);
    usuarioDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                String usuarioId = dataSnapshot.getKey();
                String nome = "";
                String profissao = "";
                String imagemPerfilUrl = "";

                if (dataSnapshot.child("nome").getValue()!=null){
                    nome = dataSnapshot.child("nome").getValue().toString();
                }

                if (dataSnapshot.child("profissao").getValue()!=null){
                    profissao = dataSnapshot.child("profissao").getValue().toString();
                }

                if (dataSnapshot.child("imagemPerfilUrl").getValue()!=null){
                    imagemPerfilUrl = dataSnapshot.child("imagemPerfilUrl").getValue().toString();
                }

                TecnicosObject obj = new TecnicosObject(usuarioId, nome, profissao, imagemPerfilUrl);
                resultmTecnicos.add(obj);
                mTecnicosAdapter.notifyDataSetChanged();

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}


text:
Q: RxJS with .NET web api data streaming Background: I have a background with Angular and .NET and am learning RxJS right now.  I have successfully put together a notification module that leverages SignalR and RxJS to handle system notifications to a user and I LOVE how easy it is to work with.
Question: I currently have a web api call that queries multiple sources in individual Task calls and then merges them into one dataset to be sent back to the client.  This call doesn't take too long right now because of few sources and the sources themselves have sample data in them. But I imagine that once I start tying real data in, that this call could take a really long time.  I'd like to find a way to configure my web api so that I could pass back an open stream of data that would be monitored by RxJS to display data as it comes in. Is there a way to do this?


text:
Q: Eliminating duplicate lists? I've a set which should hold a bunch of unique list items:
This is how I'm trying to define it.
results = set([], key= self.comparator)

This is the comparator function,
def comparator(self, l1, l2):
    if len(l1) != len(l2):
        return -1
    i = 0
    while i < len(l1):
        if l1[i] != l2[i]:
            return -1
        i += 1
    return 0

This  throws the following error,
TypeError: set() does not take keyword arguments

Clearly the set constructor doesn't accept the key,
If I don't pass the key, then I get the following error,
TypeError: unhashable type: 'list'

Thus the way I'm trying to eliminated duplicate lists is not working. How can I do it in Python.

A: You can convert your lists into tuples to do what you want:
my_lists = [[1,2,3], [1,2], [1,2,3]]
tuples = [tuple(l) for l in my_lists]

print(set(tuples))

Seems to achieve what you need.
Prints:
set([(1, 2), (1, 2, 3)])

A: Like you figured out, set does not accept a key like this. It does however expect whatever you bring it as items, to be "hashable", which actually means that it has a __hash__() method. lists do not have a working hash, as you can see from this example:
a = 'a'
a.__hash__() # prints -8546348471933684759
a = [1,2,3]
a.__hash__() # will throw TypeError

If you were to define a new class that acts like a list but has a unique hash based on it's values, you could use set on it.
class mylist(list):
    def __hash__(self):
        return sum(item.__hash__() for item in self)

a = mylist([1,2,3])
b = mylist([1,2,3])
c = mylist([4,5,6])
unique_lists = set((a,b,c))
print(unique_lists) # prints {[1, 2, 3], [4, 5, 6]}


text:
Q: Opera-like tab-switching in chrome or firefox Is there a way of switching tabs in Chrome or Firefox by scrolling the mouse-wheel while keeping the right mouse-button pressed?
In Chrome or Firefox (with tab-wheel-scroll extension) you can switch tabs by scrolling the wheel while hovering the pointer over the tab-bar.
The Opera function is much more comfortable, since you don't have to aim at the tab-bar in order to switch.
I have already tried assigning tab-switching keyboard shortcuts to the mouse-button in combination with the mouse-wheel, but it did not work at all. It seems to me that mouse-events cannot be combined in xbindkeys. Furthermore, assigning anything to the right mouse-button in xbindkeys disabled the standard functions of the button completely.
Thanks in advance, bye
YSN

A: Use FireGestures extension. What you want is in "Advanced >> Wheel Gestures". It does exactly that. There is no need to point the mouse over the tabs.

A: In Chrome I use Smooth Gestures.
https://chrome.google.com/extensions/detail/lfkgmnnajiljnolcgolmmgnecgldgeld
You can simply create gestures as you want I really like it.
For tab browsing in Chrome I use Quick Tab
https://chrome.google.com/extensions/detail/bdeifmcaonlafkglbdpbbhkeecjnkipo?hl=en
It is not like the ctrl+tab function in Opera but it much more comfortable than the built in one
But give a try to Opera 11 ;)

A: You can switch tabs in Chrome by scrolling the mouse wheel while keeping the mouse arrow over the tabs line. This is a default behavior not an extension


text:
Q: English. Age designation Which of the following is considered correct? ". . . where I was at age five." or ". . . where I was at age 5."

A: This would be a matter of style. Different style guides and audiences expect different formats. For example, some style guides specify that numbers under 100 be actually spelled out ("ninety-nine"). Other style guides do not require this. I would make sure you know who your audience is and what they expect to see.


text:
Q: variable in class wont update after using the package keyboard I'm using the package "keyboard" to create a console menu.
I want to check when confirm has been checked. However the problem is, if you click confirm, (self.current will equal the length of choices) self.current inside the definition run wont change,  when it has been changed by self.up or self.down.
Note: didn't include self.up or self.down because in self.run, self.current changes
class menu:
def __init__(self, maxChoices=1):
    self.maxChoices = maxChoices
    self.current = 0
    self.choices = ["Do something 1", "Do something 2", "Do something 3", "Do something 4", "Do something 5"]
    self.choiceSelected = []
    self.error = ""

def run(self):
    while True:
        self.show_menu(self.error)
        keyboard.add_hotkey('up', self.up)
        keyboard.add_hotkey('down', self.down)
        keyboard.wait("enter")
        keyboard.unhook_all_hotkeys()
        if self.current == len(self.choices) and len(self.choiceSelected) != 0:
            return self.choiceSelected
        elif self.current == len(self.choices):
            self.error = "\n" + bcolors.WARNING + "ERROR: Nothing selected!" + bcolors.ENDC
            str(self.current)
            input()

def show_menu(self, error=""):
    clearConsole()
    print(self.current)
    print("Choose an option:")
    print('┌' + '─' * max(len(s) + 4 for s in self.choices) + '┐')
    for choiceNum, choice in enumerate(self.choices):
        spaces = " " * (max(len(s) for s in self.choices) - len(self.choices[choiceNum]))
        if choiceNum == self.current:
            if choiceNum in self.choiceSelected:
                print(f'│{bcolors.BOLD + bcolors.OKGREEN}>>{self.choices[choiceNum]}<<{bcolors.ENDC}{spaces}│')
            else:
                print(f'│{bcolors.BOLD}>>{self.choices[choiceNum]}<<{bcolors.ENDC}{spaces}│')
        elif choiceNum in self.choiceSelected:
            print(f'│{bcolors.OKGREEN}  {self.choices[choiceNum]}{bcolors.ENDC}{spaces}  │')
        else:
            print(f'│  {self.choices[choiceNum]}{spaces}  │')
    spaces = " " * (max(len(s) for s in self.choices) - 7)
    if self.current == len(self.choices):
        print(f'│>>{bcolors.FAIL}CONFIRM{bcolors.ENDC}<<{spaces}│')
    else:
        print(f'│  {bcolors.OKBLUE}CONFIRM{bcolors.ENDC}{spaces}  │')
    print('└' + '─' * max(len(s) + 4 for s in self.choices) + '┘')
    print(error)

A: figured out the answer....
I forgot to clear self.error so whenever enter was pressed afterwards self.error printed.
What threw me off was that when i tried to do an input, on terminal it would disappear so i couldn't check the real value of self.current


text:
Q: Cannot mount encrypted time machine drive after unmount I have an 3TB external HDD with 2 partitions, one of them is 1TB dedicated to time machine (encrypted).
It works perfectly, but whenever I unmount the partitions (by using right click, Eject via finder, which offers the option to "Eject All" partitions of this drive).
When I plug the drive back in, the non-encrypted non-time-machine partition mounts fine automatically, but not the (encrypted) time machine one.
Trying to mount via the Disk Utility app yield the following error:

com.apple.DiskManagement.disenter error -119930868.)

Trying to mount via Terminal by running $> diskutil coreStorage unlockVolume GUID first to unlock the drive, then mounting that partition via $> diskutil mount GUID does not work either.
Sometimes $> diskutil list will just hand indefinitely, and when this happens even shutting down does not work (I guess macOS is waiting for something).
The only workaround I have is too reboot the mac; so that makes me think that it is not an issue with my drive.
Note: The disk is not plugged in directly, but through a thunberbolt3 dock (Caldigit TS3+).


text:
Q: Share A Post or Link on LinkedIn (HTML?) We would like to let our internal users share a post to their own LinkedIn account.
I followed the directions step-by-step from the site below:
https://tome.oauth.io/providers/linkedin/share-a-link?utm_source=coderwall&utm_medium=post&utm_content=share-post-linkedin
Their sample code works, however, when I replace their public key with mine, the linkedIn authentication box threw me an error message:

You need to pass the "client_id" parameter

Can any of you please help?
Or can I just use their public key, will that work?
Furthermore, it seems we can only share plain text content to LinkedIn, is it possible to share HTML contents to linkedIn?

A: To share a URL on LinkedIn, all you need is:
https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Microsoft LinkedIn Share URL Documentation.
Only the url parameter is supported.
For example, this works for me:

https://www.linkedin.com/sharing/share-offsite/?url=http://www.wikipedia.org/

Works fine:

If you are interested in a regularly maintained GitHub project that keeps track of this so you don't have to, check it out!  Social Share URLs


text:
Q: Calling Methods In Java - Hello World Example I am slowly but surely working my way through java and have gotten a program to work.  However, the program I am using has all of the code in the main method and I'd like to use other methods to keep things better organized.
My question is very simple so I will use the simplest of examples.  Say I wanted to create a Hello World program like this:
public class HelloWorld {

    public static void main(String[] args) {
        Test();
    }

    public void Test(){
        System.out.println("Hello World!");
    }
}

How do I call Test() correctly in java?  The way I have written it creates a compiler error.  I am coming from R which would allow something like this.
Thank you.

A: First, your method should be named test (not "Test"). Also, it should be (in this case) static.
public static void main(String[] args) {
    test();
}

public static void test(){
    System.out.println("Hello World!");
}

Or, you could also write it like so,
public static void main(String[] args) {
    new HelloWorld().test(); // Need an instance of HelloWorld to call test on.
}

public void test() { //<-- not a static method.
    System.out.println("Hello World!");
}

A: See,what you have done with your code is that you have called a non-static method from a static method which is "public static void main(String[] args)" here. Later on,with the time you will come to know that static members are the very first to be called by the compiler and then follows the normal flow of non-static members.
In Java,to call a non-static method,either you need to create a Class object to call a non-static method from the main() method,or you itself declare the non-static method as a static method,which might not be good in every case,but that would simply be called in the main() method as it is!
Correct code(if you want to call non-static methods from a static-method)  :-
 public class HelloWorld {

 public static void main(String[] args) {
    new HelloWorld().Test();
 }

 public void Test(){
    System.out.println("Hello World!");
 }
}

Alternative code(if you want to call non-staticmethod from a static-method,make the former  static)  :-
public class HelloWorld {

 public static void main(String[] args) {
   Test();
 }

 public static void Test(){
    System.out.println("Hello World!");
 }
}

A: The method Test() needs to be declared as static, so:
public static void Test(){
        System.out.println("Hello World!");
    }

or you can create a new HelloWorld object and then having it call Test():
public static void main(String[] args){
     HelloWorld foo = new HelloWorld();
     food.Test();
}


text:
Q: Why does Sqlite tell me no such column exists when I plainly created it? in Python 2.6.5 with sqlite3.version 2.4.1, I use the following code:
c = conn.cursor()

# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)''')

# Insert a row of data
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")

# Save (commit) the changes
conn.commit()

c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?
)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))

# We can also close the cursor

if we are done with it
c.close()

And it throws an error:
Traceback (most recent call last):
  File "dbtest.py", line 18, in <module>
    c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
sqlite3.OperationalError: no such column: date

My question - what the heck??? I created a column with the name "date"! I've spend the last two hours trying to figure out what in the world is wrong and I'm getting really frustrated. Also, when I try to open it by command line, I'm told:

Unable to open database "orders": file
  is encrypted or is not a database

ANY help would be greatly appreciated as I'm about to put my computer through a wall.
Thanks!

A: Incorrect syntax for that insert statement. This will work:
>>> c.execute('''insert into stocks
                 (date, trans, symbol, qty, price)values(?,?,?,?,?)''',
                 ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))


text:
Q: É correto chave estrangeira com campo nulo? PostgreSQL Estava construindo um modelo entidade relacionamento (MER) de um banco de dados para uma associação rual, é um trabalho para materia de TABD. Porém me deparei com uma situação atípica para mim, um relacionamento 0,n para 0,1. Como podem ver na figura.
Acontece que nesse banco de dados nem sempre uma transação irá ter uma pessoa relacionada (a transação pode ser a saida de dinheiro com pagamento de contas por exemplo) e como a chave estrageira está na tabela transação isso implicaria em chaves estrangeiras nulas. A minha dúvida é se isso está correto? Chaves estrangeiras podem ser nulas? Caso não, porque?
Pesquisei em alguns lugares antes de perguntar aqui mas não havia concordância nas respostas.

A: Com bases nos comentários dos autores

Andrew Ribeiro & White

cheguei a seguinte conclusão:
Não faz sentido mesmo ter uma chave estrangeira nula, ao mesmo tempo que sim pode existir uma chave estrangeira nula porém ela se torna inútil pois o acesso a tuplas com chaves estrangeiras se faz justamento pelo valor dessa, se a mesma é nula não há como acessa-lá.
O erro no relacionamento que enviei é que não faz sentido existir uma transação sem que ela seja feita por uma pessoa, então o relacionamento deveria ser (1,1) para (0,n).


text:
Q: Adding marker with OpenLayers/GeoServer I want to add a marker in web GIS with OpenLayers/GeoServer. Here is my code:

            /* General settings */
            body {
                font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: small;
            }

            /* The map and the location bar */
            #map {
                clear: both;
                position: relative;
                width: 1350px;
                height: 600px;
                border: 0px solid black;
            }

Markers Layer Example

------------------------------------------------------------------------------------------
The problem I am having is that it will not show a marker, just a webmap and I don't know why. Here is what my webmap looks like:

A: In such cases, something I would recommend you is that first of check your images path is true or not. with writing this to "http://localhost:8080/geoserver/openlayers/img/marker.png". are you getting the true result?
or you can use firebug net option if your images or script are loaded or not.
second is that get your marker features for markers are added or not.
and last thing on your app go to full extent and then add your marker to 0,0 for latlong settings...
markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(0,0),icon));
markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(0,0),icon.clone()));


text:
Q: How to load Appcomponent class before routing takes place I have set routing and display the page according to user roles. For this i am using guard on route. I am extracting userRole from service in Appcomponent class and using set and get method in main-service file. Now problem is that before i get role, routing takes place and it navigate to wrong url as it doesn't have role by then. Tough from next call, it works properly. Let me share the code:-
1.Here is guard class:-
export class HomeGuard implements CanActivate {
    constructor(private _router: Router,private mainService: MainService) {
    }
    canActivate(): boolean {
        let userRoles:any;
        alert('HomeGuard');
        userRoles = this.mainService.getSavedUserRole();
        //userRoles = ['Profile Manager','Operations','Shipper'];
        alert('userRoles are here'+userRoles);
        console.log('here in homeguard');
        if(userRoles) {
            if(userRoles.some(x => x === 'Shipper') || userRoles.some(x => x === 'Admin'))
                return true;
        }
        this._router.navigate(['/notfound']);
        return false;
    }
}

*Here is AppComponent where i am extracting userRole from service:-
export class AppComponent {
  savedUserRoles:any;
  constructor(private translate: TranslateService,private mainService: MainService) {
      console.log('Environment config', Config);
      // this language will be used as a fallback when a translation isn't found in the current language
      translate.setDefaultLang(AppSettings.LNG_TYPE);
      // the lang to use, if the lang isn't available, it will use the current loader to get them
      translate.use(AppSettings.LNG_TYPE);
      this.mainService.getCurrentUser().subscribe(result => {
        this.savedUserRoles = JSON.parse(JSON.parse(result._body).Data).Roles;
        console.log('sdfghj'+this.savedUserRoles);
        this.mainService.setSavedUserRole(this.savedUserRoles);
      });
  }
}

*Here is main-service where i have defined set and get method:-
setSavedUserRole(name: any) {
    console.log('main'+name);
    this._userRoles = name;
    }
getSavedUserRole() {
    return this._userRoles;
}


text:
Q: How can I optimize Ubuntu for minimal energy usage? How can I optimize Ubuntu for minimal energy usage? I use my laptop for development, but also for writing. I have a 9 hour flight coming up and a 6 hour battery life when already using

*

*limited screen brightness

*no usb devices

*no networking

*bumblebee installed and the nvidia card switched off

*TLP set on powersave

How can I now increase my battery life knowing that I only want to write (using LibreOffice)? I essentially want a very minimal system for a sort of 'writing mode.'

*

*Should I limit my quadcore to one core?

*Should I disable some services? Here is the list of service --status-all
[ + ]  acpid
[ + ]  anacron
[ + ]  apache2
[ - ]  apparmor
[ ? ]  apport
[ + ]  atd
[ + ]  avahi-daemon
[ ? ]  binfmt-support
[ + ]  bluetooth
[ - ]  brltty
[ + ]  bumblebeed
[ + ]  console-font
[ + ]  console-setup
[ + ]  cron
[ + ]  cups
[ + ]  cups-browsed
[ - ]  dbus
[ ? ]  dns-clean
[ - ]  elasticsearch
[ - ]  fancontrol
[ + ]  friendly-recovery
[ - ]  grub-common
[ ? ]  irqbalance
[ - ]  kerneloops
[ ? ]  killprocs
[ + ]  kmod
[ ? ]  lightdm
[ - ]  lighttpd
[ - ]  lm-sensors
[ ? ]  mysql
[ ? ]  networking
[ + ]  nmbd
[ ? ]  ondemand
[ - ]  openvpn
[ + ]  postgresql
[ ? ]  pppd-dns
[ + ]  prey-trigger
[ - ]  procps
[ - ]  pulseaudio
[ ? ]  rc.local
[ + ]  resolvconf
[ + ]  rfkill-restore
[ + ]  rfkill-store
[ - ]  rsync
[ + ]  rsyslog
[ + ]  samba
[ + ]  saned
[ - ]  selfcontrol
[ ? ]  sendsigs
[ + ]  setvtrgb
[ - ]  smartmontools
[ + ]  smbd
[ ? ]  speech-dispatcher
[ - ]  sudo
[ - ]  timidity
[ ? ]  tlp
[ - ]  udev
[ ? ]  umountfs
[ ? ]  umountnfs.sh
[ ? ]  umountroot
[ - ]  unattended-upgrades
[ - ]  urandom
[ + ]  winbind
[ - ]  x11-common

*

*Should install a more lightweight desktop environment? Can I do this in a nice and clean way (after all I have my laptop nicely set up and do not want to have to reinstall before 14.04).

*Should I do something else?

One last thing: I would like to activate or deactivate all these options with one script (which I will run only when working on battery). Please be as kind as to include suggestions on how to do what you suggest.
PS: the info in some of the possible duplicates is dated for 13.10.

A: One of the biggest uses of power is the hard drive. If you're just using the computer for it's word processing capabilities, you might be able to go for significant periods of time without reading or writing to the hard disk.

*

*Disable filesystem journaling. This is one of the most frequent uses of the hard drive. It will also allow the next item to be much more effective.

*Use buffered disk writes. It's possible to buffer disk writes for a significant period of time before writing them to the hard disk. If you're only running one program, this could potentially allow your hard disk to remove off for 20 or 30 minutes even if you're writing to the device. I use laptop-mode-tools. I don't know the ubuntu approved method for this.

*Other hard disk power saving options. (Spindown more often, etc.)

*As mentioned previously, use powertop to find other configuration
changes that can be made to reduce power consumption.

*Undervolt your CPU. This one is quite a bit more involved than the others.
https://wiki.ubuntu.com/UndervoltingHowto

A: You can set the cpu governor of all your cpu cores to "powersave". That's the lowest cpu clock, and uses the least power.
user@host:~$ for x in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo powersave > $x; done

To see which governor is currently active type:
user@host:~$ echo $(cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor)
powersave powersave powersave powersave

Default value is "ondemand".
EDIT:
When you boot you can set the number of max cpus in the grub entry by pressing e to edit the entry and add:
maxcpus=1

After changing the entry press F10 to boot.
BUT, you can limit your cpu cores, but that does not mean that you use less power consumption, than before. Note, that when the system is able to efficiently use multiple cpus, it needs for the same task less time and produces less heat, so you have to test it for your purposes. For more info cf. the kernel parameters.

A: you can use a tool named as pm-powersave. It will turn your Ubuntu into low power mode.
usage:

*

*pm-powersave true will start power save mode.

*pm-powersave false will stop the power save mode.

Fore more information
manpage for the http://manpages.ubuntu.com/manpages/saucy/man8/pm-powersave.8.html command

A: powertop provides a (not particularly accurate) estimate of the power usage of individual pieces of hardware and running processes.
Shutting down some unneeded services relating to eg, networking/bluetooth, or useless user-space processes (eg Dropbox/Ubuntu One when you have no network connection) might make a small difference. Anything running a timed loop will cause the processor to wake up from sleep and use a little extra power.

A:
Should install a more lightweight desktop environment?

How about 0 GUI's. Pure text-based environment, no Xserver running in background etc...

Should I disable some services?

I would disable/stop apache, samba, ntp, pulse, insert your network/audio related service here services.

Should I limit my quadcore to one core?

Do you need them? -> yes
No.
Do you need them? -> no
Yes.

Should I do something else?

Thousands! You can run off a USB/SSD and forget about the HDD spinning out of control. Put the CPU's in powersave mode. Disable all radio interfaces. Use powertop and set to true all power_saving mechanisms. Get an extra battery. Ad absurdium.
Related of the same author:

*

*https://unix.stackexchange.com/q/85590/41104

A: The screen is by far the biggest user of power, just push the brightness down to 0 and turn off bluetooth and wireless lan if you have a cable connection; that makes THE biggest difference and I'm not sure disabling services and tweaking caching will improve much over that


text:
Q: Как сделать, чтобы GridPane растягивался на весь экран при разворачивании приложения на весь экран в Scene Builder? Уже в начале верстки приложения столкнулся с такой проблемой. При запуске приложения в SceneBuilder,  размер приложения имеет размер, который я указал Pref Width и Pref High у GridPane, это нормально, НО! когда я хочу растянуть приложение на весь экран(например двойным кликом) то GridPane вместе со своими компонентами остается в центре и не растягивается, а мне надо,чтобы компоненты в GridPane былм на весь экран, то есть растягивались
Что нужно поменять?

Видео:
https://hdd.tomsk.ru/desk/lkgkrupw#
FXML:
    <?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXColorPicker?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane alignment="TOP_CENTER" hgap="10.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1300.0" styleClass="grid" stylesheets="@style.css" vgap="10.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/10.0.1">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" maxWidth="494.0" minWidth="10.0" prefWidth="97.0" />
    <ColumnConstraints hgrow="SOMETIMES" maxWidth="914.0" minWidth="10.0" prefWidth="903.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <AnchorPane prefHeight="200.0" prefWidth="200.0">
         <GridPane.margin>
            <Insets bottom="20.0" left="20.0" right="5.0" top="20.0" />
         </GridPane.margin>
         <children>
            <JFXColorPicker prefHeight="61.0" prefWidth="469.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
         </children>
      </AnchorPane>
      <AnchorPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.halignment="RIGHT" GridPane.valignment="CENTER">
         <children>
            <Label alignment="CENTER" text="Label" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
         </children>
         <GridPane.margin>
            <Insets bottom="20.0" left="5.0" right="20.0" top="20.0" />
         </GridPane.margin>
      </AnchorPane>
   </children>
</GridPane>


text:
Q: How to click on checkbox with selenium in python I'm trying to choose a checkbox from a certain website. this is a part of their HTML code.

<input class="deliveryCheckbox hiddenCheckbox" id="deliveryCheckbox-684" data-deliveryid="684" type="checkbox" />

I tried a few different approaches. I either get an error saying the element isn't there or that it cannot be interacted with.
This is an example of what I tried:
browser.find_element_by_xpath('//*[@id="deliveryCheckbox-684"]').click()

A: It's likely a timing issue. Many pages dynamically build DOM structure after they load.
Try adding a sleep for a second or two after loading the URL before trying to find that element. For the most robustness, you would put that in a loop and timeout after 10 seconds or so.

A: First, check answer above about timing issue.
Second, I think that you are trying to find a dynamic id locator.
Try to find by css.
browser.find_element_by_css_selector('.deliveryCheckbox.hiddenCheckbox').click()

Also, try using the xpath in the case when label is what you really need to click:
browser.find_element_by_xpath("//label[contains(@for,'deliveryCheckbox')]")

A: As far as I know, you can't click on hidden elements in selenium, and class "hiddenCheckbox" implies that it is indeed hidden. Apart from that, including errors you get and the website you are trying to scrape would make additional help possible. Currently I can only tell you to make the checkbox visible in some way.

A: Try using the time.sleep() function to see whether it is then able to click the check box or not. If it does, then use try and except method to find if the checkbox has been loaded and then click it and move forward. As suggested above, that sleep function is not a good practice.
If the program is unable to locate the checkbox, then try navigating to it through driver.find_element_by_id. Navigating elements by Id is by far the best technique I've ever used.

A: WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,"//label[@for='deliveryCheckbox-684']"))).click()

You'd have induce waits for the element to be clickable and click the label tag.
Import
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


text:
Q: getting edges / lines of vertical lines in an image Original Post
I have a batch of similar images which I need to analyze.
After

*

*thresholding

*hole filling using skimage.morphology.reconstruction (example of usage here)

*image closing

I get something like this image:

I'm interested in the edges of shape, specifically the steepness of the slope along vertical lines in the original grayscale image. I thought I could use Canny to get the contours which indeed gave me:

My questions:

*

*How would I go about separating the approximately  vertical and horizontal edges? The have very different meaning for me, as I'm not at all interested in what happens between adjacent horizontal lines (I would rather just cut those parts from the image), and I'm interested in what happens around vertical lines (white surrounding in the BW image).

*I'm would assume my lines should be straight (there could be a slope, but the noise is too high). How would I smoothen the contour lines?

*Eventually I wish to go back to the gray scale image and look at the pixel statistics in the vicinity of vertical lines. How can extract the location info of lines from the edges found by Canny?

My code:
im_th= cv2.inRange(img, 0, 500, cv2.THRESH_BINARY)
seed = np.copy(im_th)
seed[1:-1, 1:-1] = im_th.max()
mask = im_th
filled = reconstruction(seed, mask, method='erosion').astype(np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(4,4))
closed = cv2.morphologyEx(filled,cv2.MORPH_CLOSE, kernel=kernel)
edges = cv2.Canny(cv2.medianBlur(closed, 5), 50, 150)

Edit
Per suggestions of Christoph Rackwitz and mimocha, I attempted using findContours and HoughLinesP. Both results look promising, but require further work to be of use.
findContours approach
Code:
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour_img = cv2.drawContours(cv2.cvtColor(closed, cv2.COLOR_GRAY2BGR), contours, -1, (255,0,0), 3)

Resulting image (overlay over the closed image):

The contours are found nicely, I still 151 contour lines. I would want to smoothen the result and get less lines.
HoughLinesP approach
Code:
threshold = 15
min_line_length = 30
max_line_gap = 200
line_image = np.copy(cv2.cvtColor(closed, cv2.COLOR_GRAY2BGR)) * 0
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold, None, min_line_length, max_line_gap)
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),5)
lines_edges = cv2.addWeighted(cv2.cvtColor(closed, cv2.COLOR_GRAY2BGR), 0.2, line_image, 1, 0)

Resulting image:

HoughLinesP indeed guarantees straight lines, and it find the lines nicely, but I still have some lines which are too "thick" (you can see in the image some thick lines which are actually parallel lines). Thus I need some method for refining this results.
Summary so far:

*

*Both the contours approach and the Hough transform approach have gain.

*Hough transform may have an advantage as it returns straight lines, and also allows to separate horizontal in vertical lines as shown here.

*I still need a method to merge/cluster lines.

A: I would find the two relevant sections of the image by finding the wider bars, and cutting there. This is a bit of code using DIPlib (disclaimer: I'm an author), but it's quite easy to do this with just about any other package too.
import diplib as dip
import math

img = dip.ImageRead('5oC9n.png')

# Colapse the x axis by summation
y = dip.Sum(img, process=[True, False]).Squeeze()

# In our 1D result, find the transition points
y = dip.Abs(dip.Dx(y))
y = dip.Shrinkage(y, 5)  # ignore any local maxima below 5
maxima = dip.SubpixelMaxima(y)

# We want segments between 1st and 2nd, and between 3rd and 4th.
# We'll add a bit of margin too
assert(len(maxima) == 4)

# First segment
top = math.ceil(maxima[0].coordinates[0]) + 2
bottom = math.floor(maxima[1].coordinates[0]) - 2
img1 = img[:, top:bottom]

# Second segment
top = math.ceil(maxima[2].coordinates[0]) + 2
bottom = math.floor(maxima[3].coordinates[0]) - 2
img2 = img[:, top:bottom]

Next, finding the slopes of the lines, could be done by fitting a straight line to each of the edges. This other answer of mine does exactly that (the answer computes the distance between two parallel edges, but in doing so it fits a straight line and finds its normal (i.e. the slope).

A: Are you looking for something like the Hough transform? You should be able to use it on your detected edges directly.

*

*Horizontal lines doesn't affect the result. (You can filter lines by angles)

*Lines being slightly sloped doesn't affect the result.

*Hough transform tells you where lines are and what angles they are -- it fits an infinitely long line onto your image based on your edge pixels. Since you know the line slope and the shortest distance from the line to the origin, you can check every pixel that line intersects.

However, this may not answer your question if you are looking for the specific (x,y) coordinates for where each vertical line segment begins and ends.

I copied the code sample from the OpenCV tutorial and tested it on your image to find the two vertical lines:
>>> import cv2 as cv
>>> import numpy as np
>>> src = cv.imread("test.png")
>>> edge = cv.Canny(src, 50, 200, None, 3)
>>> cv.HoughLines(edge, 1, np.pi / 180, 150, None, 0, 0)
array([[[ 81.,   0.]],

       [[144.,   0.]]], dtype=float32)


text:
Q: Search and replace using Regular Expressions in Sublime Text: replace text before search text So this would be my Sample:
In Kenya since 2010 2:48
Where comes from: Bukavu 3:29
She would have been killed 5:15

now the times m:ss (like 2:48) should stay where they are, but ALSO be appended to the link that comes before it, after the "&" and in the following format: 2:48 should become t=2m48s
So, at the end, the whole thing should look like this (check the end of the links)
In Kenya since 2010 2:48
Where comes from: Bukavu 3:29
She would have been killed 5:15

Now I found out, i could use \d:.. to find the times, but I have no Idea on how to proceed or if it is possible at all with sublime text ?

A: Update 2:
I swear I checked on YouTube, and I was able to go to a video with &t=h5m10s and it would work as 0:05:10.  If you need this to be 5m10s or 0h5m10s, you'll need to do two different expressions (since Sublime Text won't let you do complex callback functions on your regex replace).
To replace h:mm:ss:
href="(.*?)"(.*?)>(\d*):(\d{2}):(\d{2})

href="$1&t=$3h$4m$5s"$2>$3:$4:$5

To replace m:ss:
href="(.*?)"(.*?)>(\d{1,2}):(\d{2})(?!:\d)

href="$1&t=$3m$4s"$2>$3:$4

The only unusual syntax that needs explanation is (?!:\d). The ?! syntax is for a "negative lookahead". This means that the match group will not be followed by an additional :\d, otherwise this would match hours/minutes/seconds.

Update:
Here is an updated expression for matching optional hours.  I double checked and you are able to use &t=h##m##s (i.e., a blank hour if it is not matched).  This means we can do one search/replace and just have a blank capture for the hour if it does not exist (you'll see what I mean in a second).
Match this:
href="(.*?)"(.*?)>((?:(\d*):)?(\d{1,2}):(\d{2}))

And replace with:
href="$1&t=$4h$5m$6s"$2>$3

Things got a little more complicated here. Lets take a closer look at the part that changes:
(            # start an overarching capture group
  (\d*):?    # capture 0+ digits followed by an optional : (hours)
  (\d{1,2}): # capture 1-2 digits followed by a : (minutes)
  (\d{2})    # capture the last 2 digits (seconds)
)            # end the capture group

Now you may wonder why I used that overarching capture group.  This is because we need a way to keep the contents of the anchor link the same.  If we didn't use this, we would have to replace it with hour:minute:second and hour may be blank (meaning 3:45 would be replaced with :3:45).

You can match this:
href="(.*?)"(.*?)>(\d)+:(\d{2})

And replace it with
href="$1&t=$3m$4s"$2>$3:$4

How this works is it first finds any anchor's href, while capturing the contents in the first capture group.  Then we capture everything up to the > in a second capture group.  Next we capture 1+ digit (third capture), followed by :, and finally capturing the last 2 digits (fourth capture).
We essentially replace this with all the same content, but make sure to append &t=$3m$4s to the end of the link.  You can see a working example on Regex101.


text:
Q: Fast radial blur shader - GLSL I trying to a do fast radio blur using GLSL shader, here is my implementation:

*

*Pass 1, calculate average color of 16 samples along the blur direction with unit step length.

*Pass 2, calculate average color of 3 samples along the blur direction with 16 step length.

through this, I want to get the result of blur length of 48, but I get some artifact here

I also tested the blur in the uniform direction, which also showed some artifacts, but less. Here is my shader code, you can test it on shadertoy:
// bruteforce mathod
#iChannel0 "file://E:/workspace/data/color_test.png"

const float u_sample_step = 1.0;
const int u_nsample = 48;
const vec2 u_center = vec2(0.5); // center in origional image, normalized to [0, 1]

void main() {
    vec2 coord = gl_FragCoord.xy / iResolution.xy;
    //vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec4 color = vec4(0.0);
    for(int i=0; i<u_nsample; ++i) {
        color += texture2D(iChannel0, coord);
        coord += cstep;
    }
    gl_FragColor = color/float(u_nsample);
}

Pass 1 of the improved method:
#iChannel0 "test.png"

const float u_sample_step = 1.0;
const int u_nsample = 16;
const vec2 u_center = vec2(0.5); // center in origional image, normalized to [0, 1]

void main() {
    vec2 coord = gl_FragCoord.xy / iResolution.xy;
    //vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec4 color = vec4(0.0);
    for(int i=0; i<u_nsample; ++i) {
        color += texture2D(iChannel0, coord);
        coord += cstep;
    }
    gl_FragColor = color/float(u_nsample);
}

Pass 2 of the improved method:
#iChannel0 "pass1.frag"

const float u_sample_step = 16.0;
const int u_nsample = 3;
const vec2 u_center = vec2(0.5); // center in origional image, normalized to [0, 1]

void main() {
    vec2 coord = gl_FragCoord.xy / iResolution.xy;
    //vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec2 cstep = u_sample_step/iResolution.xy * normalize(u_center - coord);
    vec4 color = vec4(0.0);
    for(int i=0; i<u_nsample; ++i) {
        color += texture2D(iChannel0, coord);
        coord += cstep;
    }
    gl_FragColor = color/float(u_nsample);
}


text:
Q: Create Azure EventHub Message in Azure Functions I'm trying to do some Proof of Concept with EventHub and Azure Functions. I have a Generic Webhook Function in C# that I want to pass a message to my EventHub.
I get stuck on the parameter name given on the "Integrate" tab. If I declare that name among the parameters I have to give it a type. I can't figure out what kind of type though... I've tried:

*

*String (other functions uses that together with the direction, not applicable with webhooks).

*EventData

*IEnumerable

I can't get it to work. If I don't do this I get the error message:
"Missing binding argument named 'outputEventHubMessage'"
If I give it the wrong type I get the message:
"Error indexing method 'Functions.GenericWebhookCSharp1'. Microsoft.Azure.WebJobs.Host: Can't bind to parameter."
I'm probably a bit lost in documentation or just a bit tired, but I'd appreciate any help here!
/Joakim

A: Likely you're just missing the out keyword on your parameter. Below is a working WebHook function that declares an out string message parameter that is mapped to the EventHub output, and writes an EventHub message via message = "Test Message".
Because async functions can't return out parameters, I made this function synchronous (returning an object rather than Task<object>). If you want to remain async, rather than use an out parameter, you can instead bind to an IAsyncCollector<string> parameter. You can then enqueue one or more messages by calling the AddAsync method on the collector.
More details on the EventHub binding and the types it supports can be found here. Note that the other bindings follow the same general patterns.
#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static object Run(HttpRequestMessage req, out string message, TraceWriter log)
{
    string jsonContent = req.Content.ReadAsStringAsync().Result;
    dynamic data = JsonConvert.DeserializeObject(jsonContent);

    log.Info($"Webhook was triggered! Name = {data.first}");

    message = "Test Message";

    var res = req.CreateResponse(HttpStatusCode.OK, new {
        greeting = $"Hello {data.first} {data.last}!"
    });

    return res;
}


text:
Q: wso2 1.10 store DefaultApplication Missing I have installed a standalone instance of wso2 API Manager 1.10.0 with the CARBON-PATCH-4.4.0-0084 installed. I am walking through the PhoneVerification tutorial and have published the API as instructed. I created a new user for the store and am trying to subscribe to the PhoneVerification-2.0.0 API but cannot because there is no DefaultApplication in the Applications dropdown list.  It is missing from the list.  I tried to add and application and get an error dialog saying Missing Parameters.  I am stuck and cannot go any further.  One additional piece of information, I am using mysql instead of the h2 default. I followed all the instructions to setup mysql and had no problems. Also I changed the admin password as well.

A: I have tried API Manager 1.10 with security patch CARBON-PATCH-4.4.0-0084 with no issues. I can create APIs and subscribe using the DefaultApplication. I tried with default database and a new user who is assigned to 'Internal/subscriber' role.
Please check if you have any other changes for Store Web app at 'wso2am-1.10.0/repository/deployment/server/jaggeryapps/store'. You have to replace 'store' and 'publisher' apps as instructed in the Readme of patch.
(iii) Merge and Replace resource/store to /repository/deployment/server/jaggeryapps/store
(iv) Merge and Replace resource/publisher to /repository/deployment/server/jaggeryapps/publisher
To check if the Mysql configuration worked properly, please check if there are any errors in Carbon log, at 'repository/logs/wso2carbon.log' file related to that. And double check if userstore and api-manager database tables are created properly and configured in 'repository/conf/datasources/master-datasources.xml' properly.


text:
Q: SELECT data first then UPDATE using clustered index or UPDATE directly? There's table (in SQL SERVER) which have high concurrent access (Ex: Transactions), but I need to update some data in this table. But when filtering data that needed to update, there's no indexes associated with that column(s).
What would be the best approach for minimum Table/ Rows lock time?
Approach 1:
DECLARE @vt_TxnIds TABLE
(
    [Id] INT
)

/** Filter the required data first **/
INSERT INTO @vt_TxnIds
SELECT TXN.[Id]
FROM [Transactions] TXN WITH (NOLOCK) -- NOLOCK is fine in this case
LEFT JOIN [Account] ACC WITH (NOLOCK)
    ON ACC.[Id] = TXN.[AccountId] AND
        ACC.[IsActive] = 0
WHERE TXN.[Status] = 1 -- This column is not indexed
    AND ACC.[Id] IS NULL

/** Then update by clustered Index **/
BEGIN TRAN;

UPDATE [Transactions]
    SET [Status] = 5
WHERE [Id] IN ( -- [Id] is clustered index
    SELECT [Id]
    FROM @vt_TxnIds
)

COMMIT;

Approach 2:
BEGIN TRAN;

UPDATE TXN
    SET TXN.[Status] = 5
FROM [Transactions] TXN
LEFT JOIN [Account] ACC WITH (NOLOCK)
    ON ACC.[Id] = TXN.[AccountId] AND
        ACC.[IsActive] = 0
WHERE TXN.[Status] = 1 -- This column is not indexed
    AND ACC.[Id] IS NULL

COMMIT;

I'm not considering about the execution time. For example in my case, it's okay that whole query take 15 seconds but table/ rows locked for 5 seconds. Rather than whole table locked for 10 seconds and query also take 10 seconds.
Could someone please suggest what's the best approach or any alternative approach that full-fill my requirement?
Many thanks!
Update: Creating new index is not an option.

A: The first option is pointless extra work, and does not conform to ACID properties.
The unmentioned Approach #3 is best:

*

*Approach #2 is good as a starting point

*Remove the transaction as it is only a single statement

*Remove the NOLOCK hint as that will just cause incorrect results and weird errors

*Convert the left-join to a NOT EXISTS which is often more efficient.

UPDATE TXN
    SET TXN.Status = 5
FROM Transactions TXN
WHERE TXN.Status = 1
  AND NOT EXISTS (SELECT 1
      FROM Account ACC
      WHERE ACC.Id = TXN.AccountId
        AND ACC.IsActive = 0
  );

For this to work efficiently, you will want indexes (either clustered or non-clustered)
TXN (Status, AccountId)
ACC (IsActive, Id)

Alternatively you can use filtered non-clustered indexes
TXN (AccountId) INCLUDE (Status) WHERE (Status = 1)
ACC (Id) INCLUDE (IsActive) WHERE (IsActive = 0)

If you want to prevent a lot of locking and/or you cannot add the indexes, you can do the update in a loop on a few rows at a time.
Note that a transaction is not used here, to prevent excessive locking. Obviously you cannot roll back each run of the loop once finished.
DECLARE @batchSize bigint = 1000;

WHILE (1=1)
BEGIN

    UPDATE TOP (@batchSize) TXN
        SET TXN.Status = 5
    FROM Transactions TXN
    WHERE TXN.Status = 1
      AND NOT EXISTS (SELECT 1
          FROM Account ACC
          WHERE ACC.Id = TXN.AccountId
            AND ACC.IsActive = 0
      );

    IF @@ROWCOUNT < @batchSize
        BREAK;

    WAITFOR DELAY '00:00:05';  -- or some other wait time

END;

A: Presumably this update is required for your application to function correctly. When dealing with an overzealous datababase administrator (I didn't say "incompetent", did I?  :-) you, the developer, get the application right and leave the DBA to sort out the performance and table-locking problems. They can always add an index later when your production code gets slow. To which you say "hey, good idea!" presuming they ask you.
The same logic holds true for NOLOCK. The DBA can tell you if that's necessary. (It probably isn't.) Leave it out of your work.
Your objective here is to minimize the time during which a table is locked, as you said. Your secondary objective is to minimize the number of rows involved in any particular UPDATE operation.
You can do that, in SQL Server, by using TOP (n) to control the number of rows. That means you do multiple UPDATEs and keep going until the job is done.  This kind of thing will work.  (not debugged.)
SET @batchsize = 100;
SET @count = 1;
WHILE @count > 0 BEGIN
  SET DEADLOCK_PRIORITY LOW;

  UPDATE TOP (@batchsize) TXN
         SET TXN.[Status] = 5
   FROM [Transactions] TXN
   LEFT JOIN [Account] ACC
        ON ACC.[Id] = TXN.[AccountId] AND ACC.[IsActive] = 0
 WHERE TXN.[Status] = 1
    AND ACC.[Id] IS NULL;

 SET @count = @@ROWCOUNT;

END;

This works because your UPDATE sets Transactions.Status to 5. Once a row has been updated, that same row won't be chosen again for update.
Setting the deadlock priority to low is a good idea for this sort of repeating operation.  If somehow your update query causes a deadlock with other app software it tells SQL server to stop your query rather than others.  Stopping your query  doesn't matter: your update will catch the same rows the next time it runs.
Now, obviously, this doesn't update the whole table in a single ACID transaction.  Instead it's each batch. But I suspect that will not damage your application, or your transactional code would have done the update in real time.


text:
Q: How can i add 1 day to a DateTime variable in Visual Basic? What im trying to do is to add/sum a single day to an already declared DateTime variable.
For context i take the DateTime value from a user input and then I want to add/sum 1 day for comparison and query purposes.
This is what i had in mind but i know this method wont work.
SQL.AddParam("@FromDate", FromDate + 1)

What would be the proper way to do this?

A: Dim dateTime As DateTime
dateTime = dateTime.AddDays(1)

Datetime objects provide some functions to add time.
.AddDays(days as Double)
.AddHours(hours as Double)
.AddMinutes(minutes as Double)
.AddSeconds(seconds as Double)
.AddMilliseconds(milliseconds as Double)

Or you can try to pass directly to SQL your date + 1 day.
SQL.AddParam("@FromDate", DateAdd(DateInterval.DayOfYear, 1, FromDate))

Datetime.DateAdd function Microsoft's documentation:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.dateandtime.dateadd?view=netcore-3.1


text:
Q: LibGDX Resize Event Only Fires When Window Is Made Larger So I have a problem with LibGDX that I can't figure out. I have a game that I am programming in LibGDX which is running on the desktop in Windows 7. I am trying to re-position various GUI elements when a player adjusts the size of the window. My code works just fine however the resize event only fires when the window is made larger. If the total dimensions of the window is smaller after the player let's go of the edge of the window then the resize method never gets called.
I have looked at the code in LibGDX for what determines if the resize event should fire or not and I can't determine if there is anything blocking the resize event or not. None the less the resize event should fire even if the window is being made smaller. Does anyone have any tips on what I should try? Or has anyone heard of this?
EDIT: I have logged to the console from the resize method in the top level ApplicationAdapter already. I also put a break point in the resize method to get the stack trace to look at the LibGDX code which calls the resize method. But none of these things helped.

A: Do you have a Viewport? If yes, is it a ScreenViewport? Because that's the best viewport for your situation.
Remember to add:
viewport.update(width, height);
viewport.apply();

in
@Override
public void resize(int width, int height){}

I hope it helps! Good luck!


text:
Q: Does uniform convergence of uniformly bounded, nonnegative, continuous functions to 0 on an infinite measure space imply integrals converge to 0? Let $(X, \mu)$ be an infinite measure space. Let $f_n:X \to \mathbb{R}$ be a sequence of uniformly bounded, continuous, non-negative functions on $X.$  Let $f_n \to 0$ uniformly.
Does this necessarily imply:
$$\int_{X}f_nd\mu \to 0?$$
If not, what other criteria do we need to ensure this? For the moment, some hints in the comments would be enough I think, as I'd like to work it out.

A: No, it doesn't imply.
Consider $X = \mathbb{R}$ and the sequence of functions such that
$f_i(x) = 1/(i+1) $ for $-(i+1)<x<(i+1)$ and $0$ otherwise. You can easily make each $f_i$ continuous.
Everything is well-defined here: All $f_i$ are integrable and the result of integral is finite for all $i$; the function sequence converges and so does the integral sequence.
However, the function sequence converges to zero uniformly while the integrals don't.

A: As written in the opening post, the convergence $\int_{X}f_nd\mu \to 0$ may not hold. PhoemueX gave the example $f_n \equiv 1/n$.
One has to add the assumption that for each positive $\varepsilon$, there exists a set $A=A(\varepsilon)$ of finite measure such that
$$
\sup_{n\geqslant 1}\int_{X\setminus A}  f_n  d\mu<\varepsilon.
$$
Then for a positive $\varepsilon$ and the corresponding $A$,
$$
\int f_nd\mu\leqslant \varepsilon +\int_Af_nd\mu\leqslant\varepsilon+\mu(A)\sup_{x\in X}f_n(x).
$$


text:
Q: Does having more than 3 worker per resource point decrease gathering efficiency?
Possible Duplicate:
What's the correct number of workers to put on gathering vespene and minerals in StarCraft 2?

*

*Are more better?

*Do more workers per resource point hurt production?


text:
Q: Faster iteration I have this code, which is part of a function that returns a list of SQL rows based on a time range.
The query itself (1st line of code) is quite fast. But the foreach loop that extract the relevant data takes a while to complete.
I have around 350.000 lines to iterate, and despite it's has to take a while, I was wondering if there is any change I could make in order to make it faster.
$SqlDocmasterTableResuls = $this.SqlConnection.GetSqlData("SELECT DOCNUM, DOCLOC FROM MHGROUP.DOCMASTER WHERE ENTRYWHEN between '" + $this.FromDate + "' and '" + $this.ToDate + "'")

[System.Collections.ArrayList]$ListOfDocuments = [System.Collections.ArrayList]::New()

if ($SqlDocmasterTableResuls.Rows.Count)
{
    foreach ($Row in $SqlDocmasterTableResuls.Rows)
    {
        $DocProperties = @{
            "DOCNUM"      = $Row.DOCNUM
            "SOURCE"      = $Row.DOCLOC
            "DESTINATION" = $Row.DOCLOC -replace ([regex]::Escape($this.iManSourceFileServerName + ":" + $this.iManSourceFileServerPath.ROOTPATH)),
                            ([regex]::Escape($this.iManDestinationFileServerName + ":" + $this.iManDestinationFileServerPath.ROOTPATH))
        }

        $DocObj = New-Object -TypeName PSObject -Property $DocProperties
        $ListOfDocuments.Add($DocObj)
    }

    return $ListOfDocuments

A: Avoid appending to an array in a loop. The best way to capture loop data in a variable is to simply collect the loop output in a variable:
$ListOfDocuments = foreach ($Row in $SqlDocmasterTableResuls.Rows) {
    New-Object -Type PSObject -Property @{
        "DOCNUM"      = $Row.DOCNUM
        "SOURCE"      = $Row.DOCLOC
        "DESTINATION" = $Row.DOCLOC -replace ...
    }
}

You don't need the surrounding if conditional, because if the table doesn't have any rows the loop should skip right over it, leaving you with an empty result.
Since you want to return the list anyway, you don't even need to collect the loop output in a variable. Just leave the output as it is and it will get returned anyway.
Also avoid repeating operations in a loop when their result doesn't change. Calculate the escaped source and destination paths once before the loop:
$srcPath = [regex]::Escape($this.iManSourceFileServerName + ':' + $this.iManSourceFileServerPath.ROOTPATH)
$dstPath = [regex]::Escape($this.iManDestinationFileServerName + ':' + $this.iManDestinationFileServerPath.ROOTPATH)

and use the variables $srcPath and $dstPath inside the loop.
Something like this should do:
$SqlDocmasterTableResuls = $this.SqlConnection.GetSqlData("SELECT ...")

$srcPath = [regex]::Escape($this.iManSourceFileServerName + ':' + $this.iManSourceFileServerPath.ROOTPATH)
$dstPath = [regex]::Escape($this.iManDestinationFileServerName + ':' + $this.iManDestinationFileServerPath.ROOTPATH)
foreach ($Row in $SqlDocmasterTableResuls.Rows) {
    New-Object -Type PSObject -Property @{
        'DOCNUM'      = $Row.DOCNUM
        'SOURCE'      = $Row.DOCLOC
        'DESTINATION' = $Row.DOCLOC -replace $srcPath, $dstPath
    }
}

return

A: [edit - per Ansgar Wiechers, the PSCO accelerator is only available with ps3+.]
one other thing that may help is to replace New-Object with [PSCustomObject]. that is usually somewhat faster to use. something like this ...
$DocObj = [PSCustomObject]$DocProperties

another way to use that type accelerator is to do what Ansgar Wiechers did in his code sample, but use the accelerator instead of the cmdlet. like this ...
[PSCustomObject]@{
    'DOCNUM'      = $Row.DOCNUM
    'SOURCE'      = $Row.DOCLOC
    'DESTINATION' = $Row.DOCLOC -replace $srcPath, $dstPath
    }

hope that helps,
lee


text:
Q: GitHub Actions workflow deploy complaining about env variables I am running a deploy workflow for azure and getting the following error. any idea what is it complaining about
error: error validating "STDIN": error validating data: [ValidationError(Deployment.spec.template.spec.imagePullSecrets[0]): unknown field "args" in io.k8s.api.core.v1.LocalObjectReference, ValidationError(Deployment.spec.template.spec.imagePullSecrets[0]): unknown field "command" in io.k8s.api.core.v1.LocalObjectReference, ValidationError(Deployment.spec.template.spec.imagePullSecrets[0]): unknown field "env" in io.k8s.api.core.v1.LocalObjectReference, ValidationError(Deployment.spec.template.spec.imagePullSecrets[0]): unknown field "ports" in io.k8s.api.core.v1.LocalObjectReference, ValidationError(Deployment.spec.template.spec.imagePullSecrets[0]): unknown field "volumeMounts" in io.k8s.api.core.v1.LocalObjectReference]; if you choose to ignore these errors, turn validation off with --validate=false
90
Error: Process completed with exit code 1.

It deployed the pod and the pod is stuck at this on AKS:
$ kubectl get po

NAME                                READY   STATUS             RESTARTS   AGE
 view-app-dev-895f4c475-mrmtj   0/1     ImagePullBackOff   0          4h14m

Events:
  Type    Reason   Age                       From     Message
  ----    ------   ----                      ----     -------
  Normal  Pulling  32m (x45 over 3h57m)      kubelet  Pulling image " view:latest"
  Normal  BackOff  2m23s (x1031 over 3h57m)  kubelet  Back-off pulling image " view:latest"

A: The issue was I put the imagepullsecrets in the manifest file at the wrong place.
that fixed the issue.
imagepullsecrets should be below volume mounts not above


text:
Q: Get thumbnail image of video from video url Is it possible to get the thumbnail image from a video Url? I need to thumbnails of videos in a list view.

A: Yes its possible to get the thumbnail of a video using ThumbnailUtils.
FileOutputStream out;
File land=new File(Environment.getExternalStorageDirectory().getAbsoluteFile()
                +"/portland.jpg");// image file use to create image u can give any path.
Bitmap bitmap=ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);//filePath is your video file path.
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        out=new  FileOutputStream(land.getPath());
        out.write(byteArray);
        out.close();

A: If you are specifically asking about youtube videos then there are automatically 4 generated images by Youtube.
http://img.youtube.com/vi/video_url_here/0.jpg
http://img.youtube.com/vi/video_url_here/1.jpg
http://img.youtube.com/vi/video_url_here/2.jpg
http://img.youtube.com/vi/video_url_here/3.jpg

Standard Image sizes
Player Background Thumbnail (480x360 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/0.jpg
Start Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/1.jpg
Middle Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/2.jpg
End Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/3.jpg
High Quality Thumbnail (480x360 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/hqdefault.jpg
Medium Quality Thumbnail (320x180 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/mqdefault.jpg
Normal Quality Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/default.jpg
Standard Definition Thumbnail (640x480 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/sddefault.jpg
Maximum Resolution Thumbnail (1920x1080 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/maxresdefault.jpg

A: It is working in my case
Uri videoUri = data.getData();
                String selectedPathVideo="";
                selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
                Log.i("Image File Path", ""+selectedPathVideo);

                try {
                    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);

                    imgFarmerVideo.setImageBitmap(thumb);

                } catch (Exception e) {
                    e.printStackTrace();
                }

The Support File
public class ImageFilePath {
    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri)
    {

        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

A: Try  ThumbnailUtils, to get video bitmap from file path
ThumbnailUtils.createVideoThumbnail(filePath,MediaStore.Video.Thumbnails.MINI_KIND);

A: It is possible to get thumbnail image of video from video url.
If your video type is Vimeo follow below steps:
1)Suppose your Video Url is:
http://player.vimeo.com/video/17314292
2)Get Video Id From Url : eg. 17314292
3)Call WS with Video id and XMl format
http://vimeo.com/api/v2/video/17314292.xml
You will get "thumbnail_small","thumbnail_medium","thumbnail_large" in xml format for video thumb from video id
If your video type is YouTube follow below steps:
1)Video Url :
http://www.youtube.com/embed/Nl2iMF0yKW8
2)Get Video Id From Url : eg. Nl2iMF0yKW8
3)Replace video id in this url
http://i3.ytimg.com/vi/Nl2iMF0yKW8/default.jpg
NOTE:Just replace your id here.

A: It's very important to identify the components of a problem. I'd actually say you have two separate problems:

*

*Downloading a file from an URL.

*Creating a thumbnail image from an incomplete video file.
Look into those two separately, you'll find plenty of information.

A: To get thumbnail from the URL, i only got one solution till now,
You have to use This library
It Supports file, http, https, mms, mmsh and rtmp protocols
and
It Supports aac, acc+, avi, flac, mp2, mp3, mp4, ogg, 3gp and more! formats (audio and video):

A: It is possible to get a thumbnail from a video file or url using FFMPEG.
FFMPEG must be built using the NDK (or you can find some Android built FFMPEG binaries). Here is a GitHub project to build FFMPEG:
https://github.com/guardianproject/android-ffmpeg
You can then include the FFMPEG binaries with your app and execute FFMPEG from code in your app to generate an image from the video (local or URL) using a command like:
ffmpeg -i videosite.com/video.flv -ss 00:00:15.000 -vframes 1 thumbnail_out.png

One thing to consider is at what seek time (option -ss) you grab the thumbnail for it to be a meaningful image that represents the video.


text:
Q: Implementar formato de moneda en un input de tipo rango los que sucede es que tengo una función para estilizar un input de tipo rengo (ver ejemplo funcionando), el problema radica es que ahora debo convertir el número que se muestra en formato de moneda con esta función o alguna parecida:
function toMoney(str, currency_sign){
  currency_sign = currency_sign || '$';
  var current = Number(str.toString().replace(/[^0-9.]/g, ''));
  var formatted = current.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  var wDecimals = formatted.split('.');
  wDecimals = wDecimals[0].replace(',','.')
  return currency_sign + wDecimals;
}

Pero no encuentro como pueda implementarla con lo que tengo hoy del input:

valueBubble = '<output class="rangeslider__value-bubble" style="position: absolute;" />';
updateValueBubbleMoney = function(pos, value, context) {
  var $valueBubble, position, tempPosition;
  pos = pos || context.position;
  value = value || context.value;
  $valueBubble = $('.rangeslider__value-bubble', context.$range);
  tempPosition = pos + context.grabPos;
  position = tempPosition <= context.handleDimension ? context.handleDimension : tempPosition >= context.maxHandlePos ? context.maxHandlePos : tempPosition;
  if ($valueBubble.length) {
    $valueBubble[0].innerHTML = value;
  }
};
$('.range-money').rangeslider({
  polyfill: false,
  onInit: function() {
    this.$range.append($(valueBubble));
    updateValueBubbleMoney(null, null, this);
  },
  onSlide: function(pos, value) {
    updateValueBubbleMoney(pos, value, this);
  }
});
<link href="http://rangeslider.js.org/assets/rangeslider.js/dist/rangeslider.css" rel="stylesheet" />

<input class="range-money" id="popoverClose" type="range" min="0" max="10000000" value="0">

Por favor su ayuda

A: Solo integre la función toMoney() en la función updateValueBubbleMoney(), es decir en vez de quedar así:
if ($valueBubble.length) {
  $valueBubble[0].innerHTML = value;
}

quedaría así:
if ($valueBubble.length) {
  $valueBubble[0].innerHTML = toMoney(value,"$");
}

const toMoney = (str, currency_sign) => {
  currency_sign = currency_sign || '$';
  var current = Number(str.toString().replace(/[^0-9.]/g, ''));
  var formatted = current.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  var wDecimals = formatted.split('.');
  wDecimals = wDecimals[0].replace(',','.')
  return currency_sign + wDecimals;
}

valueBubble = '<output class="rangeslider__value-bubble" style="position: absolute;" />';
updateValueBubbleMoney = function(pos, value, context) {
  var $valueBubble, position, tempPosition;
  pos = pos || context.position;
  value = value || context.value;
  $valueBubble = $('.rangeslider__value-bubble', context.$range);
  tempPosition = pos + context.grabPos;
  position = tempPosition <= context.handleDimension ? context.handleDimension : tempPosition >= context.maxHandlePos ? context.maxHandlePos : tempPosition;
  if ($valueBubble.length) {
    //$valueBubble[0].innerHTML = value;
    $valueBubble[0].innerHTML = toMoney(value,"$");
  }
};
$('.range-money').rangeslider({
  polyfill: false,
  onInit: function() {
    this.$range.append($(valueBubble));
    updateValueBubbleMoney(null, null, this);
  },
  onSlide: function(pos, value) {
    updateValueBubbleMoney(pos, value, this);
  }
});
<link href="http://rangeslider.js.org/assets/rangeslider.js/dist/rangeslider.css" rel="stylesheet" />

<input class="range-money" id="popoverClose" type="range" min="0" max="10000000" value="0">

Espero que sea lo que andas buscando.


text:
Q: Hibernate Migration SQL server 2005 to 2012 Drivers in my job we're migrating our MS SQL Server 2005 to 2012. Here we use Hibernate and the question that we're trying to figure out is, Why the applications work perfectly with the same configuration in the .cfg.xml and need no changes.
We had verified all the new version databases were were pointed correctly. So that mistake is not valid.
What I know is Hibernate hide the configuration of the connetion by the .cfg.xml but we're not sure why we don't need to upgrade or even change the xml file.
Thank you guys.

A: I believe change dialect to SQL Server 2012 : org.hibernate.dialect.SQLServer2012Dialect
you car see this.