text:
Q: I want a electricity billing system using python and Mysql I am a beginner in Python and MySQL and I am trying to make an electricity billing system where I want python to give three options 1. New user,2. existing use 3. exit and Mysql should create its table when the user enters his choice. But in my code when i enter my choice it shows error.
**import mysql.connector as sql , random , datetime as dt
import matplotlib.pyplot as plt
conn=sql.connect(host='localhost',user='root',passwd='mc.la.ren',database='EBS')
if conn.is_connected():
    print("successfully connected")
c='YES' or "yes" or 'Yes'
V='YES' or "yes" or 'Yes'
c1=conn.cursor()
while c=='YES' or "yes" or 'Yes':
    print('************************WELCOME TO ELECTRICITY BILLING SYSTEM************************')
    print(dt.datetime.now())
    print('1.NEW USER')
    print('2.EXISTING USER')
    print('3.EXIT')
    choice1=int(input('ENTER YOUR CHOICE:'))
    if choice1==1:
        username=input("Enter your username number :")
        password=input("Enter your password:")
        confirmpasswd=input("Confirm  your password:")
        if password==confirmpasswd:
            info1="insert into newuser values('{}','{}','{}')".format(username,password,confirmpasswd)
            c1.execute(info1)
            conn.commit()
            c=input("do you want to continue?(yes or no)")
        else:
            print('your confirm password is incorrect')
            print('Try again')
            c=input("do you want to continue?(yes or no)")
    elif choice1==2:
        username=input('Enter your username:')
        password=input('Enter your password:')
        info2="select * from newuser where username='{}' and password='{}'".format(username,password)
        c1.execute(info2)
        data=c1.fetchall()
        while V=='YES' or "yes" or 'Yes':
            if any(data):
                print('************************WELCOME TO ELECTRICITY BILLING SYSTEM************************')
                print("1.ACCOUNT SETTINGS")
                print("2.TRANSACTION")
                print("3.VIEW CUSTOMER DETAILS")
                print("4.GRAPHICAL REPRESENTATION")
                print('5.EXIT')
                choice2=int(input('ENTER YOUR CHOICE'))
                if choice2==1:
                    print('1.NEW CUSTOMER')
                    print('2.DELETE EXISTING ACCOUNT')
                    choice12=int(input('ENTER YOUR CHOICE:'))
                    if choice12==1:
                        accountno=random.randrange(1000000,9999999,10)
                        print("your accountno is",accountno)
                        boxid=input("enter your mete box ID:")
                        bankname=input('Enter your BANK NAME  :')
                        bankbranch=input('Enter your BANK BRANCH  :')
                        name=input('Enter your name  :')
                        address=input('Enter your address  :')
                        areacode=int(input('Enter your area PIN CODE  :'))
                        phoneno=int(input('Enter your PHONE NUMBER  :'))
                        email=input('Enter your email  :')
                        info2="insert into AddNewCustomer values({},'{}','{}','{}','{}',{},{},'{}','{}')".format(accountno,bankname,bankbranch,name,address,areacode,phoneno,email,boxid)
                        c1.execute(info2)
                        conn.commit()
                        V=input("do you want to continue?(yes or no)")
                        if V=='yes':
                            continue
                        else:
                            break
                    elif choice12==2:
                        acc=input("ENTER YOUR ACCOUNT NUMBER:")
                        use=input("ENTER YOUR USERNAME:")
                        info6=c1.execute("delete from Transaction where accountno='{}'".format(acc))
                        info7=c1.execute("delete from AddNewCustomer where accountno='{}'".format(acc))
                        info8=c1.execute("delete from newuser where username='{}'".format(use))
                        c1.execute(info6)
                        c1.execute(info7)
                        c1.execute(info8)
                        conn.commit()
                        print("THANK YOU FOR USING OUR SOFTWARE,YOUR ACCOUNT IS SUCCESFULLY DELETED")
                        V=input("do you want to continue?(yes or no)")
                        if V=='yes':
                            continue
                        else:
                            break

                elif choice2==2:
                    accountno=int(input('Enter your account number  :'))
                    info10="select * from Transaction where accountno="+str(accountno)
                    c1.execute(info10)
                    data3=c1.fetchall()
                    for row in data3:
                        paid=row[6]
                    if paid=='yes':
                        print('you have already paid the bill')
                        break
                    else:
                        unit=random.randint(0,101)
                        print('Dear customer, you have used ',unit,'units of electricity.')
                        print('One unit of curent is 150 ruppees')
                        amount=150*unit
                        toda=dt.date.today()
                        deadline=dt.date(2020,1,30)
                        if deadline<toda:
                            fine=(toda-deadline)*30
                            totamt=amount+fine
                            print('you have dealyed for ',toda-deadline,'days.The fine per day is 30 rupees.')
                            GST=(15/100)*totamt
                            totalamt=totamt+GST
                            print('Pleae payup ',totalamt,'rupees inclding GST')
                            p=input("Please Enter YES to transact")
                            if p=="YES"or 'Yes'or'yes':
                                print("Transaction successful")
                                print("You have paid the bill")
                            else:
                                print('plz pay the bill sooner')
                        else:
                            totamt=0
                            GST=(15/100)*amount
                            totalamt=amount+GST
                            print('Pleae payup ',totalamt,'rupees inclding GST')
                            p=input("Please Enter YES to transact")
                            if p=="YES":
                                print("Transaction successful")
                                print("You have paid the bill")
                            else:
                                print('plz pay the bill sooner')
                        info3="insert into Transaction values({},{},'{}',{},{},{},'{}')".format(accountno,unit,toda,totamt,GST,totalamt,p)
                        c1.execute(info3)
                        conn.commit()
                        V=input("do you want to continue?(yes or no)")
                        if V=='yes':
                            continue
                        else:
                            break
                elif choice2==3:

                    accountno=int(input('Enter your account number  :'))
                    info4="select * from AddNewCustomer where accountno=" + str(accountno)
                    c1.execute(info4)
                    data1=c1.fetchall()
                    for row in data1:
                        print(" Account Number: ", row[0])
                        print("bankname:",row[1])
                        print("bankbranch:",row[2])
                        print("Person name:",row[3])
                        print("Your meter device ID=",row[8])
                        print("Residential address:",row[4])
                        print("area code:",row[5])
                        print("phone number:",row[6])
                        print("email:",row[7])
                        info5="select * from Transaction where accountno=" + str(accountno)
                        c1.execute(info5)
                        data2=c1.fetchall()
                    for row in data2:

                        print(" Unit : ",row[1])
                        print(" paid on:",row[2])
                        print("amount to be paid without GST:",row[3])
                        print("GST=",row[4])
                        print("amount to be paid including GST:",row[5])
                    V=input("do you want to continue?(yes or no)")
                    if V=='yes':
                        continue
                    else:
                        break
                elif choice2==4:
                    info9="select accountno,totalamt from Transaction"
                    c1.execute(info9)
                    L1,L2,=[],[]
                    for i in c1.fetchall():
                        L1.append(i[0])
                        L2.append(i[1])
                    plt.plot(L1,L2)
                    plt.title("GRAPH")
                    plt.show()
                    V=input("do you want to continue?(yes or no)")
                    if V=='yes':
                        continue
                    else:
                        break
                elif choice2==5:
                    print("THANK  YOU!!!!  VISIT AGAIN!!!!")
                    break
                    c='yes'

            else:
                print('username / password is incorrect')
                break
                c=input("do you want to try again?(yes or no)")

        else:
            print("THANK  YOU!!!!  VISIT AGAIN!!!!")
            V='no'

    elif choice1==3:
        print("THANK  YOU!!!!  VISIT AGAIN!!!!")
        c='no'
        break
    else:
        print("invalid choice")
        c=input("do you want to try again?(yes or no)")
else:
    print("THANK  YOU!!!!  VISIT AGAIN!!!!")

    c='no'**

OUTPUT
successfully connected
************************WELCOME TO ELECTRICITY BILLING SYSTEM************************
2022-02-10 12:22:23.390606
1.NEW USER
2.EXISTING USER
3.EXIT
ENTER YOUR CHOICE:1
Enter your username number :1
Enter your password:1
Confirm  your password:1

It shows error (1136 (21S01): Column count doesn't match value count at row 1) at last what should i do to fix it, and if i fix one error it shows another error.


text:
Q: Imaginary header sent out by WP Since I migrated my page I get this annoying warning message. It shows up when I'm saving changes to saving anything (posts, settings...) and uploading images (that's where I noticed it). The message is as follows:
Cannot modify header information - headers already sent by (output started at path/to/theme/functions.php:1)  in /path/to/wp/wp-includes/pluggable.php on line 881

Now I know this message should show up when there's something being output to the browser before a header is called. But my functions.php is clear, at least so it looks like in dreamweaver:
<?php
add_theme_support( 'post-thumbnails' );

add_action...

I don't see no output there...
What's wrong ? I didn't get the message before, on the test domain.

A: Your functions.php file is probably encoded using UTF8 BOM.
You should try to encode it without BOM, you can achieve this using, for example, notepad++.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change domain of joomla 2.5 i installed a "Joomla" on a domain. now i want to change the domain of my "joomla". how can do it? what changes must do in "joomla" to view correctly my site?

A: "Joomla" automatically change and fix with new domain. there is no need to change anything in "Joomla".


text:
Q: 230VAC line voltage sensing using MCU pin I Am designing a circuit to detect the presence of AC line voltage.It is basically to detect the switch On/OFF for a load.
Here is the circuit.

Here Input resistor ladder to step down the voltage. Varistor added to get it away from surge (Fuse included). zener to protect the opto. Opto is darlington with transistor to reduce the opto input current and therefor the input resistor losses.
Since this going to commercial product i would like to gather some info on reliability and surge protection.
1) Is this circuit good enough to handle potential surges/Back emf from inductive loads.
2) Is there any better/cost effective alternatives.
4) I am using 8 in my board to detect 8 channels all are powered from same AC source. Is there a way to consolidate these and reduce overall cost?
Thanks in advance!

A: This is simplified version of your schematics, that should work equal.

simulate this circuit – Schematic created using CircuitLab
For example SFH628A-4 has a CTR ratio of 250 at 0.5mA IF current. The absolute maximum allowed forward current is 50mA. The insulation resistance is 5.3kV. So at 5.3kV spike, the current trough diode would be 5300/440= 12mA, which is far from absoulte rating.


text:
Q: Reverse the order of a sort using DataTables I have a column that has value "n/a" (without quotes) and numbers from 0 - 5, when sorted it shows 0 first and the other way shows n/a first and begins descending, is there a way to make it show n/a and then ascend to 5? I have tried:
 oTable.fnSort([[0, 'natural-asc']]);

and
"aaSorting": [[ 0, "natural-asc" ]],

but no luck. Also, is there a way to have it behave correctly when using a special character like $ or €? because so far I haven't been able to make it do so either.

A: If you want to apply a different sorting type you should use aoColumns like this:
        "aoColumns": [
            null,
            null,
            null,
            { "sType": "natural" },
            null
        ]

To use natural sorting you should do the following things:

*

*include the function for the natural sorting from this page

*define your own sorting function like this:
jQuery.fn.dataTableExt.oSort['natural-asc']  = function(a,b) {
    return naturalSort(a,b);
};
jQuery.fn.dataTableExt.oSort['natural-desc'] = function(a,b) {
    return naturalSort(a,b) * -1;
};

*use aoColumns like indicated above

-in any case if you post an example on jsfiddle.net it's easier to help


text:
Q: rotate error log file of MySQL 8.0 server over windows we have MySQL 8.0 installed over windows and my err log file (.err) is very large (11 GB),
so we need to rotate the error loge so it writes to a new file when the current file is 200 MB
we tried to rename the error log file but it needs to stop MySQL service.
so is there a way to rotate error log file automatically like audit file rotating


text:
Q: MD5 vs CRC32: Which one's better for common use? Recently I read somewhere that although both CRC32 and MD5 are sufficiently uniform and stable, CRC32 is more efficient than MD5. MD5 seems to be a very commonly used hashing algorithm but if CRC32 is faster/more memory efficient then why not use that?

A: One big difference between CRC32 and MD5 is that it is usually easy to pick a CRC32 checksum and then come up with a message that hashes to that checksum, even if there are constraints imposed on the message, whereas MD5 is specifically designed to make this sort of thing difficult (although it is showing its age - this is now possible in some situations).
If you are in a situation where it is possible that an adversary might decide to sit down and create a load of messages with specified CRC32 hashes, to mimic other messages, or just to make a hash table perform very badly because everything hashes to the same value, then MD5 would be a better option. (Even better, IMHO, would be HMAC-MD5 with a keyed value that is unique to the module using it and unknown outside it).

A: MD5 is a one-way-hash algorithm. One-way-hash algorithms are often used in cryptography as they have the property (per design) that it's hard to find the input that produced a specific hash value. Specifically it's hard to make two different inputs that give the same one-way-hash. They are often used as a way to show that an amount of data has not been altered intentionally since the hash code was produced. As the MD5 is a one-way-hash algorithm the emphasis is on security over speed. Unfortunately MD5 is now considered insecure.
CRC32 is designed to detect accidental changes to data and is commonly used in networks and storage devices. The purpose of this algorithm is not to protect against intentional changes, but rather to catch accidents like network errors and disk write errors, etc. The emphasis of this algorithm is more on speed than on security.

A: CRCs are used to guard against random errors, for example in data transmission.
Cryptographic hash functions are designed to guard against intelligent adversaries forging the message, though MD5 has been broken in that respect.

A: Actually, CRC32 is not faster than MD5 is.
Please take a look at: https://3v4l.org/2MAUr
That php script runs several hashing algorithms and measures the time spent to calculate the hashes by each algorithm. It shows that MD5 is generally the fastest hashing algorithm around. And, it shows that even SHA1 is faster than MD5 in most of the test cases.
So, anyway, if you want to do some quick error-detection, or look for random changes... I would always advice to go with MD5, as it simply does it all.

A: You should use MD5 which is 128bit long.
CRC32 is only 32 bit long and its purpose is to detect errors not to hash things.
In case you need only a 32bit hash function you can choose 32 bits that are returned by MD5 the LSBs/MSBs/Whatever.

A: The primary reason CRC32 (or CRC8, or CRC16) is used for any purpose whatsoever is that it can be cheaply implemented in hardware as a means of detecting "random" corruption of data.  Even in software implementations, it can be useful as a means of detecting random corruption of data from hardware causes (such as noisy communications line or unreliable flash media).  It is not tamper-resistant, nor is it generally suitable for testing whether two arbitrary files are likely to be the same: if each chunk of data in file is immediately followed by a CRC32 of that chunk (some data formats do that), each chunk will have the same effect on the overall file's CRC as would a chunk of all zero bytes, regardless of what data was stored in that chunk.
If one has the means to calculate a CRC32 quickly, it might be helpful in conjunction with other checksum or hash methods, if different files that had identical CRC's would be likely to differ in one of the other hashes and vice versa, but on many machines other checksum or hash methods are likely to be easier to compute relative to the amount of protection they provide.

A: From Wikipedia's article on MD5 (emphasis mine):

MD5 is a widely used cryptographic hash function

Now CRC32:

CRC is an error-detecting code

So, as you can see, CRC32 is not a hashing algorithm. That means you should not use it for hashing, because it was not built for that.
And I think it doesn't make much sense to talk about common use, because similar algorithms are used for different purposes, each with significantly different requirements. There is no single algorithm that's best for common use, instead, you should choose the algorithm that's most suited for your specific use.

A: It depends on your goals. Here are some examples what can be done with CRC32 versus MD5:
Detecting duplicate files
If you want to check if two files are the same, CRC32 checksum is the way to go because it's faster than MD5. But be careful: CRC only reliably tells you if the binaries are different; it doesn't tell you if they're identical. If you get different hashes for two files, they cannot be the same file, so you can reject them as being duplicates very quickly.
No matter what your keys are, the CRC32 checksum will be one of 2^32 different values. Assuming random sample files, the probability of collision between the hashes of two given files is 1 / 2^32. The probability of collisions between any of N given files is (N - 1) / 2^32.
Detecting malicious software
If security is an issue, like downloading a file and checking the source's hash against yours to see if the binaries aren't corrupted, then CRC is a poor option. This is because attackers can make malware that will have the same CRC checksum. In this case, an MD5 digest is more secure -- CRC was not made for security. Two different binaries are far more likely to have the same CRC checksum than the same MD5 digest.
Securing passwords for user authentication
Synchronous (one-way) encryption is usually easier, faster, and more secure than asynchronous (two-way) encryption, so it's a common method to store passwords. Basically, the password will be combined with other data (salts) then the hash will be done on all of this combined data. Random salts greatly reduce the chances of two passwords being the same. By default, the same password will have the same hash for most algorithms, so you must add your own randomness. Of course, the salt must be saved externally.
To log a user in, you just take the information they give you when they log in. You use their username to get their salt from a database. You then combine this salt with the user's password to get a new hash. If it matches the one in in the database, then their login is successful. Since you're storing these passwords, they must be VERY secure, which means a CRC checksum is out of the question.
Cryptographic digests are more expensive to compute than CRC checksums. Also, better hashes like sha256 are more secure, but slower for hashing and take up more database space (their hashes are longer).

A: One man's common is another man's infrequent.  Common varies depending on which field you are working in.
If you are doing very quick transmissions or working out hash codes for small items, then CRCs are better since they are a lot faster and the chances of getting the same 16 or 32 bit CRC for wrong data are slim.
If it is megabytes of data, for instance, a linux iso, then you could lose a few megabytes and still end up with the same CRC.  Not so likely with MD5.  For that reason MD5 is normally used for huge transfers.  It is slower but more reliable.
So basically, if you are going to do one huge transmission and check at the end whether you have the correct result, use MD5.  If you are going to transmit in small chunks, then use CRC.

A: I would say if you don't know what to choose, go for md5.
It's less probable to cause you a headache.


text:
Q: How to pass class style from parent to child in Angular, and using it in specific element so I'm using a template that I downloaded of ngx-admin.
I'm creating new lib of some simple components such as input with labels and etc. this lib component is style free, I would like to inject the ngx-admin styles to these components.
What shall be the best way to pass the syles and classes to the child lib components?
this is the template page.component.html which I'm using the new lib I created:

        <nb-card>
          <nb-card-header>Default Inputs</nb-card-header>
          <nb-card-body>
        <lib-input-with-lable></lib-input-with-lable> <- this is the lib I creared
          </nb-card-body>
        </nb-card>

Lib component:
import {Component, Input, OnInit} from '@angular/core';

@Component({
  selector: 'lib-input-with-lable',
  template: `

      {{title}}
      <input style="margin-left: 2rem"/>

  `,
  styleUrls: ['./input-with-lable.component.scss'],
})
export class InputAndLableComponent implements OnInit {

  constructor() { }

  @Input() title: string;
  ngOnInit(): void {
  }

}

This is how the template is using the classes for css style:
<input type="password" nbInput fullWidth placeholder="Password">

So I would like to have the ability to use nbInput & full width, which I added to page.component.scss
and I will like to use is some kind of
 <lib-input-with-lable --passing here the styles--->

and inside
to use is like this:
@Component({
      selector: 'lib-input-with-lable',
      template: `

          {{title}}
          <input ------using here the style------- style="margin-left: 2rem"/>

      `,
      styleUrls: ['./input-with-lable.component.scss'],
    })

A: Demo create one css  in input-with-lable.component.scss
.test{
  //write your css wants
}

then send input to
<lib-input-with-lable style={{style}}></lib-input-with-lable>

in child component
@Input() style: string;

then assign this attribute any element's class you want to effect css

A: You can use typescript object to write your CSS style in your parent.component.ts file and pass it as an object variable to your child component.
You can follow these steps:
1- Create an object in the parent.component.ts and populate it with your desired CSS style properties
export class ParentComponent {
    styleObj = {
        'font-weight': 'bold',
        'font-size': '30px',
        'color': '#3f51b5'
    };
}

2- Pass this object to the child component in the parent.component.html file
<child-component [myStyle]="styleObj"></child-component>

3- Get this object in the child.component.ts file as input and use it in the child.component.html file
export class ChildComponent {
    @Input() myStyle: object;
}

4- Use the input object in the child.component.html file
The sample text


text:
Q: Twists of elliptic curves over finite fields with characteristic 2 and 3 Let $E$ be an elliptic curve over a finite field $K$. In Silverman's The Arithmetic of Elliptic Curves, it is shown in Proposition 5.4. on page 343 that if the characteristic of $K$ is not equal to $2$ or $3$, then the equations of all twists of $E$ can be described explicitly:

Question: Is there a general description of the equations of an elliptic curve in Weierstrass form if $char(K)$ is $2$ or $3$?
In this paper by Kronberg, Soomro, Top, I can see how many twists an elliptic curve over a finite field with characteristic $2$ or $3$ has but I did not see (yet?) how these equations would look like.


text:
Q: SQL - Duplicate rows (changing one column) I am having hard time trying to create an view that contains duplicated values from a table in SQL Server Management Studio 17.
My table look like this:
DATE = datetime
Product = varchar(10)
Price = decimal(18,2)

Date     | Product | Price

07-12-17 |    1    | 32

06-12-17 |    24   | 35

There are 1-24 products for every day.
I want to create the following view-tabel:
Date     | Product | Price

07-12-17 |    1.1  | 32

07-12-17 |    1.2  | 32

07-12-17 |    1.3  | 32

07-12-17 |    1.4  | 32

06-12-17 |    24.1 | 35

06-12-17 |    24.2 | 35

06-12-17 |    24.3 | 35

06-12-17 |    24.4 | 35

And so on for all 24 products for every day.

A: Try to use CROSS JOIN with VALUES
SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.num) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN (VALUES(1),(2),(3),(4)) l(num)
ORDER BY t.[Date],t.Product,l.num

Variant with UNION ALL
SELECT
  t.[Date],
  t.Product+'.'+l.Label ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN
  (
    SELECT '1' Label UNION ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4'
  ) l
ORDER BY t.[Date],t.Product,l.Label

If you have another table which contains rows with numbers 1-4 then you can use CROS JOIN with that table
SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.[ID from another table]) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN [Your table with numbers] l
ORDER BY t.[Date],t.Product,l.[ID from another table]

If you need only 4 duplicates then you also can use 4 queries with UNION ALL
SELECT [Date],Product+'.1' ProductLabel,Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.2',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.3',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.4',Price FROM [Your table]
ORDER BY [Date],ProductLabel


text:
Q: Box plot of hourly data in Time Series Python How to group by a given frequency let say Hourly, and  create a set of box plot for one column in a time series data set ?
range = pd.date_range('2015-01-01', '2015-12-31', freq='1min')
df = pd.DataFrame(index = range)

# Average speed in miles per hour
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
# Distance in miles (speed * 0.5 hours)
df['distance'] = df['speed'] * 0.25
# Cumulative distance travelled
df['cumulative_distance'] = df.distance.cumsum()
df.head()

How to group by a given frequency let say Hourly, and  create a set of box plot for speed ? A sample output is given below.

A: IIUC, you need, which gives you a box of speed during each hour of the a day:
#You need to reshape your dataframe with hours as column headers
df.set_index(df.index.hour, append=True)['speed'].unstack().plot.box()

Output:

A: You can also use seaborn:
sns.boxplot(x=df.index.hour, y=df.speed)

output:


text:
Q: I can't get the description part in NestJs
Hello everyone. In the trainings I watch, this explanation comes out of everyone, but it does not come out to me. I tried all the plugins but couldn't make it. How can I handle this. Thanks in advance.
Hello everyone. In the trainings I watch, this explanation comes out of everyone, but it does not come out to me. I tried all the plugins but couldn't make it. How can I handle this. Thanks in advance.
PS
I use vscode. I've tried all the plugins related to NestJs. In all tutorials, this comes out when they move the mouse cursor between the e.g. Controller ( | ).

A: This is JSDocs and is coming from the node_modules/@nestjs/common/decorators/core/controller.decorator.d.ts
If you Ctrl + Click on @Controller (Go to Definition) you should get:
/**
 * Decorator that marks a class as a Nest controller that can receive inbound
 * requests and produce responses.
 *
 * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses.
 * It defines a class that provides the context for one or more related route
 * handlers that correspond to HTTP request methods and associated routes
 * for example `GET /api/profile`, `POST /users/resume`.
 *
 * A Microservice Controller responds to requests as well as events, running over
 * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics).
 * It defines a class that provides a context for one or more message or event
 * handlers.
 *
 * @see [Controllers](https://docs.nestjs.com/controllers)
 * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response)
 *
 * @publicApi
 */
export declare function Controller(): ClassDecorator;

This means that you have @nestjs/common package installed in your local repository.
Ensure you have no conflicting VS Code Extensions/Snippets/Plugins installed.


text:
Q: Implementing auto layout for views generated programmatically I have an app whose views are generated programmatically. Example:
-(void)loadView
{
    [super loadView];

// SET TOP LEFT BTN FOR NEXT VIEW
UIBarButtonItem *topLeftBtn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
self.navigationItem.backBarButtonItem = topLeftBtn;
[topLeftBtn release];

// programmatically set up the view for cart tableView
CGRect iouTableViewFrame = CGRectMake(0, 0, 320, 348);
iouTableView = [[UITableView alloc]initWithFrame:iouTableViewFrame style:UITableViewStylePlain];
[[self iouTableView] setDelegate:self];
[[self iouTableView] setDataSource:self];
[[self view] addSubview:iouTableView];

// set up the summary label
CGRect summaryTableFrame = CGRectMake(0, 348, 320, 18);
UILabel *summaryTableLabel = [[UILabel alloc] initWithFrame:summaryTableFrame];
[summaryTableLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
[summaryTableLabel setText:@"   Summary"];
UIColor *labelColor = UIColorFromRGB(MiddleBlueColor);
[summaryTableLabel setBackgroundColor:labelColor];
[summaryTableLabel setTextColor:[UIColor whiteColor]];
[[self view] addSubview:summaryTableLabel];

// set up the summary table
CGRect summaryTableViewFrame = CGRectMake(0, 366, 320, 44);
summaryTableView = [[UITableView alloc]initWithFrame:summaryTableViewFrame style:UITableViewStylePlain];
[summaryTableView setScrollEnabled:NO];
[[self summaryTableView] setDelegate:self];
[[self summaryTableView] setDataSource:self];
[[self view] addSubview:summaryTableView];
}

Yes. I will update to NIBs and use interface builder and storyboard in the future but I have not done ios programming in a year.
With the new iPhone 5 having a different screen size, the app just does not look good and I need to implement auto layout of some sort. Is there a way to do it programmatically for now instead of using IB?
Thanks much!

A: Yes there is, by using two methods in NSLayoutConstraint
-(NSArray*)constraintsWithVisualFormat:options:metrics:views:
-(NSLayoutConstraint*)constraintWithItem:attribute:relatedBy:toItem:attribute:
    multiplier:constant:

The visual format language is all packaged up into an NSString
So I'll take your iouTableView for example.
[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"|[iouTableView]|"
    options:0
    metrics:nil
    views:NSDictionaryOfVariableBindings(iouTableView)]];

The pipe symbol "|" represents the superview's edge.
The [] represent a view.
So what we did there was we hooked the iouTableView's left and right edge to the left and right edge of its superview.
Another example of the visual format:
Let's hook your table view, summary label and summary table vertically.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
    @"V:|[iouTableView(348)][summaryTableLabel(18)][summaryTableView(44)]"
    options:NSLayoutFormatAlignAllLeft
    metrics:nil
    views:NSDictionaryOfVariableBindings(iouTableView, summaryTableLabel, summaryTableView)]];

Now this links up all three views vertically on each of their edges, NSLayoutFormatAlignAllLeft tells all the views to align left and they'll do so based on other constraints, in this case, the previous constraint.
The ()s are used to specify the size of the views.
There's a bit more like inequalities and priorities as well as the "-" spacer symbol but check out the apple docs for that
Edit: Corrected the examples to use constraintsWithVisualFormat as shown in the method signature.

A: In addition to Aplle provided methods you can use Parus lib for operating with AutoLayout from code.
For example you will be able to specify:
PVVFL(@"[view1]-20-[view2]").fromRightToLeft.withViews(views).asArray

Instead of
[NSLayoutConstraint constraintsWithVisualFormat:@"[view1]-20-[view2]"
                                        options:NSLayoutFormatDirectionRightToLeft
                                        metrics:nil
                                          views:views]

Also you will be able to group layouts settings, mix VFL and not VFL constraints.
Parus able to prevent common mistakes, differentiate location and parameters constriaints, and provide great auto-completion support.


text:
Q: array of objects в swagger Имеется такая структура JSON:
[
  {
    "subject_id": 2,
    "subject_name": "Нейронные сети",
    "lectures": [
      {
        "lecture_id": 1,
        "name": "Введение"
      },
      {
        "lecture_id": 2,
        "name": "Структура нейрона"
      },
    ]
  }
]

Как в swagger задать корректное отображение массива объектов в lectures?
Первый объект в массиве отображается нормально, а на втором вылезает ошибка. Пример моего .yaml-файла
swagger: "2.0"
info:
  title: Learn
  description: API documentation
  version: 1.0.0

host: localhost:3000
basePath: /
produces:
 - application/json
schemes:
  - http
  - https

paths:
  /:
    get:
      summary: Returns a list of subjects and lectures.
      description: Contains id and name of subjects, lectures
      produces:
        - application/json
      responses:
        200:
          description: OK
          schema:
            type: array
            items:
              type: object
              properties:
                subject_id:
                  type: integer
                  example: 2
                subject_name:
                  type: string
                  example: "Нейронные сети"
                lectures:
                  type: array
                  items:
                    type: object
                    properties:
                      lecture_id:
                        type: integer
                        example: 1
                      name:
                        type: string
                        example: Введение

A: Вопрос решил таким образом:
                  type: array
                  items:
                    $ref: '#/definitions/Lectures'
                  example:
                    - lecture_id: 1
                      name: Введение
                    - lecture_id: 2
                      name: Структура нейрона

definitions:
  Lectures:
    type: object
    properties:
      lecture_id:
        type: integer
        example: 1
      name:
        type: string
        example: Введение


text:
Q: Json.net, deserialize dates out of range I'm having trouble deserializing dates with Newtonsoft.Json.
I have a class in C#, and complex data types in postgresql. With the row_to_json function of postgresql I have lot of the work done retriving data from database.
Everything works fine, then, when I have an infinity date, I got this error:
{"Could not convert string to DateTime: -infinity. Path 'valid_from', line 1, position 101."}

The code line I use is:
JsonConvert.PopulateObject(l[icont], myclass);

Where l is a list of json strings, icont is a counter and myclass is an instance of my class.
The closest documentation I found to my problem is here, where this problem is considered a bug: https://bugzilla.xamarin.com/show_bug.cgi?id=22955
I have few workarounds in mind:

*

*Use strings for dates in my c# class. I don't like this :-/

*Force the postgresql function to return special dates, like 01/01/1800 and 01/01/2200 and manage them. This can be OK because it is not storical data, but it is not... elegant.

How can I workaround this and keep infinity values in db?


text:
Q: Get contents source code em Javascript Ola,
estou tentando utilizar um javascript para ler o código fonte de uma outra página e escrever esse conteúdo dentro de uma div.

É algo parecido com o file_get_contents do php porém em javascript
Não está funcionando... Podem me dar uma luz? Obrigado!!

A: Falta a biblioteca jquery

Com JavaScript puro
function makeHttpObject() {
  try {return new XMLHttpRequest();}
  catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
  catch (error) {}

  throw new Error("Não foi possível criar o objeto de solicitação HTTP.");
}
var request = makeHttpObject();
request.open("GET", "URL_da_pagina", true);
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4)
    document.getElementById('somediv').innerHTML = (request.responseText);
};

HTML


text:
Q: Unable to make my script process locally created server response in the right way I've used a script to run selenium locally so that I can make use of the response (derived from selenium) within my spider.
This is the web service where selenium runs locally:
from flask import Flask, request, make_response
from flask_restful import Resource, Api
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

app = Flask(__name__)
api = Api(app)

class Selenium(Resource):
    _driver = None

    @staticmethod
    def getDriver():
        if not Selenium._driver:
            chrome_options = Options()
            chrome_options.add_argument("--headless")

            Selenium._driver = webdriver.Chrome(options=chrome_options)
        return Selenium._driver

    @property
    def driver(self):
        return Selenium.getDriver()

    def get(self):
        url = str(request.args['url'])

        self.driver.get(url)

        return make_response(self.driver.page_source)

api.add_resource(Selenium, '/')

if __name__ == '__main__':
    app.run(debug=True)

This is my scrapy spider which takes the benefit of that response to parse the title from a webpage.
import scrapy
from urllib.parse import quote
from scrapy.crawler import CrawlerProcess

class StackSpider(scrapy.Spider):
    name = 'stackoverflow'
    url = 'https://stackoverflow.com/questions/tagged/web-scraping?sort=newest&pageSize=50'
    base = 'https://stackoverflow.com'

    def start_requests(self):
        link = 'http://127.0.0.1:5000/?url={}'.format(quote(self.url))
        yield scrapy.Request(link,callback=self.parse)

    def parse(self, response):
        for item in response.css(".summary .question-hyperlink::attr(href)").getall():
            nlink = self.base + item
            link = 'http://127.0.0.1:5000/?url={}'.format(quote(nlink))
            yield scrapy.Request(link,callback=self.parse_info,dont_filter=True)

    def parse_info(self, response):
        item = response.css('h1[itemprop="name"] > a::text').get()
        yield {"title":item}

if __name__ == '__main__':
    c = CrawlerProcess()
    c.crawl(StackSpider)
    c.start()

The problem is the above script gives me the same title multiple times and then another title and so on.

What possible chage should I bring about to make my script work in the right way?

A: I ran both the scripts, and they run as intended. So my findings :

*

*downloader/exception_type_count/twisted.internet.error.ConnectionRefusedError there is no means to get through this error without permission of the server, here i.e ebay.

*Logs from scrapy:
2019-05-25 07:28:41 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 72,
'downloader/exception_type_count/twisted.internet.error.ConnectionRefusedError': 64,
'downloader/exception_type_count/twisted.web._newclient.ResponseNeverReceived': 8,
'downloader/request_bytes': 55523,
'downloader/request_count': 81,
'downloader/request_method_count/GET': 81,
'downloader/response_bytes': 2448476,
'downloader/response_count': 9,
'downloader/response_status_count/200': 9,
'finish_reason': 'shutdown',
'finish_time': datetime.datetime(2019, 5, 25, 1, 58, 41, 234183),
'item_scraped_count': 8,
'log_count/DEBUG': 90,
'log_count/INFO': 9,
'request_depth_max': 1,
'response_received_count': 9,
'retry/count': 72,
'retry/reason_count/twisted.internet.error.ConnectionRefusedError': 64,
'retry/reason_count/twisted.web._newclient.ResponseNeverReceived': 8,
'scheduler/dequeued': 81,
'scheduler/dequeued/memory': 81,
'scheduler/enqueued': 131,
'scheduler/enqueued/memory': 131,
'start_time': datetime.datetime(2019, 5, 25, 1, 56, 57, 751009)}
2019-05-25 07:28:41 [scrapy.core.engine] INFO: Spider closed (shutdown)
you can see only 8 items scraped. These are just the logos and other unrestricted things.

*Server Log :
s://.ebaystatic.com http://.ebay.com https://*.ebay.com". Either the 'unsafe-inline' keyword, a hash ('sha256-40GZDfucnPVwbvI/Q1ivGUuJtX8krq8jy3tWNrA/n58='), or a nonce ('nonce-...') is required to enable inline execution.
", source: https://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=323815597324&t=0&tid=10&category=169291&seller=wardrobe-ltd&excSoj=1&excTrk=1&lsite=0&ittenable=false&domain=ebay.com&descgauge=1&cspheader=1&oneClk=1&secureDesc=1 (1)
Ebay does not allow you to scrape itself.
So how to complete your task >>

*

*Everytime before scraping check /robots.txt for the same site.
For ebay its : http://www.ebay.com/robots.txt
And you can see almost everything is disallowed.
User-agent: *
Disallow: /*rt=nc
Disallow: /b/LH_
Disallow: /brw/
Disallow: /clp/
Disallow: /clt/store/
Disallow: /csc/
Disallow: /ctg/
Disallow: /ctm/
Disallow: /dsc/
Disallow: /edc/
Disallow: /feed/
Disallow: /gsr/
Disallow: /gwc/
Disallow: /hcp/
Disallow: /itc/
Disallow: /lit/
Disallow: /lst/ng/
Disallow: /lvx/
Disallow: /mbf/
Disallow: /mla/
Disallow: /mlt/
Disallow: /myb/
Disallow: /mys/
Disallow: /prp/
Disallow: /rcm/
Disallow: /sch/%7C
Disallow: /sch/LH_
Disallow: /sch/aop/
Disallow: /sch/ctg/
Disallow: /sl/node
Disallow: /sme/
Disallow: /soc/
Disallow: /talk/
Disallow: /tickets/
Disallow: /today/
Disallow: /trylater/
Disallow: /urw/write-review/
Disallow: /vsp/
Disallow: /ws/
Disallow: /sch/modules=SEARCH_REFINEMENTS_MODEL_V2
Disallow: /b/modules=SEARCH_REFINEMENTS_MODEL_V2
Disallow: /itm/_nkw
Disallow: /itm/?fits
Disallow: /itm/&fits
Disallow: /cta/

*Therefore go to https://developer.ebay.com/api-docs/developer/static/developer-landing.html and check their docs, there are easier example code in their site to get the items needs without scraping.


text:
Q: Refraction of light marching band analogy When trying to understand the refraction of light when it hits a slower medium, lots of people seem to be enlightened by the 'marching band' or 'marching soldiers' analogy, which 'explains' that when a platoon marching in a straight line on a concrete road hits the side of the road at an angle and goes into a swamp, the soldier which is first to hit the swamp will start walking slower while the soldiers that are still on the road keep going at the previous speed. This supposedly explains intuitively why the marching band changes direction.
I don't understand how this works at all, the soldiers hitting the slower medium will start walking slower but why on earth would they change direction as well? As I see it, the front line of soldiers will form a different angle to the direction the platoon is marching in after it has hit the interface, but the platoon should still be going in the exact same direction even if the soldiers run into each other because the guy in front is slowing down. Am I missing something in the analogy or is the analogy a really bad one (which I'm starting to suspect strongly)?

A: Imagine not the direction of the column but the direction of the front row. Suppose the front row of soldiers were carrying a horizontal bar, the one on the left hitting the swamp would slow down while the one on the right was still moving quickly so the bar (=wavefront) would change direction
It's a slightly bad analogy. A much better one is:
Imagine you were on a beach and had to reach somebody in the water. You could run to the nearest point of the water and swim diagonally, but assuming you swim slower than you run, this would take the most time. Or you could run all the way along the beach to the closest point to the person and swim the shortest distance but this is still a longer than necessary path.
But there is a point on the beach where if you ran to that point then swam, you would minimise the total time taken. The point would depend only on the ratio of your speed running and swimming. This is exactly what light does. It's called Fermat's principle and is one of the most fundamental things in physics.


text:
Q: Package manager doesn't work anymore I'm using ubuntu 10.10 and recently my package manager has stopped working because of some problems with dependencies or something. I can't upgrade, install or uninstall anything at all. This is a huge problem. I couldn't find a solution to this with google so I'm asking here for help.
This is what apt-get -f install outputs
LANG=en_US.UTF-8 sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  firefox-4.0-core
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0B of additional disk space will be used.
Setting up openjdk-6-jre-headless (6b20-1.9.5-0ubuntu1) ...
update-alternatives: error: alternative path /usr/lib/jvm/java-6-openjdk/jre/bin/java doesn't exist.
dpkg: error processing openjdk-6-jre-headless (--configure):
 subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
 openjdk-6-jre-headless
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: I'd just reinstall the package...
sudo mv /var/lib/dpkg/info/openjdk-6-jre-headless.postinst /var/lib/dpkg/info/openjdk-6-jre-headless.postinst.bad
sudo apt-get --reinstall install openjdk-6-jre-headless

A: Looks like you've got a broken Java installation.
Try sudo apt-get purge openjdk-jre.
Then I'd recommend ticking the "Partners" repository in synaptic, reloading and installing Sun's JRE with sudo apt-get install sun-java6-jre.


text:
Q: Checklist for writing copy constructor and assignment operator in C++ Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.

A: The compiler generated versions work in most situations.
You need to think a bit harder about the problem when your object contains a RAW pointer (an argument for not having RAW pointers). So you have a RAW pointer, the second question is do you own the pointer (is it being deleted by you)? If so then you will need to apply the rule of 4.
Owning more than 1 RAW pointer becomes increasingly hard to do correctly (The increase in complexity is not linear either [but that is observational and I have no real stats to back that statement up]). So if you have more than 1 RAW pointer think about wrapping each in its own class (some form of smart pointer).
Rule of 4: If an object is the owner of a RAW pointer then you need to define the following 4 members to make sure you handle the memory management correctly:

*

*Constructor

*Copy Constructor

*Assignment Operator

*Destructor

How you define these will depend on the situations. But things to watch out for:

*

*Default Construction: Set pointer to NULL

*Copy Constructor: Use the Copy and Swap ideum to provide to the "Strong Exception Guarantee"

*Assignment operator: Check for assignment to self

*Destructor: Guard against exceptions propagating out of the destructor.

A: First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go.
Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a virtual clone() function.
Otherwise, in the case you are writing a value class, you're back into the land of the Orthogonal Canonical Form of Coplien. If you have a member that can't be trivially copied, you'll need to provide a copy-constructor, a destructor, an assignment-operator and a default constructor. This rule can be refined, see for instance: The Law of The Big Two
I'd also recommend to have a look at C++ FAQ regarding assignment operators, and at the copy-and-swap idiom and at GOTW.

A: try to read this.
http://www.icu-project.org/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html
is a very good analysis of Assignment operator

A: I have no idea about exception safely here but I go this way. Let's imagine it's a templated array wrapper. Hope it helps :)
Array(const Array& rhs)
    {
        mData = NULL;
        mSize = rhs.size();
        *this = rhs;
    }

    Array& operator=(const Array& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }

        int len = rhs.size();

        delete[] mData;

        mData = new T[len];

        for(int i = 0; i < len; ++i)
        {
            mData[i] = rhs[i];
        }

        mSize = len;

        return *this;
    }


text:
Q: Git signed-off-by custom format Is there any possibility to change default format of Signed-off-by line.
By default is:
Signed-off-by: user.name <user.email>

Some of project require another format, eg:
Signed-off-by: user.name <user.email> (github: account_name)

A: Thanks to max630's comment I prepared simple hook:
#!/bin/sh

NAME=`git config user.name`
EMAIL=`git config user.email`
GITHUB=`git config user.github`

if [ -z "$NAME" ]; then
    echo "empty git config user.name"
    exit 1
fi

if [ -z "$EMAIL" ]; then
    echo "empty git config user.email"
    exit 1
fi

if [ -z "$GITHUB" ]; then
    echo "empty git config user.github"
    exit 1
fi

git interpret-trailers --trailer \
    "Signed-off-by: $NAME <$EMAIL> (github: $GITHUB)" \
    --in-place "$1"

In order to use it, please put above code in  file: .git/hook/prepare-commit-msg in your project.
You also need add git configuration used by this script,  you can do it for project:
git config user.github "<user github login>"

or set globaly:
git config --global user.github "<user github login>"

Config items user.name and user.email most likely you have already.


text:
Q: Deploy Shiny App on shinyapps.io with blpconnect() function to fetch real time data from Bloomberg I am trying to build a dashboard that gets real-time data from Bloomberg using functions like bdp, bdh. I am using blpconnect() to establish a connection with Bloomberg, however, when I deploy the app on shinyapps.io, it gives me an error. The app runs on my local computer though.
Log:
2022-07-21T18:16:23.294669+00:00 shinyapps[6670285]: Registered S3 method overwritten by 'quantmod':
**2022-07-21T18:16:23.293756+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.294230+00:00 shinyapps[6670285]: Attaching package: 'PerformanceAnalytics'
**2022-07-21T18:16:23.294287+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295015+00:00 shinyapps[6670285]: The following object is masked from 'package:dplyr':
2022-07-21T18:16:23.294349+00:00 shinyapps[6670285]: The following object is masked from 'package:graphics':
2022-07-21T18:16:23.294457+00:00 shinyapps[6670285]: legend
2022-07-21T18:16:23.294611+00:00 shinyapps[6670285]: Loading required package: TTR
2022-07-21T18:16:23.294021+00:00 shinyapps[6670285]: first, last
**2022-07-21T18:16:23.294507+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.294960+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.293965+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.294724+00:00 shinyapps[6670285]: method from
**2022-07-21T18:16:23.295071+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.294908+00:00 shinyapps[6670285]: Attaching package: 'kableExtra'
2022-07-21T18:16:23.295124+00:00 shinyapps[6670285]: group_rows
2022-07-21T18:16:23.295383+00:00 shinyapps[6670285]: The following object is masked from 'package:tidyr':
**2022-07-21T18:16:23.295436+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295278+00:00 shinyapps[6670285]: Attaching package: 'reshape2'
**2022-07-21T18:16:23.295913+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.295333+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.295541+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295969+00:00 shinyapps[6670285]: days, hours, minutes, seconds, years
2022-07-21T18:16:23.295490+00:00 shinyapps[6670285]: smiths
2022-07-21T18:16:23.295661+00:00 shinyapps[6670285]: Please respect the Bloomberg licensing agreement and terms of service.
**2022-07-21T18:16:23.294409+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.295174+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295595+00:00 shinyapps[6670285]: Rblpapi version 0.3.13 using Blpapi headers 3.8.18.1 and run-time 3.8.18.1.
**2022-07-21T18:16:23.296018+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.294781+00:00 shinyapps[6670285]: as.zoo.data.frame zoo **
**2022-07-21T18:16:23.294839+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:23.295224+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295763+00:00 shinyapps[6670285]: Attaching package: 'chron'
**2022-07-21T18:16:23.295814+00:00 shinyapps[6670285]: **
2022-07-21T18:16:23.295862+00:00 shinyapps[6670285]: The following objects are masked from 'package:lubridate':
**2022-07-21T18:16:23.295713+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:24.292359+00:00 shinyapps[6670285]: **
2022-07-21T18:16:24.292410+00:00 shinyapps[6670285]: Attaching package: 'DescTools'
**2022-07-21T18:16:24.292458+00:00 shinyapps[6670285]: **
2022-07-21T18:16:24.292512+00:00 shinyapps[6670285]: The following objects are masked from 'package:tidyquant':
**2022-07-21T18:16:24.292556+00:00 shinyapps[6670285]: **
2022-07-21T18:16:24.292599+00:00 shinyapps[6670285]: IRR, NPV, PMT
**2022-07-21T18:16:24.292645+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:24.292685+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:24.292765+00:00 shinyapps[6670285]: **
**2022-07-21T18:16:24.292723+00:00 shinyapps[6670285]: 21JUL2022_18:16:24.224 49:140583829202688 ERROR blpapi_platformtransporttcp.cpp:671 blpapi.session.transporttcp.{1}.<127.0.0.1:8194> Connection failed **
**2022-07-21T18:16:24.292806+00:00 shinyapps[6670285]: 21JUL2022_18:16:24.224 49:140583829202688 WARN blpapi_platformcontroller.cpp:371 blpapi.session.platformcontroller.{1} Platform: 0 failed 1 consecutive connect attempts, stopped trying to reconnect. **
2022-07-21T18:16:24.292841+00:00 shinyapps[6670285]: Error in value[3L] : Failed to start session.
2022-07-21T18:16:24.292923+00:00 shinyapps[6670285]: Execution halted
2022-07-21T18:16:24.292882+00:00 shinyapps[6670285]: Calls: local ... tryCatch -> tryCatchList -> tryCatchOne ->
2022-07-21T18:16:24.292961+00:00 shinyapps[6670285]: Shiny application exiting ...

Is there any way to fetch Bloomberg data into the shiny app on the shinyapps.io server?

A: There is no way to fetch this data on the Shinyapps.io-Server. Since the rblpapi is accessing your local bloomberg instance, which is not running on the shinyapps.io-server, it is not possible for the app to access the data on the server, and this is the reason why your local app version is able to fetch the data.
Futhermore, check the Bloomberg license agreement. They are very strict and percise where you are allowed to access and use the provided data. I highly question that you are allowed to use their real time data in an external cloud based app.


text:
Q: bootstrap up down vote button alignment on small screen I'm trying to implement voting system like stack overflow, I'm having problem in displaying the arrows on small screens to be on the same line (arrows near the text) like stackoverflow.
On small screens it appears on 2 different lines as shown in this screenshot
Here is what i did

     12

Column

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">

        12

Column

Lorem ipsum dolor sit amet, consectetur adipisicing elit...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

A: sorry, didn't get the problem at the first catch.. anyway.. this should help

      12

Column

Lorem ipsum dolor sit amet, consectetur adipisicing elit...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

Column

Lorem ipsum dolor sit amet, consectetur adipisicing elit...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

Column

Lorem ipsum dolor sit amet, consectetur adipisicing elit...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

https://jsfiddle.net/cpkgxd1y/1/

A: Are u expecting like this:

body{
margin:0;
padding:0;
}
.row{
margin:0 !important;
}
.voting{
width:120px;
font-size: 2em;
color: #606060;
display:flex;
flex-direction:column;
text-align:center;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

     12

Column

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...


text:
Q: Copiar valor de columna x en y si existe en y en pandas usando Python Quisiera ver una manera de hacer que en un DataFrame usando pandas con Python como la siguiente:

x
y

a
a

a
NaN

b
NaN

c
NaN

d
d

Se copien los valores de la columna x en la columna y en su posición respectiva solo si existen en la y, por ejemplo, el valor a existe en la columna y entonces se copiaría de la x a esa misma, mientas que lo mismo no sucedería en b y c porque no existen en y.

A: Si entendí correctamente, lo que pretendes sería el resultado de:

*

*Determinar qué valores distintos de NaN aparecen en la columna y. Llamemos validos al conjunto con esos valores. En tu ejemplo, el conjunto validos contendría los elementos "a" y "d"

*Para todas las filas para las cuales el valor que hay en la columna x esté en el conjunto validos, copiar el valor de la columna x a la columna y.

Esto puede implementarse bastante literalmente en la forma siguiente:
# Determinar el conjunto de "validos"
validos = set(df.y.dropna().unique())

# Asignar a la columna y el valor de la columna x, pero solo para
# las filas en las que x está en "validos"
df.loc[df.x.isin(validos), "y"] = df.x

Demo
Si el dataframe de entrada es este:
   x    y
0  a    a
1  a  NaN
2  b  NaN
3  c  NaN
4  d    d

el dataframe resultante será este:
   x    y
0  a    a
1  a    a
2  b  NaN
3  c  NaN
4  d    d

Alguna explicación adicional
df.y.dropna() se queda solo con los elementos no-NaN de la columna y, y aplicando después .unique() al resultado se eliminan duplicados. El resultado de eso es una lista, pero mediante set() lo convierto a un conjunto porque las búsquedas en conjuntos son más eficientes.
df.x.isin(validos) es una función que retorna una columna de booleanos, con el valor True únicamente en las filas en las que el valor de x esté en el conjunto validos. Al usarlo dentro de .loc[] nos seleccionará sólamente las filas que queremos cambiar. El segundo parámetro de .loc[] es "y", el nombre de la columna en la que queremos escribir.
En el otro lado de la asignación podemos poner directamente df.x, y sólo se asignarán las filas seleccionadas en el lado izquierdo, no es necesario volver a aplicar filtros en el lado derecho.

A: Basada en esta otra respuesta, puedes agrupar según la columna 'x'. Luego llenar los datos para cada agrupación con group.ffill().
df.groupby('x').ffill()

# Resultado:

#    y
#    0  a
#    1  a
#    2  NaN
#    3  NaN
#    4  d

Solo hace falta asignar este resultado para remplazar la columna 'y':
df['y']=df.groupby('x').ffill()


text:
Q: Fail to create AWS CloudFormation "Get Started" example stack I am trying to learn CloudFormation and following the "Get Started" tutorial. But for some reason, I can't really finish the task of creating this example stack using the provided template in my AWS account.

During the test, I first got the error "No subnets found for the default VPC 'vpc-4f2acc28'. Please specify a subnet." and solved it by modifying the example template to add "SubnetId" in the Properties of "WebServer" under "Resource" section. Then I got the error "The parameter groupName cannot be used with the parameter subnet" and solved it by using "SecurityGroupIds" instead of "SecurityGroups".
And last, I got the error "Failed to receive 1 resource signal(s) within the specified duration". Since this error message doesn't give much information, I can't really figure out how to solve it.
This is just the basic tutorial and I guess many people have gone through it. Does anyone know what is the problem?
This is the template I am using(just small changes I mentioned above made on the original example template):
{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "AWS CloudFormation Sample Template WordPress_Single_Instance: WordPress is web software you can use to create a beautiful website or blog. This template installs WordPress with a local MySQL database for storage. It demonstrates using the AWS CloudFormation bootstrap scripts to deploy WordPress. **WARNING** This template creates an Amazon EC2 instance. You will be billed for the AWS resources used if you create a stack from this template.",

  "Parameters" : {

    "KeyName": {
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instances",
      "Type": "AWS::EC2::KeyPair::KeyName",
      "ConstraintDescription" : "must be the name of an existing EC2 KeyPair."
    },

    "InstanceType" : {
      "Description" : "WebServer EC2 instance type",
      "Type" : "String",
      "Default" : "t2.small",
      "AllowedValues" : [ "t1.micro", "t2.nano", "t2.micro", "t2.small", "t2.medium", "t2.large", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "m4.large", "m4.xlarge", "m4.2xlarge", "m4.4xlarge", "m4.10xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge", "c4.8xlarge", "g2.2xlarge", "g2.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "d2.xlarge", "d2.2xlarge", "d2.4xlarge", "d2.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"]
,
      "ConstraintDescription" : "must be a valid EC2 instance type."
    },

    "SSHLocation": {
      "Description": "The IP address range that can be used to SSH to the EC2 instances",
      "Type": "String",
      "MinLength": "9",
      "MaxLength": "18",
      "Default": "0.0.0.0/0",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x."
    },

    "DBName" : {
      "Default": "wordpressdb",
      "Description" : "The WordPress database name",
      "Type": "String",
      "MinLength": "1",
      "MaxLength": "64",
      "AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
      "ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
    },

    "DBUser" : {
      "NoEcho": "true",
      "Description" : "The WordPress database admin account username",
      "Type": "String",
      "MinLength": "1",
      "MaxLength": "16",
      "AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
      "ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
    },

    "DBPassword" : {
      "NoEcho": "true",
      "Description" : "The WordPress database admin account password",
      "Type": "String",
      "MinLength": "8",
      "MaxLength": "41",
      "AllowedPattern" : "[a-zA-Z0-9]*",
      "ConstraintDescription" : "must contain only alphanumeric characters."
    },

    "DBRootPassword" : {
      "NoEcho": "true",
      "Description" : "MySQL root password",
      "Type": "String",
      "MinLength": "8",
      "MaxLength": "41",
      "AllowedPattern" : "[a-zA-Z0-9]*",
      "ConstraintDescription" : "must contain only alphanumeric characters."
    }
  },

  "Mappings" : {
    "AWSInstanceType2Arch" : {
      "t1.micro"    : { "Arch" : "PV64"   },
      "t2.nano"     : { "Arch" : "HVM64"  },
      "t2.micro"    : { "Arch" : "HVM64"  },
      "t2.small"    : { "Arch" : "HVM64"  },
      "t2.medium"   : { "Arch" : "HVM64"  },
      "t2.large"    : { "Arch" : "HVM64"  },
      "m1.small"    : { "Arch" : "PV64"   },
      "m1.medium"   : { "Arch" : "PV64"   },
      "m1.large"    : { "Arch" : "PV64"   },
      "m1.xlarge"   : { "Arch" : "PV64"   },
      "m2.xlarge"   : { "Arch" : "PV64"   },
      "m2.2xlarge"  : { "Arch" : "PV64"   },
      "m2.4xlarge"  : { "Arch" : "PV64"   },
      "m3.medium"   : { "Arch" : "HVM64"  },
      "m3.large"    : { "Arch" : "HVM64"  },
      "m3.xlarge"   : { "Arch" : "HVM64"  },
      "m3.2xlarge"  : { "Arch" : "HVM64"  },
      "m4.large"    : { "Arch" : "HVM64"  },
      "m4.xlarge"   : { "Arch" : "HVM64"  },
      "m4.2xlarge"  : { "Arch" : "HVM64"  },
      "m4.4xlarge"  : { "Arch" : "HVM64"  },
      "m4.10xlarge" : { "Arch" : "HVM64"  },
      "c1.medium"   : { "Arch" : "PV64"   },
      "c1.xlarge"   : { "Arch" : "PV64"   },
      "c3.large"    : { "Arch" : "HVM64"  },
      "c3.xlarge"   : { "Arch" : "HVM64"  },
      "c3.2xlarge"  : { "Arch" : "HVM64"  },
      "c3.4xlarge"  : { "Arch" : "HVM64"  },
      "c3.8xlarge"  : { "Arch" : "HVM64"  },
      "c4.large"    : { "Arch" : "HVM64"  },
      "c4.xlarge"   : { "Arch" : "HVM64"  },
      "c4.2xlarge"  : { "Arch" : "HVM64"  },
      "c4.4xlarge"  : { "Arch" : "HVM64"  },
      "c4.8xlarge"  : { "Arch" : "HVM64"  },
      "g2.2xlarge"  : { "Arch" : "HVMG2"  },
      "g2.8xlarge"  : { "Arch" : "HVMG2"  },
      "r3.large"    : { "Arch" : "HVM64"  },
      "r3.xlarge"   : { "Arch" : "HVM64"  },
      "r3.2xlarge"  : { "Arch" : "HVM64"  },
      "r3.4xlarge"  : { "Arch" : "HVM64"  },
      "r3.8xlarge"  : { "Arch" : "HVM64"  },
      "i2.xlarge"   : { "Arch" : "HVM64"  },
      "i2.2xlarge"  : { "Arch" : "HVM64"  },
      "i2.4xlarge"  : { "Arch" : "HVM64"  },
      "i2.8xlarge"  : { "Arch" : "HVM64"  },
      "d2.xlarge"   : { "Arch" : "HVM64"  },
      "d2.2xlarge"  : { "Arch" : "HVM64"  },
      "d2.4xlarge"  : { "Arch" : "HVM64"  },
      "d2.8xlarge"  : { "Arch" : "HVM64"  },
      "hi1.4xlarge" : { "Arch" : "HVM64"  },
      "hs1.8xlarge" : { "Arch" : "HVM64"  },
      "cr1.8xlarge" : { "Arch" : "HVM64"  },
      "cc2.8xlarge" : { "Arch" : "HVM64"  }
    },

    "AWSInstanceType2NATArch" : {
      "t1.micro"    : { "Arch" : "NATPV64"   },
      "t2.nano"     : { "Arch" : "NATHVM64"  },
      "t2.micro"    : { "Arch" : "NATHVM64"  },
      "t2.small"    : { "Arch" : "NATHVM64"  },
      "t2.medium"   : { "Arch" : "NATHVM64"  },
      "t2.large"    : { "Arch" : "NATHVM64"  },
      "m1.small"    : { "Arch" : "NATPV64"   },
      "m1.medium"   : { "Arch" : "NATPV64"   },
      "m1.large"    : { "Arch" : "NATPV64"   },
      "m1.xlarge"   : { "Arch" : "NATPV64"   },
      "m2.xlarge"   : { "Arch" : "NATPV64"   },
      "m2.2xlarge"  : { "Arch" : "NATPV64"   },
      "m2.4xlarge"  : { "Arch" : "NATPV64"   },
      "m3.medium"   : { "Arch" : "NATHVM64"  },
      "m3.large"    : { "Arch" : "NATHVM64"  },
      "m3.xlarge"   : { "Arch" : "NATHVM64"  },
      "m3.2xlarge"  : { "Arch" : "NATHVM64"  },
      "m4.large"    : { "Arch" : "NATHVM64"  },
      "m4.xlarge"   : { "Arch" : "NATHVM64"  },
      "m4.2xlarge"  : { "Arch" : "NATHVM64"  },
      "m4.4xlarge"  : { "Arch" : "NATHVM64"  },
      "m4.10xlarge" : { "Arch" : "NATHVM64"  },
      "c1.medium"   : { "Arch" : "NATPV64"   },
      "c1.xlarge"   : { "Arch" : "NATPV64"   },
      "c3.large"    : { "Arch" : "NATHVM64"  },
      "c3.xlarge"   : { "Arch" : "NATHVM64"  },
      "c3.2xlarge"  : { "Arch" : "NATHVM64"  },
      "c3.4xlarge"  : { "Arch" : "NATHVM64"  },
      "c3.8xlarge"  : { "Arch" : "NATHVM64"  },
      "c4.large"    : { "Arch" : "NATHVM64"  },
      "c4.xlarge"   : { "Arch" : "NATHVM64"  },
      "c4.2xlarge"  : { "Arch" : "NATHVM64"  },
      "c4.4xlarge"  : { "Arch" : "NATHVM64"  },
      "c4.8xlarge"  : { "Arch" : "NATHVM64"  },
      "g2.2xlarge"  : { "Arch" : "NATHVMG2"  },
      "g2.8xlarge"  : { "Arch" : "NATHVMG2"  },
      "r3.large"    : { "Arch" : "NATHVM64"  },
      "r3.xlarge"   : { "Arch" : "NATHVM64"  },
      "r3.2xlarge"  : { "Arch" : "NATHVM64"  },
      "r3.4xlarge"  : { "Arch" : "NATHVM64"  },
      "r3.8xlarge"  : { "Arch" : "NATHVM64"  },
      "i2.xlarge"   : { "Arch" : "NATHVM64"  },
      "i2.2xlarge"  : { "Arch" : "NATHVM64"  },
      "i2.4xlarge"  : { "Arch" : "NATHVM64"  },
      "i2.8xlarge"  : { "Arch" : "NATHVM64"  },
      "d2.xlarge"   : { "Arch" : "NATHVM64"  },
      "d2.2xlarge"  : { "Arch" : "NATHVM64"  },
      "d2.4xlarge"  : { "Arch" : "NATHVM64"  },
      "d2.8xlarge"  : { "Arch" : "NATHVM64"  },
      "hi1.4xlarge" : { "Arch" : "NATHVM64"  },
      "hs1.8xlarge" : { "Arch" : "NATHVM64"  },
      "cr1.8xlarge" : { "Arch" : "NATHVM64"  },
      "cc2.8xlarge" : { "Arch" : "NATHVM64"  }
    }
,
    "AWSRegionArch2AMI" : {
      "us-east-1"        : {"PV64" : "ami-2a69aa47", "HVM64" : "ami-97785bed", "HVMG2" : "ami-0a6e3770"},
      "us-west-2"        : {"PV64" : "ami-7f77b31f", "HVM64" : "ami-f2d3638a", "HVMG2" : "ami-ee15a196"},
      "us-west-1"        : {"PV64" : "ami-a2490dc2", "HVM64" : "ami-824c4ee2", "HVMG2" : "ami-0da4a46d"},
      "eu-west-1"        : {"PV64" : "ami-4cdd453f", "HVM64" : "ami-d834aba1", "HVMG2" : "ami-af8013d6"},
      "eu-west-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-403e2524", "HVMG2" : "NOT_SUPPORTED"},
      "eu-west-3"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-8ee056f3", "HVMG2" : "NOT_SUPPORTED"},
      "eu-central-1"     : {"PV64" : "ami-6527cf0a", "HVM64" : "ami-5652ce39", "HVMG2" : "ami-1d58ca72"},
      "ap-northeast-1"   : {"PV64" : "ami-3e42b65f", "HVM64" : "ami-ceafcba8", "HVMG2" : "ami-edfd658b"},
      "ap-northeast-2"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-863090e8", "HVMG2" : "NOT_SUPPORTED"},
      "ap-northeast-3"   : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-83444afe", "HVMG2" : "NOT_SUPPORTED"},
      "ap-southeast-1"   : {"PV64" : "ami-df9e4cbc", "HVM64" : "ami-68097514", "HVMG2" : "ami-c06013bc"},
      "ap-southeast-2"   : {"PV64" : "ami-63351d00", "HVM64" : "ami-942dd1f6", "HVMG2" : "ami-85ef12e7"},
      "ap-south-1"       : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-531a4c3c", "HVMG2" : "ami-411e492e"},
      "us-east-2"        : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-f63b1193", "HVMG2" : "NOT_SUPPORTED"},
      "ca-central-1"     : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-a954d1cd", "HVMG2" : "NOT_SUPPORTED"},
      "sa-east-1"        : {"PV64" : "ami-1ad34676", "HVM64" : "ami-84175ae8", "HVMG2" : "NOT_SUPPORTED"},
      "cn-north-1"       : {"PV64" : "ami-77559f1a", "HVM64" : "ami-cb19c4a6", "HVMG2" : "NOT_SUPPORTED"},
      "cn-northwest-1"   : {"PV64" : "ami-80707be2", "HVM64" : "ami-3e60745c", "HVMG2" : "NOT_SUPPORTED"}
    }

  },

  "Resources" : {
    "WebServer": {
      "Type" : "AWS::EC2::Instance",
      "Metadata" : {
        "AWS::CloudFormation::Init" : {
          "configSets" : {
            "wordpress_install" : ["install_cfn", "install_wordpress", "configure_wordpress" ]
          },
          "install_cfn" : {
            "files": {
              "/etc/cfn/cfn-hup.conf": {
                "content": { "Fn::Join": [ "", [
                  "[main]\n",
                  "stack=", { "Ref": "AWS::StackId" }, "\n",
                  "region=", { "Ref": "AWS::Region" }, "\n"
                ]]},
                "mode"  : "000400",
                "owner" : "root",
                "group" : "root"
              },
              "/etc/cfn/hooks.d/cfn-auto-reloader.conf": {
                "content": { "Fn::Join": [ "", [
                  "[cfn-auto-reloader-hook]\n",
                  "triggers=post.update\n",
                  "path=Resources.WebServer.Metadata.AWS::CloudFormation::Init\n",
                  "action=/opt/aws/bin/cfn-init -v ",
                          "         --stack ", { "Ref" : "AWS::StackName" },
                          "         --resource WebServer ",
                          "         --configsets wordpress_install ",
                          "         --region ", { "Ref" : "AWS::Region" }, "\n"
                ]]},
                "mode"  : "000400",
                "owner" : "root",
                "group" : "root"
              }
            },
            "services" : {
              "sysvinit" : {
                "cfn-hup" : { "enabled" : "true", "ensureRunning" : "true",
                              "files" : ["/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-auto-reloader.conf"] }
              }
            }
          },

          "install_wordpress" : {
            "packages" : {
              "yum" : {
                "php"          : [],
                "php-mysql"    : [],
                "mysql"        : [],
                "mysql-server" : [],
                "mysql-devel"  : [],
                "mysql-libs"   : [],
                "httpd"        : []
              }
            },
            "sources" : {
              "/var/www/html" : "http://wordpress.org/latest.tar.gz"
            },
            "files" : {
              "/tmp/setup.mysql" : {
                "content" : { "Fn::Join" : ["", [
                  "CREATE DATABASE ", { "Ref" : "DBName" }, ";\n",
                  "CREATE USER '", { "Ref" : "DBUser" }, "'@'localhost' IDENTIFIED BY '", { "Ref" : "DBPassword" }, "';\n",
                  "GRANT ALL ON ", { "Ref" : "DBName" }, ".* TO '", { "Ref" : "DBUser" }, "'@'localhost';\n",
                  "FLUSH PRIVILEGES;\n"
                ]]},
                "mode"  : "000400",
                "owner" : "root",
                "group" : "root"
              },

              "/tmp/create-wp-config" : {
                "content" : { "Fn::Join" : [ "", [
                  "#!/bin/bash -xe\n",
                  "cp /var/www/html/wordpress/wp-config-sample.php /var/www/html/wordpress/wp-config.php\n",
                  "sed -i \"s/'database_name_here'/'",{ "Ref" : "DBName" }, "'/g\" wp-config.php\n",
                  "sed -i \"s/'username_here'/'",{ "Ref" : "DBUser" }, "'/g\" wp-config.php\n",
                  "sed -i \"s/'password_here'/'",{ "Ref" : "DBPassword" }, "'/g\" wp-config.php\n"
                ]]},
                "mode" : "000500",
                "owner" : "root",
                "group" : "root"
              }
            },
            "services" : {
              "sysvinit" : {
                "httpd"  : { "enabled" : "true", "ensureRunning" : "true" },
                "mysqld" : { "enabled" : "true", "ensureRunning" : "true" }
              }
            }
          },

          "configure_wordpress" : {
            "commands" : {
              "01_set_mysql_root_password" : {
                "command" : { "Fn::Join" : ["", ["mysqladmin -u root password '", { "Ref" : "DBRootPassword" }, "'"]]},
                "test" : { "Fn::Join" : ["", ["$(mysql ", { "Ref" : "DBName" }, " -u root --password='", { "Ref" : "DBRootPassword" }, "' >/dev/null 2>&1 </dev/null); (( $? != 0 ))"]]}
              },
              "02_create_database" : {
                "command" : { "Fn::Join" : ["", ["mysql -u root --password='", { "Ref" : "DBRootPassword" }, "' < /tmp/setup.mysql"]]},
                "test" : { "Fn::Join" : ["", ["$(mysql ", { "Ref" : "DBName" }, " -u root --password='", { "Ref" : "DBRootPassword" }, "' >/dev/null 2>&1 </dev/null); (( $? != 0 ))"]]}
              },
              "03_configure_wordpress" : {
                "command" : "/tmp/create-wp-config",
                "cwd" : "/var/www/html/wordpress"
              }
            }
          }
        }
      },
      "Properties": {
        "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                          { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
        "InstanceType"   : { "Ref" : "InstanceType" },
        "SubnetId": "subnet-3c0e8a5a",
        "SecurityGroupIds" : ["sg-d04fe1a9"],
        "KeyName"        : { "Ref" : "KeyName" },
        "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                       "#!/bin/bash -xe\n",
                       "yum update -y aws-cfn-bootstrap\n",

                       "/opt/aws/bin/cfn-init -v ",
                       "         --stack ", { "Ref" : "AWS::StackName" },
                       "         --resource WebServer ",
                       "         --configsets wordpress_install ",
                       "         --region ", { "Ref" : "AWS::Region" }, "\n",

                       "/opt/aws/bin/cfn-signal -e $? ",
                       "         --stack ", { "Ref" : "AWS::StackName" },
                       "         --resource WebServer ",
                       "         --region ", { "Ref" : "AWS::Region" }, "\n"
        ]]}}
      },
      "CreationPolicy" : {
        "ResourceSignal" : {
          "Timeout" : "PT15M"
        }
      }
    }
  },

  "Outputs" : {
    "WebsiteURL" : {
      "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "WebServer", "PublicDnsName" ]}, "/wordpress" ]]},
      "Description" : "WordPress Website"
    }
  }
}

A: Your CloudFormation (CFN) stack is attempting to create an EC2 instance to run your Wordpress on, and there's a section in the template which instructs the CFN stack to wait for a signal from the newly created instance before proceeding.
"Failed to receive 1 resource signal(s) within the specified duration" indicates that your instance is failing to send the signal within the time limit. This can be because of a number of reasons.
Can you copy/paste or link to the CFN template you are using? Also, copy/paste your CFN stack's events log. It will give some additional information on what's happening.
Update:
Short answer:
It's more than likely your instance is failing to run through all of its startup scripts, which is preventing the signal back to the CFN stack. You'll need to SSH into your instance and inspect the logs to find out what's going on.
Instructions on where the logs are located can be found at Amazon's troubleshooting documentation.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html
Long answer:
So check out the following sections from your CFN template:
"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
                   "#!/bin/bash -xe\n",
                   "yum update -y aws-cfn-bootstrap\n",

                   "/opt/aws/bin/cfn-init -v ",
                   "         --stack ", { "Ref" : "AWS::StackName" },
                   "         --resource WebServer ",
                   "         --configsets wordpress_install ",
                   "         --region ", { "Ref" : "AWS::Region" }, "\n",

                   "/opt/aws/bin/cfn-signal -e $? ",
                   "         --stack ", { "Ref" : "AWS::StackName" },
                   "         --resource WebServer ",
                   "         --region ", { "Ref" : "AWS::Region" }, "\n"
]]}}

This section is a bash script that runs on the newly created instance after it first boots. It does the following:

*

*Install/update aws-cfn-bootstrap. This is an AWS provided client that allows your instance to interact with the CFN template that created it.
"yum update -y aws-cfn-bootstrap\n",

*Using the newly installed aws-cfn-bootstrap client, the instance looks at the CFN template and executes all of the tasks defined in the wordpress_install configset.
"/opt/aws/bin/cfn-init -v "
"         --stack ", { "Ref" : "AWS::StackName" }
"         --resource WebServer "
"         --configsets wordpress_install "
"         --region ", { "Ref" : "AWS::Region" }, "\n"

The configset is defined earlier in the template. A lot is going on here, so I can't explain it all. It'll be up to you to look at it and determine what it is doing.
"AWS::CloudFormation::Init" : {
  "configSets" : {
    "wordpress_install" : ["install_cfn", "install_wordpress", "configure_wordpress" ]
  },
  "install_cfn" : {
    "files": {
      "/etc/cfn/cfn-hup.conf": {
        "content": { "Fn::Join": [ "", [
          "[main]\n",
          "stack=", { "Ref": "AWS::StackId" }, "\n",
          "region=", { "Ref": "AWS::Region" }, "\n"
        ]]},
        "mode"  : "000400",
        "owner" : "root",
        "group" : "root"
      },
      "/etc/cfn/hooks.d/cfn-auto-reloader.conf": {
        "content": { "Fn::Join": [ "", [
          "[cfn-auto-reloader-hook]\n",
          "triggers=post.update\n",
          "path=Resources.WebServer.Metadata.AWS::CloudFormation::Init\n",
          "action=/opt/aws/bin/cfn-init -v ",
                  "         --stack ", { "Ref" : "AWS::StackName" },
                  "         --resource WebServer ",
                  "         --configsets wordpress_install ",
                  "         --region ", { "Ref" : "AWS::Region" }, "\n"
        ]]},
        "mode"  : "000400",
        "owner" : "root",
        "group" : "root"
      }
    },
    "services" : {
      "sysvinit" : {
        "cfn-hup" : { "enabled" : "true", "ensureRunning" : "true",
                      "files" : ["/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-auto-reloader.conf"] }
      }
    }
  },
  "install_wordpress" : {
    "packages" : {
      "yum" : {
        "php"          : [],
        "php-mysql"    : [],
        "mysql"        : [],
        "mysql-server" : [],
        "mysql-devel"  : [],
        "mysql-libs"   : [],
        "httpd"        : []
      }
    },
    "sources" : {
      "/var/www/html" : "http://wordpress.org/latest.tar.gz"
    },
    "files" : {
      "/tmp/setup.mysql" : {
        "content" : { "Fn::Join" : ["", [
          "CREATE DATABASE ", { "Ref" : "DBName" }, ";\n",
          "CREATE USER '", { "Ref" : "DBUser" }, "'@'localhost' IDENTIFIED BY '", { "Ref" : "DBPassword" }, "';\n",
          "GRANT ALL ON ", { "Ref" : "DBName" }, ".* TO '", { "Ref" : "DBUser" }, "'@'localhost';\n",
          "FLUSH PRIVILEGES;\n"
        ]]},
        "mode"  : "000400",
        "owner" : "root",
        "group" : "root"
      },

      "/tmp/create-wp-config" : {
        "content" : { "Fn::Join" : [ "", [
          "#!/bin/bash -xe\n",
          "cp /var/www/html/wordpress/wp-config-sample.php /var/www/html/wordpress/wp-config.php\n",
          "sed -i \"s/'database_name_here'/'",{ "Ref" : "DBName" }, "'/g\" wp-config.php\n",
          "sed -i \"s/'username_here'/'",{ "Ref" : "DBUser" }, "'/g\" wp-config.php\n",
          "sed -i \"s/'password_here'/'",{ "Ref" : "DBPassword" }, "'/g\" wp-config.php\n"
        ]]},
        "mode" : "000500",
        "owner" : "root",
        "group" : "root"
      }
    },
    "services" : {
      "sysvinit" : {
        "httpd"  : { "enabled" : "true", "ensureRunning" : "true" },
        "mysqld" : { "enabled" : "true", "ensureRunning" : "true" }
      }
    }
  },

  "configure_wordpress" : {
    "commands" : {
      "01_set_mysql_root_password" : {
        "command" : { "Fn::Join" : ["", ["mysqladmin -u root password '", { "Ref" : "DBRootPassword" }, "'"]]},
        "test" : { "Fn::Join" : ["", ["$(mysql ", { "Ref" : "DBName" }, " -u root --password='", { "Ref" : "DBRootPassword" }, "' >/dev/null 2>&1 </dev/null); (( $? != 0 ))"]]}
      },
      "02_create_database" : {
        "command" : { "Fn::Join" : ["", ["mysql -u root --password='", { "Ref" : "DBRootPassword" }, "' < /tmp/setup.mysql"]]},
        "test" : { "Fn::Join" : ["", ["$(mysql ", { "Ref" : "DBName" }, " -u root --password='", { "Ref" : "DBRootPassword" }, "' >/dev/null 2>&1 </dev/null); (( $? != 0 ))"]]}
      },
      "03_configure_wordpress" : {
        "command" : "/tmp/create-wp-config",
        "cwd" : "/var/www/html/wordpress"
      }
    }
  }
}

*Lastly, the script signals the CFN stack to let it know that all tasks are complete and the CFN stack can then go to UPDATE_COMPLETE status.
"/opt/aws/bin/cfn-signal -e $? ",
"         --stack ", { "Ref" : "AWS::StackName" },
"         --resource WebServer ",
"         --region ", { "Ref" : "AWS::Region" }, "\n"

Since your CFN stack is not receiving the signal after 15 minutes, your instance is failing somewhere in the series of tasks I listed above. It could be any number of things causing this, and the best way to find out what's wrong is to SSH into the instance and inspect the logs. AWS documentation explains where the logs are, as well as some other troubleshooting tips: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html
Lastly, when you build your CFN stack, be sure stack rollback is disabled, or else your instance will get auto-terminated when the signal fails and you won't have a chance to look at the logs.
Hope this helps! Good luck.


text:
Q: Is there a purpose for using a macro that does nothing over an empty macro in c++? Learning c++ and reading through a project, I found this.
#define EMPTY_MACRO do {} while (0)

...

#if ASSERTS_ENABLED
#define ASSERTCORE(expr) assert(expr)
#else
#define ASSERTCORE(expr) EMPTY_MACRO
#endif

What is the purpose of EMPTY_MACRO? Is it unnecessary or is there a reason for it?

A: It's there so
ASSERTCORE(expr);

behaves the same with or without ASSERTS_ENABLED. A plain #define ASSERTCORE(expr) would leave behind a lone ; and that would behave differently in some cases.


text:
Q: using php include in jquery What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('
<?php include( SITE_URL . 'activity/popup.php' ) ?>
');

My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.

A: The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';

becomes
var foo = 'This is the content of foo.php.';

after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';

which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;

Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.

A: If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append().  See how it looks.  This will give you a good idea of what the browser will end up with.


text:
Q: Extend Rails within Engine I did a Rails extension as suggested by
extending rails question using Harish Shetty answer.
I like it so much I decided to use it in my Rails Engine.  Didn't quite work.
To make it work i place the file active_record_extensions in the Lib/[ENGINE] directory and added the Require active_record_extension to my engine.rb file.
This works, but I wonder if there's is a more proper way to do it.
Also. I ran into an Issue, (don't know if i'm allowed to piggyback a second question).
I have a Model called Translation.  When i use the extended class method with that model i invoke an error 'Circular dependency detected' with
 raise "Circular dependency detected while autoloading constant #{qualified_name}"
I'm guessing that using the model extension exposed the name to something that doesn't like the fact that I used Translation.  (doesn't happen with the other models I have).  I get around it by not using the extend class method with that model.


text:
Q: Problema restricciones xsd de un xml estoy realizando un curso (donde el profesor no explica una ....) y llevo días intentando sacar restricción de un elemento que tiene un atributo en su interior. soy nuevo esto y casi no  me entero mucho.
seria posible una ayuda.
Esto es lo que pide: La distancia es un número mayor de 0. Es necesario que la distancia tenga un atributo unidad que indica la unidad en forma de cadena.
  <xs:element name="distancia">

    <xs:complexType>

        <xs:simpleContent>
            <xs:extension base="xs:integer">
                <!-- ** final restriction del atributo unidad  --><!-- **EJERC 7.4-->
                <xs:attribute name="unidad" use="required">
                    <xs:simpleType>
                        <xs:restriction base="xs:NMTOKEN"><!-- ** EN CADENA, solo llego hacer esto y no se si esta bien  -->

                        </xs:restriction>
                    </xs:simpleType>
                </xs:attribute>
                <!-- **FIN EJERC 7.4-->
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>

A: Cuando necesitas crear un tipo que incluye un elemento y sus atributos, el tipo del atributo no s epuede definir inline y  debes crear su definicion por aparte. Algo así:
  <xs:attribute name="unidad" use="required" type="xs:NMTOKEN" />
  <xs:element name="distancia">

   <xs:complexType>

    <xs:simpleContent>
        <xs:extension base="xs:integer">
           <xs:attribute ref="unidad" />
        </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>


text:
Q: How to fill in password EditText with Android uiautomator? Is it possible for the uiautomator to select a password EditText? I have no problem finding other EditText views by their android:hint property, but the uiautomatorviewer shows all password fields as NAF. I tried setting the password field content description and that didn't work either.
If it's not possible, how do you set a timeout for a tester to manually enter a password?

A: I had the same problem with API v16.
Today I tried my script with v17 (Android 4.2) and it worked like a charm.
It seems that the first version of uiautomator has some major bugs.
Here is my code:
// click the admin button
new UiObject(new UiSelector().text("admin")).click();
// set pwd text
new UiObject(new UiSelector().description("pwdEditText")).setText("admin");
// click login button
new UiObject(new UiSelector().description("loginButton")).click();

A: Sometimes, your Views won't have a ResourceId, such as the case where you need to programmatically type into a text field within a webpage rendered inside a WebView. i.e.
// Fetch the EditText within the iOrder Webpage.
final UiObject lUiObject = UiDevice.getInstance(getInstrumentation()).findObject(new UiSelector().className(EditText.class).textContains("Enter Loyalty Code"));

In such cases, we need to use the UiSelector class to dynamically search for the EditText; however, you'll find that the returned Matcher<View> isn't compatible with the onView(with(...)) methods.
When using the UiSelector, you can take advantage of a UiDevice reference to programmatically fake key presses using the approach below:
/* Declare the KeyCodeMap. */
private static final KeyCharacterMap MAP_KEYCODE = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);

/** Simulates typing within a UiObject. The typed text is appended to the Object. */
private final void type(final UiObject pUiObject, final String pString, final boolean pIsSimulateTyping, final boolean pIsClearField) throws Exception {
    // Fetch the Instrumentation.
    final Instrumentation lInstrumentation = getInstrumentation();
    // Fetch the UiDevice.
    final UiDevice        lUiDevice        = UiDevice.getInstance(lInstrumentation);
    // Are we clearing the Field beforehand?
    if(pIsClearField) {
        // Reset the Field Text.
        pUiObject.setText("");
    }
    // Are we going to simulate mechanical typing?
    if(pIsSimulateTyping) {
        // Click the Field. (Implicitly open Android's Soft Keyboard.)
        pUiObject.click();
        // Fetch the KeyEvents.
        final KeyEvent[] lKeyEvents = SignUpTest.MAP_KEYCODE.getEvents(pString.toCharArray());
        // Delay.
        lInstrumentation.waitForIdleSync();
        // Iterate the KeyEvents.
        for(final KeyEvent lKeyEvent : lKeyEvents) {
            // Is the KeyEvent a Release. (The KeyEvents contain both down and up events, whereas `pressKeyCode` encapsulates both down and up. This conditional statement essentially decimates the array.)
            if(lKeyEvent.getAction() == KeyEvent.ACTION_UP) {
                // Press the KeyEvent's corresponding KeyCode (Take account for special characters).
                lUiDevice.pressKeyCode(lKeyEvent.getKeyCode(), lKeyEvent.isShiftPressed() ? KeyEvent.META_SHIFT_ON : 0);
                // Delay.
                lInstrumentation.waitForIdleSync();
            }
        }
        // Close the keyboard.
        lUiDevice.pressBack();
    }
    else {
        // Write the String.
        pUiObject.setText(pUiObject.getText() + pString);
    }
    // Delay.
    lInstrumentation.waitForIdleSync();
}

A: I just find them by id:
onView(withId(R.id.input_password)).perform(typeText("password"));

I see that the UI Automator Viewer now also shows the resource-id property, which would be useful if you don't have access to the code.


text:
Q: Analytics API: Query for when objects are tagged? Is it possible using the Analytics API to query for when a particular type of artifact, like a defect or test case, was tagged with a particular tag?
What would the query look like?

A: If the ObjectID of your Tag of interest is 12345678910, then a query similar to the following should do the trick:
    "_TypeHierarchy":"TestCase",
    "Tags":{$in:[12345678910]},
    "_PreviousValues.Tags":{$nin:[12345678910]}


text:
Q: Vue 2 build error - ERESOLVE unable to resolve dependency tree I'm getting the following dependency issues centering around eslint when I try to build my Vue 2 app.
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: vue-crm@2.2.3
npm ERR! Found: eslint@8.16.0
npm ERR! node_modules/eslint
npm ERR!   dev eslint@">=7.5.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer eslint@"^5.0.0 || ^6.0.0" from @typescript-eslint/parser@2.34.0
npm ERR! node_modules/@typescript-eslint/parser
npm ERR!   dev @typescript-eslint/parser@"^2.26.0" from the root project
npm ERR!   peer @typescript-eslint/parser@"^2.0.0" from @typescript-eslint/eslint-plugin@2.34.0
npm ERR!   node_modules/@typescript-eslint/eslint-plugin
npm ERR!     dev @typescript-eslint/eslint-plugin@"^2.26.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!

I have tried changing the eslint version in the package.json to several different versions but nothing resolves the issue.
I have also tried running npm install --save  --legacy-peer-deps as suggested for this similar SO question and, though the build begins, it hangs shortly after at about half way through like so:
########⠂⠂⠂⠂⠂⠂⠂⠂⠂⸩ ⠋ idealTree: timing idealTree Completed in 29424ms
I am particularly confused by the line npm ERR! Found: eslint@8.16.0. I don't know where this is being found and the version number that it complains about might change each time I try another one in the package.json.
I've been trying to fix this for a couple of days now without any luck. If anyone can tell me what is needed to resolve it I would be very grateful.