text:
Q: How to validate command line input from multiple choice prompt in Ruby? I'm writing a multiple choice quiz where the user has to choose an answer by entering a letter from a to d. Each question prompt looks like this:
What is the last letter in alphabet?
(a) Y
(b) R
(c) Z
(d) Q

If the user enters anything else, I want to show a message and print the whole question again until the input is a, b, c or d.
Here's what I've tried: (simplified)
question = "What is the last letter in alphabet?\n(a) Y\n(b) R\n(c) Z\n(d) Q"

puts question
answer = gets.chomp.to_s
while answer > "d"
  puts "Please enter a, b, c, or d"
  puts
  puts question
  answer = gets.chomp.to_s
end

It works fine when entering e, f, g etc. but it doesn't catch input like ab, 1, Z, or when the user just presses enter.

A: You have only four allowed inputs. Check for those directly. Even if as inelegantly as if !(answer == "a" || answer == "b" ...). Anything else will accept some invalid input. In particular, if answer > "d" allows "ab" as a valid answer.

A: Your approach doesn't work because answer > "d" compares both strings character-wise using their (Unicode) code points. To understand what this means, take a look at the Basic Latin chart: (it's equivalent to an ASCII table)

"d" has a codepoint of U+0064. Any smaller codepoint – i.e every character in the chart before "d" – is regarded smaller. This includes all (regular) digits, all (basic latin) uppercase letters and several symbols:
"0" > "d"  #=> false
"Z" > "d"  #=> false

You could add a lower bound like answer < "a" || answer > "d" but this would still allow all strings starting with one of the allowed characters, e.g.:
"apple" < "a" || "apple" > "d" #=> false

To actually limit the answer to the four allowed values, you have to compare the string to each of them. You could combine these comparisons:
answer == 'a' || answer == 'b' || answer == 'c' || answer == 'd'

use a loop over an array of allowed values:
['a', 'b', 'c', 'd'].any? { |letter| answer == letter }

check whether the array includes the answer:
['a', 'b', 'c', 'd'].include?(answer)

# or

%w[a b c d].include?(answer)

or use a regular expression to match a to d:
answer.match?(/\A[a-d]\z/)

Note that the examples above become true if answer is between a and d. You could either negate the condition via !(...):
while !(%w[a b c d].include?(answer))
  # ...
end

or use until instead of while:
until %w[a b c d].include?(answer)
  # ...
end

A: Other answers have answered the question given in the title of your question.
I would like to suggest that you consider adopting some variation of the following code.
def get_answer(question, answers)
  choices_to_answers = construct_choices_to_answers(answers)
  loop do
    puts "#{question}"
    display_choices(choices_to_answers)
    print "answer: "
    choice = gets.chomp
    puts choice
    break choices_to_answers[choice] if choices_to_answers.key?(choice)
    puts "\nThat answer is invalid."
  puts "Enter a letter between 'a' and '#{choices_to_answers.keys.last}'\n"
  end
end

def construct_choices_to_answers(answers)
  ('a'..('a'.ord + answers.size - 1).chr).to_a.zip(answers).to_h
end

def display_choices(choices_to_answers)
  choices_to_answers.each { |k,v| puts "(#{k}): #{v}" }
end

Suppose the possible answers were as follows.
answers = %w| Y R Z Q |
  #=> ["Y", "R", "Z", "Q"]

Then
choices_to_answers = construct_choices_to_answers(answers)
  #=> {"a"=>"Y", "b"=>"R", "c"=>"Z", "d"=>"Q"}

and
display_choices(choices_to_answers)

prints
(a): Y
(b): R
(c): Z
(d): Q

Here I've assumed that the choices are always consecutive letters beginning with "a". If that assumption is correct there is no need to manually associate those letters with the possible answers.

Let me now show a possible conversation with the method (with answers as defined above).
question = "What is the last letter in the alphabet?"

get_answer(question, answers)
  #=> "R"

The following is displayed.
What is the last letter in the alphabet?
(a): Y
(b): R
(c): Z
(d): Q
answer: e

That answer is invalid.
Enter a letter between 'a' and 'd'

What is the last letter in the alphabet?
(a): Y
(b): R
(c): Z
(d): Q
answer: b

You might then construct an array of hashes that provide the question, possible answers, correct answer, possibly the weight of the question and a boolean indicating whether a correct answer was given.
questions = [
  ...
  { question: "What is the last letter in the alphabet?",
    answers: ["Y", "R", "Z", "Q"],
    correct_answer: "Z",
    weight: 1,
    correct_answer_given: nil
  },
  ...
]

The value of :correct_answer_given for each question is updated to true or false when the question is answered. Once all questions have been answered questions can be used to determine a mark for the exam.

If you wish to assign a number to each question you could write
question_number = 0

questions.each do |h|
  question_number += 1
  g = h.merge(question: "#{question_number}. #{h[:question]}")
  answer = get_answer(question, g[:answers])
  h[:correct_answer_given] = h[:correct_answer] == answer
end

If question_number #=> 12 and
h[:question]
  #=> "What is the last letter in the alphabet?",

then
g[:question]
  #=> "12. What is the last letter in the alphabet?"


text:
Q: Добавление class Есть такой список в котором при выборе пункта переводит на другую страницу. Задача что бы при переходе на другую страницу в пункте меню оставался выбраный пункт.

$.fn.ulSelect = function() {
  var ul = $(this);

  if (!ul.hasClass('zg-ul-select')) {
    ul.addClass('zg-ul-select');
  }
  // SVG arrow
  var arrow = '<svg id="ul-arrow" xmlns="http://www.w3.org/2000/svg" version="1.1" width="32" height="32" viewBox="0 0 32 32"><line stroke-width="1" x1="" y1="" x2="" y2="" stroke="#449FDB" opacity=""/><path d="M4.131 8.962c-0.434-0.429-1.134-0.429-1.566 0-0.432 0.427-0.432 1.122 0 1.55l12.653 12.528c0.434 0.429 1.133 0.429 1.566 0l12.653-12.528c0.432-0.429 0.434-1.122 0-1.55s-1.136-0.429-1.566-0.002l-11.87 11.426-11.869-11.424z" fill="#111"/></svg>';
  $('li:first-of-type', this).addClass('active').append(arrow);
  $(this).on('click', 'li', function(event) {

    // Remove div#selected if it exists
    if ($('#selected--zg-ul-select').length) {
      $('#selected--zg-ul-select').remove();
    }
    ul.before('
');
    var selected = $('#selected--zg-ul-select');
    $('li #ul-arrow', ul).remove();
    ul.toggleClass('active');
    // Remove active class from any
 that has it...
    ul.children().removeClass('active');
    // And add the class to the
 that gets clicked
    $(this).toggleClass('active');

    var selectedText = $(this).text();
    if (ul.hasClass('active')) {
      selected.text(selectedText).addClass('active').append(arrow);
    } else {
      selected.text('').removeClass('active');
      $('li.active', ul).append(arrow);
    }
  });

  $(document).on('click', function(event) {
    if ($('ul.zg-ul-select').length) {
      if (!$('ul.zg-ul-select').has(event.target).length == 0) {
        return;
      } else {
        $('ul.zg-ul-select').removeClass('active');
        $('#selected--zg-ul-select').removeClass('active').text('');
        $('#ul-arrow').remove();
        $('ul.zg-ul-select li.active').append(arrow);
      }
    }
  });
}

// Run
$('#be-select').ulSelect();
ul.zg-ul-select {
  border-radius: 2px;
  box-sizing: border-box;
  cursor: pointer;
  font-family: "Helvetica Neue", Helvetica, sans-serif;
  font-size: 2em;
  margin: 0;
  padding: 0;
}

ul.zg-ul-select li {
  border-radius: 3px;
  display: none;
  padding: 0.5em;
}

ul.zg-ul-select li.active {
  align-items: center;
  border: 1px solid #111;
  border-radius: 3px;
  box-shadow: 0 0 2px #aaa;
  color: #111;
  display: flex;
  justify-content: space-between;
}

ul.zg-ul-select.active {
  border: 1px solid #aaa;
}

ul.zg-ul-select.active li {
  border: none;
  box-shadow: none;
  display: block;
}

ul.zg-ul-select.active li:hover {
  background: #0074d9;
}

ul.zg-ul-select.active li.active {
  background: #40a6ff;
}

ul.zg-ul-select.active li.active:hover {
  background: #0074d9;
}

#selected--zg-ul-select {
  align-items: center;
  box-sizing: border-box;
  color: #111;
  display: flex;
  font-family: "Helvetica Neue", Helvetica, sans-serif;
  justify-content: space-between;
  font-size: 2em;
  width: auto;
}

#selected--zg-ul-select.active {
  border: 1px solid #111;
  border-radius: 3px;
  box-shadow: 0 0 2px #aaa;
  padding: 0.5em;
}

       Работники

       Сompany register

       User orders

Я нашел вот такой скрипт, который добавляет class="active" к нужному пункту, но добавляет его для Линки, а не для LI.

var url_keyword = window.location.pathname.split('/')[3]
$('.cabinet-menu-min li a[href*="/' + url_keyword + '/"]').addClass('active')

Помогите Добавить класс в LI и еще при выборе пункта, если нажать на верхний  линк (тот который к боксе) , то он сразу срабатывает, как сделать его не активным?

A: Теперь по-идее он добавляет класс вашему Ли. Типа он нашел ваш Линк, потом смотри на его родителя Ли, и добавляет класс ему. Ответ вам подходит?

var url_keyword = window.location.pathname.split('/')[3]
$('.cabinet-menu-min li a[href*="/' + url_keyword + '/"]').parent().addClass('active')

redpajama_set_name: RedPajamaStackExchange


text:
Q: When should we stop work and make tool? As a software engineer, we are always eager to get effective tools to boost our productivity.
And in our daily work, we are often unsatisfactory with the existing tools and would like to have better ways such as better GDB script config, Vim script and some Python script to make boring things automatic.
However, it is actually a trade-off since making tools also needs time and energy. It does not give productivity boosting immediately. Therefore, how do you judge whether it is time to stop work and to make some tools to ease your future pain?

A: With experience I have found that just pushing hard on the grunt work is usually the most time-efficient.  Making a tool is often tempting. I give up resisting when:

*

*The tool has more than one purpose.  A good chess player accomplished two things with each move: block an opponents piece and free up a bishop.  A beginner would probably need two turns to do that.  Likewise, I consider if the tool would only do one thing, or with small extra effort do two, e.g. help fix some raw data  files, and also create artificial test data.

*Future usefulness. It might save me time for this weeks' work, but is it likely to save me or someone time on a new project next week?

*It is a good time to learn a new language, library, design technique or whatever, and I have the time to do it.  The tool is a beneficial side effect of doing something education, using time already granted for education.

*When we're having serious problems getting things to work.  Like skydiving without a parachute, you really should take the time to make or buy a parachute.  If you can't get any meaningful experimental results, or the new web app won't work at all, you just gotta stop and make or buy a tool to measure what you can't see, drive components, or replace part of the system. When the work is totally hung up in need of a tool, I don't care about future use or multiple use. Necessity weighs enough.

A: My rule of thumb is that when I have to do something for the third time, it's time to either write a little script to automate it, or rethink my approach.
I'm not making a full-blown "tool" at this point, just a little script (usually bash or python; perl would work too, or even PHP) that automates what I did manually before. It's basically an application of the DRY principle (or the Single Source Of Truth principle, which is in essence the same thing) - if you have to change two source files in tandem, there has to be some common truth that they share, and that truth has to be factored out and stored in one central place. It's great if you can solve this internally by refactoring, but sometimes, this isn't feasible, and that's where the custom scripts come in.
Then later, the script may or may not evolve into a full-blown tool, but I usually start out with a very specific script with lots of things hard-coded into it.
I hate grunt work with a passion, but I also strongly believe that it is a sign of bad or incorrect design. Being lazy is an important quality in a programmer, and it better be the kind where you go through great lengths to avoid repetitive work.
Sure, sometimes the balance is negative - you spend three hours refactoring your code or writing a script to save you one hour of repetitive work; but usually, the balance is positive, more so if you consider costs that aren't directly apparent: human failure (humans are really bad at repetitive work), smaller codebase, better maintainability due to reduced redundancy, better self-documentation, faster future development, cleaner code. So even if the balance appears negative right now, the codebase will grow further, and that tool you wrote to generate web forms for three data objects will still work when you have thirty data objects. In my experience, the balance is usually estimated in favor of grunt work, probably because repetitive tasks are easier to estimate and thus under-estimated, while refactoring, automating and abstracting are perceived as less predictable and more dangerous, and thus over-estimated. It usually turns out that automating isn't that hard after all.
And then there's the risk of doing it too late: it's easy to refactor three
brand new data object classes into shape and write a script that generates web forms for them, and once you've done that, it's easy to add 27 more classes that also work with your script. But it's close to impossible to write that script when you have reached a point where there are 30 data object classes, each with hand-written web forms, and without any consistency between them (a.k.a. "organic growth"). Maintaining those 30 classes with their forms is a nightmare of repetitive coding and semi-manual search-replace, changing common aspects takes thirty times as long as it should, but writing a script to solve the problem, which would have been a lunch break no-brainer when the project started out is now a frightful two-week project with the dreading prospect of a month-long aftermath consisting of fixing bugs, educating users, and possibly even giving up and reverting to the old codebase. Ironically, writing the 30-class mess took way longer than the clean solution would have, because you could have been riding the convenient script all that time. In my experience, automating repetitive work away too late is one of the major problems in long-running large software projects.

A: I just remembered this:

The problem with this of course is that in real life situation you can't easily measure those data to select the right cell in the table. And as it was mentioned in other answers, there are other variables (the risk of error, task is too boring to do it even once, ...) you need to add to the equation.
So my answer is that it really depends on the situation and you can not hope to get any "correct" answer for all the situations. After all life would be boring if we had cookbooks for everything.

A: This is a big problem in my experience. Tool building is usually left to a motivated developer who stops work to build the tool. This often interferes with the development even if it provides value. Tool building needs to be viewed as an integrated part of the development "Process".
I remember attending code reviews where header errors would result in scheduling another review. Many of these could have been detected by a tool. e.g. incorrect sloc counts, missing requirement, formatting errors. My tool written in perl generated the header from the delivered code and validated requirements from an Oracle database. It was not part of our "Process" so in the short run building the tool was viewed as delaying delivery.
The entire team needs to periodically stop and see where there are manual efforts than can be automated by tool creation.

A: I "make tools" when one of these is true:

*

*The task is annoying me

*The risk of human error in the task is too big

The "risk" for the 2nd option doesn't have to be huge - the cost of building one small tool is usually small, so if all you save is the risk of running a 10-minute build again once a week, it will usually repay itself very fast.
I try to make tools as small as possible - just make the task a little bit easier now, and maybe improve again next time.
This means you only fix the biggest pain each time, and not creating fixes to problems that don't really hurt you.

A: All of the other answers are good, but I'd add one more reason why it's valuable to spend time to build small tools (and customise your .vimrc, .emacs etc.):
Sometimes you get creatively or motivationally "stuck in a rut" and doing something, anything, will "get the juices flowing" again (to mix metaphors). Ideally that would be something that productively pushes the project forward, but if it's a bit tangential and that inspires you, then that's good too.
You might not be staring at a blank screen, but instead simply having trouble seeing the progress you're making on a big task. In that situation ticking off something tangible can stop you feeling like you're not getting anywhere.
A variation on this is when you keep thinking about something that should be on the "back burner" - just taking a moment and doing it will get it off your mind and free you up to put your full energy into the main task again.

A: It depends on what you consider as making a tool.  Arguably I make loads of them in ways that other devs would consider frivolous... Because I make them for just about everything except the most basic filesystem commands.
I use 2 rationales to support that.

*

*It's an extension of the DRY principle. If we want to repeat something,
manual effort is the least effective use of human resources.

*It's an effective way to record what I did, so if I built something then I (or
someone else) may want to refer back to how I did it weeks or months
later and it keeps the log of work with the project.

Occasionally they grow into bigger tools and gain interactive functions, but if they don't they still have value as a record.


text:
Q: Forking with Pipes I have tried to do fork() and piping in main and it works perfectly fine but when I try to implement it in a function for some reason I don't get any output, this is my code:
void cmd(int **pipefd,int count,int type, int last);

int main(int argc, char *argv[]) {
int pipefd[3][2];
int i, total_cmds = 3,count = 0;
int in = 1;

for(i = 0; i < total_cmds;i++){
 pipe(pipefd[count++]);
 cmd(pipefd,count,i,0);
}

 /*Last Command*/
 cmd(pipefd,count,i,1);

exit(EXIT_SUCCESS);
}

void cmd(int **pipefd,int count,int type, int last){
    int child_pid,i,i2;

     if ((child_pid = fork()) == 0) {

            if(count == 1){
               dup2(pipefd[count-1][1],1); /*first command*/
            }
            else if(last!=1){
               dup2(pipefd[count - 2][0],0); /*middle commands*/
               dup2(pipefd[count - 1][1],1);
            }
            else if(last == 1){
               dup2(pipefd[count - 1][0],0); /*last command*/
            }

            for(i = 0; i < count;i++){/*close pipes*/
            for(i2 = 0; i2 < 2;i2++){
               close(pipefd[i][i2]);
            }}

            if(type == 0){
                execlp("ls","ls","-al",NULL);
            }
            else if(type == 1){
                execlp("grep","grep",".bak",NULL);
            }
            else if(type==2){
                               execl("/usr/bin/wc","wc",NULL);
            }
            else if(type ==3){
                         execl("/usr/bin/wc","wc","-l",NULL);
           }
            perror("exec");
            exit(EXIT_FAILURE);
    }
    else if (child_pid < 0) {
            perror("fork");
            exit(EXIT_FAILURE);
    }
}

I checked the file descriptors and it is opening the right ones, not sure what the problem
could be..
Edit: I Fixed the problem but I'm having child processes, which way would be the best to wait for the child , while(wait(NULL)!=-1); but that hangs

A: The problem is that pipefd is not an int**, it's an int[3][2], so when you pass it to cmd, you get garbage.  Your compiler should be giving you a warning on each call to cmd(), such as something like this:
warning: passing argument 1 of 'cmd' from incompatible pointer type

If not, turn up your warning level.
It's true that arrays decay into pointers to their first elements, so you can pass a 1-D array to a function expecting a pointer, but that's only true for the first dimension of arrays.  In particular, a 2D array does not decay into a pointer to a pointer.  It decays at the first level only, so pipefd can decay into the type int (*)[2], which is read as "pointer to array 2 of int"
So, the correct way to write cmd is this:
void cmd(int (*pipefd)[2],int count,int type, int last)


text:
Q: Software to compute spherical harmonics in higher than 3 dimensions (100 or maybe 500 dimensions)? I have been trying to find an implementation of Spherical harmonics for higher dimensional data but I couldnt find anything in Sage, Mathematica, Matlab. Does anyone have any idea of a standard/fast implementation ?
MORE DETAILS: I am adding more information about the expression that I am interested in. This comes from equation 13 from this paper on the eigenfunctions of dot product kernels.

Moreover, the Legendre Polynomials may be expanded into an orthonormal basis
  of spherical harmonics $Y^d_{n,j}$ by the Funk-Hecke equation to obtain:
  $$P^n_d(x.y) = \frac{|S_{d-1}|}{N(d,n)} \sum_{j=1}^{N(d,n)} Y_{n,j}^d(x) Y_{n,j}^d(y)$$

Here $x,y$ are vectors in $R^d$ with unit norm and I am interested in computing the spherical harmonic $Y_{n,j}^d$ at the points $x$ and $y$.

A: Does this work for you?

The HFT.m Mathematica software package performs symbolic manipulation of expressions that arise in the study of harmonic functions. This software, which is available electronically without charge, can perform symbolic calculations that would take a prohibitive amount of time if done without a computer. For example, the Poisson integral of any polynomial can be computed exactly.
Some of the capabilities of this software:

*

*symbolic calculus in $\mathbb{R}^n$

*Dirichlet problem for balls, quadratic regions, annular regions, and exteriors of balls in $\mathbb{R}^n$

*Neumann problem for balls and exteriors of balls in $\mathbb{R}^n$

*biDirichlet problem for balls in $\mathbb{R}^n$

*the Bergman projection problem for balls in $\mathbb{R}^n$

*$\color{red}{\text{finding bases for spherical harmonics in }\mathbb{R}^n}$

*explicit formulas for zonal harmonics in $\mathbb{R}^n$

*manipulations with the Kelvin transform

*Schwarz functions for balls in $\mathbb{R}^n$

*harmonic conjugation in $\mathbb{R}^2$


text:
Q: Can a table's row go to the page footer when it has a page break? I have a table with svg arrows that indicate the next block of a question.
The problem is when the table break in the middle of the page and the arrow stop in same point. I need that the table row go to the page footer.
Is that possible?
Thanks
Table row break in middle of the page
enter image description here
<fo:table inline-progression-dimension="auto" table-layout="auto" width="106mm">
                                <fo:table-column column-width="5%"/>
                                <fo:table-column column-width="74%"/>
                                <fo:table-column column-width="16%"/>
                                <fo:table-column column-width="3%"/>
                                <fo:table-column column-width="2%"/>
                                <fo:table-footer>
                                    <fo:table-row keep-with-previous.within-page="always">
                                        <fo:table-cell/>
                                        <fo:table-cell/>
                                        <fo:table-cell/>
                                        <fo:table-cell>
                                            <fo:block left="2.25mm" position="relative" top="-0.7mm">
                                                <fo:retrieve-table-marker retrieve-class-name="continuedSecondArrow" retrieve-position-within-table="last-ending-within-page"/>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell>
                                            <fo:block left="1.21mm" position="relative" top="-0.7mm">
                                                <fo:retrieve-table-marker retrieve-class-name="continuedArrow" retrieve-position-within-table="last-ending-within-page"/>
                                            </fo:block>
                                        </fo:table-cell>
                                    </fo:table-row>
                                </fo:table-footer>
                                <fo:table-body>
                                    <fo:table-row>
                                        <fo:table-cell border="1.8PT solid" display-align="center" font-size="16pt" keep-together.within-page="always" number-columns-spanned="2" number-rows-spanned="2" padding-bottom="1.5mm" padding-left="1mm" padding-top="1.5mm">
                                            <fo:wrapper>
                                                <fo:marker marker-class-name="continuedArrow">
                                                    <fo:instream-foreign-object>
                                                        <svg:svg height="6.7mm" width="2mm">
                                                            <svg:path d="M 2.1634084,0 2.1462333,10 0,10 3.4375,27.5312 6.90625,10 4.6604758,10.02932 4.7484349,-0.0293197 Z" style="black"/>
                                                        </svg:svg>
                                                    </fo:instream-foreign-object>
                                                </fo:marker>
                                            </fo:wrapper>
                                            <fo:block hyphenate="false" keep-together.within-page="10">
                                                <fo:wrapper>
                                                    <fo:marker marker-class-name="bottomContinued">
                                                        CLEFIEJOD...
                                                    </fo:marker>
                                                </fo:wrapper>
                                                LE GRLJED?
                                                <fo:wrapper>
                                                    <fo:marker marker-class-name="topContinued">
                                                        ...CLEFIEJOD
                                                    </fo:marker>
                                                </fo:wrapper>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell border-bottom="1.8PT solid black" padding-left="1.90mm">
                                            <fo:block font-size="10pt" font-weight="bold">
                                                No
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell/>
                                        <fo:table-cell/>
                                    </fo:table-row>
                                    <fo:table-row>
                                        <fo:table-cell padding-left="2mm">
                                            <fo:block font-size="6pt" font-weight="bold">
                                                #S1-
                                                <fo:page-number-citation-last ref-id="REF-0096579-CDT-6ADJWTA"/>
                                                #
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell border-top="1.8PT solid black"/>
                                        <fo:table-cell border-right="1.8PT solid black" border-top="1.8PT solid black"/>
                                    </fo:table-row>
                                    <fo:table-row keep-with-next="10" keep-with-previous.within-page="always">
                                        <fo:table-cell padding-left="3mm">
                                            <fo:block left="-0.57mm" position="relative" top="-0.68mm">
                                                <fo:instream-foreign-object>
                                                    <svg:svg height="6.7mm" width="2mm">
                                                        <svg:path d="M 2.1634084,0 2.1462333,10 0,10 3.4375,27.5312 6.90625,10 4.6604758,10.02932 4.7484349,-0.0293197 Z" style="black"/>
                                                    </svg:svg>
                                                </fo:instream-foreign-object>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell padding-left="1mm" padding-top="2mm">
                                            <fo:block-container height="10pt">
                                                <fo:block font-size="10pt" font-weight="bold">
                                                    Yes
                                                </fo:block>
                                            </fo:block-container>
                                        </fo:table-cell>
                                        <fo:table-cell/>
                                        <fo:table-cell/>
                                        <fo:table-cell border-right="1.8PT solid black"/>
                                    </fo:table-row>
                                    <fo:table-row>
                                        <fo:table-cell number-columns-spanned="4" padding-left="3mm">
                                            <fo:block>
                                                <fo:block-container>
                                                    <fo:block-container keep-with-next="always" margin-left="1mm" margin-right="1mm">
                                                        <fo:block-container margin="0mm">
                                                            <fo:block font-size="16pt" font-weight="bold" hyphenate="false" keep-with-next="always" text-align="justify">
                                                                Aftpr CRG ATF (TWD) TIROX PL ARM mpsseqp is aisvleypa eha tgp essubietpa Cerqu
                                                                Tirp Ovtihqoisgihq Bottuh is illomihetpa:
                                                            </fo:block>
                                                        </fo:block-container>
                                                    </fo:block-container>
                                                    <fo:block-container margin-left="2mm" margin-right="2mm">
                                                        <fo:block-container margin="0mm">
                                                            <fo:block keep-together.within-page="10">
                                                                <fo:table font-size="16pt" width="100%">
                                                                    <fo:table-column column-number="1" column-width="60%"/>
                                                                    <fo:table-column column-number="2" column-width="40%"/>
                                                                    <fo:table-body>
                                                                        <fo:table-row keep-together.within-page="always" keep-with-next="always">
                                                                            <fo:table-cell padding-bottom="1mm" padding-top="1mm">
                                                                                <fo:block margin-right="0.1cm" start-indent="0.1em" text-align-last="justify" text-align="left" text-indent="-0.1em">
                                                                                <fo:block hyphenate="false" keep-together.within-page="10">
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="bottomContinued">
                                                                                CLEFIEJOD...
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                <fo:block text-align-last="justify">
                                                                                <fo:inline keep-with-next.within-line="always">
                                                                                Assubietpa Cerqu Tirp Ovtihqoisgihq Bottuh
                                                                                </fo:inline>
                                                                                <fo:leader leader-length.minimum="5mm" leader-pattern="dots"/>
                                                                                </fo:block>
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="topContinued">
                                                                                ...CLEFIEJOD
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                </fo:block>
                                                                                </fo:block>
                                                                            </fo:table-cell>
                                                                            <fo:table-cell/>
                                                                        </fo:table-row>
                                                                        <fo:table-row keep-together.within-page="always" keep-with-next="always">
                                                                            <fo:table-cell/>
                                                                            <fo:table-cell padding-before="-1.32em">
                                                                                <fo:block display-align="after" start-indent="0.1em" text-indent="-0.1em">
                                                                                <fo:block hyphenate="false" keep-together.within-page="10">
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="bottomContinued">
                                                                                CLEFIEJOD...
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                <fo:block keep-together.within-page="always" vertical-align="bottom">
                                                                                AS ROQJIROD
                                                                                </fo:block>
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="topContinued">
                                                                                ...CLEFIEJOD
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                </fo:block>
                                                                                </fo:block>
                                                                            </fo:table-cell>
                                                                        </fo:table-row>
                                                                    </fo:table-body>
                                                                </fo:table>
                                                            </fo:block>
                                                        </fo:block-container>
                                                    </fo:block-container>
                                                </fo:block-container>
                                                <fo:block font-size="16pt" keep-together.within-page="always">
                                                    <fo:table>
                                                        <fo:table-column column-width="19mm "/>
                                                        <fo:table-column/>
                                                        <fo:table-body>
                                                            <fo:table-row>
                                                                <fo:table-cell padding-bottom="1.5mm" padding-top="1.5mm">
                                                                    <fo:block font-weight="bold">
                                                                        <fo:inline>
                                                                            ELFO
                                                                        </fo:inline>
                                                                        :
                                                                    </fo:block>
                                                                </fo:table-cell>
                                                                <fo:table-cell padding-bottom="1.5mm" padding-top="1.5mm">
                                                                    <fo:block text-align="justify">
                                                                        <fo:block font-size="16pt" keep-together.within-page="always">
                                                                            <fo:table>
                                                                                <fo:table-column column-width="0mm"/>
                                                                                <fo:table-column column-width="5mm"/>
                                                                                <fo:table-column/>
                                                                                <fo:table-body>
                                                                                <fo:table-row>
                                                                                <fo:table-cell/>
                                                                                <fo:table-cell padding-bottom="1mm">
                                                                                <fo:block text-align="left">–</fo:block>
                                                                                </fo:table-cell>
                                                                                <fo:table-cell padding-bottom="1mm">
                                                                                <fo:block>
                                                                                <fo:block hyphenate="false" keep-together.within-page="10">
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="bottomContinued">
                                                                                CLEFIEJOD...
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                <fo:block keep-together.within-page="always" text-align="justify">
                                                                                Aazisp Gruoha Crpw uf vussiclp Heluh zevurs eftpr aisbgerqihq tgp pvtihqoisgihq
                                                                                cuttlp.
                                                                                </fo:block>
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="topContinued">
                                                                                ...CLEFIEJOD
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                </fo:block>
                                                                                </fo:block>
                                                                                </fo:table-cell>
                                                                                </fo:table-row>
                                                                                </fo:table-body>
                                                                            </fo:table>
                                                                            <fo:table>
                                                                                <fo:table-column column-width="0mm"/>
                                                                                <fo:table-column column-width="5mm"/>
                                                                                <fo:table-column/>
                                                                                <fo:table-body>
                                                                                <fo:table-row>
                                                                                <fo:table-cell/>
                                                                                <fo:table-cell padding-bottom="1mm">
                                                                                <fo:block text-align="left">
                                                                                –
                                                                                </fo:block>
                                                                                </fo:table-cell>
                                                                                <fo:table-cell padding-bottom="1mm">
                                                                                <fo:block>
                                                                                <fo:block hyphenate="false" keep-together.within-page="10">
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="bottomContinued">
                                                                                CLEFIEJOD...
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                <fo:block keep-together.within-page="always" text-align="justify">
                                                                                Aftpr tgp cuttlp aisbgerqp eha witg tgp eirvlehp uh qruoha, tgp mpsseqp CRG TWD
                                                                                (ATF) TIRO SYS TAIP will evvper.
                                                                                </fo:block>
                                                                                <fo:wrapper>
                                                                                <fo:marker marker-class-name="topContinued">
                                                                                ...CLEFIEJOD
                                                                                </fo:marker>
                                                                                </fo:wrapper>
                                                                                </fo:block>
                                                                                </fo:block>
                                                                                </fo:table-cell>
                                                                                </fo:table-row>
                                                                                </fo:table-body>
                                                                            </fo:table>
                                                                        </fo:block>
                                                                    </fo:block>
                                                                </fo:table-cell>
                                                            </fo:table-row>
                                                        </fo:table-body>
                                                    </fo:table>
                                                </fo:block>
                                            </fo:block>
                                            <fo:block keep-with-previous.within-page="always" padding-bottom="2mm" padding-top="2mm">
                                                <fo:inline axf:border-radius="200pt" background-color="black" border="1pt solid black" color="white" font-weight="bold" padding-bottom="1mm" padding-left="1mm" padding-right="1mm" padding-top="1mm" text-align="center">
                                                    OED
                                                </fo:inline>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell border-right="1.8PT solid black"/>
                                    </fo:table-row>
                                    <fo:table-row keep-with-previous.within-page="always">
                                        <fo:table-cell/>
                                        <fo:table-cell border-bottom="1.8PT solid black" number-columns-spanned="3">
                                            <fo:wrapper>
                                                <fo:marker marker-class-name="bottomContinued">
                                                    CLEFIEJOD...
                                                </fo:marker>
                                            </fo:wrapper>
                                        </fo:table-cell>
                                        <fo:table-cell border-bottom="1.8PT solid black" border-right="1.8PT solid black" height="3mm">
                                            <fo:wrapper>
                                                <fo:marker marker-class-name="topContinued">
                                                    ...CLEFIEJOD
                                                </fo:marker>
                                            </fo:wrapper>
                                        </fo:table-cell>
                                    </fo:table-row>
                                    <fo:table-row keep-with-previous.within-page="always">
                                        <fo:table-cell/>
                                        <fo:table-cell>
                                            <fo:block left="-0.57mm" position="relative" top="-0.68mm">
                                                <fo:instream-foreign-object>
                                                    <svg:svg height="6.7mm" width="2mm">
                                                        <svg:path d="M 2.1634084,0 2.1462333,10 0,10 3.4375,27.5312 6.90625,10 4.6604758,10.02932 4.7484349,-0.0293197 Z" style="black"/>
                                                    </svg:svg>
                                                </fo:instream-foreign-object>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell/>
                                        <fo:table-cell>
                                            <fo:wrapper>
                                                <fo:marker marker-class-name="continuedArrow"/>
                                            </fo:wrapper>
                                        </fo:table-cell>
                                    </fo:table-row>
                                </fo:table-body>
                            </fo:table>

A: Table cells generally take as much space as they need but no more, so they generally don't extend to the bottom of the page when the table breaks over a page.

*

*You may be able to do things with change-bars to put a change-bar down the side and have a second change-bar with the graphic for the arrowhead.

*You may be able to have a right-hand column that contains a graphic for a page-height arrow and rely on overflow to truncate the graphic to the right height.  You'd have to work with max-height or block-progression-dimension.maximum to get the table cell to extend to the bottom of the page.  The right-angle bend in the arrow could be difficult, but you might be able to do that by putting a small graphic for the right-angle in a separate table cell.

*You might be able to use an fo:leader inside an fo:block-container or fo:inline-container that has reference-orientation="270".  The leader pattern (and content of the fo:leader) would be a graphic for a segment of the line of the arrow.  The fo:leader would be followed by a graphic for the arrowhead.

*You may be able to use fo:marker and fo:retrieve-table-marker to put a graphic for the arrowhead in the fo:table-footer only when required.  The fo:table-cell (or fo:table-row) that needs the arrowhead would set the fo:marker, and the fo:table-cell in the following fo:table-row would set an emptyfo:marker` so that the arrowhead isn't repeated.

*You may be able to float an image for the arrow to the right, but getting it to be the correct length could be tricky.
If you can provide some sample FO markup, we may be able to provide a more specific answer.


text:
Q: Why prettier is ignoring only semicolon rule in my config? I have been trying to resolve this for quite a while now: I am using a settings.json file that sits in .vscode directory in the root of my project to configure prettier. All of the rules works except the "prettier.semi": false.
settings.json :
{
  "editor.formatOnSave": true,
  "explorer.compactFolders": false,
  "prettier.arrowParens": "avoid",
  "prettier.jsxSingleQuote": true,
  "prettier.singleQuote": true,
  "prettier.tabWidth": 2,
  "prettier.trailingComma": "none",
  "prettier.semi": false
}

Any ideas what can be overriding it?
Thanks!


text:
Q: how to use pattern "EEEE, MMMM d" with locale to convert to local format For example:
DateTimeFormatter dtfr = DateTimeFormatter.ofPattern("EEEE, MMMM d", locale);
return dtfr.format(localDate);

The result is (locale is Germany):
Expected :Samstag, 28. Mai
Actual   :Samstag, Mai 28

If I use
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
return dtf
            .withLocale(locale)
            .format(localDate1);

The result is:
Expected :Samstag, 28. Mai
Actual   :Samstag, 28. Mai 2016

I can't replace the year to "" simply, because the other language may have different word to describe year.
So how could I use DateTimeFormatter(not SimpleDateFormat) to make it to work?


text:
Q: How do I make a dictionary of zeroes in KDB? Say I've got a (long) list of keys:
`a`b`c

How do I make a dictionary where every value is zero?

A: If your list is saved as a variable, this can be achieved with the count keyword. For example
q)c:`a`b`c
q)c!(count c)#0
a| 0
b| 0
c| 0

will return your dictionary of zeroes.

A: If you have a blank (or existing) dictionary you can assign 0 to all of your keys:
q)c:`a`b`c
q)d:()!()
q)d[c]:0
q)d
a| 0
b| 0
c| 0

A: Just to add one more option, can also use each-right \: with assign : to do this:
q)(`a`b`c!()):\:0
a| 0
b| 0
c| 0

A: If 0 is a default value, you could also use fill when indexing into it:
q)d:`a`b`c!til 3
q)d[`d]
0N
q)0^d[`d]
0


text:
Q: How to force a function to broadcast without invoking `np.vectorize` I want to look for a way to force a function to broadcast.
There are scenarios in which the function/method may be overwritten in a later instance, to constant function. In such case if
arr = np.arange(0, 1, 0.0001)
f = lambda x: 5
f(arr) # this gives just integer 5, i want [5, 5,..., 5]

I am aware of methods like np.vectorize which force the function to broadcast, but the problem is this is inefficient, as it is essentially for loop under the hood. (see documentation)
We can also use factory methods like np.frompyfunc which allows us to transform python function to numpy universal function ufunc See here for instance. This outperformed np.vectorize, but still is way less efficient than builtin ufunc methods.
I was wondering if there is any efficient numpy way of handling this, namely to force the function to broadcast?

A: If there was a better way to make arbitrary Python functions broadcast, numpy.vectorize would use it. You really have to write the function with broadcasting in mind if you want it to broadcast efficiently.
In the particular case of a constant function, you can write a broadcasting constant function using numpy.full:
def f(x):
    return numpy.full(numpy.shape(x), 5)

numba.vectorize can also vectorize functions more effectively than numpy.vectorize, but you need Numba, and you need to write your function in a way that Numba can compile efficiently.

A: For those who can live without generic answer, the best answer would be np.full_like(arr, val) which improves by about 20% than np.full(arr.shape, val)
And after raising this issue to author, I found some best middle ground which achieves both generality while perform rather well:
np.broadcast_arrays(x, f(x))[1]
and here are some time analysis:
arr = np.arange(1, 2, 0.0001).reshape(10, -1)

def master_f(x): return np.broadcast_arrays(x, f(x))[-1].copy('K')
def master_f_nocopy(x): return np.broadcast_arrays(x, f(x))[-1]
def vector_f(x): return np.vectorize(f)(x)

%timeit arr+1 # this takes about 10microsec
%timeit master_f(arr) # this takes about 40 mircrosec
%timeit master_f_nocopy(arr) # this takes about 20 microsec

Note this allows one to apply to projection functions such as f(x,y):=y, which is beyond the help of np.full_like.
Moreover, when it comes more complicated function like np.sin and np.cos you'll notice the difference between f(arr) and master_f_nocopy(arr) is almost negligible.


text:
Q: Get values from select multiple and get them in to database What is the best way to get the all values of one multiple select box, and then i want to save those values in one row in the database, then from that row i want to get each value separate. What is the best way to do such a thing ? My goal is to save the values and then get each separate.

A: You could do it this way
<select name="foo[]" multiple="multiple">
     <option value="dog">Dog</option>
     <option value="cat">Cat</option>
     <option value="fish">Fish</option>
</select>

<?php

$pets = $_POST['foo'];

//sanitize and verify the input here. Escape properly and what not

$query = mysql_query("INSERT INTO `pets` (`pet1`, `pet2`, `pet3`) VALUES ('".$pets[0]."', '".$pets[1]."',  '".$pets[2]."')");
?>

But to be honest it's an awful way to go about building a database. It'll be very annoying or difficult to do anything meaningful with.
Why not have the following database setup:
users:
id | name
----------
 1 | Tim

pets:
id | user_id | type
-------------------
1  | 1       | Fish
2  | 1       | Cat
3  | 4       | Kakapo

And then you would have a much more easily searchable and manipulatable database that's consistent.

A: I believe you should receive the value selected as an array in the $_POST variable so say your select has a name="products"
The values selected will be in $_POST["products"] assuming you are submitting the form via POST.
Then you can use the implode function to generate a string. For example:
$myProducts = implode("|", $_POST["products"]); //This will give you a pipeline delimeted string like : computer|laptop|monitor

$myProducts = mysql_real_escape_string($myProducts); //Just to santize before inserting in DB

Then just insert that string into the DB.
When retrieving the data you can reverse the process by using the explode function:
$myProducts = explode("|" , [The value retrieved from the database]); //This will give you an array which you can iterate and thus accessing the values individually.

Hope this helps :)

A: if i understand your question well...
$dataFromMultipleBox = array('data1', 'data2', 'data3');
$data = implode("||", $dataFromMultipleBox);

/*
After that,
write $data into database

fetch from the database again
*/

$pieces = explode("||", $rowFromDatabase);

foreach($pieces as $value) {
  echo $value;
  echo '<br>';
}

A:
What is the best way to get the all values of one multiple select box,

Since it is PHP. Give the select element a name ending in [], then you can access them as $_POST['foo'][]

and then i want to save those values in one row in the database, then from that row i want to get each value separate.

Don't do that. Have a second table with two columns. The id (as a foreign key) of the row in the other table (where you were planning to store the data) and the value itself.


text:
Q: check mysql column in table for duplicates in php I am trying to check the username column for duplicates and if one is found, "username is taken"should echo. no matter what is input as a username "username is ok" is always echoed... what is causing this and how can i change it?
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT * FROM riders WHERE username='$username' LIMIT 1";
$query = mysqli_query($connect, $sql);
$uname_check = mysqli_num_rows($query);
if ($uname_check == 0) {
    echo '' . $username . ' is OK';
    exit();
} else {
    echo '' . $username . ' is taken';
    exit();
}

A: Let's debug it the right way. When your code doesn't work you debug it; not just guess things. And to Debug MySQL issues from PHP you have to look at what values are returnedby those functions? and not just expect the best case scenario. Computer Science is not guess work, its pretty accurate for most things.
Step 1:
   // $connect = mysqli_connect("localhost", "my_user", "my_password", "world");

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

Step 2:
    $username=mysqli_real_escape_string($connect,$username);
    $sql = "SELECT 1 FROM riders WHERE username='$username' LIMIT 1";
    if ($result=mysqli_query($connect, $sql)) {
     $uname_check=mysqli_num_rows($result);
    }
    else
    {
     printf("Error message: %s\n", mysqli_error($connect));
    }

Step 3:
    echo intval($uname_check);

By the time you reach here, you will know exactly what is wrong.
After that you can continue with your if
if ($uname_check == 0)
{
    echo '' . $username . ' is OK';
}
else
{
    echo '' . $username . ' is taken';
}
exit();

A: Change the logic:
$query = mysqli_query($connect, $sql) or die(mysqli_error($connect));

if ($query){
    if($uname_check > 0) {
    {
        echo '' . $username . ' is taken';
        exit();
    } else {
        echo '' . $username . ' is OK';
    }
}
else
{
    echo 'An error occured while querying the new username';
}

And we will be able to understand if your sql query is good.

A: First, try to echo $username before your SQL request to check the value;
Second, try removing LIMIT 1 as this is useless as you do prevent duplicate creation, so it will be 0 or 1 anyway.
Third, try this one: $username=preg_replace("#[^a-z0-9\.]#i", null, $_POST['usernamecheck']);

A: i just found out myself as no answer seemed to help:
$query = mysql_query($sql, $connect);

instead of:
$query = mysql_query($connect, $sql);


text:
Q: Is there an open-jdk-8 version and if so, how can one obtain it? Browsing through the https://openjdk.java.net it's easy to find open-jdk-11 but when you go to equivalent page to download the version 8, the site prompts you to go to Oracle to get a version 8 JDK.

The JDK 8 Early Access Program has concluded. Current versions of JDK
  8 can be found on www.oracle.com/javadownload

Does the open-jdk start at version 9? As this page suggests?

A: At AdoptOpenJDK you can download prebuilt binaries for the current version (OpenJDK 12) and previous LTS versions including OpenJDK 8.


text:
Q: upload image with laravel and ajax I´m trying to upload my img with ajax, and generate one PDF with barryPDF but my problem it´s i have two different img.
for to do this, i´m sendning in my ajax and form_data one parameter and so i distint my img:
function ajaxDNI2(){
    data = new FormData();
    let token = $("meta[name='csrf-token']").attr("content");
    data.append('file', $("#dni2_cliente")[0].files[0]);
    data.append('_token', token);
    data.append('dni_atras', 'dni_atras');

    $(".dni2").addClass('borderClass');

    $.ajax({
        url: document.location.origin+'/admin/precontratos/precontratos/dataClientImages',
        method: 'POST',
        processData: false,
        contentType: false,
        data: data,
        success: function(response){
            progressDni2();
            $("#imageDniClient").attr('src', response);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

in my controller i have my function:
if($request->hasFile('file')){

                if($request->get('dni_delante') == "dni_delante"){
                    $image = $request->file('file');
                    $name = time().'.'.$image->getClientOriginalExtension();
                    $destinationPath = public_path('storage/datosCliente');
                    $image->move($destinationPath, $name);
                }

                if($request->get('dni_atras') == "dni_atras"){
                    $image2 = $request->file('file');
                    $name2 = time().'.'.$image2->getClientOriginalExtension();
                    $destinationPath2 = public_path('storage/datosCliente');
                    $image2->move($destinationPath2, $name2);

                    $pdfName = "documentacion.pdf";
                    $pathSavePdf = public_path('storage/datosCliente');

                    $pdf = PDF::loadView('pdf.dni', ['image' => $name, 'image2' => $name2])
                                    ->setPaper('a4')
                                    ->setOrientation('Portrait')
                                    //->setOption('zoom', 1.2)
                                    ->setOption('footer-center', 'EDICIONES GRUPO DELUXE 2013 S.L.U está Inscripta en el Registro Mercantil de Granada al Tomo 1548 Folio 42 Hoja GR46323 Inscrip. 1ª')
                                    ->setOption('footer-font-size', 5);

                    $pdfCreado = $pdf->save($pathSavePdf, true);
                }

            }

this function upload my img ok, but in my PDF loadView i´m sending my two img. But my problem it´s that return 500 error not defined $name
[2022-04-20 10:53:02] local.ERROR: Undefined variable: name {"userId":60,"exception":"[object] (ErrorException(code: 0): Undefined variable: name at

all my imgs it´s uploaded ok.
Thanks for readme and sorry for my bad english


text:
Q: nativeQuery in JPA I am new to JPA.
I am trying to create a nativequery with 3 joins on 3 tables.
I have written a nativequery which is something like the below:
Query query=entityManager.createNativeQuery("select p.value,m.value,t.value,t.value from ping as p,ming as m,ting as t where p.id=m.vid and m.id=t.vid");

List<Object[]> list = (List<Object[]>) query.getResultList();

I have 3 tables ping,ming,ting in my database.
I have got syntax error during execution.
check the manual that corresponds to your MySQL server version for the right syntax to use near 'ping as p,ming as m ,ting as t';

Would be helpful if some one can point me the error and What would be the better solution to join different tables over nativequery in JPA.
EDIT:I have successfully run the above query on mysql.

A: 'ping as p,ming as m ,ting as t'
Try to put dot instead coma.
Maybe your syntax is incorrect

A: Some how alias on the column is causing the problem.
I have tried running the program with out alias on the columns and everything is fine.
Found the similar question here.
hibernate native SQL query error


text:
Q: Prolog: two or more Is there in prolog something like 'two or more' (or another option) to make the following shorter ?
rule(foo,  [bar,bar]).
rule(foo,  [bar,bar,bar]).
rule(foo,  [bar,bar,bar,bar]).
rule(foo,  [bar,bar,bar,bar,bar]).

you can read it as: if there is a serie of n bars then assign the tag foo

A: between/3 is probably what you're after:
rule(foo, L) :-
    between(2, 5, N),
    length(L, N),
    maplist(=(bar), L).

A: This is a possibility
rule(foo, Out) :-
    random(2,6,N),
    length(Out,N),
    maplist(=(bar),Out).


text:
Q: Proving that a matrix is positive semidefinite Let matrices $A, B$ be positive semidefinite. Can we prove that $A(I+BA)^{-1}$ is positive semidefinite?

A: By density, it is enough to prove the property when $A$ is positive definite. Then
$$A(I+BA)^{-1}=A^{1/2}(I+A^{1/2}BA^{1/2})^{-1}A^{1/2}$$
is congruent to $(I+A^{1/2}BA^{1/2})^{-1}$, which itself is positive definite because $I+A^{1/2}BA^{1/2}\succeq I$.

A: Consider the change of basis $C^tA(I+BA)^{-1}C$ for $C=I+BA$. One gets $A+ABA$, which is positive semidefinite being a some of two positive semidefinite.
The most difficult part is to show that $I+BA$ is invertible. If not, then let $v$ be in its kernel. By taking the scalar product with $Av$, one gets that $v$ must be in the kernel of $A$, which implies $v=0$.


text:
Q: Sudo apt install doesn't work.My packages is broken I'm currently using Ubuntu 20.04 LTS.
I'm having way too many issues with my computer right now, but I will start with trying to fix my WiFi. So I tried to install net-tools, but then this happened.
    patrick@patrick-Swift-SF315-51G:~$ sudo apt install net-tools
[sudo] password for patrick:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 libc6-dbg : Depends: libc6 (= 2.31-0ubuntu9.2) but 2.31-0ubuntu9.1 is to be installed
 libc6-dev : Depends: libc6 (= 2.31-0ubuntu9.2) but 2.31-0ubuntu9.1 is to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

I tried this: apt --fix-broken install & apt-get -f install - received the same answer.
patrick@patrick-Swift-SF315-51G:~$ apt --fix-broken install
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

I also have received a notification from my Package Manager:
The package system is broken
Check if you are using third party repositories. If so, disable them since they are a common source of problems.
Furthermore, run the following command in a Terminal: apt-get install -f
The following packages have unmet dependencies:
  libc6-dbg: Depends: libc6 (= 2.31-0ubuntu9.2) but 2.31-0ubuntu9.1 is installed
    libc6-dev: Depends: libc6 (= 2.31-0ubuntu9.2) but 2.31-0ubuntu9.1 is installed
               Depends: libc-dev-bin (= 2.31-0ubuntu9.2) but 2.31-0ubuntu9.2 is installed

So my question is, how can I fix the broken packages and use Sudo apt-get install again?
Thank you for your time.
Edit:
I tried sudo apt-get clean & sudo apt-get update
Then I tried Sudo apt-get -f install, same result.
    Errors were encountered while processing:
 /var/cache/apt/archives/libc6_2.31-0ubuntu9.2_amd64.deb
 /var/cache/apt/archives/libc6_2.31-0ubuntu9.2_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I also tried to sudo dpkg --configure -a; and received this
dpkg: dependency problems prevent configuration of libc6-dbg:amd64:
 libc6-dbg:amd64 depends on libc6 (= 2.31-0ubuntu9.2); however:
  Version of libc6:amd64 on system is 2.31-0ubuntu9.1.

dpkg: error processing package libc6-dbg:amd64 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libc6-dev:amd64:
 libc6-dev:amd64 depends on libc6 (= 2.31-0ubuntu9.2); however:
  Version of libc6:amd64 on system is 2.31-0ubuntu9.1.

dpkg: error processing package libc6-dev:amd64 (--configure):
 dependency problems - leaving unconfigured
Processing triggers for libc-bin (2.31-0ubuntu9.1) ...
Errors were encountered while processing:
 libc6-dbg:amd64
 libc6-dev:amd64

A: Try the following workflow

sudo apt-get clean

sudo apt-get update

sudo apt-get -f install

sudo dpkg --configure -a


text:
Q: MongoDB write concern for strong consistent I have Java processes to update MongoDB 3.6.0. I have 1 - primary, 2 replicas. The flow is

*

*Update some data in a document having a specific "_id"

*Read from replicas
Sometimes, read gets an older version of the document.We decided to use WriteConcern to address this -
WriteConcern(WriteConcern.W3.withWTimeout(100, TimeUnit.MILLISECONDS).withJournal(false));

With the introduction of WriteConcern there will be some latency and to avoid too much latencies i skipped updating the Journal log
Is the above config going to work ?

A: This is a high level view of the writing process:

*

*Data is written to a snapshot,

*from snapshot to journal ~0.1s

*from snapshot to disk 1s

If you set up writeConcern = 3, and one server goes down, the user will never get an acknowledgment.
Also, disabling journaling won't fasten replication. I recommend to use writeConcern majority, and keep journal. But if you prefer to disable journaling, then the only problem would be data written between that 1s in 3.


text:
Q: How to remove a file that start with ">" or other unusual characters I've accidentally created a file called
> option[value='2016']

How can I delete it?
My attempts:

$ rm "> option[value='2016']"
rm: cannot remove '> option[value='2016']': No such file or directory
$ rm \> o*
rm: cannot remove '>': No such file or directory
rm: cannot remove 'o*': No such file or directory
$ rm `> o*`
rm: missing operand
Try 'rm --help' for more information.
$ rm \> option*
rm: cannot remove '>': No such file or directory
rm: cannot remove 'option*': No such file or directory
$ rm '\> option*'
rm: cannot remove '\\> option*': No such file or directory
$
$ rm "\> option*"
rm: cannot remove '\\> option*': No such file or directory

File listing:
HAPPY_PLUS_OPTIONS/
o*
op*
> option[value='2016']
> option[value='ALFA ROMEO']
README.md
rspec_conversions/
.rubocop.yml
SAD/
SAD_PLUS_OPTIONS/

A: You can also use the "--" option which according to man:
 The rm command uses getopt(3) to parse its arguments, which allows it to
 accept the `--' option which will cause it to stop processing flag options at
 that point.  This will allow the removal of file names that begin with a dash
 (`-').  For example:
       rm -- -filename

So I tried:
touch -- "> option[value='2016']"

And removed it with:
rm -- "> option[value='2016']"

Easiest way to check if the filename was correctly entered:
rm -- ">[tab]

And let auto-complete do the job.
PS: As tempting as it sounds, don't create a file name "-rf *". Bad things may happen.
-rw-r--r--    1 stephan  staff      0 Sep 13 14:11 -rf *

Always use "-i" to be safe.
iMac:~ stephan$ rm -i -- "-rf *"
remove -rf *? Y

A: The initial problem was a leading space, thus
rm " > option[value='2016']"
    ^ here

works.
Updated the question to be about files starting with > etc.

A: For an interactive approach (often safer):
If there are some special named files in current directory.
You can use rm ./ and then TabTab to list files and then you can select the file and delete it.

A: another option
ls -i

which give (with proper inode value)
5233 > option[value='2016']   5689 foo

then
find . -inum 5233 -delete

optionnaly (to preview)
find . -inum 5233 -print

you can also add -xdev if there is another filesystem beneath .

A: For rm, there's nothing magical about >. You only need to make sure the angle bracket gets to it (=prevent the shell from interpretting it as a redirection).
> "> option[value='2016']"  #create it
rm "> option[value='2016']" #remove it

#remove all files in the current directory that have > in them
rm -- {,.}*\>*

If you're on a sensible modern system, you should be able to get properly escaped names with tab completion.


text:
Q: WooCommerce - how to retrieve current orderby/sorting selection? I need to retrieve the current order of products (as ids) on the shop page for further use. Sorting is done via the standard dropdown (date, price: low to high, price: high to low).
Using $orderby, I can manage this for date and price ASC. But the value of $orderby is the same for price ASC and DESC. How can I correctly retrieve the current value for each sorting option?
if ($orderby == 'date ID') {
  $ordertype = 'date';
  $meta = '';
  $order = 'desc';
}
elseif ($orderby == 'price')  {
  $ordertype = 'meta_value_num';
  $meta = '_price';
  $order = 'asc';
}

$query = new WC_Product_Query( array(
 'limit' => -1,
 'orderby'        => $ordertype,
 'meta_key'       => $meta,
 'order'          => $order,
 'return'         => 'ids',
) );

$products = $query->get_products();

print_r($products);

A: I think your standard dropdown needs to be in this order.
HTML
<select>
    <option value="date">Date</option>
    <option value="low_to_high">Low to High</option>
    <option value="high_to_low">High to Low</option>
</select>

and based on selection your condition will be.
PHP
<?php

if ($orderby == 'low_to_high') {
    $ordertype = 'meta_value_num';
    $meta      = '_price';
    $order     = 'asc';
}elseif ($orderby == 'high_to_low') {
    $ordertype = 'meta_value_num';
    $meta      = '_price';
    $order     = 'desc';
}else{
    $ordertype = 'date';
    $meta      = '';
    $order     = 'desc';
}

$query = new WC_Product_Query( array(
    'limit'    => -1,
    'orderby'  => $ordertype,
    'meta_key' => $meta,
    'order'    => $order,
    'return'   => 'ids',
) );

$products = $query->get_products();

print_r($products);

?>


text:
Q: How to add new functions to ng-blur in the controller? I want to add a new function to the ng-blur of all input/textarea fields.
The input fields and textarea's has a existing ng-blur in the html and I want to add a new function to the existing ng-blur within the controller.
I tried to add it with setAttribute, but that override the existing ng-blur functions.
const formElems= iElem[0].querySelectorAll('input, textarea');
formElems[0].setAttribute('data-ng-blur', 'newFunction()');
$compile(angular.element(formElems[0]))($scope);

I want to extend the functions inside ng-blur, but not directly in the HTML.
How to add new functions inside the controller to the ng-blur of all input and textarea's and keep the current functions?

A: You don't need to do anything in your template.
Just create a new function in your controller and call this function from already exists function. It will not break your existing functionality.
See example below -

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName= "John";
  $scope.lastName= "Doe";

  $scope.myFunction = function(){
    console.log('Your current working code');
    $scope.extendedFunction();
  }

  $scope.extendedFunction = function(){
    console.log('You should write your new code here');
  }

});

First Name: <input type="text" ng-model="firstName" ng-blur="myFunction();">

Last Name: <input type="text" ng-model="lastName" ng-blur="myFunction();">

Full Name: {{firstName + " " + lastName}}

A: Finally, I found a solution by getting the existing attribute first by using getAttribute().
const oldAttributes = formElems[0].getAttribute('ng-blur');
formElems[0].setAttribute('ng-blur', oldAttributes + ' testConsole();');


text:
Q: Quickbooks authentication error - Java SDK Quickbooks v3.0 This is my first attempt to work with Quickbooks API. To get started with it I wanted to try few API calls.
I have already created account on Quickbooks and got the following credentials -
consumerKey
consumerSecret
accessToken
accessTokenSecret
appToken
companyId

Downloaded IPP java sdk for QuickBooks v3.0 and the from the downloaded package, I am currently using the following jar files -
ipp-v3-java-devkit-2.3.2-jar-with-dependencies.jar
ipp-java-qbapihelper-1.2.0-jar-with-dependencies.jar

Here is the code which I am executing.
import com.intuit.ipp.core.Context;
import com.intuit.ipp.core.ServiceType;
import com.intuit.ipp.data.Customer;
import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.security.OAuthAuthorizer;
import com.intuit.ipp.services.DataService;

 public class TestQuickBooks {
  public static void main(String[] args)
   throws FMSException
   {
    // following credentials are replaced with my original credential
    // when executing the code
    String consumerKey = "...";
    String consumerSecret = "...";
    String accessToken = "...";
    String accessTokenSecret = "...";
    String appToken = "...";
    String companyId = "...";

    try {
      OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey,
                                                  consumerSecret,
                                                  accessToken,
                                                  accessTokenSecret);
      Context context = new Context(oauth,
                                    appToken,
                                    ServiceType.QBO,
                                    companyId);
      DataService service = new DataService(context);

      Customer customer1 = new Customer();
      customer1.setDisplayName("ABCD");

      // this is the line which is throwing exception
      Customer resultCustomer = service.add(customer1);

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

copying the exception message here --
com.intuit.ipp.exception.AuthenticationException: ERROR CODE:3200, ERROR MESSAGE:message=ApplicationAuthenticationFailed; errorCode=003200; statusCode=401, ERROR DETAIL:null

I am checking Quickbooks documentation but can't figure out what is causing this authentication exception. As for the credentials, I have double checked it and those are correct.
I found that Quickbooks has an API playground but no luck with this as well.
Tried this API call -
https://appcenter.intuit.com/api/v1/PingSecure

I provided my credentials and specified format as JSON and no url parameter.
it is returning the following message -
{
    "ErrorMessage": "This API requires Authorization.",
    "ErrorCode": 22,
    "ServerTime": "/Date(1412166272838)/"
}

My hope was api playground shouldn't return authentication error since my credentials were correct. However the only way I can see api calls is when I log in to the API explorer
I am not really sure what is missing here - can't make an API call from API playground and also programmatically using Java SDK.

A: Please add the below property:
Config.setProperty(Config.BASE_URL_QBO,"https://sandboxquickbooks.api.intuit.com/v3/company");

before:
DataService service = new DataService(context);

This worked for me.

A: 401 suggests 'authentication' error.
Please refer this post, where I've mentioned how to call QBO V3 endpoints, using any standard Restclient.
InvalidTokenException: Unauthorized-401
If you see a 401 exception again, then please generate a new set of accessToken and accessSecret using OAuthPlayground tool and use those in Java devkit.


text:
Q: How to forbid forwarding packets to private network addresses via interface On my server, I have a default route to interface eth0. It has public internet address and faces ISP network. I have packet forwarding enabled, and few local interfaces/bridges with private 10.x.x.x addresses. Also, all packages that are outgoing to ISP network is masqueraded. The problem: if I understand correctly, any packet to non-existent 192.168.x.x address will be forwarded through public server interface (uplink) to my ISP. That is not desired.
How can I configure linux to prevent forwarding any packets with private network address destination through a public network interface? I guess just adding a single iptables rule would not be enough because there are multiple standard private network spaces (10.x.x.x, 192.16.x.x, 172.16.x.x and maybe others. Also ipv6 addresses aside). Is there any iptables plugin/system policy to accomplish that? I'd expect some system policy to mark the interface as uplink that faces internet.
Reasoning: my ISP does not like any packages with private network range destinations. I'm using a DNS server that is accessed through VPN to my work. So when VPN goes down, my ISP gets DNS requests to private network addresses and locks down the entire internet connection. They say that is done for security (just for the case if some virus overwrites my system DNS to a custom one).

A: You have one publicly-numbered interface eth0, which is your default route, and you don't want any traffic forwarded from any privately-numbered interfaces out the public one.  Try
iptables -A FORWARD -o eth0 -j REJECT

Getting the rule in the right place in your FORWARD chain is left as an exercise.  You should be able to generalise to ipv6 from there, also.
Edit: you can turn off all v4 forwarding with echo 0 > /proc/sys/net/ipv4/ip_forward, and all v6 forwarding with echo 0 > /proc/sys/net/ipv6/conf/all/forwarding.  But you didn't say you wanted all forwarding off, just forwarding "from or to private network addresses through a public network interface".  I'm not aware of any /proc structure to disable the forwarding of RFC1918 traffic only, and I'd be surprised if there were one.

A: Any packet that doesn't match a routing rule on the system will be directed to the default route, if there is any. By default, if you have an IP assigned on a given network a routing rule will be added automatically forwarding that traffic to the assigned interface. If your server is not on these networks you want to block, then it's a good idea to check whatever is generating that traffic in order to get rid of it completely, otherwise you'll still have it bothering you on your local network devices.
The IANA private network IP ranges are pretty well defined and only 4, as can be seen even on this wikipedia article. I suggest you add firewall outbound blocking rules to these network ranges, as destinations, after allowing the ranges you actually use.
Example iptables commands:
iptables -A FORWARD -d 10.0.0.0/8 -j REJECT
iptables -A FORWARD -d 172.16.0.0/12 -j REJECT
iptables -A FORWARD -d 192.168.0.0/16 -j REJECT
ip6tables -A FORWARD -d fd00::/8 -j REJECT

Note: Traffic destined to these ranges is dropped on ISPs, as they will have nowhere to forward it to. Some, however, may impose restrictions on your traffic if you leak these packages.
Also if you fear traffic inspection or leakage on the ISP level this is far from the only thing you need to do to secure yourself.


text:
Q: AngularJS : using Two.js, Cannot read property 'appendChild' of null I want to create an edit polygon using AngularJS : i used this function  but i have error :Cannot read property 'appendChild' of null.
Controller AngularJS  :
  var two = new Two({ type: Two.Types.svg }).appendTo(document.getElementById("ImgCamera"));
    var polygon = new Two.Polygon(10,10,5,4)
    $scope.drawWheel = function () {
        var center_X = 420;
        var center_Y = 140;
        var radius = 100;
        var ellipse = $scope.two.makeEllipse(center_X, center_Y, radius, radius);
        ellipse.linewidth = 0;
        ellipse.fill = "#66BB6A";
        var spoke_color = "#FF5722";
        var x1 = center_X;
        var y1 = center_Y;
        for (var i = 0; i < self.spokes; i++) {
            var x2 = x1 + radius * Math.cos(i * 5);
            var y2 = y1 + radius * Math.sin(i * 5);
            var line = self.two.makeLine(x1, y1, x2, y2);
            line.linewidth = 3;
            line.stroke = "white";
        }
        self.two.update();
    }

HTML code :


text:
Q: Silverlight Application 5 working and bandwidth I just wanted to confirm, that if a build a silverlight application and the whole package including the dll consumed comes to 50 mb and then when user use this application in browser then does all the 50 mb app gets transfered over web? If yes then does there is any workaround for it?

A: Yes, the entire XAP file including the DLL(s) you have included will have to be downloaded. It is however possible to use the application library caching technique to make the download more efficient.
By checking the Reduce XAP size by using application library caching checkbox in the project Properties window, Silverlight tab, only the assemblies required at startup will be downloaded to begin with. Remaining assemblies (parts) are downloaded when required. The assemblies or parts will also be cached on the file system for later retrieval when the user revisits the Silverlight application.


text:
Q: Hash as the value of the checked checkbox, remove if uncheck checkbox JavaScript:
if ($('#mycheckbox').is(':checked')) {
    window.location.hash = this.val();
} else {
    window.location.hash = '';
}

HTML:
<input type="checkbox" name="vehicle" value="Bike">

My problem is, when I checked checkbox my hash cleared and checkbox value add to hash.
I want when checked, checkbox value append to hash and when unchecked, checkbox value remove from hash.

A: First, add the id to your input tag. Then you need to concatenate the input's value to the hash by first getting the current value of hash (window.location.hash). Similarly, when removing, you need to just remove the value part from the hash not the entire hash string.
  <script>
  $(document).ready(function(){
    $("#mycheckbox").on("change", function(){
      if ($('#mycheckbox').is(':checked')) {
        window.location.hash = window.location.hash + $(this).val();
      }
      else {
        window.location.hash = window.location.hash.replace( $(this).val(), '' );
      }
    });//change
  });//document ready
</script>

<input type="checkbox" name="vehicle" id="mycheckbox" value="Bike">

A: <input id="mycheckbox" type="checkbox" name="vehicle" value="Bike"> Bike

<script>
$('#mycheckbox').on('change', function(){
    window.location.hash = this.checked ? window.location.hash + this.value : window.location.hash.replace(this.value,'');
});

</script>


text:
Q: Vuex doesn't detect actions or mutations but detects getters fine I'm trying to set up Vuex in my Vue app.
app.js
require('./bootstrap');

window.Vue = require('vue').default;

import Vuex from "vuex";
Vue.use(Vuex);
import storeData from "./store";

const store = new Vuex.Store(
   storeData
)

Vue.component('home', require('./components/Home.vue').default);

const app = new Vue({
    el: '#app',
    store
});

store.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const state = {
    members: [],
};

export const getters = {
    members: state => () => {
        return state.members;
    }
};

export const actions = {
    async getMembers({ commit, state, dispatch }){
        const res = await this.$axios.get('getMembers');
        const { data } = await res;
        commit('setMembers', data);
    }
};

export const mutations = {
    setMembers(state, members){
        state.members = members;
    },
};

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
});

Home.vue
<template>

Home

                        {{ members }}

</template>

The homepage is showing the "members" getter with on issues. I see it in developer tools as an empty array and if I set it to anything else it will show it. However it is not detecting the actions or mutations if I try to make a mutation. The action for example says: "[vuex] unknown action type: getMembers" Any idea what may be causing this?

A: The store is initialized twice with new Vuex.Store, the constructor is provided with store instance the second time, this results in a bug.
It's store that is exported from store.js, not store data.
It can be:
const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations
});

export default store;

Then it's clear that it's store instance that is exported from store.js.
Vue.use(Vuex) is also called twice, this likely won't cause problems except a warning because Vue plugins usually contain a safeguard against multiple initialization. store.js doesn't need to contain it, it's common to initialize plugins in application entry point.
This is a potential mistake:
require('./bootstrap');

window.Vue = require('vue').default;

import Vuex from "vuex";
...

Imports are hoisted according to specs, this behaviour is setup-dependent but it shouldn't be expected that this code will be evaluated in this order.
Needs to be:
import './bootstrap';
import Vue from "vue";
import Vuex from "vuex";
import store from "./store";

window.Vue = Vue;
...


text:
Q: How to install Disqus on a static website with CSP enabled? How should one proceed if one needs to implement Disqus through the Universal Code option on a website with Content Security Policy (CSP) enabled, e.g. a static website built with Hexo?
According to Mozilla's MDN web docs:

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks.

Because CSP blocks any sort of script tags within HTML files, leaving scripts only to .js files, the suggested implementation of Disqus for Universal Code is not an option.
For example, fontawesome provides specific implementation details of its service for CSP-enabled websites, as can be found here.
Thank you all in advance!


text:
Q: create stored procedure with a 'use' statement i inherited an ms sql server 2008 server application and upon checking the stored procedures, i noticed that they start with a USE [ELECS] statement, ELECS being the database name.
when i tried to recreate one of the stored procedures, what i got was an error saying that a stored procedure cannot have a use statement.

Msg 154, Level 15, State 1, Procedure TESTME, Line 3 a USE database
  statement is not allowed in a procedure, function or trigger.

does ms sql server have a special feature that allows this?

A: There are certain "top level" statements that need to come first in an execution block.  You can cap off/close an execution block with the word GO
So:
USE [db]
GO

CREATE PROC....

If you're talking about a USE statement inside the sproc, then no, you can't do that.  The sproc is already scoped by the DB it was created in.  If you want to access another DB you need to use three-part naming, e.g. ELECS.dbo.tablename assuming dbo is your schema.

A: You most likely saw USE above the CREATE/ALTER PROCEDURE statement.
In which case it was being used to set which database the procedure should be updated on.
It cannot be used within a stored procedure, but if you wish to make reference to a different database you can set this in your table reference. Ie: for a SELECT statement:
SELECT *
FROM [DatabaseName].dbo.[TableName]

A: Use Go before USE[databaseName] statement. Worked for me in SQL 2005
Example:
GO

USE [Database_Name]

Go

ALTER PROCEDURE [dbo].[Procedure_name]

A: That's right, the USE statement is not really part of the stored procedure but rather it's own statement that instructs the tool (i.e. Enterprise Manager or Query Analyzer) which database to use. It never gets send to the sql server itself and has no meaning for it...