text:
Q: Should check every numeral of number and got bad output i have a task:
got a range on input
[x;y]
then i should check every number from that range and check every numeral in number. if its odd, i should print it
for example: 3, 20
i should print 4,6,8,20
def check(num):
if int(num) % 2 == 0:
    return True

x, y = int(input()), int(input())

numbers = []
if x <= y:
while x != y:
    for i in str(x):
        if check(i):
            numbers.append(x)
    x += 1

else:
while y != x:
    for i in str(y):
        i = int(i)
        if check(i):
            numbers.append(y)
    y += 1
if y == x:
    for i in str(x):
        if check(i):
            numbers.append(x)
print(numbers)

it prints
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29]
instead of 2,4,6,8,20,22,24,26,28

A: You are checking and approving based on a single digit for each number. You should check all of them before appending the entire number. That's why you get 22 twice: once for the first 2 and once for the second. You get 10, because even though 1 is odd, 0 is even and so you append it to your list.
Move the check for the entire number into the function check and have it return True only if all digits are even. This shortens your code. Also note that you can trivially swap x and y if the user entered them in the wrong order.
The function check immediately returns False as soon as it finds a digit i is odd, and you can see it can only return True if the loop ended and all digits were even.
    def check(num):
        for i in str(num):
            if int(i) % 2 != 0:
                return False
        return True

    x, y = int(input()), int(input())
    if x > y:
        x,y = y,x

    numbers = []

    while x <= y:
        if check(x):
            numbers.append(x)
        x += 1
    print (numbers)

Result, with 3 and 20 entered (but 20 and 3 would also work):
[4, 6, 8, 20]


text:
Q: Generate random int value from 3 to 6 Is it possible in Microsoft SQL Server generate random int value from Min to Max (3-9 example, 15-99 e.t.c)
I know, I can generate from 0 to Max, but how to increase Min border?
This query generate random value from 1 to 6. Need to change it from 3 to 6.
SELECT table_name, 1.0 + floor(6 * RAND(convert(varbinary, newid()))) magic_number
FROM information_schema.tables

Added 5 sec later:
SELECT table_name, 3.0 + floor(4 * RAND(convert(varbinary, newid()))) magic_number
FROM information_schema.tables

A: You can do this:
DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

SELECT CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)

And that was taken directly from this link, I don't really know how to give proper credit for this answer.

A: Here is the simple and single line of code
For this use the SQL Inbuild RAND() function.
Here is the formula to generate random number between two number (RETURN INT Range)
Here a is your First Number (Min) and b is the Second Number (Max) in Range
SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.
( CAST(RAND()*(25-10)+10 AS INT) )
Example:
SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)
SELECT RAND()*(b-a)+a;

Example:
SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

A: Simply:
DECLARE @MIN INT=3; --We define minimum value, it can be generated.
DECLARE @MAX INT=6; --We define maximum value, it can be generated.

SELECT @MIN+FLOOR((@MAX-@MIN+1)*RAND(CONVERT(VARBINARY,NEWID()))); --And then this T-SQL snippet generates an integer between minimum and maximum integer values.

You can change and edit this code for your needs.

A: Nice and simple, from Pinal Dave's site:
http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/
DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 3 ---- The lowest random number
SET @Upper = 7 ---- One more than the highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

(I did make a slight change to the @Upper- to include the upper number, added 1.)

A: A helpful editor added the 'Select' before each statement but the point of this item is that it can generate unique keys for each row in a return, not just one item (For that I would us the Rand() function).
For example:
Select top 100 Rand(),* from tblExample
Would return the same random value for all 100 rows.
While:
Select top 100 ABS(CHECKSUM(NEWID()) % 10),* from tblexample
Would return a different random value between 0 and 9 on each row in the return.
So while the select makes it easier to copy and paste, you can copy the logic into a select statement if that is what is required.
This generates a random number between 0-9
SELECT ABS(CHECKSUM(NEWID()) % 10)

1 through 6
SELECT ABS(CHECKSUM(NEWID()) % 6) + 1

3 through 6
SELECT ABS(CHECKSUM(NEWID()) % 4) + 3

Dynamic (Based on Eilert Hjelmeseths Comment - thanks to jiraiya for providing the visual presentation)
SELECT ABS(CHECKSUM(NEWID()) % (@max - @min + 1)) + @min

Updated based on comments:

*

*NEWID generates random string (for each row in return)

*CHECKSUM takes value of string and creates number

*modulus (%) divides by that number and returns the remainder (meaning max value is one less than the number you use)

*ABS changes negative results to positive

*then add one to the result to eliminate 0 results (to simulate a dice roll)

A: In general:
select rand()*(@upper-@lower)+@lower;

For your question:
select rand()*(6-3)+3;

<=>
select rand()*3+3;

A: I see you have added an answer to your question in SQL Server 2008 you can also do
SELECT 3 + CRYPT_GEN_RANDOM(1) % 4 /*Random number between 3 and 6*/
FROM ...

A couple of disadvantages of this method are

*

*This is slower than the NEWID() method

*Even though it is evaluated once per row the query optimiser does not realise this which can lead to odd results.

but just thought I'd add it as another option.

A: SELECT ROUND((6 - 3 * RAND()), 0)

A: Lamak's answer as a function:
-- Create RANDBETWEEN function
-- Usage: SELECT dbo.RANDBETWEEN(0,9,RAND(CHECKSUM(NEWID())))
CREATE FUNCTION dbo.RANDBETWEEN(@minval TINYINT, @maxval TINYINT, @random NUMERIC(18,10))
RETURNS TINYINT
AS
BEGIN
  RETURN (SELECT CAST(((@maxval + 1) - @minval) * @random + @minval AS TINYINT))
END
GO

A: DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);

Step by step
DECLARE @min INT = 3;
DECLARE @max INT = 6;

DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk;
SELECT @result;

Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.
CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT        RAND() AS seed

and then create the random function
CREATE FUNCTION udf_RandomNumberBetween
(
    @min INT,
    @max INT
)
RETURNS INT
AS
BEGIN
    RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nginx virtual hosts for multiple LXC containers I am having the following configuration:
I have 5 LXC containers that are running nginx. On each container there are a couple of virtual hosts set up in nginx. That means for a container I have multiple virtual hosts that are available through port 80.
Each container has an IP like 10.0.3.100, 10.0.3.101, etc.
On the host machine, I also have a nginx server running that has virtual hosts defined.
I would like to know how can I achieve the following: The nginx virtual hosts on the host machine to map on each virtual host on the containers.
For example:
HOST: d1.example.com -> CONTAINER1: d1.example.com
HOST: d2.example.com -> CONTAINER1: d2.example.com
HOST: d3.example.com -> CONTAINER2: d3.example.com
All of them should be available on port 80.
Is there any way to achieve this setup?

A: This is a reverse-proxy and the directive you are looking for is proxy_pass. The host instance of nginx will have multiple server containers like:
server {
  listen 80;
  server_name d1.example.com;
  location / {
    proxy_pass       http://10.0.3.100;
    proxy_set_header Host              $host;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Accept-Encoding   "";
  }
}

See the proxy module documentation and the WebSocket documentation (if applicable).


text:
Q: Serialized calls to BAPI_GOODSMVT_CREATE and roll area
TL;DR: If you use BAPI_GOODSMVT_CREATE to create multiple co-dependent movements and one of them is a transfer posting, then you need to use a wrapper - per SAP note 369518. If there's no transfer posting somewhere, a COMMIT is enough

Has anyone looked into the specifics of Note 369518?
It describes a requirement to start a new roll area before calling BAPI_GOODSMVT_CREATE for a goods receipt that depends on a previous goods movement (posted also by the BAPI within the same LUW).
What is unclear to me: Does it apply to goods receipts in general? Or somehow only to goods receipts that involve an "implicit" (sic) GI for stock in transfer?
I am looking for a technical walkthrough of the section "Reason and Prerequisites".
I need to decide if for a sequence of movements 262,102,101,261 on the same batch, the BAPI should be called in a new roll area each time. For this, the user will need to be asked to close a window if they have the maximum internal sessions already open. (Edit: The part in italics may not apply as I believe that DESTINATION 'NONE' will start a new user session)

A: Best I can tell, the answer hinges on the note's "machine translation" into English: Google offers the alternative phrasing "only with a real outgoing goods, inventory is read from the database", which clears it up a bit:
The BAPI looks into the buffer always, regardless of which movement type it is tasked to create. The issue is that a transfer posting (A08 in MIGO) does not update the buffer. While a "real outgoing" goods issue (A07 in MIGO) does, allowing the subsequent goods receipt to correctly detect the stock.
So only if a prerequisite movement is a transfer posting, is it necessary to start the dependent call in a new roll area.


text:
Q: In search of proof that $\widetilde{e^{ix}}:\mathbb{R}\to S^1$ is not epic in $\mathbf{hTop}$ I came across this assertion:

There is an epimorphism $X \overset{f}\to Y\;$ in Top such that the homotopy class $X \overset{\tilde{f}}\to Y\;$ of $f$ is not an epimorphism in hTop.

Then, by way of elaboration, the text briefly refers to "the covering projection of the real line onto the circle, defined by: $x \mapsto e^{ix}$."
I interpret this to mean that $f\;$ is $x \mapsto e^{ix}$, so $X = \mathbb{R}$, and $Y = S^1$.  If this interpretation is correct, I can see that this $f:\mathbb{R}\to S^1$ is an epimorphism in Top, but I still don't see how to complete the alluded-to counterexample.
More specifically, if I understand the situation correctly, the claim above amounts to asserting that there exist a topological space $(Z, \tau\,)$ and a pair of Top morphisms $g_1, g_2:S^1 \to Z$ such that all the following hold:

*

*$\tilde{g_1}\;\;\tilde{\scriptstyle\circ}\;\;\tilde{f}\,\;=\;\;\tilde{g_2} \;\;\tilde{\scriptstyle\circ}\;\;\tilde{f}\;\;$

*$\tilde{g_1}\,\;\neq\;\;\tilde{g_2}\;\;$

*$g_1\;\;{\scriptstyle\circ}\;\;f\,\;\neq\;\;g_2\;\;{\scriptstyle\circ}\;\;f\;\;\;$  (otherwise, $f\;$ being epic would imply $g_1 = g_2$, and this would lead to a contradiction with (2))

The fact that $f\;$ is surjective makes it very difficult for me to envision a situation in which both (1) and (2) could possibly hold.  (Also, if truth be told, maybe I have no business fighting with this problem, given that my familiarity with hTop doesn't go much beyond having read the definitions needed to follow the above.)
Any suggestions for suitable $(Z, \tau\,)$, $g_1$, and $g_2$ would be much appreciated.

A: Since $\mathbb{R}$ is contractible, it is homotopy equivalent to a point, hence all maps from $\mathbb{R}$ to a path-connected space are homotopy equivalent.
Now $g_1: z \mapsto z$ and $g_2: z \mapsto z^2$ aren't homotopy equivalent as maps $S^1 \to S^1$ (they are distinguished by the degree — which is a homotopy invariant; or if you prefer $g_1$ induces the identity on $\pi_1(S^1) \cong \mathbb{Z}$ while $g_2$ induces multiplication by $2$) but their composition with any $f: \mathbb{R} \to S^1$ is null-homotopic by the first paragraph.


text:
Q: Accessing object in a nested form i have the following nested form :
<%= form_for @contrat,:url => backend_orders_update_report_url(@contrat) do |f| %>
<%= f.fields_for :contrat_lines do |fcl| %>
    <%=  fcl.object.inspect  %>
  <% end %>
<% end %>

the output is the following :
nil

In the nested forms i want to display a few elements not as form but as raw text and a few ones as form field. Usually in a form by doing f.object.name, i would access the name and be able to display it as I want. However, here if i do fcl.object, there is only nil. It should display the inspection of a contrat_line object.
Is it possible to access the data in a nested form?
EDIT :
the controller action :
def show_report
  @contrat = Contrat.find(params[:id])
end

Here is what models look like with the relation at the beggining :
ContratLine :
class ContratLine < ActiveRecord::Base
  include Priceable

  belongs_to :contrat
  belongs_to :good
  #a enlever ici et dans la base
  attr_accessible :active_start,:active,:good_id,:pricing,:contrat
  validates :active_start, :presence=> true,:if => "active"
  validate :active_start_smaller_than_active_stop
  validate :active_start_day_cannot_be_greater_than_28
  has_one :pricing, :as => :priceable, :dependent => :delete
  before_validation :convert_month_year_to_date
  after_save :set_user_subscription_date

Contrat :
class Contrat < ActiveRecord::Base

  has_many :contrat_lines, :dependent => :delete_all

  belongs_to :user
  attr_accessible :user_id,:pricing_id,:state,:adresse_id,:adresse,:payment,:adresse_attributes,:automatic,:start_date,:end_date
  enum_attr :state, %w(basket waiting_data to_confirm paid) do
    labels :basket=>'Panier',  :to_confirm=>'Non payé',:paid=>'Payé'
  end
  enum_attr :payment, %w(debit_card wire_transfer cheque direct_debit)
  belongs_to :adresse
  accepts_nested_attributes_for :adresse, :allow_destroy => true
  scope :by_state,  lambda { |state| where("state = ?",state) }
  scope :last_automatic, where("automatic = true").order("invoice_date DESC")
  scope :last_with_adresse, where("state != 'basket'").order("invoice_date DESC")

  before_validation :set_numbers

A: You're missing an accepts_nested_attributes_for :contrat_lines as well as :contrat_lines_attributes in attr_accessible


text:
Q: Collecting user input. Reading and writing to text files in python Basically what I want to do is have the notepad list show up in python so the user can see what is on the list without opening the file. I have done that. Now I want to have the user input a product that they want, and save it, and print out the product and the price. This is what the text file looks like:
000,67463528,50mm bolts,2.20
001,34512340,plain brackets,0.50
002,56756777,100mm bolts,0.20
003,90673412,l-shaped brackets,1.20
004,45378928,normal brackets,0.80
005,1638647,10mm bolts,0.10
006,14372841,plain brackets,1.29
007,29384754,200mm bolts,0.50
008,12345768,screwdriver,10.99

So far I can add products to the end of the code, and I can insert text at a certain line number. I am working out how to print out a receipt based on user input. I am new to python studying this as a hobby, any help would be greatly appreciated. Thanks!
This is the python code:
def search():
    gtin = input("What is the GTIN code? ")
    des = input("What is the name of the product? ")
    price = input ("What is the price of the product? ")
    position_str = input("What line do you want this inserted at? ")
    print("This is the list now: ")
    position = int(position_str)

    with open("task2.txt", "r") as a_file:
        data = a_file.readlines()

    data.insert(position, "00" + position_str + "," + gtin + "," + des + "," + price + "\n")

    data = "".join(data)

    with open("task2.txt",  "w") as a_file:
        a_file.write(data)

    input()

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()

def add():
    print("The data you put here will be added onto the end ")
    gtin = input("What is the GTIN-8? ")
    des = input("What is the description? ")
    price = input("What is the price? ") #gets all the info they want to add
    print("This is the list now: ")

    with open("task2.txt","a") as a_file:
            a_file.writelines("   ," + gtin + "," + des + "," + price + "\n")
            a_file.close()
            print("Product has been added")

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()

def reciept():

    print()

#this is the menu. this is where the user will make choices on what they do

def menu():
    print("What would you like to do?")

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()

    print("1. Add a product onto a specific line number?")
    print("2. Or add a product onto the end?")
    print("3. Buy products and have them printed onto a reciept?")
    choice=int(input("Which one?: "))
    if choice==1:
        search()
    elif choice==2:
        add()
    elif choice==3:
        reciept()

menu()

A: What to fix and documentation locations
Firstly, I also cannot seem to replicate exactly what you're doing so, I worked up my own solution to some extent...
If you provided a text document with the information in it, it might help with debugging.
That aside... I noticed that if you don't have your "task2.txt" file created, you don't have a way to create one.
This can be done with Task2 = open("task2.txt", "w"). Input / Output Documentation for Python 2.7
Secondly, some of the formatting can be improved by using expressions; I.E.,
\t [tab],
\n [newline],
\r [return],
So you can abide by PEP-8 standard rules. PEP-8 Documentation
Alright, so that's out of the way, what you need to do next is understand the different between open and with open... Not too much difference here, except that with open forces you to immediately jump into a loop. If the document doesn't have information in it, you result in an error (this is the issue I have right now).
Storing it as a list (task2 = open([file], 'r') is better as it allows you to utilize it later. You should also run a check to see if the file even exists...
Example
Thirdly, here are a few tips n' tricks:
import os

boolCheckOnFile = os.path.isfile("[Location to File]\\task2.txt")
# Check if it exists
if boolCheckOnFile==False:
    # Create file, "w" for write
    task2Creation = open("[Location to File]\\task2.txt", "w")
    # Close the file to reopen and read it or write to it...
    task2Creation.close()

# Again "w" for write, "a" for append, "r" for read, "r+" for read/write...
task2 = open("[Location to File]\\task2.txt", "r+")

From here, you can write to the file by enacting str.write(information). But it's always best to close the file when you're actually done with the file... So the changes you made to it are permanent str.close().
Word of advice, print() # print "()", you must fill it, so at least do a newline, like so:
print("\n")
What I did to fix some beginners issues
Finally, below is my iteration of the corrected version (for just the menu portion of your script)...
def menu():

    print("What would you like to do?")

    # Check if file exists
    if os.path.isfile('C:\\users\\[username]\\Desktop\\task2.txt')==False:
        # Create it and promptly close it, so it is in the correct location
        task1 = open('C:\\users\\[username]\\Desktop\\task2.txt','w')
        task1.close()

    # Open for read-write
    task2 = open('C:\\users\\[username]\\Desktop\\task2.txt','r+')

    # splits for new line break, making an array
    info = task2.read().split("\n")

    # Check to see if the file is empty
    if len(info) is not 0:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.",
                                                                   "GTIN-8",
                                                                   "Item Name",
                                                                   "Price"))
        # Read each line of document
        for line in info:
            arrayOfItems = line.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(arrayOfItems[0],
                                                                       arrayOfItems[1],
                                                                       arrayOfItems[2],
                                                                       arrayOfItems[3]))

    else:
        print('You have no items listed!')

    print("\n")

    print("1. Add a product onto a specific line number?")
    print("2. Or add a product onto the end?")
    print("3. Buy products and have them printed onto a reciept?")
    choice=int(input("Which one?: "))
    if choice==1:
        search()
    elif choice==2:
        add()
    elif choice==3:
        reciept()

menu()

Good luck and enjoy making python scripts and programs! It's fun and challenging at times. I was once in your shoes, just remember it gets easier as you keep working on it.
ALSO:
Check out some other Stack Overflowers works... Sometimes an easy solution like this can be resolved by looking at some other peoples work and questions...
Opening file for both reading and writing
Basic read and write
Lowercase examples plus reading and writing
Copying files for modifying documents and creating saves


text:
Q: How to resume cfn-init commands after reboot in linux - redhat 7.4? Is it possible to resume cfn-init in Redhat linux after reboot?
I have cfn-hup and cfn-auto-reloader setup correctly. And I have 'reboot' as one of the commands. All the commands run perfectly till this reboot command. And after the machine comes back from reboot it does not resume the rest of the cfn-init commands. In windows there's 'WaitAfterCompletion' option. Is there anything as such in linux? Just wondering if I'm missing something here. Thanks!!

A: Overall, in linux, you shouldn't have to reboot within a script unless it is something like a kernel update. That being said,
Don't think cfn-init has a direct way to resume operation after reboot in linux, but you can use this linux workaround (using a file to resume script) and call it in your user-data to resume your remaining portion of cfn-init post reboot.
https://unix.stackexchange.com/questions/145294/how-to-continue-a-script-after-it-reboots-the-machine

A: I usually handle linux reboot with user-data, this is an example with amazon linux 2 but it should work with redhat as well.
UserData:
  Fn::Base64: !Sub |
    #!/bin/bash -xe
    exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
    # update the system
    yum update -y
    # Check if kernel update requires a reboot, if yes it does reboot
    needs-restarting -r ||
    {
      # reset user data so it processes again after reboot
      rm -f /var/lib/cloud/instances/*/sem/config_scripts_user
      echo rebooting ... $(date)
      reboot
      exit
    }
    # commands that run after reboot ...


text:
Q: Fill remaining whitespace in line with dots (multiline text) I'm trying to get an html page to look something like this:

I got pretty close but I'd like to make another step and try to fill with dots all the whitespace in the text until the end of the line. All without using js.
I found different solutions for a single line element like most of the ones I have in the document but nothing that worked for a multiple line element.
Closer I got was using an :after selector to add some dots as content and setting the overflow: hidden on the text, which caused my longer lines to disappear.
I'm approaching this using a table atm:

.container {
  width: 600px;
  text-align: justify;
  font-family: 'Arial Narrow', arial, sans-serif;
}

table {
  width: 100%;
}

.incipit {
  width: 10%;
}

.text {
  width: 90%;
}

.page {
  width: 15px;
}

.level-0>.text {
  width: 100%;
}

.level-0 {
  font-weight: bold;
}

.level-1 {
  font-weight: bold;
}

    Table of Contents

      First level index element
      1

      Art. 1
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel elementum erat. In non magna tellus. Donec id tellus ut leo consequat elementum. Praesent eu ligula in neque ultricies mollis sit amet sed risus.
      1

here's a fiddle with the code I have right now.
Has any of you ever struggled with the same problem? Any advice appreciated

A: You can use :after to fill the available space with dots(.).. I have added overflow: hidden and position:relative at td level.
.text:after{
    content: " ....................................................................................................................... ";
    position: absolute;
    padding-left: 5px;
}

See the Snippet below:

.container {
  width: 600px;
  text-align: justify;
  font-family: 'Arial Narrow', arial, sans-serif;
}

table {
  width: 100%;
}

.incipit {
  width: 10%;
}
td{
  overflow: hidden;
    position: relative;
}

.text {
  width: 90%;
}
.text:after{
    content: " ....................................................................................................................... ";
    position: absolute;
    padding-left: 5px;
}

.page {
  width: 15px;
}

.level-0 > .text {
  width: 100%;
}

.level-0 {
  font-weight: bold;
}

.level-1, .level-2 {
  font-weight: bold;
}

  Table of Contents

    First level index element
    1

    Art. 1
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel elementum erat. In non magna tellus. Donec id tellus ut leo consequat elementum. Praesent eu ligula in neque ultricies mollis sit amet sed risus.
    1

    Art. 2
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel elementum erat. In non magna tellus. Donec
    2

You can test it here also..

A: Just use a dotted border on the bottom of a div.  You can use flexbox to force a div to span the remainder of the space.  I didn't use a table just a normal div it is more flexible in its use case but if you want to use a table you can apply the same philosophy.  Here is a simple example:

.row {
  display: flex;
  width: 100%;
}

.dots {
  flex: 1;
  border-bottom: 1px dotted #000;
}

First level index element

1


text:
Q: How to generate .pyi files for a compiled Python extension? I build a compiled Python extension (.pyd file) with C++ and pybind11. I would like to generate a single Python interface .pyi file for my .pyd file.
There are a few similar questions referring to the mypy stubgen module, however, this one produces a UnicodeError trying to run stubgen Dummy where Dummy is Dummy.pyd file:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 2: invalid start byte
Another project, make-stub-files does not work with .pyd files at all, giving the ('not a python file' error.
Are there any tools that could let me generate .pyi files either from the source .cpp files or from compiled .pyd files?
The issue is registered in the mypy GitHub repository.

A: The issue was registered in the mypy GitHub source repository and fixed in a pull request.
The reason for the issue was that when mypy was trying to figure out whether a given module is a Python extension it checked for the .so file extension used on Linux, but did not check for the .pyd file extension used on Windows.


text:
Q: Installing Android Marshmallow on a Nexus device I want to test out my app on a device running Marshmallow. From my understanding, this should be possible on a Nexus 5, 6 or 9 device. To install this, do you have to use the update feature on the device to get the newest version or can you use the Android SDK to install an image?

A: This is documented at length in the M preview documentation.
At a high level:

*

*Download the appropriate system image here.

*Reboot into the bootloader with adb reboot bootloader

*Run fastboot oem unlock

*Navigate to wherever you unzipped the system image and run flash-all

*Run fastboot oem lock


text:
Q: Special Characters are Converted to ? When Inserting into Oracle Database Using R I'm making a connection to an oracle database using the ROracle package and DBI package.  When I try to execute insert statements that have special characters, the special characters get converted to non-special characters. (I'm sure there's more correct terms for "special" and "non-special" that I'm not aware of).
First I make the following connection:
connection <- dbConnect(
  dbDriver("Oracle"),
  username = "xxxxx",
  password = "xxxxx",
  dbname = "xxxx"
  )

Then I execute the following insert statement on a table I already have created.  Column A has a type of nvarchar2.
dbSendQuery(connection, "insert into TEST_TABLE (A) values('£')")

This is what gets returned:
Statement:            insert into TEST_TABLE (A) values('#')
Rows affected:        1
Row count:            0
Select statement:     FALSE
Statement completed:  TRUE
OCI prefetch:         FALSE
Bulk read:            1000
Bulk write:           1000

As you can see, the "£" symbol gets replaced by a "#".  I can execute the insert statement directly in PL/SQL and there's no issue, so it seems to be an issue with R.  Any help is appreciated.

A: This was resolved by running Sys.setenv(NLS_LANG = "AMERICAN_AMERICA.AL32UTF8") before creating the connection.


text:
Q: Refactoring generator code in a Python class I have a need to refactor the generator part of run(self) in the following class to a separate method so that it can be overriden in a subclass.
class First():
    def run(self):

        for item in list1:
            print(f"run2 in Second {item}")
            yield item

        print("run")

Below is my attempt but it doesn't work. The self.run2() part of the run method seems to have no effect. How do I properly do this?
list1 = [1,2,3]

class First():
    def run(self):
        self.run2()   #### This seems to be ignored.
        print("run")

    def run2(self):
        print("run2 in First")

class Second(First):
    def new(self):
        print("second new")

    def run2(self):
        for item in list1:
            print(f"run2 in Second {item}")
            yield item

class Third(Second):
    def some(self):
        pass

third = Third()
third.new()    ## outputs "second new"
third.run()    ## outputs "run", not "runs in Second xxx"


text:
Q: Lowess method in statsmodels converts real values to NaN values. What is happening? I have a set of two-column dataframes and I want to generate smoothed estimates of the 2nd-column value for the given 1st-column value. The structure of a couple of the dataframes is like that:
         Mbp    cM
0  10.849607  64.5
1  10.864685  64.5
2  10.895010  64.5
3  10.988436  64.5
4  11.120783  66.6

[5 rows x 2 columns]

         Mbp    cM
0  11.153451  66.6
1  11.184827  66.6
2  11.185363  66.6
3  11.185411  66.6
4  11.185423  66.6

[5 rows x 2 columns]

To do the smoothing I am using the lowess method from the statsmodels python module. Below is the command line that I use for doing the smooting:
smoothed_subset = lowess(df_subset['Mbp'], df_subset['cM'])

However the ouput of the method converts all the values of the 'Mbp' column to 'nan'. I cannot see the reason why. Below you can see the output for the two dataframes shown above.
[[ 64.5   nan]
 [ 64.5   nan]
 [ 64.5   nan]
 [ 64.5   nan]
 [ 66.6   nan]]
[[ 66.6   nan]
 [ 66.6   nan]
 [ 66.6   nan]
 [ 66.6   nan]
 [ 66.6   nan]]

I would appreciate any help! Thanks!
Editing:
I run repr(df_subset['Mbp']) and repr(df_subset['cM']) for one of the dataframes as suggested by Alex W and below is the output:
0    10.849607
1    10.864685
2    10.895010
3    10.988436
4    11.120783
Name: Mbp, dtype: float64

0    64.5
1    64.5
2    64.5
3    64.5
4    66.6
Name: cM, dtype: float64

A: Try explicitly setting the optional parameters, just in case the defaults have changed.
I'm not sure how the algorithm works internally, but you may be suffering from having so many identical cM values.  Can you alter them slightly for testing purposes?  Even 1% might make a large difference in computability:
         Mbp    cM
0  10.849607  64.50
1  10.864685  64.51
2  10.895010  64.52
3  10.988436  64.53
4  11.120783  66.60

[5 rows x 2 columns]

         Mbp    cM
0  11.153451  66.61
1  11.184827  66.62
2  11.185363  66.63
3  11.185411  66.64
4  11.185423  66.65

[5 rows x 2 columns]

I'm concerned that the NaN comes from a division by 0 somewhere.

A: I solved that issue by setting the it parameter to 0, instead of the default value of 3.
The it parameter corresponds to the number of residual-based reweightings to perform.


text:
Q: Using Live Property Explorer with ComboBox Has anyone successfully used VS2015 Live Property Explorer to inspect ComboBox items? There is no obvious way to select or hover ComboBox items when the "Enable Selection" button is ON.

*

*If I click "Enable Selection" first, clicking on the ComboBox doesn't open it.

*If I open the dropdown first, clicking on "Enable Selection" closes the dropdown.

I also tried manually traversing through the hierarchy in Live Property Explorer, but the dropdown list is not part of the ComboBox hierarchy.
Or am I missing something simple?


text:
Q: Nested ARM template and dependsOn in another Resource Group I am trying to create a Function App with VNET Integration in ARM. I have made all that work just fine in one main template.
Now I have a new requirement where the VNET needs to be in another RG and thus seperate from the Func App RG, but the Func App still needs to have VNET integration to the VNET in the other RG.
I'm struggling how to define the ARM template, so that I deploy the Func App in one RG and VNET in another. The hard part is how to define this so that the Func App integrates into a VNET in another RG in the same ARM template using nested template.
Here is my ARM template:
"resources": [{
        "type": "Microsoft.Resources/deployments",
        "apiVersion": "2019-10-01",
        "name": "nestedTemplate",
        "resourceGroup": "[parameters('VNETPeered_RG_Name')]",
        "subscriptionId": "0a2009c0-e2ae-4991-aa0e-5c34c141e4cb",
        "properties": {
            "mode": "Incremental",
            "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {},
                "variables": {},
                "resources": [{
                        "comments": "Virtual Network for VNET integration feature in the Premium Plan for the Function App",
                        "type": "Microsoft.Network/virtualNetworks",
                        "apiVersion": "2019-11-01",
                        "name": "[variables('virtual_network_name')]",
                        "location": "[resourceGroup().location]",
                        "properties": {
                            "addressSpace": {
                                "addressPrefixes": [
                                    "[parameters('vnetAddressPrefix')]"
                                ]
                            },
                            "subnets": [{
                                    "name": "[variables('subnet_name')]",
                                    "properties": {
                                        "addressPrefix": "[parameters('subnet1Prefix')]",
                                        "serviceEndpoints": [{
                                                "service": "Microsoft.Storage",
                                                "locations": [
                                                    "[resourceGroup().location]"
                                                ]
                                            }
                                        }
                                    }]
                            }
                        }]
                }
            }
        },
        {
            "comments": "Function App to host the functions themselves. Integrates into a VNET and makes use of Azure DNS Private Zones.",
            "type": "Microsoft.Web/sites",
            "apiVersion": "2019-08-01",
            "name": "[variables('function_app_name')]",
            "location": "[resourceGroup().location]",
            "dependsOn": [
                "nestedTemplate",
                "[resourceId('Microsoft.Storage/storageAccounts', variables('storage_account_name'))]",
                "[resourceId('Microsoft.Web/serverfarms', variables('app_service_plan_name'))]"
            ],
            "kind": "functionapp",
            "identity": {
                "type": "SystemAssigned"
            },
            "properties": {
                "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('app_service_plan_name'))]",
                "siteConfig": {
                    "appSettings": [{
                        "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
                        "value": "[reference(variables('application_insights_resourceId'), '2018-05-01-preview').InstrumentationKey]"
                    }]
                },
                "clientAffinityEnabled": true
            },
            "resources": [{
                "type": "networkConfig",
                "apiVersion": "2019-08-01",
                "name": "virtualNetwork",
                "dependsOn": [
                    "[resourceId('Microsoft.Web/sites', variables('function_app_name'))]"
                ],
                "properties": {
                    "subnetResourceId": "[reference(resourceId('RG-FunctionsGroup','Microsoft.Network/virtualNetworks/subnets', 'vn-MY-VNET', 'sn-MY-SUBNET'),'2020-05-01')]",
                    "isSwift": true
                }
            }]
        ]
    }

On this I get the following error when I try to deploy it with az deployment group command from az cli:
Deployment failed. Correlation ID: 39b0173b-8a51-42c5-a796-1d3427556194. {
  "error": {
    "code": "InternalServerError",
    "message": "There was an unexpected InternalServerError.  Please try again later.  x-ms-correlation-request-id: 844e9f35-2e9c-411a-817d-9045511558cb"
  }
}

A: reference() will work but TLDR; it's a little heavyweight
https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource#resourceid
is all you need in this case.  To "reference" any resource in ARM you'll use the resourceId - there are a handful of functions to help but it really helps if you understand the basics of the resourceId, which is summarized here:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource#return-value-6
When you want a resourceId to a resource in the same deployment (which is not the same as the same template) you can use the shorthand version
resourceId({namespace/resourceType}, {resourceName})
If it's in a different RG, you need to add the RG param, and if it's in a different sub you need to add that too. I can't tell for certain with your snippet, but it looks like all you need in your case is this (assuming the vnet and fn app are in the same subscription):
"subnetResourceId": "[resourceId(parameters('VNETPeered_RG_Name'), 'Microsoft.Network/virtualNetworks/subnets', variables('virtual_network_name'), variables('subnet_name'))]"

That help?

A: Your problem is in this part of code:
 "properties": {
                "subnetResourceId": "[reference(resourceId('RG-FunctionsGroup','Microsoft.Network/virtualNetworks/subnets', 'vn-MY-VNET', 'sn-MY-SUBNET'),'2020-05-01')]",
                "isSwift": true
            }

You are pointing the subnet with the wrong resource group. Change the resource group where the vnet and the subnet is deployed.
 "properties": {
                "subnetResourceId": "[reference(resourceId(parameters('VNETPeered_RG_Name'),'Microsoft.Network/virtualNetworks/subnets', variables('virtual_network_name'), variables('subnet_name')),'2020-05-01')]",
                "isSwift": true
            }


text:
Q: How to change click function based on button class in Angular In Angular I have a button which toggles a class - What I want to do is add events based on the button class. Should this be done via an If statement within a function? So far my code is below:
HTML button
<!-- toggle button -->
<button type="button" class="btn btn-primary mt-3 ml-3 btn-button" (click)="status=!status; func()" [ngClass]="{'btn-danger' : status, 'btn-primary' : !status}"  [disabled]="clicked">{{status ? 'Delete' : 'Add'}}</button>
<!-- toggle button -->

Component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

public btn: any;

func () {
   if (this.btn.hasClass('btn-primary')) {
      alert('Primary clicked');
   } else if (this.btn.hasClass('btn-danger')) {
     alert('Danger clicked');
   }
 }
}

A: Instead of the class name, you can check the status value.
Try like this:
Working Demo
.html
(click)="func()"

.ts
  func() {
    this.status = !this.status;
    if (this.status) {
      alert("Primary clicked");
    } else if (!this.status) {
      alert("Danger clicked");
    }
  }

A: You can look this demo may this helps you
You can change class on basics of action property;
<button (click)="onClick()" [ngClass]="action =='Add' ? 'btn-primary': 'btn-danger'"> {{action}}</button>

On button click
 onClick() {
    if(this.action == 'Add') {
      this.action = 'Delete';
      alert('Primary Clicked');
    } else {
      this.action = 'Add';
        alert('Danger clicked');
    }
  }

A: How about:
<button id="myBtn" type="button" class="btn btn-primary" (click)="func()">{{buttontext}}</button>

TS
buttontext: string = 'ADD';
func () {
    let element = document.getElementById("myBtn");
    element.classList.toggle("btn-danger");
    element.classList.toggle("btn-primary");
    this.buttontext = this.buttontext === 'ADD' ? 'DELETE' : 'ADD';
}

A: You can use viewchild and ElementRef with a Hostlistener for click event, it would be something like this:
export class AppComponent {

@ViewChild('yourButton') deleteAddButton:ElementRef;
func (class) {
   if (deleteAddButton.nativeElement.classList.contains(class)) {
      alert('Primary clicked');
   } else () {
     alert('Danger clicked');
   }
 }
@HostListener('click', ['$event'])
clickHandler(event) {
  if(deleteAddButton.nativeElement.classList.contains('btn-primary')) {
    this.func('btn-primary');
  }
}
}

In html:
<button #deleteAddButton ...</button>


text:
Q: .NET Core MVC app runs locally but not in container (System.DirectoryServices.Protocols not supported) We created an application using Visual Studio 2017's project tamplate ".NET Core Web Application (Model-View-Controller)", selecting "Change Authentication->Individual User Accounts"
We then developed the application and were getting read to push our first container.
After a publish to folder, we tested inside the publish folder by running
dotnet nameof.dll

All tests passed.  Snippet from docker log:
Hosting environment: Production
Content root path: \publish
Now listening on: http://localhost:5000
Application started.  Press Ctrl+C to shut down.

So far so good.
We then tried building a simple container with this Dockerfile:
FROM microsoft/aspnetcore:2
WORKDIR app
EXPOSE 80
COPY  publish .
CMD ["dotnet", "nameof.dll"]

The site came up but with a warning.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {8f452e97-17ae-45cb-bcfb-d97a81ce1199} may be persisted to storage in unencrypted form.
Hosting environment: Production
Content root path: /app
Now listening on: http://[::]:80
Application started. Press Ctrl+C to shut down.

Other than that, everything looked fine.  Browsed to the site.  Looking good.
When we tried to log in this exception is thrown:
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: System.DirectoryServices.Protocols is not supported on this platform.
System.PlatformNotSupportedException: System.DirectoryServices.Protocols is not supported on this platform.
   at System.DirectoryServices.Protocols.DirectoryIdentifier..ctor()
   at System.DirectoryServices.Protocols.LdapDirectoryIdentifier..ctor(String server)
   at CycleMenu.Controllers.AccountController.<Login>d__11.MoveNext() in C:\gg\AramarkCycleMenu\src\CycleMenu\CycleMenu\Controllers\AccountController.cs:line 78
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()

Clearly something is missing from the docker image, but if it's not in the publish folder, where is it?  How could this work outside the container but not inside?
We tried

*

*building with different base images

*Linux and Windows containers

*Adding Microsoft.Windows.Compatibility (I lost the link to the article that guided us to do that)

*banging our heads against the wall.

According to this discussion: https://github.com/dotnet/corefx/issues/2089 System.DirectoryServices.Protocols was originally not included in .NET Core, but now it is (Nov 2017).  Could it be the images on docker hub aren't up to date yet, and that's why we're getting "...not supported on this platform"?
Running dotnet --version returns 2.1.4 both inside the container and outside.
Can you provide any help or insight how to get past this error and get the otherwise working code correctly into a docker image?
Edit to answer: Running Docker for Windows on Windows 10

A: I was experiencing the same issue using Nuget package System.DirectoryServices.Protocols version 4.6.0 in a dotnet core 3.0 docker container based on mcr.microsoft.com/dotnet/core/aspnet:3.0.
But, as we can see in the issue you refereed to there will be no support for other platforms than Windows: https://github.com/dotnet/corefx/issues/2089#issuecomment-373219911

A: Microsoft has added System.DirectoryServices.Protocols support for Linux and MacOS. Reference: https://github.com/dotnet/runtime/issues/23944


text:
Q: How to display an image using tag in JSP Here is the code to retrieve image in action class. I have tried it, but not able to display it I don't know about the image processing. How should I use tags in JSP to display the image?
public String displayImage()
  {
    Connection con = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    String sql,result="";
    con=JdbcHelper.getConnection();
    if(con!=null)
    {
      try
      {
        sql = "SELECT INPUT_FILE_BLOB FROM message_details where message_id=?";
        preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1, messageid);
        resultSet = preparedStatement.executeQuery();
        if(resultSet.next())
        {
          Blob image = resultSet.getBlob("INPUT_FILE_BLOB");
          System.out.println("=============Image2\n" +image);
          int len1 = (int) image.length();
          System.out.println("=============len1\n" +len1);
          byte [] rb1 = new byte[len1];
          InputStream readImg1 = resultSet.getBinaryStream(1);
          try {
            int index1=readImg1.read(rb1, 0, len1);
            System.out.println("index1"+index1);
            response.reset();
            response.setContentType("image/jpg");
            response.getOutputStream().write(rb1,0,len1);
            response.getOutputStream().flush();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
      catch(SQLException e)
      {
        try
        {
          con.rollback();
        }
        catch (SQLException e1)
        {
          result = e1.getMessage();
          e.printStackTrace();
        }
        result = e.getMessage();
        e.printStackTrace();
      }
      finally
      {
        JdbcHelper.close(resultSet);
        JdbcHelper.close(preparedStatement);
        JdbcHelper.close(con);
      }
    }
    else
      result = Constants.SUCCESS;

  }

A: You should do it in struts 2 way by implementing a Custom Result Type to display image on the JSP.
Here is an Example for displaying dynamic image in Stuts2.
It creates a custom result type by implementing Result interface.
public class CustomImageBytesResult implements Result {
.
.
.
}

A: After retrieving an image from the database as Blob or byte array you are writing direct to response. In this case you should not return SUCCESS result, you need to return NONE result. Then in the JSP you could access an image as a separate thread using img tag that will call your action that return an image.
See also How can we display dynamic or static images that can be provided as an array of bytes,
and How to display image in Struts2.


text:
Q: Hide a UIbutton when another UIbutton is pressed I have a record button, which when pressed, I want to hide the instructions button.
Here's the code for the record button:
// Create custom overlay
// Create instruction/record button
// Add instruction/record button to custom overlay
[_videoRecordBtn addTarget:self action:@selector(startVideoRecord:) forControlEvents:UIControlEventTouchUpInside];

So in startVideoRecord I should have something like:
-(IBAction)startVideoRecord:(id)sender{
    [_instru setHidden:YES];
    // start recording...
}

But I have no idea how to pass the _instru button over to startVideoRecord.

A: You can do this by 2 way..
1 way - > you set the tag of instructions button.
and use this
-(IBAction)startVideoRecord:(id)sender{

UIButton *instruBtn = (UIButton*)[self.view viewWithTag:your button tag];

instruBtn.hidden = YES;

// start recording...
}

2nd Way - > you make property for your instructions button and use like this
  -(IBAction)startVideoRecord:(id)sender{

    self.instruBtn.hidden = YES;

    // start recording...
    }

A: Add a property to your ViewController to keep a reference to your instructionsButton:
@property (nonatomic, strong) UIButton *instructionsButton;

When you create your instructionsButton, assign it to this property.
Then you can access the button via this property anywhere in your ViewController with self. instructionsButton.
So, your action method would be like:
-(IBAction)startVideoRecord:(id)sender{
    self.instructionsButton.hidden = YES;
    // start recording...
}


text:
Q: How to create multiple columns in Pandas dataframe based on year I have 10 years of hourly water level data that I'm trying to line up in separate columns based on year. The current format of the data is in two columns, one for the date and time (ex. 06/04/1989 06:00:00) of the reading and one for the water level. I'd like separate the data into individual columns based on year. I thought it was a straightforward task but with my limited experience in Pandas, I'm find it challenging. Any advice would be appreciated.
Input:
Obs_date         SLEV(metres)

31/12/1990 20:00    0.15
31/12/1990 21:00    0.14
31/12/1990 22:00    0.13
31/12/1990 23:00    0.16
...
31/12/1991 20:00    0.12
31/12/1991 21:00    0.13
31/12/1991 22:00    0.09
31/12/1991 23:00    0.08

Output:
Obs_date          1990   1991
31-Dec 20:00:00   0.15   0.12
31-Dec 21:00:00   0.14   0.13
31-Dec 22:00:00   0.13   0.09
31-Dec 23:00:00   0.16   0.08

A: First convert Obs_date to datetimes by to_datetime, then create new column by Series.dt.year and custom format by Series.dt.strftime and last pivoting by DataFrame.pivot with convert index to column by DataFrame.reset_index and DataFrame.rename_axis is used for remove column name:
df['Obs_date'] = pd.to_datetime(df['Obs_date'], format='%d/%m/%Y %H:%M')
df['year'] = df['Obs_date'].dt.year
df['Obs_date'] = df['Obs_date'].dt.strftime('%d-%b %H:%M:%S')

df = df.pivot('Obs_date', 'year','SLEV(metres)').reset_index().rename_axis(None, axis=1)
print (df)
          Obs_date  1990  1991
0  31-Dec 20:00:00  0.15  0.12
1  31-Dec 21:00:00  0.14  0.13
2  31-Dec 22:00:00  0.13  0.09
3  31-Dec 23:00:00  0.16  0.08

Or is possible create Series y and d and reshape by DataFrame.set_index with Series.unstack:
df['Obs_date'] = pd.to_datetime(df['Obs_date'], format='%d/%m/%Y %H:%M')
y = df['Obs_date'].dt.year
d = df['Obs_date'].dt.strftime('%d-%b %H:%M:%S')

df = df.set_index([d, y])['SLEV(metres)'].unstack().reset_index().rename_axis(None, axis=1)
print (df)
          Obs_date  1990  1991
0  31-Dec 20:00:00  0.15  0.12
1  31-Dec 21:00:00  0.14  0.13
2  31-Dec 22:00:00  0.13  0.09
3  31-Dec 23:00:00  0.16  0.08

If need processing data later and need correct order better is convert datetime to DatetimeIndex with some default year with 29.February, e.g 2020:
df['Obs_date'] = pd.to_datetime(df['Obs_date'], format='%d/%m/%Y %H:%M')
y = df['Obs_date'].dt.year
d = pd.to_datetime(df['Obs_date'].dt.strftime('2020-%m-%d %H:%M:%S'))

df = df.set_index([d, y])['SLEV(metres)'].unstack().rename_axis(None, axis=1)
print (df)
                     1990  1991
Obs_date
2020-12-31 20:00:00  0.15  0.12
2020-12-31 21:00:00  0.14  0.13
2020-12-31 22:00:00  0.13  0.09
2020-12-31 23:00:00  0.16  0.08


text:
Q: Setting an image above of a UITableViewController Iam currently working on a iPad project where i build my code on top of the premade "Split View-based Application".
I am trying to place a image above of the UITableViewController when i rotate my iPad into landscape mode, however i do not know if it is possible without having the image appear in the popover-menu when displaying in portrait mode.
I can't place a UIImageView inside IB, so trying to do it from the code.
Here is a image of my table: 1

A: Create and position the image programaticaly when initializing the view, and implement the following method in the view controller:
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
        imageOverTableview.hidden = !UIInterfaceOrientationIsLandscape(interfaceOrientation);

        return YES;
    }


text:
Q: Capture 'Modified' [Date/Time] on each record in SharePoint I have a Custom list in SharePoint. This list contains up to 5000 records at any given time, for employees to go in to rate each record. I want to do an analysis on when records were modified and by who. Not just the last Modified stamp.. but all of the Modified stamps till the record is removed from SharePoint.
Is there a way to capture the 'Modified' state of a record. If so, could you please explain.
Just a heads up, I only have access to OTB SharePoint with access to MS Access{I have an Access db set up that holds all records}, InfoPath Design, and Powershell (I've never used Powershell)

A: You can use Sharepoint Designer to do this - kick of the workflow when an item is created & modified.
You'd need the workflow to copy the value of the Modified By and Modified Date to additional fields, I'll call them ModifiedByWas and ModifiedDateWas - configure these new field as Multiple Lines of Text fields e.g.

When the item is created, Sharepoint should copy the values over to these new fields.  Then when an item is modified by a user, the workflow should again kick off and copy over the new value to the ModifiedByWas and ModifiedDateWas fields.  Be sure to configure your new fields with the Append Changes to Existing Text.  The fields can be plain text, they don't have to match my rich text setting.
p.s. You might also want to try out CONCATENATE, which is a calculated column - you could use it to create one Multiple Lines of Text field displaying a combined value Modified By & Modified Date.


text:
Q: SCM8014 to FVS338 I have a SMC8014 Router/Modem that Comcast provided me with their business class service.  It was not filtering malicious traffic as aggressively as I had hoped, so I purchased a NetGear ProSafe FVS338, and put this behind the SMC8014, and all my machines behind that.  After some brief configuration, all machines can see out to the internet.
I also have a single web server, and I have not been able to configure things so that incoming requests can reach it.  This is where I need help!
I would like to have the FVS339 do NAT, so that I can assign a 192.168 address to my webserver.  I've tried everything I know of, and I can't get things going.
I set the SMC8014 to have a LAN facing IP of 10.0.0.1, and I assigned the FVS339 a WAN facing IP of 10.0.0.2.  I would like to be able to tell the SMC8014 to just forward all traffic to 10.0.0.2, but I haven't had any success.
In my (unfortunately limited) understanding, what I probably want here is a static route, but I don't know how to cofigure one, or if this is really what I want.  The SMC8014 wants a Destination IP, a Subnet Mask and a Gateway IP.
Any help would be appreciated.

A: First some advice: use one router or the other, not both (at least until you understand this better).
For outgoing connections, the router does DNAT = Dynamic Network Address Translation, where several internal IP addresses appear to be connecting from your external address.  For incoming connections to your webserver the router does SNAT = Static NAT, forwarding the incoming connections to the internal IP address. You should be able to find config options for SNAT.


text:
Q: Zend Custom Modules Routes i have this set up:
    application
    ---admin
    -----controllers
    -------IndexController.php
    ---public
    -----controllers
    ---modules
    -----users
    -------controllers
    -----pages
    -------controllers

I'd like to have this routes :
www.domain.com/admin/modulename/controller/action/

or if module not exist i use admin controllers
www.domain.com/admin/controller/action/

Any suggesiton?
Thanks

A: In your bootstrap file write this code :
$router = Zend_Controller_Front::getInstance()->getRouter();
if($moduleName){
$route = new Zend_Controller_Router_Route(
                  ':module/:controller/:action/',
                  array(
                      'controller' => $ControllerName,
                      'module' => '$moduleName',
                      'action'     => $ActionName
                  )
              );
}else{
$route = new Zend_Controller_Router_Route(
                  ':controller/:action/',
                  array(
                      'controller' => $ControllerName,
                      'action'     => $ActionName
                  )
              );
}

$router->addRoute('default', $route);


text:
Q: accessing substrings from lines in a text file and storing them I have a text file like this
chr1:16840617-16840780    RNU1-1             (2 columns are tab separated)
chr3:142139047-142139211    RNU1-100P
............
............

I want to loop over the lines of text file and save column 1 and column 2 in sep variables, something like this :
OLDIFS=$IFS; IFS=$'\n'; for line in $(cat test.txt);do LOC="save location";NAME="save name";done

After saving name and location I have to do couple of steps more to get my desired output but as of now I want to store them.

A: Try
while read column1 column2
do
  something with $column1
  something more $column2
  ...
done < test.txt

Using the read directly from a while & redirected file saves you the cat (completely unnecessary use of ;}) and changing IFS.


text:
Q: Using JLayeredPane to add multiple JPanels to a JPanel I am trying to add multiple panels to another panel. I want them to be on top of each other so I'm using JLayeredPane. I've added a button to each one. Two buttons should appear when it works.
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class PanelTest {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel mainPanel = new JPanel();
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();

    JLayeredPane layers = new JLayeredPane();
    mainPanel.add(layers);

    panel2.setOpaque(false);
    panel1.setOpaque(false);
    panel1.setVisible(true);
    panel2.setVisible(true);

    panel1.add(new JButton("1111111111"));
    panel2.add(new JButton("2"));

    frame.setContentPane(mainPanel);
    layers.add(panel1, new Integer(2));
    layers.add(panel2, new Integer(3));

    frame.setVisible(true);
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Only the grey background of the mainPanel is visible. What am I doing wrong?

A: When adding a component to a JLayeredPane, you're essentially adding the component to a null layout using container. This means that you must fully specify both the component's size and its position, often solving both with a setBounds(...) call. Call this on panel1 and panel2, for example:
panel1.setBounds(10, 10, 100, 100);
panel2.setBounds(70, 70, 100, 100);

Edit:

setting bounds didn't make any difference

Setting the size (bounds) is required but you still have an additional problem.
You are adding the JLayeredPane to a JPanel which uses a FlowLayout. By default a FlowLayout respects the preferred size of the component added to it. Since JLayeredPane uses a null layout its preferred size is (0, 0) so there is nothing to paint.
Two solutions:

*

*You don't need the JPanel, just use: frame.setContentPane(layers);

*If you really want to use the panel then you need to change the layout manager: JPanel mainPanel = new JPanel( new BorderLayout());


text:
Q: How to get rid of the "\n" in my python output u'The disclosure relates to systems and methods for detecting features on\n     billets     of laminated veneer lumber (LVL). In some embodiments, an LVL\n     billet is provided and passed through a scanning assembly. The scanning\n     assembly includes anx-raygenerator and anx-raydetector. Thex-raygenerator generates a beam ofx-rayradiation and thex-raydetector\n     measures intensity of the beam ofx-rayradiation after is passes through\n     the LVL billet. The measured intensity is then processed to create an\n     image. Images taken according to the disclosure may then be analyzed todetectfeatures on the LVL billet.'

Above is my output.
Now I want to get rid of "\n" in Python.
How can I realize this?
Should I use re module?
I use text to represent all the above text and text.strip("\n") have no use at all.
Why?
thank you!

A: For a string, s, doing:
s = s.strip("\n")

will only remove the leading and trailing newline characters.
What you want is
s = s.replace("\n", "")

A: Have you tried the replace function?
s = u'The disclosure relates to systems and methods for detecting features on\n     billets     of laminated veneer lumber (LVL). In some embodiments, an LVL\n     billet is provided and passed through a scanning assembly. The scanning\n     assembly includes anx-raygenerator and anx-raydetector. Thex-raygenerator generates a beam ofx-rayradiation and thex-raydetector\n     measures intensity of the beam ofx-rayradiation after is passes through\n     the LVL billet. The measured intensity is then processed to create an\n     image. Images taken according to the disclosure may then be analyzed todetectfeatures on the LVL billet.'

s.replace('\n', '')

A: try this
''.join(a.split('\n'))

a is the output string

A: str = 'The disclosure relates to systems and methods for detecting features on\n     billets     of laminated veneer lumber (LVL).'
str.replace('\n', '')
' '.join(str.split())

Output
The disclosure relates to systems and methods for detecting features on billets of laminated veneer lumber (LVL).


text:
Q: How to write a virtual conditional breakpoint in java I'm sorry if the question title may mis-inform you, but I cannot find a proper word to explain that.
If you ever working with .NET, you would know that there is Assert class that will automatically wake up and attach debugger if necessary and then have debugger (Visual Studio) pausing at the Assert command, given the Assert command failed.
Given I'm running a java program and having debugger connected, then how can I have debugger to break on certain condition without manually setup a break point?
I'm expecting something like that:
void doSomeThing(String x){
   if (x==null) breakDebuggerNow();
}

A: If you use eclipse you can modify breakpoints in the breakpoint view (per default in debug perspective) by the context menu (right click on your break point).
You can set Hit Count, or Enable Condition. Another option is to trigger on exceptions, click the icon with a 'J!' set select a specific exception.

A: As far as I know there is no exactly such feature in Java. JVM doesn't know about debugger if it is not attached. For .Net this is Windows who does some favor in this aspect. However, there is assert that is intended for such usage. It will raise java.lang.AssertionError that is not an Exception and thus shouldn't be handled by usual catches. If your debugger is set up to handle unhandled exceptions (or rather Throwables) it will catch such case.


text:
Q: How/why does this JS singleton pattern work? I came across this rather interesting way to create a JavaScript singleton that can be instantiated with the new keyword, like var x = new SingletonClass(). I have a pretty good grasp of variable scope and closures, etc., but I'm having a hard time understanding exactly why this block of code works the way it does.
// EDIT: DO NOT USE this code; see the answers below
function SingletonClass() {
  this.instance = null;
  var things = [];

  function getInstance() {
    if (!this.instance) {
      this.instance = {
        add: function(thing) {
          things.push(thing);
        },
        list: function() {
          console.log(things.toString());
        }
      };
    }
    return this.instance;
  }

  return getInstance();
}

var obj1 = new SingletonClass();
obj1.add("apple");
obj1.list();  //"apple"

var obj2 = new SingletonClass();
obj2.add("banana");
obj1.list();  //"apple,banana"
obj2.list();  //"apple,banana"

obj1.add("carrot");
obj1.list();  //"apple,banana,carrot"
obj2.list();  //"apple,banana,carrot"

My intuition says that each time a new SingletonClass is instantiated, this refers to that fresh new object -- but then since a totally separate object is returned by the constructor, I would figure this would just get discarded. But it hangs around. How? Why?
There's some tiny little detail going on here that I'm missing. Can anybody shine some light on it?
EDIT: Turns out this code is bad. The reason why it "magically" seems to hold a reference to the instance is because it's actually silently storing it in the global object. It's bad practice at best, and undoubtedly bug-prone.

A: Don't confused by the this inside the function getInstance, that this is the global object window, so you are creating an object and assigned to the window object, and next time you call the constructor, you are checking whether window.instance is existing.
The code this.instance = null; is meanless, just confusing you. Remove it won't change anything.
The below is from the MDN.

When the code new foo(...) is executed, the following things happen:

*

*A new object is created, inheriting from foo.prototype.

*The constructor function foo is called with the specified arguments
  and this bound to the newly created object. new foo is equivalent to
  new foo(), i.e. if no argument list is specified, foo is called
  without arguments.

*The object returned by the constructor function becomes the result
  of the whole new expression. If the constructor function doesn't
  explicitly return an object, the object created in step 1 is used
  instead. (Normally constructors don't return a value, but they can
  choose to do so if they want to override the normal object creation
  process.)

Note the step3, when you have return statement in constructor, the returned result will be the result of the new expression.

A: When the constructor calls getInstance(), the this pointer inside getInstance() is set to window so this.instance inside of it is a global variable window.instance.
This code just uses a global variable window.instance to keep track of the one instance and could be made a LOT simpler than it is.
A much cleaner way to implement this would be this.  The one global instance is stored as a property of the function itself rather than in a top-level global variable.
    function SingletonClass() {
        var things = [];

        // if there is a previous instance, return it
        if (SingletonClass.inst) {
            return SingletonClass.inst;
        }
        // if not called with 'new', force it
        if (!this instanceof SingletonClass) {
            return new SingletonClass();
        }

        // remember the first created instance
        SingletonClass.inst = this;

        // add methods that can see our private `things` variable
        this.add = function(thing) {
           things.push(thing);
        }

        this.list = function() {
            console.log(things.toString());
        }
    }

A: It's using window - getInstance's this is not the same as SingletonClass's this:
function Singleton() {
    console.log("This is:", this);
    this.instance = null;

    function _get() {
        console.log("_get's this is:", this);
        if (!this.instance) {
           console.log("Instance is null");
           this.instance = { test: 1 };
        }
        return this.instance;
    }

    return _get();
}

var x = new Singleton();

// Output is:
This is:
Singleton
_get's this is:
Window
Instance is null

A better way to implement the Singleton pattern in JavaScript might be:
function Singleton() {

    // Handle not being called with `new`
    if (!this instanceof Singleton) {
        return new Singleton();
    }

    var instantiating = !!Singleton.instance,
        things = [];

    Singleton.instance = instantiating ? this : Singleton.instance;

    if (instantiating) {
        this.list = function() {
            console.log(things.toString());
        }

        this.add = function(item) {
            things.push(item);
        }
    }

    return Singleton.instance;
}

This still suffers from limitations. For example, if someone replaces Singleton.instance with another object then tests between different instances of Singleton may break - e.g.:
var x = new Singleton();
// Har, har, we be breaking things!
Singleton.instance = {"not": "the", "same": "at", "all": true};
var y = new Singleton();

console.log(x === y); // false

A: The keyword this in the getInstance function indicates a Window object. In the SingletonClass function, it indicates a SingletonClass object.
With lexical scope, the add and list functions always refer to the same things array.

A: This seems to be a good link on singletons:
Simplest/Cleanest way to implement singleton in JavaScript?
Here is an example that pertains to what you are doing above:
var myInstance = {
    method1: function () {
        return "Apple";
    },
    method2: function () {
        return "Orange";
    },
    banana: "Banana"
};

myInstance.grape = "Grape";

console.log(myInstance.method1(), myInstance.method2(), myInstance.banana, myInstance.grape);

Here is working link:
http://www.quirkscode.com/flat/forumPosts/singleton/singleton.html


text:
Q: Navigation bar flickering when over scroll in SwiftUI When overscroll up the transition between inline and large navigation is not smooth and there is a short flickering

struct ContentView: View {

    var body: some View {

      NavigationView {
            ScrollView {
                Text("Content")
                    .frame(width: 100, height: 300)
            }.navigationBarTitle(Text("Title"), displayMode: .large)
        }
    }
}


text:
Q: Low ESR capcitors for switching pre-regulator (LM2596) In LM2596 switching regulator datasheet suggested to use low ESR capacitors. since I'm going to use LM2596 as a pre-regulator for a linear regulator to reduce the voltage drop on linear regulator, is it still necessary to use low ESR capacitor?

A: You will note that the recommendation for a low ESR capacitor is to maintain stability of the control loop.  Even if you are regulating after the LM2596, you would still want to maintain proper stability.  Use the recommendation of the datasheet and go with the low ESR cap.

A: Use Low ESR caps in the feedback loop and for the filter capacitor after the inductor. The input capacitor, is not as important, but the design might incur more loss and have slightly higher ripple with a higher ESR on the input capacitor. I believe the regulator will help with regulaton, especially with short traces.  The best way to find out if the design will be tolerant to a low ESR cap is to simulate it in SPICE.

Source: https://www.onsemi.com/pub/Collateral/LM2596-D.PDF

A: It is extremely important to use capacitor that is withing the allowed ESR limits, but as low as possible, because linear regulators can be bad at handling high frequency ripple so less ripple is better. If you look at LM338 datasheet, ripple rejection is very near 0dB at 150kHz and it can even amplify ripple at higher frequencies. Consider adding extra filtering between regulators, or consider if some other regulator is better.


text:
Q: Is there a way to declare new variables in a loop using string? I need to set 7 items from a match to 7 strings, so instead of doing something like this
var item0 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item0.ToString())).FirstOrDefault().Key;
var item1 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item1.ToString())).FirstOrDefault().Key;
var item2 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item2.ToString())).FirstOrDefault().Key;
var item3 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item3.ToString())).FirstOrDefault().Key;
//...

I thought of doing something easier in a for loop like this
string[] itemsList = new string[7];
for (int j = 0; j < itemsList.Length; j++)
    {
        string nextItem = $"Item{j}";
        itemsList[j] = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.nextItem.ToString())).FirstOrDefault().Key; //problem is here
    }

But c# doesn't realize I'm trying to use the nextItem string. Is there a way I can use a string to define what item I want?

A: You can use reflection. ie:
string[] itemsList = new string[7];
var stats = matches[i].Participants[participantNum].stats;
for (int j = 0; j < itemsList.Length; j++)
{
    var nextItem = stats.GetType().GetProperty($"item{j}").GetValue(stats).ToString();
    var v = items.Data.Where(p => p.Key.Equals(nextItem)).FirstOrDefault(); //problem is here
    itemsList[j] = (v != null)?v.Key:"";
}

PS: Probably in your model, you should define an List Items for an easier manipulation.


text:
Q: Ajax php mysql - fetch multiple values I want to fetch data from table 'driver'  by using sql where (name = '? ') condition
and fill the result into three text boxes .

<form action="my_parse_file.php"  method="post" id="form2">

  <fieldset >   <legend>Dispatch</legend>

        Dispatch_date:
        <input type="date" name="dispatch_date" value="" size="32" />

        Driver_name:
        <select name="driver_name" id="driver_name" onchange="javascript:ajax_post();">
          <?php
do {
?>
          <option value="<?php echo $row_drivers['Driver_Name']?>"><?php echo $row_drivers['Driver_Name']?></option>
          <?php
} while ($row_drivers = mysql_fetch_assoc($drivers));
  $rows = mysql_num_rows($drivers);
  if($rows > 0) {
      mysql_data_seek($drivers, 0);
      $row_drivers = mysql_fetch_assoc($drivers);
  }
?>
        </select>

        Driver_id:
        <input type="text" name="driver_id" value="" size="32" />

        Contact No.
        <input type="text" name="contact_no" id="contact_no" />

        Truck_id:
        <input type="text" name="truck_id" value="" size="32" />

        Nums. of skids
        <input type="number" min="0" max="30"  id="skids"  required="required" />

        <input type="submit" value="Insert record" />
          <?php ?>

  </fieldset>
  <input type="hidden" name="MM_insert" value="form2" />
</form>

I am trying to fetch data from other php page
<?php echo ' Driver Name' ?>
<?php echo ' Driver ID' ?>
<?php echo ' Contact no' ?>

so please help I am just new to Ajax and php

A: Encode the output of the PHP file you're fetching with AJAX as JSON using json_encode and then parse hr.responseText as JSON and access the data accordingly.
Have a look here: http://www.json.org/js.html


text:
Q: Getting content from http request android, conent ill-formed I am trying to connect to the twitter API using OAuth2 method toget the bearer token.
I am using an AsyncTask making the call to Twitter. My request seems to be accepted and return an error code 200, but when I try to read the content which is supposed to contain the token that I want, but the format is odd, as well as the content-length of the response.
I am building it according to this link.
Here is the AsyncTask I am using to make the request:
private class RequestBearerTockenTask extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... string) {

        // On récupère les keys passées en paramètre
        String consumerKey = string[0];
        String secretKey = string[1];

        // On encode en base64 le bearerToken en accord avec la doc twitter
        String base64encodedBearerToken = Base64.encodeToString((consumerKey + ":" + secretKey).getBytes(), Base64.NO_WRAP);

        // Variables locales de la fonction
        String bearerTocken = "";
        URL url = null;
        HttpURLConnection urlConnection = null;

        try {
            // On formate la requete HTTP
            url = new URL("https://api.twitter.com/oauth2/token");
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Host", "api.twitter.com");
            urlConnection.setRequestProperty("User-Agent", " My Twitter App v1.0.23");
            urlConnection.setRequestProperty("Authorization", "Basic " + base64encodedBearerToken);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            urlConnection.setRequestProperty("Content-Length", "29");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip");

            String requestBody =  "grant_type=client_credentials";
            byte[] outputInBytes = requestBody.getBytes("UTF-8");
            OutputStream os = urlConnection.getOutputStream();
            os.write( outputInBytes );
            os.close();

            // On lit l'entete de la reponse
            int responseCode = urlConnection.getResponseCode();

            switch (responseCode) {
                case 200:
                case 201:

                    BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String line;
                    while ((line = rd.readLine()) != null) {
                        bearerTocken += line;
                    }
                    break;
                default:
                    bearerTocken = "";
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bearerTocken;
    }
}

The bearerToken at the end is like:

����������������V*��N͋/�,HU�RJJM,J-R�QJLNN-.�K�����/�rW03��5��+81��$���=?[��)�ɱ���B�إа�2�)+����$�2��
  ����?���?7�;�0�2�995=�-=/$$�"�30T�����������9�뇛������

with a content length of 149 instead of 140 according to the documentation.
Do you have any clue why I am getting such a response?

A: If you are not decoding/handling the gzip compression, why you are using it? the content is encoded in gzip. Before using it, you need to decode it. I suggest you not to use that encoding while calling the API. remove the code line urlConnection.setRequestProperty("Accept-Encoding", "gzip"); and all should work.


text:
Q: TestNG + Spring test: EntityManager return null with testng I am new to testng framework .while migrating to testng from junit ,entityManager return null value .its looks strange for me can any one spot my mistake . here i placed my code snippets.thank you .
Entity
@Entity
@Table(name = "school")
public class School {
    private Integer id;
    private String schoolName;
    private String address;

    getters and setters here
}

Test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/applicationContext.xml" })
@Transactional
public class SchoolTest {

@PersistenceContext
private EntityManager entityManager;

String address,schoolName;

@BeforeClass
public void init() {
    address = "chinna kadai st";
    schoolName = "SVM School";
}
@Test
public void save_school() {
    School school = new School();
    school.setAddress(address);
    school.setSchoolName(schoolName);
    entityManager.persist(school);
}
}

the above code is working well while using Junit

A: Instead of using @RunWith(SpringJUnit4ClassRunner.class), you need to extend your test class from AbstractTransactionalTestNGSpringContextTests
Read here for more info in Spring Reference docs.


text:
Q: Multiple database dependencies is causing to connect database in Quarkus I have two environments like onprem and aws, for
onprem we have connected with Oracle database and required configuration
is done and but for aws we are using aurora postgres and whenever
i have tried to add postgres dependency then deploying into
aws environment it's giving error so is it possible if we have
multiple dependencies in same pom file and used for different environments.
Quarks version : 1.13.3.final
Sample configuration:

Oracle:
-------
quarkus.datasource.db-kind=oracle
quarkus.datasource.username=user-default
quarkus.datasource.password=password-default
quarkus.datasource.reactive.url=jdbc:oracle:thin://localhost:5432/default

Postgresql:
-----------
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=user-default
quarkus.datasource.password=password-default
quarkus.datasource.reactive.url=postgresql://localhost:5432/default

Code or issue:
The issue i'm getting is as follows:
2021-11-11 07:18:45,173 WARN [org.hib.eng.jdb.env.int.JdbcEnvironmentInitiator] (main) HHH000342: Could not obtain connection to query metadata: java.sql.SQLException: Driver does not support the provided URL: jdbc:postgresql://
        at io.agroal.pool.ConnectionFactory.connectionSetup(ConnectionFactory.java:220)
            at io.agroal.pool.ConnectionFactory.createConnection(ConnectionFactory.java:204)
            at io.agroal.pool.ConnectionPool$CreateConnectionTask.call(ConnectionPool.java:490)
            at io.agroal.pool.ConnectionPool$CreateConnectionTask.call(ConnectionPool.java:472)

Dependencies:
quarkus-jdbc-oracle
quarkus-jdbc-postgresql

A: According to the official documentation, you can use Multiple Datasources.
However if you have more than 1, then you must provide a Name, otherwise how will Quarkus know which Drivers to use.
The format : quarkus.datasource.<datasourceCustomName>.  If it is not your default DataSource which will not require a name.
Important to Notice: For now, multiple datasources are only supported for JDBC and the Agroal extension. So it is not currently possible to create multiple reactive datasources.
https://quarkus.io/guides/datasource#multiple-datasources
Multiple Datasources

Configuring Multiple Datasources
For now, multiple datasources are only supported for JDBC and the
Agroal extension. So it is not currently possible to create multiple
reactive datasources.
The Hibernate ORM extension supports defining several persistence
units using configuration properties. For each persistence unit, you
can point to the datasource of your choice.
Defining multiple datasources works exactly the same way as defining a
single datasource, with one important change: you define a name.

In the following example, you have 3 different datasources:

*

*The default one,

*A datasource named users,

*A datasource named inventory,

each with its own configuration.
quarkus.datasource.db-kind=h2
quarkus.datasource.username=username-default
quarkus.datasource.jdbc.url=jdbc:h2:mem:default
quarkus.datasource.jdbc.max-size=13

quarkus.datasource.users.db-kind=h2
quarkus.datasource.users.username=username1
quarkus.datasource.users.jdbc.url=jdbc:h2:mem:users
quarkus.datasource.users.jdbc.max-size=11

quarkus.datasource.inventory.db-kind=h2
quarkus.datasource.inventory.username=username2
quarkus.datasource.inventory.jdbc.url=jdbc:h2:mem:inventory
quarkus.datasource.inventory.jdbc.max-size=12

A: quarkus.datasource.db-kind is fixed at build time. The property can not change at runtime.
You have to build the app for Oracle and seperate for Postgresql
https://quarkus.io/guides/all-config#quarkus-datasource_quarkus.datasource.db-kind


text:
Q: Error on running php in online web hosting I have two PHP files that I have set up on an online web hosting platform in order to integrate the database into my android application. Whenever I run the URL : https://wounding-pat.000webhostapp.com/register.php in order to test if the register.php code is running correctly, I get the following messages on my browser.
Connection Successful
Notice: Undefined index: name in /storage/ssd2/158/3185158/public_html/register.php on line 5
Notice: Undefined index: email in /storage/ssd2/158/3185158/public_html/register.php on line 6
Notice: Undefined index: password in /storage/ssd2/158/3185158/public_html/register.php on line 7
Notice: Undefined index: subject in /storage/ssd2/158/3185158/public_html/register.php on line 8
Notice: Undefined index: counsellor in /storage/ssd2/158/3185158/public_html/register.php on line 9
Notice: Undefined variable: connection in /storage/ssd2/158/3185158/public_html/register.php on line 13
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /storage/ssd2/158/3185158/public_html/register.php on line 13
Error
The following is my init.php code
<?php

$host = "localhost";
$database = "id3185158_csetestonlinedb";
$username = "id3185158_root";
$password = "admin";

//$con = mysqli_connect($host, $username, $password, $database);

if (mysqli_connect($host, $username, $password, $database)) {

    echo "Connection Successful";

} else {

    echo "Connection Unsuccessful";

}

?>
The following is my register.php code
<?php

require "init.php";

$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$subject = $_POST["subject"];
$counsellor = $_POST["counsellor"];

$sql_query = "insert into teachers values('$name', '$email', '$password', '$subject', '$counsellor');";

if (mysqli_query($connection, $sql_query)) {

    echo " Data Inserted";

} else {

    echo " Error";

}

?>

A: *

*If you are hitting this URL directly in browser address bar, which will be the GET method the code will not work. Try tools like postman to create POST method request to this URL along with the required params like email, password, subject, counsellor.

*There is no variable defined with name $connection in your register.php file, http://php.net/manual/en/function.mysqli-connect.php function returns the variable which you should set to $connection.

A: If you run the url in browser then it definitely shows the error because you are getting variable through post. It will only work if you send a post request to register file with all the parameters which you are getting through post.
Also try to use isset like that
  If (isset($_POST[`name`] )) {
$name=$_POST['name' ] ;
}

Also run your insert query when values are coming.


text:
Q: AWS Aurora RDS 2nd reader gets no queries Running a Postgres Aurora RDS with one writer and two readers.
One reader is used heavily, but the other is barely used at all according to CloudWatch.

The Laravel application this is connected to points the read host to the reader cluster endpoint so that Aurora can do the balancing internally, but it does not appear to be doing that, instead favoring the 1st reader exclusively.
Is there some misconfiguration in the RDS or something else going on?

A: We have also faced the same issue and it got resolve after reduced the DNS TTL value in our Java application.
Amazon Aurora for MySQL or PostgreSQL distribute workload between reader nodes as below (From AWS Manual)

Aurora uses a  DNS based round-robin load balancing mechanism for
  balancing connections between the reader instances.  This load
  balancing is handled through Amazon Route 53's DNS service.  This
  means that your application makes a DNS query for each new connection
  request. Each time the reader endpoint is resolved, the instance IP of
  one of the reader is provided for the connection. In order to get the
  instance IP of a different reader each time, one must keep resolving
  the endpoint without caching DNS. Aurora DNS cache uses a short Time
  to Live (TTL) of  5 seconds. To ensure both the readers are equally
  utilized, care must be taken not to increase the TTL more than 5
  seconds for a client and network configuration. Caching DNS responses
  for longer than 5 seconds can result in overutilization of one reader
  over others as you have been experiencing.

In your application check the DNS TTL set for the application and adjust it down to 5 seconds.


text:
Q: Customize the menu depending on situation in WPF How can I customize the menu to the situation in WPF?
I have a main window with a basic menu. In this window, I can load different UserControls and then I want the menu to be expanded with different menu options depending on which User Control is used.
Example:
Main menu:
File
   Open
   -
   MRU
   -
   Exit

For viewing of UserControl 1:
File
   Open
   Edit
   -
   MRU
   -
   Exit

For viewing of UserControl 2:
File
   Open
   Edit
   -
   MRU
   -
   Exit
View
   Show codes
   Show capital letters

In Editing
File
   Open
   Save
   Save as...
   -
   MRU
   -
   Exit
Edit
   Add
   Remove
   Move
   -
   Cancle Edit

A: I would bind the menu to a Collection, and have the different UserControls alter the Collection when loaded.
EDIT - Here's an example
Your main View would contain something like this
<Menu ItemsSource="{Binding Path=CurrentUserControl.MenuItems}">
    <Menu.Resources>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Header" Value="{Binding MenuItemText}" />
            <Setter Property="Command" Value="{Binding MenuItemCommand}" />
            <Setter Property="CommandParameter" Value="{Binding MenuItemCommandParameter}" />
        </Style>
    </Menu.Resources>
</Menu>

While each UserControl would contain a Collection property of the MenuItems you would like to display
public class MenuItem
{
    public string MenuItemText {get; set;}
    public ICommand MenuItemCommand {get; set;}
    public object MenuItemCommandParameter {get; set;}
}

...
public ObservableCollection<MenuItem> MenuItems;

A: You can use the CompositeCollection to merge multiple collection into one.
Following the example from 1:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Grid Background="Transparent">
    <Grid.Resources>
        <x:Array Type="{x:Type sys:Object}" x:Key="extensions">
            <Separator />
            <MenuItem Header="Extension MenuItem 1" />
            <MenuItem Header="Extension MenuItem 2" />
            <MenuItem Header="Extension MenuItem 3" />
        </x:Array>
    </Grid.Resources>
    <Grid.ContextMenu>
        <ContextMenu>
            <ContextMenu.ItemsSource>
                <CompositeCollection>
                    <MenuItem Header="Standard MenuItem 1" />
                    <MenuItem Header="Standard MenuItem 2" />
                    <MenuItem Header="Standard MenuItem 3" />
                    <CollectionContainer Collection="{StaticResource extensions}" />
                </CompositeCollection>
            </ContextMenu.ItemsSource>
        </ContextMenu>
    </Grid.ContextMenu>
  </Grid>
</Window>

A: I did found a solution: http://www.codeproject.com/KB/menus/WPFMergeMenu.aspx
But there should be something better

A: How about binding the visibility of certain menu options to booleans in the ViewModel, and using an IValueConverter to switch between Visible and Collapsed?

A: A simple approach is to build a series of if-then constructs in your code behind, to change the visibility of various menu items, depending on what user controls are visible.