text:
Q: CSS/JS? How to reflect a border-radius?
I try to code a little rock-paper-scissors based game and used the CSS/JS-code from this youtube tutorial to create neon buttons with a snake animation around the edges of the button.
https://youtu.be/3RRgVHd2TXQ
I then softened the edges of the buttons using "border-radius: 15px" - but the reflection has still sharp corners.
How can I solve this?
Also the snake-animation to shine around the edges of the button does not work :( - would be great to know why!?
Try the game: https://bamory.com/?hotlink=FARTWAR  (click link to start a game-session and invite another player with the session-code appearing on top of the screen)
CODE:
html{
  text-align: center;
  }

}

body.chapter2 {
    color: yellow;
}

input {
    margin: 10px;
    height: 50px;
    width: 90%;
}

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap');
*
{
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif;
    box-sizing: border-box;
}
body
{
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: #050801;
  flex-direction: column;
}
.button
{
  border-radius: 15px;
    position: relative;
    display: inline-block;
    padding: 10px 15px;
    margin: 10px 10px;
    color: #03e9f4;
    font-size: 24px;
    text-decoration: none;
    text-transform: uppercase;
    overflow: hidden;
    transition: 0.5s;
    letter-spacing: 4px;
    -webkit-box-reflect: below 1px linear-gradient(transparent, #0005);
  width: 25%;
}
.button:nth-child(1)
{
    filter: hue-rotate(290deg);
}
.button:nth-child(3)
{
    filter: hue-rotate(110deg);
}
.button:hover
{
    background: #03e9f4;
    color: #050801;
    box-shadow: 0 0 5px #03e9f4,
                0 0 25px #03e9f4,
                0 0 50px #03e9f4,
                0 0 200px #03e9f4;
}
.button span
{
    position: absolute;
    display: block;
}
.button span:nth-child(1)
{
    top: 0;
    left: 0;
    width: 25%;
    height: 2px;
    background: linear-gradient(90deg, transparent, #03e9f4);
    animation: animate1 1s linear infinite;
}
@keyframes animate1
{
    0%
    {
        left: -100%;
    }
    50%, 100%
    {
        left: 100%;
    }
}
.button span:nth-child(2)
{
    top: -100px;
    right: 0;
    width: 2px;
    height: 100%;
    background: linear-gradient(180deg, transparent, #03e9f4);
    animation: animate2 1s linear infinite;
    animation-delay: 0.25s;
}
@keyframes animate2
{
    0%
    {
        top: -100%;
    }
    50%, 100%
    {
        top: 100%;
    }
}
.button span:nth-child(3)
{
    bottom: 0;
    right: -100%;
    width: 100%;
    height: 2px;
    background: linear-gradient(270deg, transparent, #03e9f4);
    animation: animate3 1s linear infinite;
    animation-delay: 0.5s;
}
@keyframes animate3
{
    0%
    {
        right: -100%;
    }
    50%, 100%
    {
        right: 100%;
    }
}
.button span:nth-child(4)
{
    bottom: -100%;
    left: 0;
    width: 2px;
    height: 100%;
    background: linear-gradient(360deg, transparent, #03e9f4);
    animation: animate4 1s linear infinite;
    animation-delay: 0.75s;
}
@keyframes animate4
{
    0%
    {
        bottom: -100%;
    }
    50%, 100%
    {
        bottom: 100%;
    }
}

Thanks for your help! (it´s my first time using JS / stackoverflow - please forgive me if I inserted too much code or did other mistakes!)

A: how about give up box-reflect and use transform. take look at this:
css box-reflect alternative for older browser
it's more messy but why not more to learn


text:
Q: How to make resource available to the network? I have this Building Simulator application that uses Django. It simulates different actions in a building and you can query it to see what is the temperature inside etc. I set it up on my Ubuntu Server 12.10 and it is located in my /home/myusername/Documents/BuildingSimulator directory. It listens on port 8000 so when I open: 127.0.0.1:8000/admin locally, I can see admin panel. When I try to access it form my local network I can't. I think that is happening due to the fact that it is located in my /home/myusername directory which is available only to myusername user. Where should I put this application so that it can be accessed form anywhere? Or what should I do to make this folder accessible to anybody?
I should add that I have Webmin running on port 10000 and It works fine when I access it remotely.
Here is the output of sudo netstat -tlnp:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      1530/dnsmasq
tcp        0      0 192.168.1.39:53         0.0.0.0:*               LISTEN      1252/named
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN      1252/named
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      966/sshd
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      749/cupsd
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      1500/postgres
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN      1252/named
tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      784/smbd
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      13713/python
tcp        0      0 0.0.0.0:993             0.0.0.0:*               LISTEN      1256/dovecot
tcp        0      0 0.0.0.0:995             0.0.0.0:*               LISTEN      1256/dovecot
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1278/mysqld
tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      784/smbd
tcp        0      0 0.0.0.0:110             0.0.0.0:*               LISTEN      1256/dovecot
tcp        0      0 0.0.0.0:143             0.0.0.0:*               LISTEN      1256/dovecot
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1806/apache2
tcp        0      0 0.0.0.0:10000           0.0.0.0:*               LISTEN      1766/perl
tcp        0      0 0.0.0.0:6000            0.0.0.0:*               LISTEN      1713/X
tcp6       0      0 :::21                   :::*                    LISTEN      2432/proftpd: (acce
tcp6       0      0 :::53                   :::*                    LISTEN      1252/named
tcp6       0      0 :::22                   :::*                    LISTEN      966/sshd
tcp6       0      0 ::1:631                 :::*                    LISTEN      749/cupsd
tcp6       0      0 ::1:953                 :::*                    LISTEN      1252/named
tcp6       0      0 :::445                  :::*                    LISTEN      784/smbd
tcp6       0      0 :::993                  :::*                    LISTEN      1256/dovecot
tcp6       0      0 :::995                  :::*                    LISTEN      1256/dovecot
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN      1849/java
tcp6       0      0 :::139                  :::*                    LISTEN      784/smbd
tcp6       0      0 :::110                  :::*                    LISTEN      1256/dovecot
tcp6       0      0 :::143                  :::*                    LISTEN      1256/dovecot
tcp6       0      0 :::8080                 :::*                    LISTEN      1849/java
tcp6       0      0 :::6000                 :::*                    LISTEN      1713/X

A: Django Documentation:

django-admin.py runserver
Starts a lightweight development Web server on the local machine. By
  default, the server runs on port 8000 on the IP address 127.0.0.1. You
  can pass in an IP address and port number explicitly.
Note that the default IP address, 127.0.0.1, is not accessible from
  other machines on your network. To make your development server
  viewable to other machines on the network, use its own IP address
  (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled).

You have to run:
django-admin.py runserver 0.0.0.0:8000

Then you'll be able to connect from network.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python script raises an error depending on how it was called from the shell I'm making this small tool to convert a skype's chat database into a somewhat more readable representation under the form of an IRC-like chat export. I'm making this because I saved some of my old skypes chats' .db files, and now I'm trying to extract the content from them. That part I got working, now however there's something I just cannot figure out why it happens.
If I invoke my script as ./skype2text.py file.db chat_partner_id it works fine, and prints the chat with the specified user id to stdout
Having that working I wanted to save the output to a file instead of printing it to stdout, so I just ran it as echo $(./skype2text.py file.db chat_partner_id) first just to see how it went, so I could redirect it to a file, and that's when the weird stuff happens. It prints the first chat line and crashes. (And also completely ignores newlines after that).
$ echo $(./skype2text.py "main 1.db" miya)
Traceback (most recent call last):
File "./skype2text.py", line 62, in <module>
  print(u"<" + row[0] + u"> " +  unicode(parser.unescape(unicode(row[1]))))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 47: ordinal not in range(128)
<Luda> C'est moi <ss type="wink">;)</ss> <MiYa> None

Here is the code
#!/usr/bin/env python2
# charset=utf-8

from __future__ import print_function

import sys
import sqlite3
import os.path
import HTMLParser

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def eprint_use():
    eprint("usage : " + sys.argv[0] + " <file.db> <partner's skype ID> [output file]")

# actual code here
# first of all check argv and print the help message if it's wrong

if len(sys.argv) < 3 or len(sys.argv) > 4:
    eprint_use()

else:
    database_path = sys.argv[1]
    partner_id = sys.argv[2]
    output_path = sys.argv[3] if len(sys.argv) == 4 else partner_id + '.txt'

    if not os.path.isfile(database_path):
        sys.exit('the file %s does not exist' % (database_path))

    connection = sqlite3.connect(database_path)
    cursor = connection.cursor()

    parser = HTMLParser.HTMLParser()

    cursor.execute("SELECT from_dispname,body_xml FROM Messages WHERE dialog_partner='" + partner_id + "' ORDER BY timestamp")

    for row in cursor.fetchall():
        print(u"<" + row[0] + u"> " +  unicode(parser.unescape(unicode(row[1]))))

I've ommitted most of the comments at the top that serve no purpose, so line 62 here refers to the very last line.
I may be doing something wrong with the SQL queries at some point. I don't really check if the input is valid either, but that's not really the point. Why does this happen ? Why does calling the script differently causes it to crash although it works perfectly on its own ? I've checked sys.argv as well and it contains the same thing in both cases. Also yes, I have an output_path variable which is not used, I'll adapt the output depending on the third parameter, if it contains a filename I'll output to the file instead, for now. The weirdest is why does it cause an unicode exception ?
$ bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
$ python2 --version
Python 2.7.10

A: probably the default encoding is utf-8 in first case (when it works), and it is ascii in second case (when UnicodeEncodeError happens)
maybe try:
for row in cursor.fetchall():
    res = u"<" + row[0] + u"> " +  unicode(parser.unescape(unicode(row[1])))
    print(res.encode('utf-8'))


text:
Q: Android Sqlite trigger operation go through
This is my first table it has 3 columns and all are entered by the user. No complication and it works fine. But there is another table and it is dependent on this table 3rd column. i.e. on room number column. Please ignore the names convention as i have not really followed any naming conventions.

This is my second table and as you can see it has its last column as room number. please ignore name convention. this room number column is foreign key it is dependent on the 1st table entry or delete
Now I have created a schema for the 2nd table. which declares that it has 5 columns and the last one is the foreign key.
 private static final String DATABASE_CREATE_NOTES_ID_TABLE =
    ("CREATE TABLE "+ DATABASE_NOTES_TABLE +" ("+ KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            KEY_TIME + " TEXT, "+
            KEY_NOTES + " TEXT, "+
            KEY_DATE +  " TEXT, " +
            KEY_ROOMS + " INTEGER , FOREIGN KEY (" + KEY_ROOMS + ") REFERENCES " + DATABASE_PATIENT_TABLE +" (" +KEY_ROOM_NUMBER+ "));");

Tables as you see is getting created successfully.
Now I have to write a TRIGGER statement, based on that when I delete a room number from the first table, then all the rows in the 2nd table which has the same room number should be deleted. And If I add a new room number in the first table then it should be added in the 2nd table.
The trigger statement for insert of new room number that I have written is as follows
    db.execSQL("CREATE TRIGGER fk_notesTable_roomNumber " +
                " BEFORE INSERT "+
                " ON "+DATABASE_NOTES_TABLE+
                " FOR EACH ROW BEGIN"+
                " SELECT CASE WHEN ((SELECT "+KEY_ROOM_NUMBER+" FROM "+DATABASE_PATIENT_TABLE+" WHERE "+KEY_ROOM_NUMBER+"=new."+KEY_ROOMS +" ) IS NULL)"+
                " THEN RAISE (ABORT,'Foreign Key Violation') END;"+
                "  END;");

This piece of code I have added in the onCreate() of my database file. What else do I do ? Nothing is happening here.
Please kindly point me out where I am making mistake.
Thanks in tons,
Shaista

A: You have added an INSERT trigger. This raises an error if you try and insert a row that doesn't match the constraint specified in the trigger; it does nothing about deleting rows from one table when rows from another are deleted.
You need an AFTER DELETE trigger on the first table which deletes the corresponding rows.


text:
Q: YAML File : Reading Yaml file and Writing the file in Same Format I have a Yaml file which is in the below format:
connector:
  Key1: Test
  Key2: 22
  Key3: Strringname
  Key4: TestingFucntion
When I am trying to read the file and write it into another file the format is different.
!!package name
connector: {key1: Test, key2: 22
, key3: Strringname, key4: TestingFucntion}
Below is the code which i have used to read the file and write it :
             Map<String, Object> data = new HashMap<String, Object>();
             data.put(key1, value1);
             DumperOptions options = new DumperOptions();
             options.setIndent(4);
             options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
             options.setPrettyFlow(true);
             Yaml yaml = new Yaml();
             InputStream in =  new FileInputStream(new File(FIle name));
             Prop cc = yaml.loadAs(in,Prop.class);
             cc.getconnector().setkey3(Strringname);
             Writer fwriter = new OutputStreamWriter(new FileOutputStream(File name), "UTF-8");
             yaml.dump(cc, fwriter);

Any suggestions for writing the file in the same format as it is.

A: Use DumperOptions.FlowStyle.BLOCK instead if you want to have the mapping in block style. You also need to tell the Yaml constructor about your options – right now, they don't do anything.
To remove the root tag and give the options to Yaml, add
final Representer representer = new Representer();
representer.addClassTag(Prop.class, Tag.MAP);
Yaml yaml = new Yaml(representer, options);

This sets the tag of the class Prop to !!map, the default YAML tag for mappings. This will be omitted unless you're outputting it in canonical style.

That being said, the important thing is: In general, you cannot ensure that the format stays the same. SnakeYAML does not support that and doing so would technically be a breach of the specification. The keys will always written out in the order you defined in the Prop class, not in the order in which they occurred in the original file. Deserialization drops information like whitespace, comments and other formatting details.
If you have any Map in your data, the order of the keys will be arbitrary (as in: you cannot define or change it). If the original document contained ... or ---, that information will be lost. If the original document contained scalars with '' or "", that information is lost.
You can only define consistent output behavior (i.e. define your options and always use them), but if the input uses a different style, that style will always be lost.


text:
Q: Setup Emacs for Django development I am trying to set up emacs for django development. I already have elpy, jedi and flycheck set up and working with my venvs, but when I go to look for extending my setup for django development, I find too many related modes that seem to be doing similar things.
Specifically package-list-packages gives me the following options:

*

*django-commands

*django-manage

*django-mode

*djangonaught

*pony-mode

*python-django

Searching the web for comparisons doesn't seem to yield much result and I can't find anything relevant or recent here. Now I can certainly try each and every one of these for a day or two and evaluate them one by one, but I was wondering if somebody can at least help me eliminate some of the options or give me some advice on the matter. Thank you.


text:
Q: $L_f(z) = \frac 1 {2 \pi i}\int_{ \mathbb{T} } \frac{ \zeta+z}{ \zeta ( \zeta -z)} f( \zeta ) d\zeta$ I'm trying to prove that for any harmonic function $u$, we have :
let $ \Omega \subset \mathbb{R}^2$ and $ \overline B(0,R) \subset \Omega $
$$ u \colon \Omega \to \mathbb R  $$

$$\forall z \in B(0,R) : u(z) = \Re \ \ \frac 1 {2 \pi i}\int_{
 |\zeta| = R } \frac{ \zeta+z}{ \zeta ( \zeta -z)} u( \zeta ) d\zeta $$

I've tried a few things:
I've shown that
$$ \int_{|\zeta| = R } \frac{ \zeta+z}{ \zeta ( \zeta -z)} u( \zeta ) d\zeta
=
2 \int_{|\zeta| = R } \frac{ u( \zeta ) }{ ( \zeta -z)}  d\zeta
-
\int_{|\zeta| = R } \frac{ u( \zeta ) }{ \zeta}  d\zeta $$
Which ( I'm not sure about this point... but in complex analysis I think it would have made sense ) is proportional to
$$ 2 \operatorname{Res}_z(u) - \operatorname{Res}_0(u) $$
But I don't think I'm going anywhere ...
So I started again and I studied the function :
$$L_f(z) = \frac 1 {2 \pi i}\int_{ \mathbb{T} } \frac{ \zeta+z}{ \zeta ( \zeta -z)} f( \zeta ) d\zeta$$
I would still need to prove that this is holomorphic, but the derivative is given by :
$$L'_f(z) = \frac 1 { \pi i}\int_{ \mathbb{T} } \frac{  f( \zeta ) }{ ( \zeta -z)^2    }d\zeta$$
I was very surprised because the RHS is exactly the expression of $ 2 f'(z) $ according to Cauchy Integral Formula. So I was believing that $L_f \equiv f$. But in order to prove the equality, I would still need to prove that :
$$- \int_{ \mathbb{T} } \frac{ f( \zeta ) }{ \zeta}  d\zeta
=
\frac 1 { \pi i}\int_{ \mathbb{T} } \frac{  f( \zeta ) }{  \zeta -z    }d\zeta $$

So could you please tell me if my reasoning is true/ going somewhere, if I'm allowed to talk about residues for harmonic functions...
Or if you have another solution for the main problem, I would also be very grateful to read it :)

A: This is basically Poisson's formula for harmonic functions in the unit disk, namely
$$
u(z) = \frac{1}{2\pi} \int_0^{2\pi} u(e^{i\theta}) \frac{1-|z|^2}{|e^{i\theta}-z|^2} \, d\theta = \Re \left[\frac{1}{2\pi} \int_0^{2\pi} u(e^{i\theta}) \, \frac{e^{i\theta} +z}{e^{i\theta}-z} \, d\theta \right].
$$
Rewriting the integral in complex form, with $\zeta = e^{i\theta}$, we get that $d\theta = \frac{dz}{iz}$, so
$$
u(z) = \Re \left[\frac{1}{2\pi} \int_0^{2\pi} u(\zeta) \, \frac{\zeta +z}{\zeta-z} \, \frac{d\zeta}{i\zeta} \right] = \Re \left[\frac{1}{2\pi i} \int_0^{2\pi} u(\zeta) \, \frac{\zeta +z}{\zeta (\zeta-z)} \, d\zeta \right].
$$


text:
Q: Flip and negate a coordinate point in java? How would you take a point object and flip the coordinates and switch their signs? If you wanted to add a method called flip to the code below:
    public class Point {
    private int x;
    private int y;

    // flip method goes here

}

I've tried things like:
    public class flip(){
    x = 0-x;
    y = 0-y;
    Point p = new Point(y,x);
}

But it's not working. (81,21) and I only get (-81,-21). It doesn't flip it. But method can't take any parameters, if that's even relevant. Thanks.

A: If you want to flip the coordinates in place (so calling p.flip() modifies Point p, then this should work:
public class Point {
    private int x;
    private int y;

    public void flip() {
        int tmp = x;
        x = -y;
        y = -tmp;
    }
}

If you want the flip() method to return a new point with the coordinates flipped, then you can do this:
public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point flip() {
        return new Point(-y, -x);
    }
}

A: Try this:
public Point flip(Point orig){
    return new Point(-orig.y, -orig.x);
}

If you can not pass it any parameters, make them class variables.
private Point mPoint;

public void flip(){
    mPoint.x = -mPoint.y;
    mPoint.y = -mPoint.x;
}

A: Something like the following code would work in your situation:
public Point flip(Point point)
{
  return new Point(-point.getY(), -point.getX());
}


text:
Q: VPN with Encryption gives twice the download speed? I am currently paying for internet through SuddenLink which has offered me 50Mb download and 3MB upload. I have also bought a VPN through PrivateInternetAccess, which has pretty much doubled my download speed while downloading files encrpyted from my ISP.
The speedtest.net has shown with the VPN running with 128Mb down and 10Mb up.
Please Note The Data Encryption is BlowFish, Data Authentication is SHA256, and the Handshake is RSA-4096.
I have been told that this is not possible at all by several people, but when I go to show them the results from actually downloading a file and the speedtests, we are all confused.
Is this actually happening? As they are asking and were saying, is it the speeds which we see from the end-point of the VPN to the server which we are preforming the speed test to?
Also, I will provide screenshots of the speed test with and without the VPN also.
Update 1
I am not sure if this matters or not, but it may in the end. I live in a very, very rural location in West Virginia. I am lucky to not have 256K Dail-up internet thanks to my ISP, SuddenLink. I am starting to think it could be a congestion issue with my region?

A: In the past I have had the same effect with my ISP (in a rural area too, though this is but a coincidence).
The root of the matter was that he implemented a bandwidth limitation on port 80 only. This was especially obvious with speedtest.net, where the initial speed would peak, then decrease to less than half of its peak value.
I discovered  by pure chance that this did not occur on OpenVPN, where I managed to obtain the peak speed value during the whole speedtest.net test. This was made possible by the fact that the site I connected to (my work site) has a very nice, very fast, large-bandwidth connection.
Alerted by this, I tried a large file transfer via scp, and, lo and behold, I achieved the same large speeds as with the OpenVPN, rather than the lower http speeds.
You may try the same, and see whether a bandwidth limit is applied on ports 22 (scp) and 21 (ftp). It is most illuminating to use files already significantly compressed like pdfs, since this will rule out the incidence of compression per se.
Though admittedly sloppy, these bandwidth limitations are still effective, since most people use the Internet only for downloading Web pages.
EDIT:
Strictly speaking, there is a way to test this: if you control the VPN server, you may stop any other activity on the server on port 80, and start listening for VPN connections on port 80; you will also have to modify the port you connect to on the client's program. Now, if your ISP is limiting bandwidth use on port 80, the VPN should clock at exactly the same speed as the non-VPN connection.


text:
Q: How to wait for element using mocha, chai & protractor So my idea was to make a function that is trying to find a element for x seconds. If the element is not presented (Be able to write on the element) and/or not able to send any keys to the element then wait. If it passed given wait seconds (etc 10 sec) then it should throw a exception.
For right now I did:
    it('enter email', function (done) {
        browser
            .then(() => browser.wait(piPage.getEmailValue().isPresent(), 10000))
//getEmailValue = element(by.id('email').getAttribute("value");
            .then((isPresent) => {
                assert.equal(isPresent, true, 'Email failed entering.')
            })
            .then(() => piPage.enterEmail("test@test.com"))
            .then(() => done());
    });

which actually finds the element and send keys if the value is presented. HOWEVER it seems that the 10 seconds browser.wait doesn't seem to apply and it instead immediately triggers without waiting at all. I had to manually add
browser.driver.sleep(10000).then(function() {
    console.log('waited 10 seconds');
});

but it isnt something I want.
What I would like to do is that have browser.wait to find the element is presented/able to send_keys until x seconds and then if the element is found then we continue, else throw a exception basically.

A: The isPresent() method waits for the element to be present in the html DOM, but that doesn't necessarily means the element is interactable yet. For that you'd need to chain it with an explicit wait like elementToBeClickable(element)
const EC = protractor.ExpectedConditions;

waitForElement = async () => {
    const present = await yourElement.isPresent();
    if (present) {
        await browser.wait(EC.elementToBeClickable(yourElement));
        await yourElement.sendKeys('something');
    }
};

A: When you pass 10 s it's actually said: i will give you 10 s to find it but if you find it before the 10s return the value expected
Schedules a command to wait for a condition to hold. The condition may be specified by a {@link webdriver.Condition}, as a custom function, or as a {@link webdriver.promise.Promise}.

For a {@link webdriver.Condition} or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a {@link webdriver.promise.Promise promise}, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisified. Note the resolution time for a promise is factored into whether a wait has timed out.

Note, if the provided condition is a {@link WebElementCondition}, then the wait will return a {@link WebElementPromise} that will resolve to the element that satisified the condition.

Example: waiting up to 10 seconds for an element to be present and visible on the page.

The only solution as I know is to use sleep()
I recommended to use instead of many then()
import { browser, element, by, ExpectedConditions as ec } from 'protractor';

    await browser.wait(ec.visibilityOf(element(by.id('menu-id')), 5000);


text:
Q: Scroll element into view - top nav I've this code in the snippet. It's an intersection Observer that tracks visible headers and adds an "active" class to the corresponding anchor tag in the top nav.
I would like to know if it's possible for the 'li' element with class "active" to also be scrolled into view.
I have tried a mutationObserver but I can't seem to make it work by any means.
Thanks!

  window.addEventListener('DOMContentLoaded', () => {

    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        const id = entry.target.getAttribute('id');
        if (entry.intersectionRatio > 0) {
          document.querySelector(`ul li a[href="#${id}"]`).parentElement.classList.add('active');
        } else {
          document.querySelector(`ul li a[href="#${id}"]`).parentElement.classList.remove('active');
        }
      });
    });

    // Track all sections that have an `id` applied
    document.querySelectorAll('h2[id]').forEach((h2) => {
      observer.observe(h2);
    });

  });
.table_of_content li{
    display:inline-flex;
    margin-right: 20px;
    border-right: 2px solid black;
    padding-right:15px;
}
.table_of_content {
    border-left:none;
    z-index:1000;
    position: sticky;
    background-color:white;
    top: -1px;
    overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;

}
.table_of_content ul {
    margin: 0 auto;
    padding: 15px 0;
}

.table_of_content li.active > a {
    color:#ff9900;
    border-radius:5px;
    text-decoration:underline;
}
.section {
    max-width: 400px;
}

In this article

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

Heading 6

Heading 7

Heading 8

Header 1

      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Culpa, ex. Eaque laboriosam fugiat debitis quisquam maiores ipsa aspernatur quam provident tenetur! Ipsa possimus illum provident. Quam, quaerat cum? Earum, reiciendis!

Header 2

      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quia neque, repudiandae minus sit ratione expedita debitis hic sequi recusandae repellat? Eligendi, reiciendis voluptatem. Quidem tempore cupiditate obcaecati rem omnis quis commodi, rerum in delectus beatae eius nulla? Harum laborum, obcaecati ipsa officiis velit voluptatibus alias facilis at recusandae dolores molestias, autem quas. Repellendus ducimus soluta culpa dicta vel eveniet recusandae beatae odit id exercitationem ratione, nemo inventore, unde dolores eligendi quasi pariatur rem labore? Labore eum doloremque non illo, autem optio, excepturi ad quis reiciendis exercitationem necessitatibus fugit? Repellendus dolore ea magnam tempora in corporis sed totam et suscipit! Nihil?

Header 3

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto debitis, eligendi odit quam necessitatibus enim alias perferendis ut maxime quod quae ipsam minima voluptates voluptatibus at nobis, esse sequi beatae dolor quis. Quia officiis consequuntur, delectus dolore temporibus reprehenderit reiciendis sunt perspiciatis aspernatur, facere veniam. Ad corporis a voluptate provident soluta eveniet? Sunt est deserunt amet assumenda iste odit ad placeat! Vitae aliquam aliquid, molestiae cum aut unde velit laboriosam, perferendis rem asperiores pariatur quam optio quo nostrum saepe quia id dignissimos, consequatur molestias sed nulla ipsum? Molestias ab sapiente dolores ut. Dolor vero quod, distinctio laborum expedita incidunt repudiandae.

Header 4

      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Illo consequatur, harum doloribus nisi vitae odit non deserunt et veritatis modi maxime repudiandae quasi cum eveniet inventore, fuga similique accusamus ad magnam alias qui optio delectus provident. Asperiores labore molestias quod laborum quasi sequi suscipit, optio tenetur esse soluta debitis eaque, doloribus reiciendis voluptatum iure dolorum quibusdam vel nihil quo ratione cupiditate necessitatibus aliquid obcaecati totam. Deserunt laudantium officiis et? Quas doloribus ipsum nam similique libero velit, tempora, delectus exercitationem cumque autem in iste, perspiciatis repudiandae a aliquid nobis ut voluptate corrupti unde recusandae voluptas rem aut nisi quam. Inventore, dolor.

Header 5

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi explicabo, numquam aliquam minus eveniet vero neque ratione quidem voluptatem ipsa officiis soluta beatae dicta eligendi quo, nemo quaerat atque mollitia! Vitae mollitia voluptatum natus iusto eum quis debitis, similique illo, libero necessitatibus illum provident ad inventore sed consectetur molestias ipsa impedit obcaecati cumque et. Eveniet, molestiae deserunt rem earum dolor neque animi dignissimos dolore atque provident at numquam repellendus aliquam adipisci officia maxime fuga unde reiciendis saepe, sint culpa recusandae. At neque sapiente mollitia doloremque, architecto voluptatem delectus nulla laboriosam dicta quo animi magnam nisi in? Voluptatum harum et est!

Header 6

      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Debitis distinctio nesciunt ut similique dicta cum est quis soluta harum quam, dolorem sequi repellat, atque provident eius. Atque ea quibusdam quo! Rem nihil pariatur ex magni odio modi sed unde quidem laboriosam doloremque repellat quo eum nemo eaque mollitia adipisci exercitationem ipsam blanditiis, consectetur atque libero totam quaerat officia soluta? Cum ipsam a incidunt cumque earum quod ea quibusdam vel ratione? Minima, id voluptate! Minima cumque quisquam, quod blanditiis quas et est laudantium placeat explicabo, dolorum velit, facilis cupiditate aspernatur nostrum dicta voluptatem adipisci suscipit debitis enim ullam commodi? Magni, consequatur.

Header 7

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis alias soluta qui accusantium in repellendus, doloremque ullam quis esse optio veniam fugit doloribus mollitia ea, dolorum rem. Unde, adipisci. Totam vel harum maiores illo nobis culpa labore corrupti quasi atque consequuntur, minus odio deleniti iure, ab natus aliquam consectetur asperiores quia eveniet dolorem similique dolore eos quisquam. Quis, ipsam corrupti? Atque molestiae omnis asperiores dolores eos obcaecati aspernatur, recusandae eaque numquam consectetur aut corporis vitae dignissimos et ipsum eum odit id incidunt voluptate perferendis! Saepe tempora iste aspernatur enim quidem labore voluptatem id dolor quam esse! Quibusdam reiciendis inventore hic!

Header 8

      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est amet inventore quae eveniet sequi unde! Consequatur necessitatibus minima molestias quia vero recusandae unde veniam nobis qui saepe minus culpa ab rem aspernatur officiis earum et doloribus, provident eius asperiores. Harum consectetur odio blanditiis, sunt rerum necessitatibus exercitationem vero dolorem rem, cupiditate pariatur officiis repudiandae deserunt modi sequi aspernatur ratione libero perspiciatis illo cum saepe debitis tempora sapiente! Possimus modi nostrum ipsum placeat nam praesentium quos vero in, non dolor debitis dolorum nobis cum natus obcaecati, soluta reprehenderit sapiente. Eius ducimus placeat numquam incidunt magni repudiandae accusantium quasi alias vitae vero!

A: All you have to do is make add a line to your script.
When you add class "active" to active li element, make the a tag scroll into the view, like so
window.addEventListener("DOMContentLoaded", () => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      const id = entry.target.getAttribute("id");
      if (entry.intersectionRatio > 0) {
        document
          .querySelector(`ul li a[href="#${id}"]`)
          .parentElement.classList.add("active");

        // The following line scrolls the active "li" element into view
        document.querySelector(`ul li a[href="#${id}"]`).scrollIntoView();
      } else {
        document
          .querySelector(`ul li a[href="#${id}"]`)
          .parentElement.classList.remove("active");
      }
    });
  });

  // Track all sections that have an `id` applied
  document.querySelectorAll("h2[id]").forEach((h2) => {
    observer.observe(h2);
  });
});

Hope it helps.

A: I modified your code just a bit to get this working. The important part is where you add the active class to your current active element: currentActiveElement.scrollIntoView()
This ensures, that the current element with the active class is always scrolled into the view.

  window.addEventListener('DOMContentLoaded', () => {

    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        const id = entry.target.getAttribute('id');
        if (entry.intersectionRatio > 0) {
          let currentActiveElement = document.querySelector(`ul li a[href="#${id}"]`);
          currentActiveElement.parentElement.classList.add('active');
          currentActiveElement.scrollIntoView();
        } else {
          document.querySelector(`ul li a[href="#${id}"]`).parentElement.classList.remove('active');
        }
      });
    });

    // Track all sections that have an `id` applied
    document.querySelectorAll('h2[id]').forEach((h2) => {
      observer.observe(h2);
    });

  });
.table_of_content li{
    display:inline-flex;
    margin-right: 20px;
    border-right: 2px solid black;
    padding-right:15px;
}
.table_of_content {
    border-left:none;
    z-index:1000;
    position: sticky;
    background-color:white;
    top: -1px;
    overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;

}
.table_of_content ul {
    margin: 0 auto;
    padding: 15px 0;
}

.table_of_content li.active > a {
    color:#ff9900;
    border-radius:5px;
    text-decoration:underline;
}
.section {
    max-width: 400px;
}

In this article

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

Heading 6

Heading 7

Heading 8

Header 1

      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Culpa, ex. Eaque laboriosam fugiat debitis quisquam maiores ipsa aspernatur quam provident tenetur! Ipsa possimus illum provident. Quam, quaerat cum? Earum, reiciendis!

Header 2

      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quia neque, repudiandae minus sit ratione expedita debitis hic sequi recusandae repellat? Eligendi, reiciendis voluptatem. Quidem tempore cupiditate obcaecati rem omnis quis commodi, rerum in delectus beatae eius nulla? Harum laborum, obcaecati ipsa officiis velit voluptatibus alias facilis at recusandae dolores molestias, autem quas. Repellendus ducimus soluta culpa dicta vel eveniet recusandae beatae odit id exercitationem ratione, nemo inventore, unde dolores eligendi quasi pariatur rem labore? Labore eum doloremque non illo, autem optio, excepturi ad quis reiciendis exercitationem necessitatibus fugit? Repellendus dolore ea magnam tempora in corporis sed totam et suscipit! Nihil?

Header 3

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto debitis, eligendi odit quam necessitatibus enim alias perferendis ut maxime quod quae ipsam minima voluptates voluptatibus at nobis, esse sequi beatae dolor quis. Quia officiis consequuntur, delectus dolore temporibus reprehenderit reiciendis sunt perspiciatis aspernatur, facere veniam. Ad corporis a voluptate provident soluta eveniet? Sunt est deserunt amet assumenda iste odit ad placeat! Vitae aliquam aliquid, molestiae cum aut unde velit laboriosam, perferendis rem asperiores pariatur quam optio quo nostrum saepe quia id dignissimos, consequatur molestias sed nulla ipsum? Molestias ab sapiente dolores ut. Dolor vero quod, distinctio laborum expedita incidunt repudiandae.

Header 4

      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Illo consequatur, harum doloribus nisi vitae odit non deserunt et veritatis modi maxime repudiandae quasi cum eveniet inventore, fuga similique accusamus ad magnam alias qui optio delectus provident. Asperiores labore molestias quod laborum quasi sequi suscipit, optio tenetur esse soluta debitis eaque, doloribus reiciendis voluptatum iure dolorum quibusdam vel nihil quo ratione cupiditate necessitatibus aliquid obcaecati totam. Deserunt laudantium officiis et? Quas doloribus ipsum nam similique libero velit, tempora, delectus exercitationem cumque autem in iste, perspiciatis repudiandae a aliquid nobis ut voluptate corrupti unde recusandae voluptas rem aut nisi quam. Inventore, dolor.

Header 5

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi explicabo, numquam aliquam minus eveniet vero neque ratione quidem voluptatem ipsa officiis soluta beatae dicta eligendi quo, nemo quaerat atque mollitia! Vitae mollitia voluptatum natus iusto eum quis debitis, similique illo, libero necessitatibus illum provident ad inventore sed consectetur molestias ipsa impedit obcaecati cumque et. Eveniet, molestiae deserunt rem earum dolor neque animi dignissimos dolore atque provident at numquam repellendus aliquam adipisci officia maxime fuga unde reiciendis saepe, sint culpa recusandae. At neque sapiente mollitia doloremque, architecto voluptatem delectus nulla laboriosam dicta quo animi magnam nisi in? Voluptatum harum et est!

Header 6

      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Debitis distinctio nesciunt ut similique dicta cum est quis soluta harum quam, dolorem sequi repellat, atque provident eius. Atque ea quibusdam quo! Rem nihil pariatur ex magni odio modi sed unde quidem laboriosam doloremque repellat quo eum nemo eaque mollitia adipisci exercitationem ipsam blanditiis, consectetur atque libero totam quaerat officia soluta? Cum ipsam a incidunt cumque earum quod ea quibusdam vel ratione? Minima, id voluptate! Minima cumque quisquam, quod blanditiis quas et est laudantium placeat explicabo, dolorum velit, facilis cupiditate aspernatur nostrum dicta voluptatem adipisci suscipit debitis enim ullam commodi? Magni, consequatur.

Header 7

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis alias soluta qui accusantium in repellendus, doloremque ullam quis esse optio veniam fugit doloribus mollitia ea, dolorum rem. Unde, adipisci. Totam vel harum maiores illo nobis culpa labore corrupti quasi atque consequuntur, minus odio deleniti iure, ab natus aliquam consectetur asperiores quia eveniet dolorem similique dolore eos quisquam. Quis, ipsam corrupti? Atque molestiae omnis asperiores dolores eos obcaecati aspernatur, recusandae eaque numquam consectetur aut corporis vitae dignissimos et ipsum eum odit id incidunt voluptate perferendis! Saepe tempora iste aspernatur enim quidem labore voluptatem id dolor quam esse! Quibusdam reiciendis inventore hic!

Header 8

      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est amet inventore quae eveniet sequi unde! Consequatur necessitatibus minima molestias quia vero recusandae unde veniam nobis qui saepe minus culpa ab rem aspernatur officiis earum et doloribus, provident eius asperiores. Harum consectetur odio blanditiis, sunt rerum necessitatibus exercitationem vero dolorem rem, cupiditate pariatur officiis repudiandae deserunt modi sequi aspernatur ratione libero perspiciatis illo cum saepe debitis tempora sapiente! Possimus modi nostrum ipsum placeat nam praesentium quos vero in, non dolor debitis dolorum nobis cum natus obcaecati, soluta reprehenderit sapiente. Eius ducimus placeat numquam incidunt magni repudiandae accusantium quasi alias vitae vero!


text:
Q: Does ansible support prototyping tasks? Does ansible support prototyping tasks in a similar way that puppet does?
Like, in puppet I can do something like this:
File {
  notify => Service['httpd'],
}

file { '/etc/httpd/conf/httpd.conf':
  source => "puppet:///modules/httpd/httpd.conf",
}

...where every file declaration will have the notify property of the initial File block unless the subsequent declaration overrides it.
Is there a functional equivalent in ansible? I'm thinking something like this
---
- prototype: task prototype
  notify:
  - command: "apachectl graceful"
- name: install a configuration
  copy: src=/opt/ansible/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
  """something puts my notify here without me having to write it"""

Obviously not very useful for one file declaration but exceedingly useful if you have 20 of them.

A: No, Ansible has nothing like that.
Though it might be possible to implement it yourself by creating an action plugin and a callback plugin. The action plugin would be the prototype declaration. The callback plugin can fire after any Ansible action, e.g. when a task successfully completes.
The only thing I'm not sure about is, if you can trigger a remote action or even a notify from within the callback plugin handlers.


text:
Q: Horocycle transformation in the Poincare half plane model I was puzzeling with how to find an easy formula to calculate the length of a horocycle in the Poincare half plane model
Then I had the brainwave that I can just use a transformation and then find the formula from that
My brainwave in detail:

*

*Given the points $P_1 (x_1, y_1) $ and $P_2 (x_2, y_2) , P_1 \not= P_2, (y_{1,2}  \gt 0) $

*Find the transformation that moves:
$P_1 \to (0, 1) $ and $P_2 \to (z, 1)  $ with  $ z \gt 0 $

*The length of the horocycle is then simply $z$
I can move $P_1 \to (0, 1) $.
But how to get in the same transformation move $P_2 \to (z, 1) $?
For people more into the complex plane (i am not so familiar with it)
how to move
$ p_1 \to i $ and $p_2 \to (z + i ) $ with z being real in a single mobius transformation

A: Here's how to do it in a couple of steps, which can easily be converted into an analytic formula. I'll assume $P_1 \ne P_2$.

*

*In the Euclidean plane, let $C$ be a circle contained in the closed upper half plane, passing through $P_1$ and $P_2$, and tangent to the real line. There will always be exactly two such circles. Let $Q$ be the point of tangency in the real line.

*Apply a Mobius transformation taking $Q \to \infty$. The image of the circle $C$ is now a horizontal line $y=c$ (all Mobius transformations have real coordinates, as befit isometries of the hyperbolic metric on the upper half plane).

*Compose with the Mobius transformation $w \mapsto \frac{1}{c} w$ (I'll use $w=x+iy$ as my complex variable). The image of $C$ is now the line $y=1$, and the the images of $P_1$ and $P_2$ both lie on this line, with $P_1 \mapsto (x',1)$

*Compose with the Mobius transformation $w \mapsto w - (x'+i)$.

Thus, by composing three Mobius transformations, you will get the Mobius transformation of your desire.


text:
Q: Oracle Trigger Still carrying old value for New I write some trigger to automatically change value in state_id field in ESTABLISHMENT table after user updating ADDRESS table through online apps. The Issue is, when user updating OTHER_STATE_ID = 16 and POSTAL_STATE_ID = 16 in tble Address, the value for OTHER_STATE_ID in table ESTABLISHMENT still carrying old value. Only POSTAL_STATE_ID field updated with new value. I have check the trigger code and found out nothing weird code. It seems that the trigger keep old value for updating other_state_id. Here are data scenario:-

*

*Before updating (ADDRESS table)

*

*For ADDRESS_TYPE = 1, value LOCATION_STATE_ID = 8

*For ADDRESS_TYPE = 2, value POSTAL_STATE_ID = 8

*For ADDRESS_TYPE = 11, value OTHER_STATE_ID = 8
Before triggering (ESTABLISHMENT table)

*

*value LOCATION_STATE_ID = 8

*value POSTAL_STATE_ID = 8

*value OTHER_STATE_ID = 8

*Value after updating (ADDRESS table)

*

*User update value LOCATION_STATE_ID = 8

*For ADDRESS_TYPE = 2, value POSTAL_STATE_ID = 16

*For ADDRESS_TYPE = 11, value OTHER_STATE_ID = 16
After triggering (ESTABLISHMENT table)

*

*value LOCATION_STATE_ID = 8

*value POSTAL_STATE_ID = 16

*value OTHER_STATE_ID = 8
Maybe something weird happen in this lines of codes. Anyone..?
Full Codes As below

    create or replace
TRIGGER "TR_ADDRESS_EE"
   AFTER INSERT OR UPDATE
   ON ADDRESS
   FOR EACH ROW
BEGIN
   IF INSERTING
   THEN
      IF (:NEW.STATE_ID IS NOT NULL)
      THEN
         IF (:NEW.RECORD_TYPE_ID = 401)
         THEN
            IF (:NEW.ADDRESS_TYPE = 1)
            THEN
               UPDATE ESTABLISHMENT
                  SET LOCATION_STATE_ID = :NEW.STATE_ID
                WHERE ESTABLISHMENT_ID = :NEW.RECORD_ID;
            ELSIF (:NEW.ADDRESS_TYPE = 2)
            THEN
               UPDATE ESTABLISHMENT
                  SET POSTAL_STATE_ID = :NEW.STATE_ID
                WHERE ESTABLISHMENT_ID = :NEW.RECORD_ID;
            ELSIF (:NEW.ADDRESS_TYPE = 11)
            THEN
               UPDATE ESTABLISHMENT
                  SET OTHER_STATE_ID = :NEW.STATE_ID
                WHERE ESTABLISHMENT_ID = :NEW.RECORD_ID;
            END IF;
         END IF;
      END IF;
   ELSIF UPDATING ('STATE_ID')
   THEN
      IF (:OLD.RECORD_TYPE_ID = 401 AND :NEW.STATE_ID <> :OLD.STATE_ID)
      THEN
         IF (:NEW.ADDRESS_TYPE = 1)
         THEN
            UPDATE ESTABLISHMENT
               SET LOCATION_STATE_ID = :NEW.STATE_ID
             WHERE ESTABLISHMENT_ID = :OLD.RECORD_ID;
         ELSIF (:NEW.ADDRESS_TYPE = 2)
         THEN
            UPDATE ESTABLISHMENT
               SET POSTAL_STATE_ID = :NEW.STATE_ID
             WHERE ESTABLISHMENT_ID = :OLD.RECORD_ID;
         ELSIF (:NEW.ADDRESS_TYPE = 11)
         THEN
            UPDATE ESTABLISHMENT
               SET OTHER_STATE_ID = :NEW.STATE_ID
             WHERE ESTABLISHMENT_ID = :OLD.RECORD_ID;
         END IF;
      END IF;
   END IF;
END;


text:
Q: Работа с архивом 7z в c++ builder В c++ builder есть простая форма, где пользователь может выбрать 7z архив. Необходимо по нажатию кнопки изменить определённый файле в выбранном архиве.
Может, я неправильно гуглю, но не смог найти ни одного туториала как это сделать. Везде пишут про lzma, но нигде ни слова про то, как эту библиотеку подключить и как с ней работать. Хотелось бы либо подробных разъяснений что и как сделать, либо ссылку туда, где они есть
Заранее спасибо

A: Есть TSevenZipVCL,
Есть JclCompression из JCL: JEDI Code Library
Выбирай по вкусу. :)


text:
Q: NetSuite Saved search - available inventory comparison between 2 locations I am trying to build a saved search that can perform available inventory comparison between two locations.  It will display  inventory items that have low inventory less than or equal to 2 at one location, and if the same items have inventory available at another location equal to or greater than 2, so we then use that information to perform inventory transfers. Ideally, I want to then use the saved search and try to build a scheduled workflow to then create auto inventory transfer records.
I currently have a saved search which lists columns of available inventory by each location. We then have to export the saved search into excel and then filter down the list of items based on above comparisons, and then create inventory transfers via csv imports. Again, at this point I am trying to build a saved search which will eliminate the use of excel.

A: CASE WHEN {inventorylocation.id} = '1' AND {locationquantityavailable} >= 2 THEN (CASE WHEN {inventorylocation.id} = '6' AND {locationquantityavailable} <= 2 THEN 1 ELSE 0 END) ELSE 0 END
Yes , this worked for me


text:
Q: Beamer navigation bars to show only \subsubsections and \subsubsubsections I need to customize my navigation bars in the following manner:

*

*Subsubsection title shows up in navigation bars where section title are usually placed

*A new command \subsubsubsection is defined

*Title of the \subsubsubsection shows up where where subsection titles are usually placed.

This presentation would not use \section and \subsection. In effect I need to map two commands to take their place. The reason why I need this is that I am utilizing same slides via \input{} for two different scenarios. In one presentation I don't wish them to show up in navigation bars as they are a minor part of a huge presentation, but in the other they would be the only content and sectioning should be visible in navigation bars. Here is my minimal (non) working example. I usually use Warsaw theme, but hopefully the solution would be theme agnostic.
\documentclass[compress]{beamer}
\usetheme{Warsaw}

\begin{document}

\subsubsection{Section} %This should show up in navigation bar in a place where the section title is usually placed

\begin{frame}{Sample Slide I}
 Content
\end{frame}

\subsubsubsection{Subsection} %This should show up in navigation bar in a place where the subsection title is usually placed

\begin{frame}{Sample Slide I}
Content
\end{frame}
\end{document}

A: The design of beamer discourages \subsubsection use and is built around a formal structure of \section/\subsection/(\subsubsection) (i.e. subsections have to be part of sections). Indeed, support for \subsubsections is partial at best. There is no support for \subsubsubsection (not a standard LaTeX command anyway: \paragraph is the name for this concept in the base classes but this is quite deliberately not defined in beamer).
Where the source has to use \subsubsection and \subsubsubsection, I'd therefore go with redirecting these to \section and \subsection, respectively:
\documentclass[compress]{beamer}
\let\subsubsection\section
\let\subsubsubsection\subsection
\usetheme{Warsaw}

\begin{document}

\subsubsection{A}

\begin{frame}{Sample Slide I}
 Content
\end{frame}

\subsubsubsection{AA}

\begin{frame}{Sample Slide I}
Content
\end{frame}
\end{document}

The \let block could be set up conditionally if required, of of course you could give them custom names (\mysection or similar).


text:
Q: Há alguma diferença entre uma tupla e um objeto com os mesmos tipos de elementos numa lista? Preciso operar com muitos pontos e fiquei em dúvida se ao usar um objeto, no lugar de uma tuple, para representar cada ponto irá aumentar o consumo de memória.
metodo1() é um método genérico para fazer algum tipo de operação com os pontos.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
    def metodo1(self):
        self.x = int(self.x/2)
        self.y = int(self.y/3)

p1 = [Point(i+1, i-1) for i in range(10)]
p2 = [(i+1, i-1) for i in range(10)]

Para esse exemplo, qual seria a melhor usar (a tupla ou a classe) em termo de performance, caso fosse fazer os mesmos tipos de operações com a lista depois?
for i in range(10):
    p1[i].metodo1()
    p2[i] = (int(p2[i][0]/2), int(p2[i][1]/3))

print(p1)
print(p2)

A: Sim - por padrão, apesar de uma instância de uma classe só consumir de memória os dados de cada instância, e os dados compartilhados com a classe (como o metodo1, nesse caso), são compartilhados entre todas as instâncias, por padrão, uma classe em Python vai ter um espaço de nomes (namespace) que é representado internamente por um dicionário: ele aparece como o atributo __dict__ na instância - e só ele consome quase 200 bytes.
Mas a linguagem resolve isso com um mecanismo que permite desligar o namespace dinâmico, reservando apenas espaço para atributos pré-definidos.São os "slots": na criação de uma classe sem o uso de dataclass, deve-se declarar o atributo __slots__ na classe, como em __slots__ = ("x", "y") : isso evita a criação do dicionário e de uma estrutura de dados usado para refereências fracas (__weakref__) e uma instância da classe fica equiparável, em consumo de memória, a uma tupla com a mesma quantidade de atributos.
O decorator dataclass implementa, a partir da versão 3.10 do Python, o parâmetro slots=True que faz a mesma coisa:
from dataclasses import dataclass
...

@dataclass(slots=True)
class Point:
    x: int
    y: int
    def metodo1(self):
        self.x = int(self.x/2)
        self.y = int(self.y/3)

(para versões anteriores, é só declarar o atributo __slots__ = ("x", "y") no corpo da classe, mesmo para uma dataclass)


text:
Q: BROWNIE ISSUES:NONETYPE 5:31:35 in the video, Typed the codes in exactly the same way and ran it but I keep getting this error
INFO: Could not find files for the given pattern(s).
Brownie v1.18.1 - Python development framework for Ethereum
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli_main_.py", line 64, in main
importlib.import_module(f"brownie._cli.{cmd}").main()

File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli\run.py", line 42, in main
active_project.load_config()
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie\project\main.py", line 462, in load_config
_load_project_config(self._path)
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_config.py", line 222, in _load_project_config
and "cmd_settings" in values
TypeError: argument of type 'NoneType' is not iterable
This is the code;
from brownie import FundMe, MockV3Aggregator, network, config
from scripts.helpful_scripts import get_account

def deploy_fund_me():
    account = get_account()
# pass the pricefeed address to our fund me contract

# if we are on a persistent address like rinkeby, use the associated address
# otherwise, deploy mocks
if network.show_active != "development":
   price_feed_address = config["networks"][network.show_active()][
             "eth_usd_price_feed"
]
else:
   print(f"The active network is{network.show_active()}")
print("Deploying Mocks...")
mock_aggregator = MockV3Aggregator.deploy(
      18, 200000000000000000000, {"from": account}
)
price_feed_address = mock_aggregator.address
print("Mocks Deployed!")

fund_me = FundMe.deploy(price_feed_address, {"from": account}, publish_source=True)
print(f"Contract deployed to {fund_me.address}")
def main():
    deploy_fund_me()

A: I answered this here:
File "brownie/_config.py", line 222, in _load_project_config and "cmd_settings" in values TypeError: argument of type 'NoneType' is not iterable
I had the same exact issue and it was because my brownie-config.yml file was incorrect. You can't have any blank variables in your config file.
Under networks I had:
networks:
  rinkeby:
    eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
    verify: True
  kovan:
  mainnet:

having 'kovan' and 'mainnet' set to blank caused the error.
The solution is to either delete those two lines or comment them out like this:
networks:
  rinkeby:
    eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
    verify: True
  # kovan:
  # mainnet:


text:
Q: how to add space between the li in a collapse navbare I trying to add space between the li in my collapse navbar
but the problem is when I minimise just a little my navigator the navbar doesn't collapse correctly image

this the code that I use:

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>

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

     HELLO
    <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">

    </button>

choice1

choice2

choice3

choice4

            Connexion

A: You need to add the following CSS:

.navbar-default .navbar-nav>li>a {
  padding: 15px 0;
}

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

         HELLO
        <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">

        </button>

choice1

choice2

choice3

choice4

                Connexion


text:
Q: Excel: Remove word from a string and show exact word in adjacent cell I have spent a few days trying to figure the below out - can you help?
| I have   this in Column(A):       | And I need the   Brand name in column(A): | ...and product   description in Column (B):  |
|-----------------------------------|-------------------------------------------|-----------------------------------------------|
| Stanley Fatmax   Knife Saw Blades | Stanley Fatmax                            | Knife Saw Blades                              |
| Yale Lock   Brass                 | Yale                                      | Lock Brass                                    |

The problem is that some brand names have 2 words, and not every entry in the column has a brand name.
NB.  I have a list identifying the exact brands names 200, so identifying them shouldn't be a problem?

A: OK, These formulas require an exact match to a Brand Name in the list of allowable Brand Names, and also produce a blank result when no Brand Name can be found.

This array formula in B2:
=IFERROR(INDEX(D$2:D$6,MATCH(1,FIND(D$2:D$6,A2),0)),"")
must be entered with CTRLShiftEnter and then filled down.
The FIND() portion of this formula tries to find the whole list of Brand Names in the Description in A2.  It returns an array with a #VALUE error everywhere except where there's a match (exact), and it gives a 1 in that position.  MATCH() finds the position of the 1, and then INDEX() reads the correct Brand Name out of the list.  The IFERROR() produces a blank if a valid Brand Name was not found.
This formula in C2, filled down:
=IF(B2="","",MID(A2,LEN(B2)+2,LEN(A2)-LEN(B2)-1))
just removes the Brand Name from the description and spits out what's left. And it also produces a blank if the Brand Name wasn't found.  But note that if you add "Stanley Leverlock" in Column D above, then the correct Brand Name and Product will be filled in.
Hope this helps.

A: maybe something like this would work,
in B1:
=VLOOKUP(A1, 'YOUR BRAND NAMES RANGE HERE', 1, TRUE)

Then drag down
edit as per comments:
try using the below in B1:
=VLOOKUP(A1,C:C,1,TRUE)


text:
Q: salt and crypt assistance i got my login page, and on it I am also using it to autheticate both username and password.
im stuck on checking the password against that provided in the database. This is because I've done this code in my registration for more security.
$hashed_password = crypt('pass1');

Would anyone be able to assist me in creating a if statement to check the database encrypted password to that of the user provided. I really appreciate it.
in the login page....this is my password post.
$password = htmlentities(trim($_POST['password']));

A: // let the salt be automatically generated
$hashed_password = crypt('mypassword');

// You should pass the entire results of crypt() as the salt for comparing
if (crypt($user_input, $hashed_password) == $hashed_password) {
   echo "Password verified!";
}

EDIT
crypt() takes two paramaters, and second is so called salt (see wiki). If not provided, salt will be autogenerated (hence can be considered random). Salt is used in the whole alghorithm, therefore to compare you want to crypt() user provided password with the same salt you did before otherwise result will be different. To make this possible salt is added to crypt result (at the begining) so providing previous result for comparion purposes simply feeds crypt() with old salt (it is either 2 or 12 chars depending on alghoritm used).


text: Q: An example illustrating separation theorem of convex sets in infinite dimensions In finite dimensions, it is easy to find an example of convex sets separated by hyperplanes. I really want to see an example of convex sets and hyperplanes in the infinite dimensions that illustrate the separation theorem. Thank all.


text:
Q: ImageView is not changing in method i have UIImageView and i am trying to change in to use in cell, but it is always empty
Here is ImageView
private var picture: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: ""))
        return imageView
    }()

Here is func
public func configureTableViewCell(picture: UIImageView) {
        self.picture = picture
    }

Here is how i use this
cell.configureTableViewCell(picture: UIImageView(image: UIImage(named: "image")))

But if i use image in TableViewCell like here everyting is OK
private var picture: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "image"))
        return imageView
    }()


text:
Q: Strange things happening for me with Bootstrap's 992px breakpoint Can anyone help me understand, when ONLY at 992px, the viewpoint width becomes strange. It seems to jump to the 768px breakpoint when at 992px or below.
Snippet here:
http://www.codeply.com/go/beilYT04YA
EDIT:
Why is this getting so many  downvotes?
I've asked all my mentors about this and they haven't the slightest as to why it's happening.
Was hoping someone could help

A: (Actually this is a good question - just your code is overly complex for a simple question.)
Your CSS uses a lot of declarations like this one:
@media screen and (max-width: 992px) {
  header .navbar-toggle {
    display: block;
    ...

This implies a break-point at anything up to, and including, 992.
[  --> max  ]

Bootstrap has it's breakpoints like this:
@media (min-width: 992px) {
  .col-md-1, .col-md-2, ...

This implies a breakpoint from, and including, 992 and up.
[  min --->  ]

So what you have here is a sweet spot at 992 where both conditions are true.
To fix this, just -1 on the max ... i.e. @media screen and (max-width: 991px) {


text:
Q: Is this model secure for offline storage? I'm making interface based on 3rd party api. My app works as data analyzer, and to do that i need to download lots of data and this data keeps updating.
But api has limits, and i can't have user download entire set of data at each session. That would not scale.
So i'm thinking simplest way is to let user sync when he wish to, and save the data in local storage.
However, i don't want any user on that computer to have access to all data.
Therefore, i've come up with this scheme that will let the data be safe.

*

*send javascript via https.

*using js do oauth and retrieves data from api servers.

*get opensource library like cryptojs also using https.

*Encrypts data using user's (secret key + salt) and then save both in storage. So even if someone sees it then he can't understand it.

*Then at every new session take stored salt and secret key to match hash(es) and get that data. Or simply start new auth process from step 2.

*if hashed data is older than 30 days delete it. (which could mean user no longer uses the computer or has forgotten password, either way data should be outdated and will need to be resynced by downloading all again)


text:
Q: Lucene: get newest document for category I'm pretty new to lucene index, so I apologize in advance if what I am trying to do is trivial.
I have an index where the documents contain (among other) two fields:
documentoId and employeeId.
Each employee can submit various documents. The structure is pretty much the same as in the bookstore example.
What I am trying to achieve, is to get  all the newest documents matching a query, meaning with the highest documentoId for each employeeId.
In SQL, this would be something like:

select max(documentoId ), employeeId
from documents
where content like 'mySearchValue'
group by employeeId

I don't know if I should use facet API, or if this can be done with queries, or with the searchAfter method...I'm pretty lost with the documentation.
Any help would be greatly appreciated!
Thanks

A: Custom sorting of the hits will do the trick. Google the search.sort parameter in Lucene.

A: Lucene supports grouping search; what you need to do is to define your group and how does it have to be sorted. In the example below, I group by documentoId and sort in descending order.
public static void main(String[] args) throws IOException, ParseException {
    StandardAnalyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_46);
    RAMDirectory ramDirectory = new RAMDirectory();

    IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(Version.LUCENE_46, standardAnalyzer));

    Document d0 = new Document();
    d0.add(new TextField("employeeId", "foo", Field.Store.YES));
    d0.add(new IntField("documentoId", 1, Field.Store.YES));
    indexWriter.addDocument(d0);

    Document d1 = new Document();
    d1.add(new TextField("employeeId", "bar", Field.Store.YES));
    d1.add(new IntField("documentoId", 20, Field.Store.YES));
    indexWriter.addDocument(d1);

    Document d2 = new Document();
    d2.add(new TextField("employeeId", "baz", Field.Store.YES));
    d2.add(new IntField("documentoId", 3, Field.Store.YES));
    indexWriter.addDocument(d2);

    indexWriter.commit();

    GroupingSearch groupingSearch = new GroupingSearch("documentoId");
    Sort groupSort = new Sort(new SortField("documentoId", SortField.Type.INT, true));  // in descending order
    groupingSearch.setGroupSort(groupSort);
    groupingSearch.setSortWithinGroup(groupSort);

    IndexReader reader = DirectoryReader.open(ramDirectory);
    IndexSearcher searcher = new IndexSearcher(reader);

    TopGroups<?> groups = groupingSearch.search(searcher, new MatchAllDocsQuery(), 0, 10);

    Document highestScoredDocument = reader.document(groups.groups[0].scoreDocs[0].doc);
    System.out.println(
            "Descending order, first document is " +
                    "employeeId:" + highestScoredDocument.get("employeeId") + " " +
                    "documentoId:" + highestScoredDocument.get("documentoId")
    );
}

The above code detects that the d1 (middle document) scores at the top and prints the following:

Descending order, first document is employeeId:bar documentoId:20

Above code does not address content like 'mySearchValue' part, you would have to replace MatchAllDocsQuery with a relevant query to do that.

A: For those in the same situation, I solved my problem using mindas comment and modifying it to use my group field:
GroupingSearch groupingSearch = new GroupingSearch("employeeId");
Sort groupSort = new Sort(new SortField("documentoId", SortField.Type.INT, true));  // in descending order
groupingSearch.setGroupSort(groupSort);
groupingSearch.setSortWithinGroup(groupSort);

int offset = 0;
int limitGroup = 50;
TopGroups<?> groups = groupingSearch.search(is,query, offset, limitGroup);

List<Document> result = new ArrayList();
for (int i=0; i<groups.groups.length; i++) {
    ScoreDoc sdoc = groups.groups[i].scoreDocs[0]; // first result of each group
    Document d = is.doc(sdoc.doc);
    result.add(d);
 }


text:
Q: How do I make $(this) relevant inside a function called by live external id I have a live function that triggers the 'openwindow' function and I need to also be able to call that 'openwindow' function seperately, hence my 'initial function call'. The problem is, the id #open-window featured in my live call is the id I want to be able to apply $(this) to (in the openwindow function). If anyone has any suggestions on how to make this possible, I would appreciate it.
function openwindow(user, token) {
if(user==''){
    var user = $(this).attr('data-name');
    var token = $('#token').attr('data-value');
}
//append some information

}

//event triggered on click
$('#open-window').live('click', openwindow);

//initial function call
openwindow('hey','hey');

A: It's simple:
$('#open-window').live('click', openwindow);

function openwindow(event, user, token) {
 if(user==''){
    var user = $(event.target).attr('data-name');
    var token = $('#token').attr('data-value');
 }
}

A: Why do you need to use the same function for something that is completely different? A better approach would probably be to just seperate them out:
function openwindow(user, token) {
    // do some work...
}

//event triggered on click
$('#open-window').live('click', function(e) {
    openwindow($(this).attr('data-name'), $('#token').attr('data-value'));
});

//initial function call
openwindow('hey','hey');

A: Not sure of the exact functionality you want.  But here is an attempt to modify what you had to use the event object that jQuery provides.  You can use this object to store your own data (as I show) and get the original dom object.
Some documentation here.
http://api.jquery.com/category/events/event-object/
function openwindow(event) {
   inUser = event.data.user;
   inToken = event.data.token;

   if(inUser=='default'){
      var user = $(event.target).attr('data-name');
      var token = $('#token').attr('data-value');
   }
//append some information
}

//event triggered on click
$('#open-window').live('click', { user : 'default', token : 'default' }, openwindow);

//initial function call
openwindow({ data : { user : 'hey', token :'hey' },
             target : '#somelocation that has a data-name' });

A: theres a apply method on all functions with allows you the chose what the this
context of the function is gonna be.
like
myFunction.apply(newThis, [arguments,in,a,array]);

this isn't really a good programing convention tho you should probably use an anonymous function in the live callback and call openWindow with the right arguments .


text:
Q: Image orientation lost when resizing with javascript I need to show an image in the largest size possible so I use javascript to create a square div with the maximum dimensions that fit the browser window.
I load the image and then I then change the width and height attributes to values that will make the image fit.
This works fine for 99% of images, but I have some that are shown in landscape format when they actually in portrait. I know they should be portrait because they are shown correctly in Windows explorer, Photoshop etc, and even when I right-click on the displayed image in a browser and select "show image in new window"
I have even rotated the image with PhotoShop and it is still shown landscape.
This makes me think that metadata is not being respected.
In ASPX Page_Load... imgImage.ImageUrl = "~/" & tPath
In HTML
function resizeImg() {
        var windowWidth = window.innerWidth || document.documentElement.clientWidth;
        var windowHeight = window.innerHeight || document.documentElement.clientHeight;
        var imgMax = windowHeight - 54;
        var div = document.getElementById('divImage');
        div.style.width = imgMax  + 'px';
        div.style.height = imgMax + 'px';
        var divW = div.offsetWidth;
        var divH = div.offsetHeight;
        var winR = divW/divH
        var newImgH = imgH;
        var newImgW = imgW;
        if(newImgW > divW) {
            newImgW=divW
            newImgH = Math.floor(Math.round(divW / imgR));
        }
        if(newImgH > divH) {
            newImgH=divH
            newImgW =Math.floor(Math.round(divH * imgR));
        }
        img.setAttribute('width',newImgW);
        img.setAttribute('height',newImgH);
        img.setAttribute('hspace',(divW - newImgW)/2);
        img.setAttribute('vspace', (divH - newImgH) / 2);

}


text:
Q: '91' Object Variable/With Block not set on ADODB Connection line I am trying to query a database to fill a listbox (as well as other various tasks). I get the following error when I run my code:
Error:
91
Object variable or With block variable not set

My Code:
Private Sub UserForm_Initialize()
    On Error GoTo UserForm_Initialize_Err
    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim StrDBPath As String
    Dim strSQL As String

strSQL = "SELECT [Heads A].[Date Entered], [Heads A Issues].Department, [Heads A Issues].Equipment, [Heads A Issues].[Operation Issues], Sum([Heads A Issues].Downtime) AS SumOfDowntime1, IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew')) AS Crew " & _
        "FROM [Heads A] INNER JOIN [Heads A Issues] ON [Heads A].[HeadLineA ID] = [Heads A Issues].[HeadLineA ID]" & _
        " GROUP BY [Heads A].[Date Entered], [Heads A Issues].Department, [Heads A Issues].Equipment, [Heads A Issues].[Operation Issues], IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew'))" & _
        " HAVING ((([Heads A].[Date Entered])>=#" & Sheets("Choices").Cells(2, 1).Value & "# And ([Heads A].[Date Entered])<=#" & Sheets("Choices").Cells(2, 2).Value & "#) And (([Heads A Issues].Department)='" & Sheets("Choices").Cells(2, 3).Value & "') And ((IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew'))) Like IIf('" & Sheets("Choices").Cells(2, 4).Value & "'='all','*-Crew','" & _
        Sheets("Choices").Cells(2, 4).Value & "'))) ORDER BY [Heads A Issues].Department, [Heads A Issues].Equipment;"

StrDBPath = Application.ActiveWorkbook.Path & "\Daily Closing Report V997.accdb"

cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;" & _ 'THIS IS WHERE THE ISSUE IS
                         "Data Source=" & StrDBPath & ";" &_
                         "Jet OLEDB:Engine Type=5;" & _
                         "Persist Security Info=False;"

rst.Open strSQL, cnn, adOpenStatic, adLockOptimistic

CopyText (strSQL)

If (rst.RecordCount = 0) Then
    MsgBox "0 records found."
    Unload UserForm1
    Exit Sub
End If

If rst.RecordCount > 0 Then
    rst.MoveFirst
End If
With Me.ListBox1
    .Clear
    Do While rst.EOF = False
        .AddItem rst![Department,Heads A]
        rst.MoveNext
    Loop
    End With
UserForm_Initialize_Exit:
     On Error Resume Next
     rst.Close
     cnn.Close
     Set rst = Nothing
     Set cnn = Nothing
     Exit Sub
UserForm_Initialize_Err:
     MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
     Resume UserForm_Initialize_Exit
End Sub

I have narrowed down that the error is appearing on the line where I open my connection (marked above), but I'm not sure why it is acting up as it is. TIA!

A: Early bind it as new.
Dim cnn As new ADODB.Connection

You can do as Don Jewett said and do it in two lines:
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection

That is late binding and in your case just an extra line of code. If you have code where your connection may never be made due to logic, it is good to do late binging near the opening of the connection so the binding doesn't happen until it is needed.  But since you are using your connection and recordset right away, you might as well early bind it.


text:
Q: What's the best way to protect a board from corrosion in a hot/moist environment? Some of my projects need to live outside for long periods.  Sometimes, moisture gets into the enclosures.  That means that a circuit board might be sitting around in contact with water for hours on end at upwards of 100F.
I've noticed that solder joints can start to corrode, and recently moisture made it under the solder mask on a board and actually ate through one of the traces, breaking the circuit.  I know the ideal answer is to make a perfectly sealed enclosure, but I'd like to toughen the boards up a bit as a second level of defense.
Can anyone suggest some tips and tricks for making PCBs more corrosion resistant?  Does scrubbing off excess flux help?  What about spray acrylic sealant?  Special solder?

A: The coating zebonaut mentioned is the best solution.
Another thing to pay attention to is avoiding DC voltage gradients wherever possible.
What I mean is that when your choosing which pins to use on parts, don't choose 2 adjacent pins such that one is almost always say, +5V, and the other is always 0v (GND).
The constant voltage gradient between the two pins will drive electro-chemical reactions, corrosion and the like.
Try to separate pins when possible, use the lowest voltage possible, and as a last option if the signal levels can be modulated, even if it serves no purpose but to modulate them, such as pulsing an LED or a switch you don't really need to, do it to avoid the constant gradient.

A: In re conformal coating: a garage shop I talked to once admitted that for conformally coating boards, they just dipped them in urethane deck varnish. They claimed this worked well enough that they used it for PCBs for salt-water marine installs.
I actually got them to do a dead board for me. Cosmetically it wasn't nice (ever seen an epoxy-coated board? Like that, big drips and all) but coverage was 100%. I chickened out of trusting them with the real thing though.
For a hobby project or a garage shop, I think it's worth trying. The big problem with any conformal coating is masking - keeping coating out of where it shouldn't be. Given that most coatings are transparent and thus noninspectable (my experience is that UV dyes don't homogenize and so are worse than useless), process is everything. Do it wrong and you're dead. Dipping has the advantage that you can keep connectors clear if they are all on one side. If not, you can use an acid brush to paint around them.
In summary: haven't tried it myself, but "Home Depot Brand" coating is what I'll try if I ever do my own outdoors project.

A: Sounds like your boards are in a very tough environment, but anyway, it is common practise (and an accepted industry standard) to use so-called Conformal Coating.
I know from experience at one of my previous companies that it does help.
Material varies, but the article in the above link explains a lot and internet searches for "Conformal Coating" will yield many products. I have used brushes to apply the coating after reworking PCBs, but in volume production, spray or dipping are used.

A: I used to "paint" the ready PCB with rosin soluted in alcohol. When the alcohol evaporates, it leaves a air-sealing rosin coating on the PCB. However I don't know how it behaves in outdoor conditions maybe it melts in hot.
Alternatively there are special PCB protecting sprays, here is an overview: http://www.acc-silicones.com/products/conformal-coatings-from-acc.ashx

A: Conformal coating (something silicone-based) is the less extreme solution, but if your part is small enough (or environment harsh enough) you might consider potting it.  However, when potted, boards will be extremely difficult to rework if needed, while conformal coat is somewhat easy (if annoying) to scrape off.

A: I can tell you the conformal coating things are worth crap in the marine industry it has to be completely encased in potting

A: We are using a technique called low pressure PCB overmolding. A plastic coating is injection molded around the PCB. The injection process forces out air pockets resulting in a very uniform and non-permeable environmental protection.
https://cavist.com/
Typical tooling for such a process is prohibitively expensive for small one-off boards. But you could do it with a 3D printer and a benchtop injection molding machine.
https://www.techkits.com/


text:
Q: OutputCache and missing "_caches" field I'm trying to use the code seen here.  When I try to execute this line
FieldInfo cachesInfo = cache.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance);

cachesInfo ends up being null.  I added a foreach loop to look at the object and my results show no field called "_caches".
_entries
_expires
_usage
_lock
_disposed
_totalCount
_publicCount
_maxCount
_maxCountOverload
_flushUndercount
_insertBlock
_useInsertBlock
_insertBlockCalls
_utcLastTrimCompleted
_iSubCache
_cacheMultiple
_cacheCommon

I'm using the code as is in the link.  What is it that I'm missing?
(Warning: I am woefully ignorant on this subject but have been tasked with figuring it out.  I know cachesInfo is null, I know I'm not seeing "_caches", but I don't know why).
Thanks greatly for your help.

A: It looks like this is a difference in .Net versions.  See here.  The field "_caches" exists in .Net 3.5.  I changed my code to look more like the .Net 2.0 example (using "_entries") and it works.


text:
Q: Multi-boot 3 OS Grub recovery/configuration so right now I have 3 OS installations on my laptop: 2 Windows 10 and 1 Ubuntu.
I first installed my 1º Windows, then Ubuntu and now I installed my 2º Windows 10.
The thing is before I installed the last one, GRUB was fine (the entry menu was working perfect). After the 2º Windows installation there was no change so I ran "boot-repair" on Ubuntu and now the laptop automatically launchs the "Windows boot window" (don't know the exact name).
My question is: how can I recover GRUB and then make the 2 Windows entries work (on GRUB, not on the "windows boot manager")?
Thank you.
(By the way, if you are wondering why I want 2 Windows 10 installations is because I want to separate my private and working installation).

A: If you are not afraid of using command line I would suggest using it, also the steps for graphical "Boot-Repair" are given:
How to reinstall GRUB using Ubuntu live CD/USB - official docs
When booting Ubuntu USB or CD/DVD select UEFI boot, like "USB UEFI" for example.


text:
Q: Wordpress - Add numerical values of custom fields together I have a custom post type created in my WordPress blog called 'reviews'.  Inside this I have a custom field with a number out of 5.
I am trying to add all of these numbers together and then divide by the amount of posts to get an aggregate score.
I am attempting to use this code...
<?php
$total_score=0;
$meta_key = 'target';//set this to your custom field meta key
$allscores=$wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE     meta_key = %s", $meta_key));
foreach ($allscores as $score) {
$total_score = $total_score + $score;
}
echo 'Total score is '.$total_score;
?>

But I am getting a result of 0, can anyone see where I am going wrong?

A: Turns out it was me all along, the numbers entered in the database were spelt out alphabetically rather than numerical so the 0 result I was receiving was technically correct :)


text:
Q: FORTRAN Error: BUS ERROR/SEG while printing a variable All,
I am working on estimation of a physical variable for my research and I ran into an odd issue. I already know the roots and differences between bus error and segmentation fault. But the problem is that, when I am printing a four dimension variable like this somewhere:
PRINT *, RH(1,1,1,1)

I am able to get reasonable value.
But, again, the same command in a loop leads to an error. Sometimes it shows me bus error and sometimes SEG one.

*

*The variable has never been modified from the first PRINT command until the
second one.

*I am running this on a cluster machine with 32GB RAM. So, RAM capacity should suffice.

*RH is  defined as  REAL*8  :: RH(IIPAR,JJPAR,LLPAR,25)        !RH
I would be thankful if someone could help on this.
Best,
Amir


text:
Q: Maven project worked before "clean install". Why? I have two maven projects and both are working fine independently. I am able to create a jar file and run it from console as well as from eclipse.
I copied over some classes from the second project into the first and made a few changes so that it runs as a single project with features from both.
I have two pom files, so I combined them into a single pom file.
The thing is that I am able to run it from eclipse fine and able to get the output I was hoping for.
But I am not able to run it after executing the jar file created from "mvn package".
I am using shade maven plugin.
If I use maven build.. with clean install as goal, it again showing errors.
My question is this, why this discrepancy?

A: We would need more information to correctly diagnose the issue. One thing to look at is to ensure that any changes to dependencies which are projects in Eclipse have been installed as a command line build will only look in your repo, not at your Eclipse project.

A: This may happen when you have a dependency which exists as an open project in your eclipse workspace.
Try closing every project except the one where you're having this problem. Does it still compile in eclipse then?


text:
Q: Select/Highlight Columns in Excel 2010 Based on Their Addresses I have a column in Excel which contains the addresses of the cells that need to be selected and then highlighted. Please find below a snapshot:
Col#   Row#     Corresponding Address
8      1        $H$1
9      2        $I$2
10     3        $J$3
10     4        $J$4
9      5        $I$5
10     6        $J$6
10     7        $J$7
10     8        $J$8
11     9        $K$9
12     10       $L$10
12     11       $L$11
11     12       $K$12

As an example, I need to select  cell $H$1 and highlight it.
I would like to perform this task automatically for a large matrix. What would the vba code be for this task?
Any help is highly appreciated

A: You would need to loop through the Corresponding Address column and set, (assuming that you want the cell colour changed in order to highlight it) the Interior.Colour to a RGB value:
Dim x As Worksheet, y As Worksheet
Dim CtrA As Long
Set x = Worksheets("SheetName1")
Set y = Worksheets("SheetName2")
For CtrA = 2 To x.Rows.Count
    y.Range(x.Range("C" & CtrA)).Interior.Color = RGB(0, 255, 0)
Next

where x is a reference to the sheet containing the table in your question, and y is a reference to the sheet that contains the cells you want to highlight.


text:
Q: How to use angular2-webpack-starter and angular-cli together? I am new to Angular2 and webpack-starter.  And have the webpack-starter with ng2-boostrap working well.  But as I attempt to begin to add components with angular-cli I see 'You have to be inside an ember-cli project in order to use the generate command.' which makes some sense, but it would be very helpful for this newbie to use something like 'ng g compoenent ...' to add new components.  Or if there was a gulp task to do this for webpack-starter that would help.
I googled around and didn't find anything obvious and didn't want to break the webpack-starter project.  Any help would be greatly appreciated.  I can always hand build all the files for new components, but that seems very wasteful and error prone when starting out.

A: Combining this two would be a pain in the neck because they might be on different version of everything. ( Angular2 , typescript , zone and .... ).
I'd suggest you create a new angular-cli project and move all your stuff from the starter kit to that and then continue from there.
If you don't want to do that, you can go inside your starter project and run ng init.
This command initialises the cli stuff inside your starter kit, but initially it'll ask you couple question about overriding your file like app.module.ts and ... which it's your decision to do so or not.
And then your project becomes a cli project and you have all the goodies.
But I still prefer the first approach , the second becomes extremely messy.

A: I don't recommend you mixing the CLI generated structure with an other stater because the starter might not follow the angular style guides (which the CLI does). It'll be a real mess.
Indeed, it's good to mention that you can use the angular-cli to create and run your app, that is the official way of dealing with angular apps.
However, for the time being, the CLI doesn't allow you to edit the internal webpack config. You will be able to customise this configuration using an addons system that the team is working on. Till then, you can still use a custom webpack config (one of your own) in order to do what the CLI can't do yet. Just add webpack deps + a web.config.js file into your project.


text:
Q: How to find who downloaded data from Google Cloud Platform: Services:"Cloud Storage", SKUs "Download Worldwide Destinations" Is it possible to find the IP address or the e-mail address of a Google Cloud Platform user who has downloaded a large amount of data from Cloud Storage over a past period of time?
Can anyone explain how to do it using gcloud command-line tool?

A: You can enable Storage Usage Logs (they are disabled by default as John Hanley mentioned), here's what the documentation has to say about it:

Storage logs provide information about the storage consumption of that bucket for the last day and are created daily. Once set up, usage logs and storage logs are automatically created as new objects in a bucket that you specify.

To check the status of the logs you can use gsutil command:
gsutil logging get gs://example-bucket

If logging is enabled, the server returns the logging configuration in the response:
{"logBucket": "example-logs-bucket", "logObjectPrefix": "log_object_prefix"}

You will then be able to see the IP address that made the request but no email.
Have a look at the log format to see what other values they contain:
c_ip- The IP address from which the request was made. The "c" prefix indicates that this is information about the client.


text:
Q: convert iterative function to recursive function i have a problem on iterative function and recursive function.
i have a iterative function and i have to convert it into a recursive one.
could you give me some advice on my code?thanks so much
the code is to determine if the array of data points correspond to a concave function using recursion.
Here is the code of the iterative version:
bool isConcave(double a[], int n)
{
int slope = 1;
bool concave = true;

for (int i = 1; i < n && concave; i++)
{
    double delta = a[i] - a[i-1];

    if (slope > 0)
    {
        if (delta < 0)
            slope = -1;
    }
    else if (delta > 0)
        concave = false; // slope == -1 and delta > 0
}
return concave;
}

And, here is the code of my recursive version which can't work:
bool isConcave_r(double a[], int n, int& slope)
{
//Implement this function using recursion
double delta = a[n] - a[n-1];
bool concave = true;

if (n == 0)
    return false;
if (slope > 0)
{
    if (delta < 0)
    {
        slope = -1;
    }
    else
        concave = true;
}else
    return 0;

//dummy return statement
return isConcave_r(a, n, slope);

}

A: Not necessary the best/cleanest way, but you may replace any loop
for (int i = 0; i != N; ++i) {
    body(i, localVars);
}

by
void body_rec(int N, int i, LocalVars& localVars)
{
    if (i == N) return;
    body(i, localvars);
    body_rec(N, i + 1, localVars);
}

or
int body_rec(int N, int i, LocalVars& localVars)
{
    if (i == N) return localVars.res; // or any correct value
    body(i, localvars);
    if (localVars.end) { // break the "loop", and so stop the recursion.
        return localVars.res; // or any correct value
    }
    return body_rec(N, i + 1, localVars);
}

So, in your case, you forget to pass slope into the recursion.
[edit]
Full solution:
bool isConcave_r(int N, int i, double a[], int slope)
{
    if (i >= N) return true;

    const double delta = a[i] - a[i-1];

    if (slope > 0) {
        if (delta < 0) {
            slope = -1;
        }
    }
    else if (delta > 0) {
        return false;
    }
    return isConcave_r(N, i + 1, a, slope);
}

bool isConcave(double a[], int n)
{
    int i = 1;
    int slope = 1;
    return isConcave_r(n, i, a, slope);
}

Note also that the name seems "incorrect", you don't check if the "curve" is concave, case where delta == 0 should be specific I think...

A: In the iterative version of your program, the computation moves from 1 to n-1, but in the recursive version computation moves form n-1 to 1. So, instead of tail recursion, use head recursion. And slope should be static variable. So, declare slope as static variable. It will work.


text:
Q: Tkinter Scrollbar porblems when using update() inside a for loop I'm creating an entry list which works fine when I don't use the update() but when I use it the scroll bar is grayed out.
This is the code that works fine:
from tkinter import *

root = Tk()

main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
canvas = Canvas(main_frame, highlightthickness=0)
canvas.pack(side=LEFT, fill=BOTH, expand=1)
scrollbar = Scrollbar(main_frame, orient=VERTICAL, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion = canvas.bbox("all")))
second_frame = Frame(canvas)
canvas.create_window((0,0), window=second_frame, anchor="nw")

for i in range(100):
    x = Frame(second_frame)
    x.pack(fill=BOTH, padx=20, pady=0)

    resultados_entry = Entry(x, width=73)
    resultados_entry.pack(side=LEFT, fill=BOTH, expand=1, padx=0)
    resultados_entry.insert(0, str(i))

root.mainloop()

And this is the one that doesn´t:
from tkinter import *

root = Tk()

main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
canvas = Canvas(main_frame, highlightthickness=0)
canvas.pack(side=LEFT, fill=BOTH, expand=1)
scrollbar = Scrollbar(main_frame, orient=VERTICAL, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion = canvas.bbox("all")))
second_frame = Frame(canvas)
canvas.create_window((0,0), window=second_frame, anchor="nw")

for i in range(100):
    x = Frame(second_frame)
    x.pack(fill=BOTH, padx=20, pady=0)

    resultados_entry = Entry(x, width=73)
    resultados_entry.pack(side=LEFT, fill=BOTH, expand=1, padx=0)
    resultados_entry.insert(0, str(i))

    root.update()

root.mainloop()

I want to use root.update() inside of my for loop because I want to display the entries as they are created. I don't want to wait until the for loop finished to start displaying them.


text:
Q: Unpacking a JSONField into multiple django form fields I am using a JSONField from django.contrib.postgres.fields in my Django model. I want to set up my update form so that it looks at the object being passed into it, iterates through the JSON from the JSONfield, and dynamically creates the right amount of CharFields.
models.py:
class myclass(models.Model):
    purpose_section = JSONField()

forms.py:
class myclassForm(forms.ModelForm):
    class Meta:
        model = myclass
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for i in self.fields['purpose_section'].initial:
            self.fields['purpose_section_%s' % i] = forms.CharField(label="purpose_section_" + i,value=i.content)

When I try to access the page, I receive an error:
'NoneType' object is not iterable
Any ideas on what I'm missing?

A: I'm not sure what view you're using, but assuming it's a view that'll pass the instance of the DB row you're trying to edit (such as UpdateView with a url that passes the pk to it),
You can try this in your form:
for key in self.instance.purpose_section:
   self.fields[key] = forms.CharField(label=key, max_length=256)
   self.fields[key].initial = self.instance.purpose_section[key]

If you're not using a view that does that, you'll need to pass the instance yourself.