text:
Q: Can anyone tell me how to increase the snake size in my code? Here is my code below. Every time when I try to increase the length, It does not seem to increase and when I run the game.
When I run the game, It sometimes makes the head of the snake flicker/blink certain times and when snake eats the food, still it does not increase the length instead of blinking little at certain times
I have attached code with my applied logic. Please is there any solution to this problem?
Here is my code with what I applied as the increase length logic:
Here is my logic:
import pygame
import time
import sys
import random

a = print("1) Easy")
b = print("2) Medium")
c = print("3) Hard")

while True:
    difficulty = input("Enter Difficulty Level: ")
    if difficulty == "1":
        speed = 5
        break
    elif difficulty == "2":
        speed = 6
        break
    elif difficulty == "3":
        speed = 8
    else:
        print("Choose from Above Options Only!")

# Initialise Game
pygame.init()
clock = pygame.time.Clock()

# Screen and Window Size:
screen_width = 800
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
caption = pygame.display.set_caption("Snake Game")
icon = pygame.image.load("snake.png")
pygame.display.set_icon(icon)

# Colors
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
white = (255, 255, 255)

# Snake Editing
x1 = 350
y1 = 300
snake = pygame.Rect([x1, y1, 20, 20])

x1_change = 0
y1_change = 0

snake_size = 15

snk_list = []
snk_length = 1

# Snake Food
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
food_height = 15
food_width = 15

# Game State
game_over = True

# Game over
font = pygame.font.SysFont("freelansbold.tff", 64)

# Score Counter
score = 0
score_font = pygame.font.SysFont("chiller", 50)

# TO INCREASE SNAKE LENGTH LOGIC:
def plot_snake(gameWindow, color, snk_list, snake_size):
    for x, y in snk_list:
        pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])

def game_over_text(text, color):
    x = font.render(text, True, (240, 0, 0))
    screen.blit(x, [screen_width//2 - 135, screen_height//2 - 25])

def score_show():
    text = score_font.render("Score: " + str(score), True, (255, 255, 255))
    screen.blit(text, (20, 10))

def main_loop():
    global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size, snk_length
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = speed * -1
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = speed
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = speed * -1
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = speed
                x1_change = 0

    # Game Over Checking
    if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
        game_over = False

    x1 += x1_change
    y1 += y1_change

    if abs(x1 - food_x) < 7 and abs(y1 - food_y) < 7:
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 0.2
        snk_length += 5

    # Drawing On Screen
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, red, [x1, y1, 15, 15])
    pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
    score_show()
    pygame.display.flip()

#SNAKE LENGTH LOGIC
    head = []
    head.append(x1)
    head.append(y1)
    snk_list.append(head)

    if len(snk_list) > snk_length:
        del snk_list[0]

    plot_snake(screen, red, snk_list, snake_size)
    # Final Initialisation
    pygame.display.flip()
    clock.tick(70)

# Main Game Loop
while game_over:
    main_loop()

# Game_Over
screen.fill((0, 0, 0))
game_over_text("Game Over!!!", (255, 0, 0))
pygame.display.flip()
time.sleep(2)
pygame.quit()
quit()

A: The moving distance of the snake must be "snake_size":
def main_loop():

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = -snake_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = snake_size
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = -snake_size
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = snake_size
                x1_change = 0

But use pygame.time.Clock to control the frames per second and thus the game speed.
def main_loop():

    # [...]

    clock.tick(speed)

Use pygame.Rect and collidrect to find the collision of the snake and the food. See also How to detect collisions between two rectangular objects or images in pygame. Increment snk_length, when a collision is detected:
def main_loop():
    # [...]

    global snk_length

    # [...]

    snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
    food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
    if snake_rect.colliderect(food_rect):
        snk_length += 1
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 1

Follow the instructions of How do I chain the movement of a snake's body?. Put the new head position of the snake at the head of snk_list, but delete the elements at the tail:
def main_loop():

    # [...]

    #SNAKE LENGTH LOGIC
    snk_list.insert(0, [x1, y1])
    if len(snk_list) > snk_length:
        del snk_list[-1]

Complete main_loop:

def main_loop():
    global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size
    global snk_length
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = -snake_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = snake_size
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = -snake_size
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = snake_size
                x1_change = 0

    # Game Over Checking
    if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
        game_over = False

    x1 += x1_change
    y1 += y1_change

    snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
    food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
    if snake_rect.colliderect(food_rect):
        snk_length += 1
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 1

    # Drawing On Screen
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, red, [x1, y1, 15, 15])
    pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
    score_show()
    pygame.display.flip()

    #SNAKE LENGTH LOGIC
    snk_list.insert(0, [x1, y1])
    if len(snk_list) > snk_length:
        del snk_list[-1]

    plot_snake(screen, red, snk_list, snake_size)
    # Final Initialisation
    pygame.display.flip()
    clock.tick(speed)


text:
Q: Am I up against an uncrackable UEFI chip on this HP notebook? I recently got a new HP laptop with Windows 10 installed and prefered some versatility, so I plugged in one of my many Linux live USBs to get to work. I was greeted with ENTER ADMINISTRATOR PASSWORD, even though I didn't set a UEFI password; all I'd like to do is boot Debian from a USB drive.
An incomplete list of what I've tried, spending ~250 hours trying to get past the UEFI Administrator Password with no luck:

*

*Using all of the typical generic default passwords and passwords suggested by BIOS-pw from lockout codes

*CMOS:

*

*Used cmospwd to kill the CMOS memory

*Used CMOS Deanimator to kill the CMOS memory and the EEPROM memory

*Manually disassembled the laptop and removed the CMOS battery

*Manually discharged every exposed capacitor on the motherboard

*Physically removed the hard drive

*

*Formatted the master boot record

*Windows Startup Repair:

*

*Reinstalled Windows

*Advanced boot options into UEFI

*Device Manager:

*

*Uninstalled System Firmware

*Uninstalled all of the processors

*Decompiled entire libraries of .dll related to the mystery password

*Decrypted gigabytes of relevant System32 files from:
hex, base64, octal, charcode, base32, xml, json, aes, sha1, sha2, sha3, among others

*Forged certificates from other Windows systems onto Linux bootloaders

*Called HP customer support, spending ~7hrs on the phone with them, with their ultimate answer being "Take it to a shop and have the offending hardware removed and replaced"

A: I think you would need to reprogram the EEPROM chip on the motherboard, as this is where the password lives and is why the password isn't susceptible to CMOS resetting, power outages, or pretty much any intervention short of physical access to the chip; even if you reverse-engineered HP's UEFI updater, you'd have to find a way to get it signed by a trusted cert.

*

*Guide to resetting the EEPROM Obviously, you may need to tweak the process if your laptop model is different

*Alternatively, you can use Fedora on a USB even though Secure Boot is enabled

A: you can probably pay $10 to get it from http://www.whatsmypass.com/bios-password-recovery-service. They're legit. Or, if you prefer to learn how to do it yourself you can join HPWLab (https://www.egyfixlab.com/laptop/whats-new/). Engineer Osama can help you. He wrote a program called LBE (Laptop Bios Extractor) which can reset the password by extracting and rewriting the section of code where the password is located. It is highly technical. The program costs $105. Each laptop manufacturer is different. Several of the major ones, all you have to do is enter the Bios password three times and you receive a code which you send off to the above. Or, in the case of Dell, they just use the Service Tag to decode the necessary password.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matrix trace & norm For any nonnegative semidefinite matrix $A$ and any matrix $B$, we have
$$\mbox{tr} (AB) \le \mbox{tr} (A) \, \|B\|$$
where $\mbox{tr}(\cdot)$ is the trace and $\|\cdot\|$ is the operator norm. How to prove this?

A: We can work in an orthonormal basis in which $A$ is diagonal. In that case the diagonal entries of $AB$ are $a_{ii}b_{ii}$, so
$$
tr(AB) \leq|tr(AB)|=\left|\sum a_{ii}b_{ii}\right| \leq \sum a_{ii}|b_{ii}| \leq \sum a_{ii} \|B\|=tr(A)\|B\|.
$$

A: A more general version of the result Beenakker cites that allows for normal $B$ (not just symmetric):$\newcommand\tr{\operatorname{tr}}\newcommand\E{\mathbb{E}}$
Take $x\sim\mathcal{N}(0,I)$ and recall that $\tr(C) = \E[x^\mathsf{T}Cx]$. If $B = Q \Lambda Q^*$ is unitarily diagonalizable let $\Lambda^{1/2}$ be a (possibly complex) square root of $\Lambda$. Then using the cyclic property of the trace
$$
\begin{align}
\tr(AB) &= \tr(\Lambda^{1/2} Q^*AQ\Lambda^{1/2})\\
&= \E[(\Lambda^{1/2}x)^\mathsf{T} Q^*AQ (\Lambda^{1/2}x)]\\
&= \sum_{i\neq j} \lambda_i^{1/2}\lambda_j^{1/2}\E[x_ix_j](Q^*AQ)_{ij} + \sum_{i} \lambda_i\E[x_i^2](Q^*AQ)_{ii}\\
&= \sum_{i} \lambda_i(Q^*AQ)_{ii}.
\end{align}
$$
From here, since $(Q^*AQ)_{ii}\geq 0$ by the PSD condition, it follows that
$$\tr(AB) \leq \lambda_{\max}\sum_{i} (P^{-1}A P)_{ii} = \lambda_{\max}\tr(P^{-1}AP) = \lambda_{\max}\tr(A)$$
and
$$\tr(AB) \geq \lambda_{\min}\sum_{i} (P^{-1}A P)_{ii} = \lambda_{\min}\tr(P^{-1}AP) = \lambda_{\min}\tr(A)$$
as desired.

A: For hermitian $B$, the inequality is very easy to prove: use that $\|B\| - B$ is positive semidefinite together with the fact that the product of two positive semidefinite matrices has nonnegative trace. This gives $\mathrm{tr}(A(\|B\| - B)) \geq 0$, from which the inequality follows immediately.
For general $B$, we can therefore argue that
$$\mathrm{Re}(\mathrm{tr}(AB)) = \tfrac{1}{2}\mathrm{tr}(A(B + B^*))\leq \mathrm{tr}(A)\cdot \tfrac{1}{2}\|B + B^*\| \leq \mathrm{tr}(A) \|B\|.$$
Upon multiplying $B$ by a suitable complex scalar, this implies that
$$|\mathrm{tr}(AB)| \leq \mathrm{tr}(A) \|B\|$$
is true for all positive semidefinite $A$ and any $B$.
I don't have the book at hand right now, but I imagine that this is somewhere to be found in the early chapters of Bhatia's Matrix Analysis.

A: Expanding my comment into an answer, which offers a more general result.

Theorem (von Neumann). Let $A$ and $B$ be arbitrary $n\times n$ complex matrices. Then, $$|\text{trace}(AB)| \le \sum_{i=1}^n \sigma_i(A)\sigma_i(B),$$ where $\sigma_i(\cdot)$ denotes the $i$-th singular value.

As an immediate corollary we have the OP's result, because for a PSD matrix $A$, $\sigma_i(A)=\lambda_i(A)$.

Corollary. Let $A$ be Hermitian positive semidefinite, and $B$ be arbitrary. Then, $|\text{trace}(AB)| \le \text{trace}(A)\|B\|$, where $\|\cdot\|=\sigma_1(\cdot)$ denotes the operator norm.

Note. Using von Neumann's trace inequality, we can also show the more general version of the OP's question, namely a Hölder inequality:
\begin{equation*}
|\text{trace}(AB)| \le \langle \sigma(A), \sigma(B)\rangle \le \|\sigma(A)\|_p\|\sigma(B)\|_q = \|A\|_p\|B\|_q,
\end{equation*}
where $\sigma(A)$ is the vector of singular values, and $\|\cdot\|_p$ denotes the Schatten $p$-norm, and $1/p + 1/q=1$ ($p,q\ge1$). For $p=1$ and $q=\infty$ we recover the OP's question.

A: A proof of
$$\lambda_n(B)\,{\rm tr}\,A\leq {\rm tr}\,(AB)\leq\lambda_1(B)\,{\rm tr}\,A$$
where $\lambda_n$ is the $n$-th largest eigenvalue of $B$ so $||B||=\lambda_1(B)$ and $A$, $B$ are positive semidefinite $n\times n$ matrices, is given in The design of suboptimal linear time-varying systems (1968). The inequality still holds for $B$ real symmetric and $A$ positive semidefinite, as proven in Trace bounds on the solution of the algebraic matrix Riccati and Lyapunov equation (1986). The restriction of positive semidefinite $A$ cannot be relaxed, as pointed out in Inequalities for the trace of a matrix product (1994).


text:
Q: Is there a Maven flag indicating whether a build is a SNAPSHOT? Is there a specific maven property indicating whether the current project.version is a SNAPSHOT or not?
Obviously this could be done by parsing the project.version string, but I'm interested in a specific property.

A: ${project.version.snapshot} is not currently a supported property for Maven 3.
See Maven Properties Guide
Currently, there is an open feature request to add regex matching for profile activation. You may want to go comment and upvote the issue:
http://jira.codehaus.org/browse/MNG-3826
The use case is exactly what you are mentioning:

Activate a profile when project.version is not SNAPSHOT
is it possible?


text:
Q: Power Pivot Data Model error I am currently working on a Power Pivot Data Model and came across an error

"duplicate values in linked table, Many to one relationship"

I am confused and stuck in the data model. For reference here I am attaching the image.

A: Did not see an image, but am familiar with the message.
You have linked to a field in the lookup table that has at least one duplicated value.
Check first if you have linked to the correct field in the lookup table.
If not, just delete the relationship and try again. If so, you can check for duplicate values in a column by using Power Query.
Import you table into Power Query, remove all columns except the linking field column. Add a custom column that only contains the value of one.
Next group by your linking field and sum the 1's in the custom column. Filter out any sum that is just 1. What's left are the duplicated values for you linking field and the custom column tells you how many times the linking field value was found.


text:
Q: get text in between text using regex I want to extract the text in between the %3A.
Here is the sample phrase :
http://www.sample.com/res?ccode=1232&note=sampletext&token=12Add-12sre-24Aod-23343-34kdi%3A3232121%3ATVLOPQUI%3AIOOPDA%3AKKKKK%3A&ltr=23232

I tried below expression:
[&]{1}token[=]{1}([a-zA-Z0-9-%]*)(%3A(.*?)%3A){1}

but the expected phrase is : 3232121
whereas, it is capturing the invalid thing.
Can you please suggest me, how to do that in better way

A: You can use a positive lookbehind to find %3A, then match all digits after that.
(?<=%3A|:)(\d+)

https://regex101.com/r/IHaXQT/4

A: Assuming that there are no literal & inside the params, you may use the following pattern:
[&?]token=[^&%]*%3A([^%&]+)

See the regex demo
Details:

*

*[&?]token= - a &token= or ?token= substring

*[^&%]* -  zero or more chars other than & and %

*%3A - a %3A substring

*([^%&]+) - Group 1 capturing 1 or more chars other than % and &.


text:
Q: JavaFX Saving editable TableView to SQL I have created a two column editable TableView which the user can edit and change the data thats inside each cell. Now my question is, once the user has changed some data around in each cell, how do I then save this data or print it out in a way to add to an SQL query like this example below
INSERT INTO table_name
VALUES (Value from table,Value from table,Value from table,...);

//Editable cell
PriceColumn.setCellFactory(TextFieldTableCell.forTableColumn());
PriceColumn.setOnEditCommit(
        new EventHandler<CellEditEvent<NewCustomerList, String>>() {
            @Override
            public void handle(CellEditEvent<NewCustomerList, String> t) {
                ((NewCustomerList) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setPrice(t.getNewValue());
            }
        }
);

A: You could do this by getting the required values and then passing them onto the DAO class to execute the query on the DB. Example follows-
PriceColumn.setOnEditCommit(
        new EventHandler<CellEditEvent<NewCustomerList, String>>() {
            @Override
            public void handle(CellEditEvent<NewCustomerList, String> t) {
                ((NewCustomerList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setPrice(t.getNewValue());
                String newPrice = t.getNewValue();
                String uniqueIdentifier = t.getRowValue().getUniqueIdentifier(); //Unique identfier is something that uniquely identify the row. It could be the name of the object that we are pricing here.
                daoObj.updatePrice(newPrice, uniqueIdentifier); //Call DAO now
            }
        }
);

And somewhere in the deep dark jungles of DAO class,
private final String updateQuery = "UPDATE <TABLE_NAME> SET <PRICE_COLUMN> = ? WHERE <UNIQUE_COLUMN> = ?"; //If you require multiple columns to get a unique row, add them in the where clause as well.

public void updatePrice(String newPrice, String uniqueIdentifier) {
    PreparedStatement ps = con.prepareStatement(updateQuery); //con is the connection object
    ps.setString(1,uniqIdentifier); //if a string
    ps.setString(2,newPrice); //if a string
    ps.executeQuery();
}

If this is not what you were expecting, then can you please clarify your requirement?


text:
Q: Which one is true? In order to assess the number $N$ of individuals of a species of animal living on an island, we propose to adopt the capture-recapture method. For this we capture $800$ individuals. These individuals, which correspond to the proportion $p$ of the total number of individuals living on the islands, are marked and then released. $1000$ animals are subsequently captured, of which there are $250$ animals marked during the first capture. Which of the following statements are true?

*

*We have $0.20$ as estimation of $p$

*$p = \frac{800}{N}$

*We have $3200$ as estimation of $N$
I am not sure how to deal with this. Can you help?
EDIT:
I know that two of them are right, but I can say which ones?

A: The assumptions are that in each case, the animals captured constitute a random sample of the animals on the island,  that whether an animal is captured in the second sample is independent of whether that animal is captured in the first sample, and that no animals are born or die between the two samplings.
If there were $N$ animals in all, the expected number of marked animals in
the second sampling would be $1000 \times 800/N$.  Thus if the actual number is
$X$, you might take $800000/X$ as an estimator of $N$.

A: If $X$ represents the number of marked inividuals we observe out of our sample of $1000$ individuals, then for $x\in\{0,1,.\ldots,800\}$ we have $$P(X=x|N=n)=\frac{{800 \choose x}{n-800 \choose 1000-x}}{{n \choose 1000}}$$ Here, $N$ represents the number of individuals in the entire population. Define the function $f$ on the domain $\{1550,1551,\ldots\}$ by $$f(n)=P(X=250|N=n)$$ I would use the value of $n$ that maximizes $f$ as an estimator of $N$.


text:
Q: Sorting not working with Knockout and Isotope Update: forgot the one question per question rule. Cut second question out of this one.
Trying to make a list of users sortable by different criteria with animation. Was already using Knockout so this demo seemed like a good direction to take. I switched to an Isotope 2.0 fork of the integration code here.
Sometimes the sorting doesn't update properly, as shown in this version - http://codepen.io/matelich/pen/PPoqdz - Medal and Component should have #0 and #1 switched from each other, but the ui doesn't update.
        switch (content) {
           case 'alphabetTab':
              ViewModel.users.sort(function (u1, u2) {
                 return u1.UserName.localeCompare(u2.UserName);
              });
              break;
           case 'medalTab':
              ViewModel.users.sort(function(u1, u2) {
                 return u1.MedalScore < u2.MedalScore ? 1 : (u1.MedalScore > u2.MedalScore ? -1 : 0);
              });
              break;
          case 'componentTab':
             ViewModel.users.sort(function(u1, u2) {
                return u1.LearnedComponents < u2.LearnedComponents ? 1 : (u1.LearnedComponents > u2.LearnedComponents ? -1 : 0);
             });
        }
        for (i = 0; i < ViewModel.users().length; i++) {
           console.log(ViewModel.users()[i].UserName);
        }
        ViewModel.users.valueHasMutated();


text:
Q: Difficulty positioning a div I want to place a div relative to other elements on the page.
Here is the initial CSS:
#puzzle
{
 display:inline-block;
 vertical-align: top;

 (position: static;)
}

#success
{
 display: none;
 position: absolute;
 top: 235px;
 left: 130px;
 border: 3px solid blue;
 border-radius:25px;
 color: blue;
 background-color: #cfd;
 text-align:center;
 padding:40px;
 font-size:20pt;
}

When desired, I execute this code:
let p = puz.getBoundingClientRect();
let s = getelem("success");
s.style.left = p.left;
s.style.top = p.top;
s.style.display = "block";

And the result is:
puz.getBoundingClientRect()
DOMRect { x: 38, y: 183, ... }

document.getElementById("success").getBoundingClientRect()
DOMRect { x: 38, y: 33.833 ... }

(X and Y are synonyms for Left and Top)
Which looks like this:

The question is:
Why is s.top different from p.top?

A: #success is positioned absolutely, so the flow of the other elements in the DOM do not impact its positioning and properties like top impact its positioning, whereas #puzzle has position static (the default), and is not impacted by top and the like but is fitted into the document flow.
From https://www.w3schools.com/Css/css_positioning.asp

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

If you want #success to be positioned within the #puzzle at its top left corner, you can set position: relative on #puzzle and ensure it's a parent to #success in the HTML.


text:
Q: Forms Authentication adding additional information along with ReturnUrl With Forms Authentication when the app needs to redirect to sign-in page is there an event or any extensibility point that will let me do additional work to the request before it redirects to the sign-in page?
I would like to send additional information in the query string that could vary such that it wouldn't work to just statically embed that in the link in the loginUrl node in the web.config.
Edit: For clarification, I want to intercept the request prior to being redirected TO the login page.
Example:
<authentication mode="Forms">
      <forms loginUrl="http://the/interwebs/login.aspx" timeout="2880"
                enableCrossAppRedirects="true" />
</authentication>

And prior the user being redirected to http://the/interwebs/login.aspx I would like to be able to pack in query values so the url could end up something like http://the/interwebs/login.aspx?Action=Refresh

A: You can do this via handling the event HttpApplication.AuthenticateRequest
    private void Application_AuthenticateRequest(Object source, EventArgs e)
    {

        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;

        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = context.Request.Cookies[cookieName];

        if (authCookie == null || string.IsNullOrEmpty(authCookie.Value))
        {
            //... do something
        }

FYI, We currently do this via an IHttpModule implementation.

A: I've done this before with an http module. My example (stripped down), in vb.net. I'm just checking for a 401 status code and doing my own redirect. The big trick here was that I had to remove and add back the web.config httpModules to make sure my httpmodule stepped in from of the url authorization module. In my case I had some url rewriting for localization, and I needed to send the locale ID to the login page as it was lost by the normal redirect in the url authorization module. I made heavy use of Reflector to build up the base path (not shown), as these are private methods.
    Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
        AddHandler context.EndRequest, AddressOf Context_EndRequest
    End Sub

    Private Sub Context_EndRequest(ByVal sender As Object, ByVal e As EventArgs)

        If TypeOf sender Is HttpApplication Then

            Dim hApplication As HttpApplication = DirectCast(sender, HttpApplication)
            Dim hContext As HttpContext = hApplication.Context

            If (hContext.Response.StatusCode = &H191) Then

                hContext.Response.Redirect(String.Format("{0}?ReturnUrl={1}&someparam2={2}", basepath, HttpUtility.UrlEncode(hContext.Request.RawUrl), someparam2))

            End If

        End If

    End Sub

web.config changes
  <httpModules>
      <clear/>
      <!-- custom -->
      <add name="SomeHttpModule" type="SomeCompany.SomeProduct.SomeHttpModule"/>
      <!-- add back defaults, exlude PassportAuthentication, AnonymousIdentification, Profile -->
      <add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/>
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
      <add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
      <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
      <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
  </httpModules>

A: You don't have to use the Forms authentication's mechanism to redirect people to a URL. You can do that in code. Just sign them in and Redirect them yourself using Response.Redirect.


text:
Q: After 10 minutes network idle NSInputStream for network socket stops reading until next write on the NSOutputStream for that socket After 10 minutes of network inactivity network events are no longer  delivered to the NSInputStream in my app.
During this 10 minute period the app is not deactivated, backgrounded or terminated. I confirmed this when reproducing this with lldb because my AppDelegate would have logged these events. When testing on my device without attachment to lldb I kept the device awake by continually tapping it.
During the 10 minute period I interact with the UI elements of the app.
At the end of the 10 minute period I trigger the app to write to the NSOutputStream for the socket. Immediately after the write to the NSOutputStream the NSInputStream notifies my app of the pending data to read. During this 10 minute period the socket is not closed or disconnected.
If the network idle period is only 9 minutes the socket properly processes read events.
This seems pretty odd because the socket is not closed or reconnected (I confirmed that on both the client and server) and also because the app is not backgrounded or suspended and the phone is not locked.
I have <key>UIRequiresPersistentWiFi</key><true/> in my Info.plist. However I think that would only have impact at the 30 minute mark.
I can reproduce this in the IOS simulator or on a physical device and on IOS 9.1 and 92. On a physical device I reproduced this both with and without lldb. When testing on my device i used wifi.
I think I can add a workaround by making my app send a heartbeat to the server at the 10 minute mark, but as far as I can tell that shouldn't be required.
I would appreciate any help with this.
Thank you!


text:
Q: Solving a sort algorithm in constant space I'm trying to solve the following question:

Given an array of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Challenge: Try sorting the list using constant space

The first part where I can use extra space is easy, basically what I did is find the min,max and the middle value store them as keys in a hashmap and their frequencies as the hashmap values, and then fill the new created array with the correct values:
import java.util.Map;
import java.util.HashMap;
class Testing{

    public static void sortArr(int[] arr){
        int[] newArr=new int[arr.length];
        Map<Integer,Integer> hm=new HashMap<Integer,Integer>(3);
        int mini=minArr(arr);
        int maxi=maxArr(arr);
        int midNum=Integer.MAX_VALUE;

        for(int num : arr){
            if(hm.containsKey(num)){
                hm.put(num,hm.get(num)+1);
            }else{hm.put(num,1);}
        }

        for(int num : hm.keySet()){
            if(num!=mini && num!=maxi){
                midNum=num;
                break;
            }
        }

        for(int i=0;i<arr.length;++i){
            if(i<hm.get(mini)){
                newArr[i]=mini;
            }else if(i>(arr.length-hm.get(maxi))){
                newArr[i]=maxi;
            }else{
                newArr[i]=midNum;
            }
        }

        for(int num : newArr){
            System.out.println(num);
        }
    }

    public static int minArr(int[] arr){
        int mini=Integer.MAX_VALUE;
        for(int num : arr){
            if(num<mini){
                mini=num;
            }
        }
        return mini;
    }

    public static int maxArr(int[] arr){
        int maxi=Integer.MIN_VALUE;
        for(int num : arr){
            if(num>maxi){
                maxi=num;
            }
        }
        return maxi;
    }

    public static void main(String args[]){
        int[] arr={-4,-4,9,9,-4,3,9,3,3,3,3,9,9,-4,9,3};
        sortArr(arr);
    }
}

What I'm interested is the Challenge part, which I'm unable to solve, any help is appreciated, thanks.

A: If you want just the final result, you can do it using three counters.

*

*Count the number of 1, 2, and 3 on the list.

*Then using a loop, from the first of the list, write the digit with the found counted number

As an example, you have 2 1, 2 2, and 3 3. Then you loop over the array and write these numbers from the first of array base on the value of the counter for each number.
The extra space is three variables which is a constant space. Also, the time complexity is Theta(n) as we loop through the array two times.


text:
Q: Applying img hover to a certain picture only? I would like to add the img hover specifically to the top banner and no other image. Is there any code that lets you do this? Thank you for any reply.

<TITLE>Cascade Studios™</TITLE>

A: Just give that one particular image a class...
img {
  opacity: 1.0;
  transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
 -webkit-transition: opacity 1s ease-in-out;
 }
.topbanner:hover {
  opacity: 0.5;
  transition: opacity .55s ease-in-out;
 -moz-transition: opacity .55s ease-in-out;
 -webkit-transition: opacity .55s ease-in-out;
}

Then in your HTML

A: Give it unique ID and define CSS rule for that ID:

<TITLE>Cascade Studios™</TITLE>

A: You can give id to the top banner image and apply :hover pseudo-class on that as shown below:
img#top_banner:hover {
//hover styles comes here
}


text:
Q: Needed the details about the Image(Media) in Twilio Api I'm setting up a server for the WhatsApp using Twilio API. As I'm sending the media file from the WhatsApp to Twilio it doesn't show any details about it, while sending a text it shows the details in the body.
The response I getting while sending the images is:
body:
      { SmsMessageSid: 'SM94cXXXX8f8d18a8dbf809cXXXXXXXXXX',
       NumMedia: '0',
        SmsSid: 'SM94cXXXX8f8d18a8dbf809cXXXXXXXXXX',
        SmsStatus: 'received',
        Body: '',
        To: 'whatsapp:+14XXXXXXXXX',
        NumSegments: '1',
        MessageSid: 'SM94cXXXX8f8d18a8dbf809cXXXXXXXXXX',
        AccountSid: 'ACXXXXXX6f5f98b5adc708d57aedXXXXXX',
        From: 'whatsapp:+9199XXXXXXXX',
        ApiVersion: '2010-04-01' },
     _body: true,
     length: undefined,
     read: [Function],
     route: Route { path: '/sms', stack: [Array], methods: [Object] } },
  locals: {},
  statusMessage: 'OK',
  statusCode: 200,
  [Symbol(outHeadersKey)]:
   { 'x-powered-by': [ 'X-Powered-By', 'Express' ],
     'content-type': [ 'Content-Type', 'image/jpeg' ] } }

While The response I got while sending the text is:
body:
    { SmsMessageSid: 'SMd7b60aXXXXXXc830a894c5e91XXXXXXX',
            NumMedia: '0',
            SmsSid: 'SMd7b60aXXXXXXc830a894c5e91XXXXXXX',
            SmsStatus: 'received',
            Body: 'Hello',
            To: 'whatsapp:+14XXXXXXXXX',
            NumSegments: '1',
            MessageSid: 'SMd7b60aXXXXXXc830a894c5e91XXXXXXX',
            AccountSid: 'ACXXXXXX6f5f98b5adc708d57aedXXXXXX',
            From: 'whatsapp:+91XXXXXXXXXX',
            ApiVersion: '2010-04-01' }

The Code used is :
const http = require('http');
    const express = require('express');
    const accountSid = 'XXXXXXXX';
    const authToken = 'XXXXXXXX';
    const client = require('twilio')(accountSid, authToken);
    const MessagingResponse = require('twilio').twiml.MessagingResponse;
    const bodyParser = require('body-parser');
    const app = express();
    app.use(bodyParser.urlencoded({ extended: false }));
    app.post("/sms",function(req,res){
            rt(req,res);
    });
    function rt (req,res){
        res.writeHead(200, {'Content-Type': 'image/jpeg'});
        console.log(res);
    }
     http.createServer(app).listen(1337, () => {
      console.log('Express server listening on port 1337');
    });

Please provide the help How to get details about images from the response.

A: Twilio developer evangelist here.
At the moment, Twilio does not support incoming media in WhatsApp messages. This support is being worked on and should be out soon.


text:
Q: Visual studio 2008 - Clearcase integration Checkout issue I've integrated clearcase plugin to visual studio 2008. I'm facing problem with unreserved checkout option with plugin.
I modified,
TOOLS -> options -> Rational clearcase -> clearcase user options . I removed the check "Reserved" under "operations" tab. I click OK.
After this setting , I selected a file to checkout --> a popup asking for comments appeared , BUT , Reserved is "Checked" in that final window for checkout. What ever we do that check is not going off. Pleaase help . Context is Unreserve checkout option by default for all the files. I modified the setting in CCRC also to default unreserved checkout.
Thanks,
Srinivas

A: I don't see any recent issue in this plugin in the Integration CC - Visual Studio page.

Note: the picture above is just here for general illustration.
It is not meant to say that you should click on the "unreserved, nonmastered" option: this is unrelated to your issue
Can you check that the file is actually checked out in reserve mode after you click ok on the checkout dialog?
You can do this with a a DOS session, by going on the parent directory of the file, and typing:
cleartool ls

By the way, what exact version of ClearCase are you using?
Are you using a full ClearCase client or only the CCRC gui? (meaning a light client communicating with a CCRC server)


text:
Q: How to correctly use loop I have macros that invites friends to FB groups, friends name is taken from CSV file, so i need write loop, than will invites all people from csv file . Here is my macros
var macro,start;
macro =  "CODE:";
macro +=  "SET !ERRORIGNORE YES" + "\n";
macro +=  "SET !EXTRACT_TEST_POPUP NO" + "\n";
macro +=  "SET !DATASOURCE FB<SP>Groups.csv" + "\n";
macro +=  "SET !DATASOURCE_COLUMNS 1000" + "\n";
macro +=  "SET !LOOP 1" + "\n";
macro +=  "SET !DATASOURCE_LINE {{!LOOP}}" + "\n";
macro +=  "URL GOTO=" + "\n";
macro +=  "TAG POS=1 TYPE=I ATTR=CLASS:" + "\n";

So i think from here must starts loop
macro +=  "TAG POS=2 TYPE=SPAN ATTR=TXT:Invite<SP>Friends" + "\n";
macro +=  "SET !DATASOURCE FB<SP>Users.csv" + "\n";
macro +=  "SET !DATASOURCE_COLUMNS 1000" + "\n";
macro +=  "SET !LOOP 1" + "\n";
macro +=  "SET !DATASOURCE_LINE {{!LOOP}}" + "\n";
macro +=  "TAG POS=1 TYPE=INPUT:TEXT ATTR=CLASS:" + "\n";
macro +=  "TAG POS=1 TYPE=SPAN ATTR=CLASS:uiButtonText" + "\n";
iimPlay(macro)

A: Play with this snippet:
var macro = "CODE:";
for (i = 1; i <= 3; i++) {
    macro +=  "SET !DATASOURCE FB<SP>Users.csv" + "\n";
    macro +=  "SET !DATASOURCE_LINE " + i + "\n";
    macro +=  "PROMPT {{!COL1}}" + "\n";
    iimPlay(macro);
}

Hope, you can catch the idea.

Here is a way of how to define the number of rows in your csv-file:
var numRows = 0;
while (true) {
    var macro = "SET !DATASOURCE FB<SP>Users.csv" + "\n";
    macro += "SET !DATASOURCE_LINE " + (numRows + 1) + "\n";
    if (iimPlayCode(macro) == 1)
        numRows++;
    else
        break;
}
alert(numRows);


text:
Q: Error: width suffixes are invalid in ARM mode I'm trying to manually issue ARMv7 movt and movw instructions for a cpu feature test. I'm catching a compile error with Clang.
The test program is below. According to the ARM folks, .inst.w is the way to do this. It handles big-endian and little-endian properly, and places the code in the .text section instead of a data section.
$ cat test.cxx
int test()
{
  int a;
  asm volatile (
        ".inst.w 0xf2412334  \n\t"   // movw r3, 0x1234
        ".inst.w 0xf2c12334  \n\t"   // movt r3, 0x1234
        "mov %0, r3          \n\t"   // mov [a], r3
        : "=r" (a) : : "r3");
  return a;
}

GCC is fine:
$ g++ -O1 -march=armv7-a test.cxx -c
$ objdump --disassemble test.o
...
00000000 <_Z4testv>:
   0:   f241 2334       movw    r3, #4660       ; 0x1234
   4:   f2c1 2334       movt    r3, #4660       ; 0x1234
   8:   4618            mov     r0, r3
   a:   4770            bx      lr

However, Clang:
$ clang++ -O1 -march=armv7-a test.cxx -c
test.cxx:5:2: error: width suffixes are invalid in ARM mode
        ".inst.w 0xf2412334  \n\t"   // movw r3, 0x1234
        ^
<inline asm>:1:2: note: instantiated into assembly here
        .inst.w 0xf2412334
        ^
test.cxx:5:25: error: width suffixes are invalid in ARM mode
        ".inst.w 0xf2412334  \n\t"   // movw r3, 0x1234
                               ^
<inline asm>:2:2: note: instantiated into assembly here
        .inst.w 0xf2c12334
        ^
2 errors generated.

If I change .inst.w to .inst, then Clang produces garbage:
$ clang++ -O1 -march=armv7-a test.cxx -c
$ objdump --disassemble test.o
...
00000000 <_Z4testv>:
   0:   f2412334        vcge.s8 d18, d1, d20
   4:   f2c12334        vbic.i32        d18, #5120      ; 0x00001400
   8:   e1a00003        mov     r0, r3
   c:   e12fff1e        bx      lr

I verified Clang is defining __GNUC__, so it should be able to consume this code.
How do I get Clang to assemble the movt and movw instructions?

A: The main difference is that your GCC is configured to default to thumb mode, while clang isn't.
ARM has got two different 32 bit instruction sets, ARM and Thumb, and even if the instruction names are similar, the encodings are different. The ARM instruction set encodes all instructions as fixed length 32 bit instructions, while Thumb originally was a much smaller instruction set with all instructions being 16 bit. Since Thumb2 (which is the case for ARMv7), the instructions can either be a single 16 bit instruction or a pair of two 16 bit instructions.
The disassembly you showed indicates this:
   0:   f241 2334       movw    r3, #4660       ; 0x1234
   4:   f2c1 2334       movt    r3, #4660       ; 0x1234
   8:   4618            mov     r0, r3
   a:   4770            bx      lr

The latter two instructions are plain 16 bit opcodes (4618 and 4770), while the former two are two pairs of 16 bits (f241 2334 and f2c1 2334) separated with whitespace.
The clang disassembly however doesn't split the opcodes in half, and have full 32 bit opcodes for all instructions:
   0:   f2412334        vcge.s8 d18, d1, d20
   4:   f2c12334        vbic.i32        d18, #5120      ; 0x00001400
   8:   e1a00003        mov     r0, r3
   c:   e12fff1e        bx      lr

In this case, passing -mthumb to Clang should get the same behaviour as GCC, and vice versa, passing -marm to GCC should reproduce the same failure there.
The .w suffix to .inst is to indicate that the value should be handled as a wide 32 bit instruction (as opposed to a narrow 16 bit one), which only makes sense in Thumb mode. IIRC, both GCC (since some time) and Clang (since release 8) should be able to deduce the kind of Thumb instruction without the .w suffix as well.
Instead of forcing the compiler to one mode or another, you probably want something like this instead though:
  asm volatile (
#ifdef __thumb__
        ".inst.w 0xf2412334  \n\t"   // movw r3, 0x1234
        ".inst.w 0xf2c12334  \n\t"   // movt r3, 0x1234
#else
        ".inst   0xe3013234  \n\t"   // movw r3, 0x1234
        ".inst   0xe3413234  \n\t"   // movt r3, 0x1234
#endif
        "mov %0, r3          \n\t"   // mov [a], r3
        : "=r" (a) : : "r3");


text:
Q: SVN : how to change hostname? I'd like to sep up SVN repo on local machine. But we already have apache running under localhost. When I use instalator form subversion site with apache option it installs another apache and when I type "localhost" in browser I see this new apache (not the old one).
Question is how to run this new apache under other host name. When installing it asks about it, so I set different name, but it still works under localhost (nothing happens). I'd like to have access to svn via URL e.g. "svnrepo" not "localhost". What can I do about it? Which lines of config should be changed (and/or what's more should be changed?)
Another way I'm thinking of to solve this problem is to integrate this svn-apache module with mine apache. But still I don't really know how to do it (my apache is 2.2.6)

A: Now that you've got two Apaches installed the easiest way to do this is to assign a second IP address to your machine and then map the two Apache instances to the different IP addresses.
How to add a 2nd IP address depends vastly on your operating system (the process is called Multi-Homing) and seeing as you haven't specified an OS I can't speculate on how this is done in your situation.
Once you have two IP addresses on your machine, change the listen directive in each of the httpd.conf files to bind each version of apache to a different IP address.
Then, at your DNS server, give the SVN IP address a name (like svnrepo), and hey presto, http://svnrepo/ will point to the SVN apache, leaving the 2nd instance seperate.

The "correct" way of doing this properly (I use that term loosely because there's nothing inherantly wrong with two installations, it's just more maintenance) is to enable the dav_svn module in your original Apache installation and set up your repository that way

A: To enable dav_svn - turn the module on then add the following config:
<Location /svn>
  DAV svn
  SVNParentPath /var/lib/svn
  AuthType Basic
  AuthName "Subversion Repository"
  AuthUserFile /etc/apache2/dav_svn.passwd
  Require valid-user
</Location>

Replace the paths for Windows style ones. SVNParentPath is the path to a folder which contains your repositories. AuthUserFile is the path to a standard apache passwords file. Skip all the commands with Auth* at the beginning if you don't need authentication.
You will be able to access the SVN repositories via http using this url http://localhost/svn/repository_name

A: I think I'd go with your last point, and integrate the Subversion server into your existing Apache (httpd) instance.
I'd recommend the SlikSVN version of the Windows server, as it comes without any httpd instance or bindings. You will then have the command-line tools to manage repositories (svnadmin, etc.).
I've always done the SVN/httpd bindings by hand, and the best reference I've found was "Version Control with Subversion" (the red-bean book). The information on manually configuring Apache also has a number of basic examples, and can also help you set up authentication if needed.


text:
Q: Change prefix for Discord bot in Java How do I change my Discord bot's prefix in Java? Here is my code:
package Rekt.YourAssistant;

import javax.security.auth.login.LoginException;

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;

public class Main {
    public static JDA jda;

    //Main Method
    public static void main(String[] args) throws LoginException {
        jda = JDABuilder.createDefault("NzU4MTIxMTkwMjExNDUyOTQ4.X2qVYA.aW6C3UrekBZQrmA-AmMxYEMyibI").build();
    }
}

A: I do not know anything about the JDA but it appears not to have a command handler out of the box - you'd need to find and install one or write your own.
Therefore, prefixes are not a pre-managed concept. Here's is how the JDA Github example shows making one command (simplified by me to get to the relevant information):
public class MessageListenerExample extends ListenerAdapter
{
    public static void main(String[] args)
    {
       //start bot
    }

    @Override
    public void onMessageReceived(MessageReceivedEvent event)
    {
        //These are provided with every event in JDA
        JDA jda = event.getJDA();

        Message message = event.getMessage();           //The message that was received.

        String msg = message.getContentDisplay();              //This returns a human readable version of the Message. Similar to
                                                        // what you would see in the client.

        if (event.isFromType(ChannelType.TEXT))         //If this message was sent to a Guild TextChannel
        {
           if (msg.equals("!ping"))
           {
             //do something
           }
           if (msg.startsWith("!alias"))
           {
             //do something else
           }
        }
     }
}

Notice that the if msg.equals or msg.startsWith methods act on strings with their own prefix: !
I highly recommend you read the entire example as there is a LOT I cut out to just show the prefix part.
P.S. You should regenerate the Bot Token you posted in your question. It's on the internet now, and with it people can take control of you bot. When you post another question you can just write "my-token-goes-here" and people will know what you mean.

A: You can use a GuildMessageReceivedEvent and then use
// Set This Prefix String To Whatever You want As Your Prefix
String prefix = "/"
if(event.getMessage().getContentRaw.equals(prefix + "help"){
   event.getMessage().getChannel().sendMessage("You used /help command");
}


text:
Q: How to Filter Data from an API call by Category and Display it in the UI? I'm trying to retrieve the data by category, by generation to be specific from a Pokemon API and retrieve all the pokemon species into the generation it falls as selected in the option list but I'm having some hard time to do so. I can already get the array of pokemon species in the console log but I can't implement it in my view. Anyone who can help me with this. Thank you!
Here's the method I used for fetching species by generation:
  getPokeGenerationSpecies(id) {
    return this.http.get(`${this.baseUrl}/generation/7`).pipe(
      map((poke) => {
        let id = Object.keys(poke["id"]);
        poke["id"] = id.map((idKey) => poke["id"][idKey]).filter((id) => id);
        return poke;
      })
    );
  }

As you can notice above, I only hardcoded the index value to 7 but what I really want is to get it dynamically as I select a generation number.
This is what I log in the console:

Here, I would like to access all the list of pokemon_species and display all of it in my view.
This is the interface I'm trying to achieve dynamically:

But I only hardcoded the data here:

POKÉDEX

  <ion-card-subtitle> Search by generation. </ion-card-subtitle>
  <ion-item>
    <ion-label>Select</ion-label>
    <ion-select (ionChange)="onChange($event)">
      <ion-select-option [value]="1">Generation 1</ion-select-option>
      <ion-select-option [value]="2">Generation 2</ion-select-option>
      <ion-select-option [value]="3">Generation 3</ion-select-option>
      <ion-select-option [value]="4">Generation 4</ion-select-option>
      <ion-select-option [value]="5">Generation 5</ion-select-option>
      <ion-select-option [value]="6">Generation 6</ion-select-option>
      <ion-select-option [value]="7">Generation 7</ion-select-option>
    </ion-select>
  </ion-item>

<ion-content>
  <ion-list>

Generation 1

      <ion-item>
        <ion-label>Charmander</ion-label>
      </ion-item>
      <ion-item>
        <ion-label>Pikachu</ion-label>
      </ion-item>
      <ion-item>
        <ion-label>Bulbazour</ion-label>
      </ion-item>
      <ion-item>
        <ion-label>Pichu</ion-label>
      </ion-item>
      <ion-item>
        <ion-label>Salamander</ion-label>
      </ion-item>
      <ion-item>
        <ion-label>Meow</ion-label>
      </ion-item>

  </ion-list>

Here's my onChange method:
 onChange(event) {
    let value = event.detail.value;
    console.log(event.detail.value);
    if (value == "") {
      this.offset = 0;
      this.loadPokemon();
      return;
    }

    this.pokeService.findPokemonByGeneration(value).subscribe(
      (res) => {
        this.pokemon = [res];
      },
      (err) => {
        this.pokemon = [];
      }
    );
  }

And here's my findPokemonByGeneration method:
  findPokemonByGeneration(search) {
    return this.http.get(`${this.baseUrl}/generation/${search}`).pipe(
      map((generation) => {
        generation["generationIndex"] = generation["id"];
        return generation;
      })
    );
  }

A: Why cannot directly use the array filter function
return poke.filter((item) => {
  return  item.id === id;
});

Or create a generic pipe to filter any property, see the link it may help you:
Filter and Sorting in Angular


text:
Q: C++0x - lambda expression does look same as Java's anonymous inner class? Is my interpretation of lambda expression in the context of c++ and Java is correct?

A: They are not quite as same. Both create unnamed classes, but their similarity ends at that point.
In C++ you create a closure catching your local variables, optionally by reference. In Java, you just get a snapshot of the current local variable's values (and those variables need to be "final").
The purpose of anonymous inner classes is to extend another class or implement another interface ad-hoc. For that reason, anonymous inner classes can simulate the job of lambda expressions to some extend, for example by implementing the Runnable interface. Lambda expressions are specifically designed to be called and possibly modify the local variables in their environment.

A: A Java anonymous inner class can refer to final data in the enclosing method, and to all data (including mutable) in the enclosing class. So methods in anonymous classes cannot change the values of variables in the enclosing method, but they can change values of members in the enclosing class.
A C++ lambda can refer to all data (including mutable) in the enclosing function, and if it is nested inside a member function then it can do the same for the data of the enclosing class. The precise degree of dependency on the enclosing scope(s) is declared by the programmer, so it is explicit rather than implicit.
This makes them quite similar but the Java feature treats local variables/parameters in methods differently, on the principle that they should not be mutable from outside the method, especially in a language which has traditionally employed threading so casually.
Compare with C# lambdas, which have no restrictions and all dependencies are implicit. This makes them by far the least verbose of these features (also helped by them having the best type inference). But on the downside, they invalidate all the simple rules about threading, i.e. it is no longer necessarily true that local variables are "on the thread stack" and hence never require locking before access.

A: C++0x lambda expressions are unnamed methods, Javas anonymous classes are unnamed classes. So they share not having a name but the concepts are different.
Starting with the most obvious fact, that lambda functions (may) return a value and anonymous classes can be used to create instances (objects).
BTW - wikipedia mentions, that only lambda functions are proposed for C++0x.


text:
Q: i use opencv version 4 and python version 3.how can i run this code #  White region shows sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.cv.CV_DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)`enter code here`

plt.imshow(sure_fg,cmap='gray')
plt.axis('off')
plt.show()

This code gives following error:

File "C:/Users/Mahbuba/Desktop/brine.py", line 90, in
      dist_transform = cv2.distanceTransform(opening,cv2.cv.CV_DIST_L2,5)
AttributeError: module 'cv2.cv2' has no attribute 'cv'

A: cv2.cv.CV_DIST_L2 in your code should be cv2.DIST_L2


text:
Q: How to isolate a tuple from sql ordering while ordering the rest? I searched for an answer here and didn't find one closer to my question.
I have the following situation: I need to display a person first and then show the rest in ascending order. All the people from the same table. I tried UNION but after that, the SQL seems to mix everything again.
I have tried this:
select name from people where name = 'John'
UNION
select name from people order by name

Since UNION does not select duplicated values. But in the end, it mixed up every result and did not show in the correct order that should be:
John
Ana
Bruce

What am I doing wrong?

A: You need to use order by to get what you want.  In MySQL, this is pretty easy:
select name
from people
order by (name = 'John') desc, name

Results sets (like tables) represent unordered sets in SQL.  The only way to impose an order is to use order by.  The order by at the end of a union/union all query applies to the entire query.
As an aside, your code would come close to working if you used union all -- which is much preferred over union.  The union operation does additional work to remove duplicates.  In this case, that reorders the results, a convenient reminder that you can only depend on the order of results when you use order by.

A: Also you can use UNION ALL in a derived table
SELECT name
FROM
(
    SELECT 1 AS Row_Id, name
    FROM people
    WHERE name = 'John'

    UNION ALL

    SELECT 2 AS Row_Id, name
    FROM people
) t
ORDER BY Row_Id


text:
Q: Plot in a Jupyter notebook depending on a true/false checkbox I have an interactive notebook with a few widgets, that displays a plot (+other data) based on the information given by the widgets.  The plot is only displayed if a Checkbox is checked.
Everything works well except one thing: the Checkbox has a True value by default. When loading the notebook for the first time, it appears as clicked but the plot is not displayed -- if I interact with the widgets in any other way (either by re-clicking this checkbox twice, or by modifying some of the other widgets), then the plot is displayed.
Is there a way to have the plot displayed at the beginning without waiting for the user to interact?

A: Start by creating your checkbox with the False value
cb = widgets.Checkbox(value=False)
Then, once you have set up your observse, in the code, change the value of the checkbox to True, and this should trigger your code.
cb.value = True


text:
Q: AttributeError: 'Images' object has no attribute 'pop' I am working with this code so I have my main code here:
from draw_image import Images
start = Images()
start.display_image()
start.delete_line()
start.display_image()

and this is my draw_image code:
class Images:

def image(jumper_image):
    """This function is to create the list"""
    jumper_image = []

def display_image(jumper_image):
    """This is how the user will see the image correctly through the loop"""
    jumper_image = [
        "    ___    ",
        "   /___\   ",
        "   \   /   ",
        "    \ /    ",
        "     o     ",
        "    /|\    ",
        "    / \    ",
        "           ",
        "^^^^^^^^^^^"
        ]
    for image in jumper_image:
        print(image)
    return jumper_image

def delete_line(jumper_image):
    """ This function is supposed to delete the first line of the jumper_image"""
    jumper_image.pop(0)

It seems that the delete_line function is not recognizing the list, do you guys have any idea why this is happening? or what would be a solution for this problem?

A: I would recommend using a python constructor to initialize jumper_image:
class Images:

  def __init__(self):
    self.jumper_image = [
        "    ___    ",
        "   /___\   ",
        "   \   /   ",
        "    \ /    ",
        "     o     ",
        "    /|\    ",
        "    / \    ",
        "           ",
        "^^^^^^^^^^^"
        ]

  def display_image(self):
    """This is how the user will see the image correctly through the loop"""

    for image in self.jumper_image:
        print(image)

  def delete_line(self):
    """ This function is supposed to delete the first line of the jumper_image"""
        self.jumper_image.pop(0)

start = Images()
start.display_image()
start.delete_line()
print('After deleting first value in list\n')
start.display_image()

    ___
   /___\
   \   /
    \ /
     o
    /|\
    / \

^^^^^^^^^^^
After deleting first value in list

   /___\
   \   /
    \ /
     o
    /|\
    / \

^^^^^^^^^^^


text:
Q: How to pause Java.uti.Timer? I am developing a JavaFX application where I am using java.util.Timer to track user mouse movement.
The concept is If the mouse doesn't move for some seconds in the scene then the buttons will be invisible whenever the mouse moves button will appear again. And whenever user put the cursor over a button timer will be stopped.And when exit the button timer will start again.
This is the start timer method
    public static void startTimer(){

    timer = new Timer();
    task = new TimerTask() {

        @Override
        public void run() {

            if(detection>0){
                Util_Class.getUi_obj().getLeftbuttongroup().setVisible(false);
                Util_Class.getUi_obj().getRightbuttongroup().setVisible(false);
            }else{
                detection++;
            }

        }
    };

    timer.schedule(task, 2000, 2000);
    System.out.println("TIMER STARTED");
    //startTimer();
}

This is to stop the timer
public static void stopTimer(){

    timer.cancel();
    System.out.println("TIMER STOPED");
}

public void leftbuttonmovehandler(MouseEvent event){

    if(event.getEventType()==MouseEvent.MOUSE_ENTERED){
        System.out.println("MOUSE ENTERED");
        Main.stopTimer();
    }else if(event.getEventType()==MouseEvent.MOUSE_EXITED){
        System.out.println("MOUSE EXITED");
        Main.start();
    }

}

Now my code works fine at first whenever the app starts but when i reload the app the callback functions triggers as expected but the buttons disappear despite the cursor is on the button.
It would be great if someone helps me.

A: A PauseTransition can be used to hide the Buttons after a specified time.
Whenever a MOUSE_MOVE event is triggered, on the scene, play the PauseTransition from the beginning ; if the MOUSE_MOVE is triggered for one of the Buttons stop the PauseTransition instead and prevent the event from reaching the Scene by consuming it
private PauseTransition timer;

private void startTimer() {
    btn.setVisible(true);
    btn2.setVisible(true);
    timer.playFromStart();
}

private void stopTimer() {
    btn.setVisible(true);
    btn2.setVisible(true);
    timer.stop();
}

private Button btn, btn2;

@Override
public void start(Stage primaryStage) {
    timer = new PauseTransition(Duration.seconds(3));

    btn = new Button("Button 1");
    btn2 = new Button("Button 2");

    timer.setOnFinished(evt -> {
        btn.setVisible(false);
        btn2.setVisible(false);
    });

    EventHandler<MouseEvent> buttonMouseMoveHandler = evt -> {
        evt.consume();
        stopTimer();
    };

    btn.setOnMouseMoved(buttonMouseMoveHandler);
    btn2.setOnMouseMoved(buttonMouseMoveHandler);

    VBox box = new VBox(100, btn, btn2);

    StackPane root = new StackPane(new Group(box));

    Scene scene = new Scene(root, 500, 500);
    scene.setOnMouseMoved(evt -> {
        startTimer();
    });

    startTimer();

    primaryStage.setScene(scene);
    primaryStage.show();
}


text:
Q: What is the difference between buy and purchase When we use the word "to buy" and when the word "to purchase"? I do not understand the difference between these words.

A: They are essentially the same. To purchase is perhaps a bit more formal.
In regular conversation with friends and colleagues, "I bought that". I'd use purchase more when writing formal reports, or talking to your boss "The company purchased 25 reams of paper."

A: If it comes to the sense of obtaining something by paying money, both "purchase" and "buy" are usually used interchangeably  as a verb.  Nevertheless, the use of "buy" is more common in daily conversational English than that of purchase. The use of purchase is a bit formal.
In some contexts, however, it sounds more natural to use buy instead of purchase such as I will buy him the book/let me buy you a drink.
Similarly, when you use these words as a plural noun, it's more natural to use purchase in some contexts such as she opened the bag of her purchases/her purchases were so heavy that she had to take a taxi.  Besides, you often say in informal English when you buy something at a low/high price "it's a good/bad buy". "It's a good/bad purchase" sounds a bit weird.

A: They mean exactly the same thing 99.9% of the time, and typically you can freely use purchase where you'd use buy and vice versa.
One exception: There at least one expression (possibly regional) involving buy that would sound weird if you used purchase, for example:

A: He just told me that she's sick and won't be coming in today.
B: I don't buy that.  She probably just is hungover from too much partying last night.

Here, "I don't buy that" means "I don't believe that" - using purchase here would not work.
The saying "bought it hook, line, and sinker" - meaning to have believed someone's words later discovered to be deceptive - also would not work with purchase.

A: The difference between buy and purchase is that:
Buying is the act or process of buying goods for immediate consuming, while purchasing is the process or act of buying goods for the purpose of resale.


text:
Q: How can I "pack" 3 digits into a single number, within a given range? I am trying to condense 3 numbers, all of which lie within the range of -50 million to +50 million. How can I condense all 3 into a single number and then retrieve the 3 numbers again from un-condensing the single number.
For example if I have:
-3000, 122, 103 will become a single number such as "9484010392"
Uncondensing "9484010392" will return [-3000, 122, 103]
The number 9484010392 is just chosen at random and serves no connection to the numbers in the example, it's just to clarify what I mean by a single condensed number.
etc.
P.S. Writing the program in Java :)

A: To "merge" 3 numbers into a single number, where the merged value is small when the 3 inputs are small, including sign, we can interleave the bits of the numbers, putting a separate sign bit last (LSB).
E.g. for inputs [-3000, 122, 103], the bit math is:
-3000  ->  sign=1, mag = 3000 = 0b1011_1011_1000  ->  0b1_0111_0111_0001
122  ->  sign=0, mag = 122 = 0b111_1010  ->  0b1111_0100
103  ->  sign=0, mag = 103 = 0b110_0111  ->  0b1100_1110

To merge them, we need to inject two 0-bits between the bits, and shift two of the numbers one and two bits to the left, then combine them using bitwise OR.
shift=0, 1011101110001  ->  1000001001001000001001001000000000001
shift=1,      11110100  ->                10010010010000010000000
shift=2,      11001110  ->               100100000000100100100000
                       OR:  1000001001001110111011011100110100001 = 69958744481

If the result is stored in a 64-bit long, that leaves 21 bits for each number, which is 1 sign bit and 20 magnitude bits, so it can handle values up to ±1048576, i.e. about ±1 million.
If you want a range up to ±50 million, the result must be stored in a BigInteger.
Don't know if this is what you're looking for, but good luck coding it, if it is.


text:
Q: Implement horizontal scroll view like Slide Image Gallery? i want to implement Image Gallery that load from url and put it into horizontal scroll view . i want to set my image view into match_parent  but it doesn't work .. how to get a view like this ??
And this is my xml and view .
<HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_margin="12dp"
            android:id="@+id/slideshow">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <com.android.volley.toolbox.NetworkImageView
                    android:layout_height="match_parent"
                    android:layout_width="match_parent"
                    android:id="@+id/slide1"
                    android:scaleType="fitXY"
                    android:src="@drawable/ic_launcher"/>

                <com.android.volley.toolbox.NetworkImageView
                    android:layout_height="match_parent"
                    android:layout_width="match_parent"
                    android:id="@+id/slide2"
                    android:scaleType="centerInside"
                    android:src="@drawable/ic_launcher"/>

                <com.android.volley.toolbox.NetworkImageView
                    android:layout_height="match_parent"
                    android:layout_width="match_parent"
                    android:id="@+id/slide3"
                    android:scaleType="centerCrop"
                    android:src="@drawable/ic_launcher"/>
            </LinearLayout>
        </HorizontalScrollView>

A: Use RelativeLayout instead of LinearLayout and align the elements using rightOf

A: After some investigation I made to solve similar problem for myself, I came up to using ViewPager. I think, that is what you wanted to do.


text:
Q: Advanced Android Animation - Scale: Moving near by Views I am able to scale Views using standard animation procedures.
Animation anim = new ScaleAnimation(1.0F, 1.0F, 1.0F, 2.0F);
    anim.setFillAfter(true);
    anim.setDuration(animationLength);
    anim.setInterpolator(this, android.R.anim.linear_interpolator);
    view.setAnimation(anim);
        view.startLayoutAnimation();

view is a ViewAnimator but the type shouldn't really matter.
The entire view is contained within a LinearLayout.
So as I scale up the view as above, I am expecting the views bellow the image (buttons, text etc) to move down and be shown below the scaled up image. This is not happening, the end result is that the view is twice as large, but the buttons do not move, and are shown on top (rendered over, not linearly on top) my scaled up view.
Now, I could go about transforming the rest of the view but this seems inefficient, so is there a better way of doing this?
Thanks Aiden


text:
Q: Entity Framework 4: inheritance and Associations I do derive my entities from a base-class that provides tracking.

Since User derives from TrackableBase and TrackableBase is associated with User, I get an error:

"Unable to determine a valid ordering for dependent operations.
  Dependencies may exist due to foreign key constraints, model
  requirements or store generated values."

Is this model just not possible, or am I doing something wrong?


text:
Q: getting notice in php file while executing what is the meaning of undefined property DOMElement::$node Vaoue
I searched in google I didn't get any annswer for this.

A: what is the meaning of undefined property DOMElement::$node Vaoue
It simple means that you have a undefined property DOMElement in your code.
To Help you in details we realy like to se more from the code which causes the error

A: Well, a good start would be to post the code you're trying to execute. Anyways most likely, a property you're trying to access is undefined.


text:
Q: Sharepoint Branding I am trying to brand share point. I have created a mastepage in the top level site. I have soem controls in there which I have overridden. When I apply the master page onto other sites my custom controls do not display but the default ones's do. Any idea what might be going wrong>

A: Take a copy of a working OOTB master page and be sure to include all the contentplaceholders in your new one. If you don't you'll have problems. Stay away from so-called minimal master page downloads being offered online.
As for your custom controls, deploy them as a Feature and activate it on the WFE. Include your customizations in a Feature also.


text:
Q: Vectorize Pandas Dataframe into Numpy Array I have a problem where I need to convert a pandas dataframe into an array of list of lists.
Sample:
import pandas as pd
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])

I know there is the as_matrix() function which returns below:
df.as_matrix():
# result:array([[1, 2, 3],
                [2, 2, 4],
                [3, 2, 4]])

However, I require something in this format
  [array([[1], [2], [3]]),
   array([[2], [2], [4]],
   array([[3], [2], [4]])]

IE. I need a list of arrays containing list of lists where the inner most list contains a single element and the outer most list in the array represents the row of the dataframe. The effect of this is that it basically vectorizes each row of the dataframe into a vector of dimension 3.
This is useful especially when I need to do matrix / vector operations in numpy and currently the data source I have is in .csv format and I am struggling to find a way to convert a dataframe into a vector.

A: Extract the underlying array data , add a newaxis along the last one and then split along the first axis with np.vsplit -
np.vsplit(df.values[...,None],df.shape[0])

Sample run -
In [327]: df
Out[327]:
   0  1  2
0  1  2  3
1  2  2  4
2  3  2  4

In [328]: expected_output = [np.array([[1], [2], [3]]),
     ...: np.array([[2], [2], [4]]),
     ...: np.array([[3], [2], [4]])]

In [329]: expected_output
Out[329]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]

In [330]: np.vsplit(df.values[...,None],df.shape[0])
Out[330]:
[array([[[1],
         [2],
         [3]]]), array([[[2],
         [2],
         [4]]]), array([[[3],
         [2],
         [4]]])]

If you are working with NumPy funcs, then in most scenarios, you should be able to do away with the splitting and directly use the extended array version.
Now, under the hoods np.vsplit  makes use of np.array_split and that's basically a loop. So, a bit more performant way would be to avoid the function overhead, like so -
np.array_split(df.values[...,None],df.shape[0])

Note that this would have one extra dimension than as listed in the expected output. If you want a squeezed out version, we could use a list comprehension on the new-axis extended array version, like so -
In [357]: [i for i in df.values[...,None]]
Out[357]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]

Thus, another way would be to add the new axis within the looping -
[i[...,None] for i in df.values]

A: First convert your DataFrame to a matrix. Then add a dimension and convert it to a list.
Try:
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])
my_matrix = df.as_matrix()
my_list_of_arrays_of_list_lists = list(np.expand_dims(my_matrix, axis=2))

my_list_of_arrays_of_list_lists represents what you are looking for and gives you:
Out[42]: [array([[1],[2],[3]]),
          array([[2],[2],[4]]),
          array([[3],[2],[4]])]


text:
Q: Three JS issue with texture offset and repeat for positioning elements of a spritesheet I have a sprite sheet (exported with Texture Packer), and am using the offset and repeat properties (of a texture) to show elements of my sprite sheet.
This is currently not working ( and cropping out wrong elements of my texture ) - would love it if anyone has some insight about where I am going wrong.
Here is my code:
var tx = this._loadedTexture.clone(); // THREE.Texture
var txData = this._atlas.frames[name];
var txFrame = txData.frame;//txFrame = Object {x: 122, y: 0, w: 68, h: 64}
var img = tx.image; // HTMLImageElement - image.width = 256 image.height = 512

tx.repeat.x = txFrame.w / img.width;
tx.repeat.y = txFrame.h / img.height;

tx.offset.x = ( txFrame.x  / img.width );
tx.offset.y = ( txFrame.y / img.height );
tx.needsUpdate = true;

Thank you .

A: Solved it. For future reference, this is what I ended up with to get a sprite sheet working with a texture atlas in ThreeJS (0.73):
tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
tx.repeat.set( txFrame.w / img.width, txFrame.h / img.height );
tx.offset.x = ( ( txFrame.x ) / img.width );
tx.offset.y = 1 - ( txFrame.h / img.height ) - ( txFrame.y / img.height);

Hopefully this will hope someone else out there.


text:
Q: Firestore permutation explosion of composite index I'm stuck in the composite index of firestore. I have a couple of fields under a user, which are like A(string), B(string), C(string), D(array), E(array), F(array), G(array). Users can be searched and queried by different combinations of these fields. For example, "A == 'Male', B == '2020' ", which tells me to create composite index and after I created the query like "A == 'Male', B == '2020', C == "Ontario' " still needs a new composite index.

*

*What I'm wondering is that do I have to create all the permutation of composite index?

*The array fields are more than two, but the SDK only allows one "array-contains" clause. What can I do for this? For this, I have tried to split an array [element1,element2] to the structure like "element1 : true, element2 : true", which can be queried by "==" clause. But the problem is that the array is dynamic, every time I append a "==" clause, the SDK tells me I need to create a new composite index.

Anyone has any ideas about this?

A: There is no tooling that will create all the desired combinations automatically.  However, the documentation suggests that you can use the Firebase CLI to deploy indexes that are defined using its JSON configuration.  This configuration file is not documented, so you will have to reverse engineer it based on indexes that you create manually.  An example of one such index configuration is here.  What you can do is manually create an index, then run firebase init, choose Firestore, and it will dump the indexes to its JSON config, which you can edit and redeploy.  As of today, you will have to run firebase init in a fresh folder to get new indexes from the server.
Once you know how to deploy indexes like this, you can write code to create all the combinations of indexes in that JSON config.  It's not pretty, but it's doable.


text:
Q: Slick Carousel - conflicting filter functions breaking each other (responsive) I have a model bar for a website using the slick carousel, there are multiple filters that on desktop are being controlled by an  and on tablet/mobile being controlled by a  drop down. They work independently of each other but if I choose one filter on desktop and then shrink the window down and choose a different filter slider breaks or because unresponsive.
I have two seperate functions for each filter selector and ideally it would be best if they could be combined but my javascript skills just are not that good, I have fiddled around with this for a little too long now and have officially thrown in the towel. Any help would be greatly appreciated and please don't judge my code too harshly
HTML

All Vehicles

Cars

Minivans & Trucks

Crossovers & SUVs

Hybrids & EVs

  <select class="columns column-2 large-12 medium-12 small-12 show-for-small-only">
    <option class="all-vehicles">All Vehicles</option>
    <option class="car">Cars</option>
    <option class="truck">Minivans & Trucks</option>
    <option class="suv">Crossovers & SUVs</option>
    <option class="hybrid">Hybrids & EVs</option>
  </select>

2015 Yaris

$14,845 msrp | 30/37 est. mpg

                View Details

2016 Corolla

$17,230 msrp | 28/37 est. mpg

            View Details

2016 Camry

$23,070 msrp | 25/35 est. mpg

                View Details

2015 Avalon

$32,285 msrp | 21/31 est. mpg

                View Details

2015 Sienna

$28,700 msrp | 18/25 est. mpg

                View Details

2015 Tacoma

$20,965 msrp | 21/25 est. mpg

                View Details

2016 Tundra

$28,640 msrp | 15/19 est. mpg

                View Details

2015 Rav-4

$23,680 msrp | 24/31 est. mpg

                View Details

2015 Venza

$29,065 msrp | 20/26 est. mpg

                View Details

2015 Highlander

$29,765 msrp | 20/25 est. mpg

                View Details

2016 4Runner

$33,510 msrp | 17/22 est. mpg

                View Details

2016 Sequoia

$44,965 msrp | 13/17 est. mpg

                View Details

2015 Land Cruiser

$80,155 msrp | 13/18 est. mpg

                View Details

2016 Camry Hybrid

$26,790 msrp | 43/39 est. mpg

                View Details

2015 Avalon Hybrid

$36,470 msrp | 40/39 est. mpg

                View Details

2015 Highlander Hybrid

$47,850 msrp | 27/28 est. mpg

                View Details

2015 Prius

$24,200 msrp | 51/48 est. mpg

                View Details

2015 Prius C

$19,540 msrp | 53/46 est. mpg

                View Details

2015 Prius Plug-In Hybrid

$29,990 msrp | EPA est. 95 Ev Mode/50 hybrid mode

                View Details

2016 Prius V

$26,675 msrp | 44/40 est. mpg

                View Details

Javascript
    //vehicle scroller
  $('.model-container').slick({
    slidesToShow: 4,
    prevArrow: $('.veh-pagenation #slickPrev'),
    nextArrow: $('.veh-pagenation #slickNext'),
    responsive: [
      {
        breakpoint: 1020,
        settings: {
          slidesToShow: 3,
          arrows: false,
        }
      },
      {
        breakpoint: 767,
        settings: {
          slidesToShow: 1,
          arrows: false,
        }
      }
    ]
  });

var filtered = false;

  $(".vehicle-type-selector select").change(function() {
    if ($(".vehicle-type-selector span.active").length) {
      $(".vehicle-type-selector span.active").removeClass("active");
      var filtered = true;
    } else {
      var filtered = false;
    }

    var filtername = $("option:selected").attr('class');

    if (filtered === false) {
      $('.model-container').slick('slickUnfilter');
      $('.model-container').slick('slickFilter', '.' + filtername);
    } else {
      $('.model-container').slick('slickUnfilter');
      $('.model-container').slick('slickFilter', '.' + filtername);
      $('.model-container').slick('slickGoTo', 0);
      filtered = false;
    }

    if ($(".vehicle-type-selector span.active").length) {
      $(".vehicle-type-selector span.active").removeClass("active");
    }

    if ($(".vehicle-type-selector option:selected").length) {
      $("option:selected").removeAttr("selected");
    }

    $('.vehicle-type-selector select').find('option.' + filtername).attr('selected','selected');
    $(".vehicle-type-selector span#" + filtername).toggleClass("active");

    });

  $(".vehicle-type-selector span").on('click', function(){
    if ($(".vehicle-type-selector option:selected").length) {
      $("option:selected").removeAttr("selected");
      var filtered = true;
    } else {
      var filtered = false;
    }

   var filtername = $(this).attr('id');

  if (filtered === false) {
    $('.model-container').slick('slickUnfilter');
    $('.model-container').slick('slickFilter', '.' + filtername);
  } else {
    $('.model-container').slick('slickUnfilter');
    $('.model-container').slick('slickFilter', '.' + filtername);
    $('.model-container').slick('slickGoTo', 0);
    filtered = false;
  }

  if ($(".vehicle-type-selector span.active").length) {
    $(".vehicle-type-selector span.active").removeClass("active");
  }

  $(this).toggleClass("active");
  $('.vehicle-type-selector select').find('option.' + filtername).attr('selected','selected');

  if($(".model-container .slick-track").children().length < 5) {
    $(".veh-pagenation").hide();
  } else {
    $(".veh-pagenation").show();
  }
  console.log("arrows");

});

here a url to the "working" model http://schottman-toyotadesign.schottmandesign.com


text:
Q: faketime ignoring chronyc sources I'm trying to do a "chronyc sources" call but with faketime. When in a terminal, "chronyc source|cat" works fine, but when I do faketime 'last friday 5pm' chronyc sources|cat, it outputs nothing.
whats even more odd is that I have an identical computer that works when I call chronyc with fake time.
Does anyone know why this is happening? Is it maybe some setup config I have messed up? I've tried reinstalling chrony as well as faketime.

A: The issue was with SELinux. Apparently chrony doesn't interact well when SELinux is in enforced mode. I switched it to permissive and it behaves as expected now. I can call faketime 'last friday 5pm' chronyc sources as well as use it in my popen code


text:
Q: How do you get the content of a file revision in Google Drive SDK? I'm attempting to get revision histories for google drive (actually, docs) files using the Google Drive .NET SDK. I can get the metadata for a list of revisions for a given file just fine, but it appears that for any given Revision, the DownLoadUrl field is always null, and the ExportLinks all point back to the most recent complete version of the doc (i.e., not to the revision indicated by the metadata).
Any suggestions? Is this just how it works? I've noticed that the return value in the API explorer for the Revision object behaves in the same way.
https://developers.google.com/drive/v2/reference/revisions/get
Thanks in advance!

A: The downloadUrl field is only populated on files with content stored in Drive and not for Google native formats.
Please edit your question to add the file metadata if the API is still not behaving as expected.

A: I tried a bit and used this link:
https://developers.google.com/drive/v2/reference/revisions/list
in the items you have the links to the item.
I have also tried the
https://developers.google.com/drive/v2/reference/revisions/get  and it works.
It returns the downloadUrl for the revision.


text:
Q: Loading ffdf data take a lot of memory I am facing a strange problem:
I save ffdf data using
save.ffdf()

from ffbase package and when i load them in a new R session, doing
load.ffdf("data.f")

it gets loaded into RAM aprox 90% of the memory than the same data as a data.frame object in R.
Having this issue, it does not make a lot of sense to use ffdf, isn´t it?
I can't use ffsave because i am working in a server and do not have the zip app on it.
packageVersion(ff) # 2.2.10
packageVersion(ffbase) # 0.6.3

Any ideas about ?
[edit] some code example to help to clarify:
data <- read.csv.ffdf(file = fn, header = T, colClasses = classes)
# file fn is a csv database with 5 columns and 2.6 million rows,
# with some factor cols  and some integer cols.
data.1 <- data
save.ffdf(data.1 , dir = my.dir) # my.dir is a string pointing to the file. "C:/data/R/test.f" for example.

closing the R session... opening again:
load.ffdf(file.name) # file.name is a string pointing to the file.
#that gives me object data, with class(data) = ffdf.

then i have a data object ffdf[5] , and its memory size is almost as big as:
data.R <- data[,] # which is a data.frame.

[end of edit]
*[ SECOND EDIT :: FULL REPRODUCIBLE CODE ::: ]
As my question is not answered yet, and i still find the problem, i give a reproducible example ::
dir1 <- 'P:/Projects/RLargeData';
setwd(dir1);
library(ff)
library(ffbase)

memory.limit(size=4000)
N = 1e7;
df <- data.frame(
 x = c(1:N),
 y = sample(letters, N, replace =T),
 z = sample( as.Date(sample(c(1:2000), N, replace=T), origin="1970-01-01")),
 w = factor( sample(c(1:N/10) , N, replace=T))   )

df[1:10,]
dff <- as.ffdf(df)
head(dff)
#str(dff)

save.ffdf(dff, dir = "dframeffdf")
dim(dff)
# on disk, the directory "dframeffdf" is : 205 MB (215.706.264 bytes)

### resetting R :: fresh RStudio Session
dir1 <- 'P:/Projects/RLargeData';
setwd(dir1);
library(ff)
library(ffbase)
memory.size() # 15.63
load.ffdf(dir = "dframeffdf")
memory.size() # 384.42
gc()
memory.size() # 287

So we have into memory 384 Mb, and after gc() there are 287, which is around the size of the data in the disk. (checked also in "Process explorer" application for windows)
> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=Danish_Denmark.1252  LC_CTYPE=Danish_Denmark.1252    LC_MONETARY=Danish_Denmark.1252 LC_NUMERIC=C                    LC_TIME=Danish_Denmark.1252

attached base packages:
[1] tools     stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ffbase_0.7-1 ff_2.2-10    bit_1.1-9

[END SECOND EDIT ]

A: In ff, when you have factor columns, the factor levels are always in RAM. ff character columns currently don't exist and character columns are converted to factors in an ffdf.
Regarding your example: your 'w' column in 'dff' contains more than 6 Mio levels. These levels are all in RAM. If you wouldn't have columns with a lot of levels, you wouldn' see the RAM increase as shown below using your example.
N = 1e7;
df <- data.frame(
 x = c(1:N),
 y = sample(letters, N, replace =T),
 z = sample( as.Date(sample(c(1:2000), N, replace=T), origin="1970-01-01")),
 w = sample(c(1:N/10) , N, replace=T))
dff <- as.ffdf(df)
save.ffdf(dff, dir = "dframeffdf")

### resetting R :: fresh RStudio Session
library(ff)
library(ffbase)
memory.size() # 14.67
load.ffdf(dir = "dframeffdf")
memory.size() # 14.78

A: The ffdf package(s) have mechanisms for segregating object in 'physical' and 'virtual' storage. I suspect you are implicitly constructing items in physical memory, but since you offer not coding for how this workspace was created, there's only so much guessing that is possible.


text:
Q: Alternative method to save data than my.settings for VB.Net I need to save approximately 1600 different pieces of information for a windows forms application.
What is the best way to go about this? For example some of the user settings would look like this measuringItem1Name, measuringItem1Equation, measuringItem1Enabled, measuringItem1Offset, measuringItem2Name...
I have looked into my.settings, however, I found that it would be very tedious and error prone to type out every user setting.
It seems like the best solution would be to have a type of table that can access each individual cell and edit that information.
Does something like this exist? If so, how would it be implemented with VB.Net?

A: I'd recommend creating a class with properties to hold your settings.  Mark the class as serializable.  Then serialize and deserialize an instance of this class as application startup / shutdown to the user's profile directory.  This will allow you to have strongly typed settings that save separately per user if you ever need that option.  It will also allow you to easily set default values for the settings.
You can make the "settings" class as deep as you want, with properties made up of other sub setting classes or lists of settings by index.  It's a very powerful pattern.
For example:
settings.MeasuringItem(1).Enabled = True
settings.MeasuringItem(1).Equation = "1+1"
settings.MeasuringItem(1).Offset = 15

settings.MeasuringItem(2).Enabled = True
settings.MeasuringItem(2).Equation = "1+1"
settings.MeasuringItem(2).Offset = 15

Settings is the main settings class with a Generic.List(of MeasuringItem) property on it.  MeasuingItem is another class with .Enabled As Boolean, .Equation as string , etc properties on it.
I haven't really checked this for errors.  You will want to do a lot more safety checking, but this should get you started.
<Serializable>
Public Class Settings

    Public Sub New()
        _measuringItems = New List(Of MeasuringItem)
    End Sub

    Private _measuringItems As List(Of MeasuringItem)
    Public ReadOnly Property MeasuringItems As List(Of MeasuringItem)
        Get
            Return _measuringItems
        End Get
    End Property

    Public Sub Save()
        Using s As New IO.FileStream("Path to save", IO.FileMode.Create)

            Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            formatter.Serialize(s, Me)
        End Using
    End Sub

    Public Shared Function Load() As Settings
        Dim settings As Settings = Nothing

        Using s As New IO.FileStream("Path to load", IO.FileMode.Open)

            Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            settings = CType(formatter.Deserialize(s), ServerHost.Settings)
        End Using
        Return settings
    End Function

End Class

<Serializable>
Public Class MeasuringItem
    Public Property Enabled As Boolean = True 'These are the default values
    Public Property Equation As String = "1+1"
    Public Property Offset As Integer = 15
End Class

A quick example of usage:
    'Create a completely new settings instance with 100 measuring items
    Dim settings1 As Settings = New Settings
    For i As Integer = 1 To 100
        settings1.MeasuringItems.Add(New MeasuringItem)
    Next
    settings1.MeasuringItems(0).Enabled = False
    settings1.MeasuringItems(5).Equation = "testing"

    'Save it
    settings1.Save()

    'load the saved settings
    Dim settings2 As Settings = Settings.Load

A: I would recommend using a database to store the values in.  I don't know your operating environment (for example, I have several enterprise SQL servers available for my use.)  You could go with  SQL Express Edition, which is free.  SQL Lite is an option as well.  You could even use Access, but that requires MS Office be installed.
If you don't want to go the database route, you can create a settings class, and make the class serializable .  This will serialize the object to either a binary file or a XML file (depending on how you set it up.)  If you want to go this approach, I'll post the code for you.


text:
Q: positioning footer at the bottom of the page using css Here is my codepan link to show footer at bottom
But dont know why it shows space between footer and bottom of the page.

FIDDLE: JSFIDDLE
code:

What is thenWat?

How does it work?

Feedback

Contact us

css contains bootstrap.css and other inline css

A: Use this CSS, I bet it will work like charm
bottom: 0px;
width: 100%;
position: fixed;

with this CSS, even you resize your window it will not make difference to it. This will always keep your footer at bottom.

A: #footer{
    height: 34px; /* Think about this height */
    /* ... */
}


text:
Q: Filling a 2D matrix so that no two neighbouring values are the same I want to get an estimate for the worst-case scenario of an algorithm where the number of iterations depends on how many pixels in an image have neighbours that differ from themselves. Assuming the image to be in grayscale, I'm looking for a way to generate an M x N matrix filled with random values in the range [0, 255] where no two pixels with the same value are contiguous (including "corner" neighbours, i.e. this is for the 8-neighbour case).
Edit: should've made this clearer in the original posting. I'm looking to get a relatively uniform sampling of all values in the range [0, 255].
How would one do this? The efficiency of the solution doesn't really matter, I'm looking for something that's easy to reason about.

A: 0 1 0 1 0 1 0
2 3 2 3 2 3 2
1 0 1 0 1 0 1

etc.
More generally, the dumbest way to try to colour a graph is to visit each vertex in turn (in any order you like), and give it a colour that hasn't already been used for a vertex that's adjacent to it. If (as in this case) you have more colours than the greatest possible number of adjacent vertices, you can't lose.
The grid above is the result of visiting the matrix from left-to-right along each row, and using the smallest available value. You can instead choose one at random from the available values:
import random
rows = [[None] * 10 for i in xrange(10)] # or numpy matrix
for i, row in enumerate(rows):
    for j, _ in enumerate(row):
        available = set(xrange(256))
        if j > 0:
            available.discard(row[j-1])
        if i > 0:
            available.difference_update(rows[i-1][max(0,j-1):j+2])
        row[j] = random.choice(tuple(available))
print '\n'.join(map(str, rows))

A: Try this:
import numpy as np
np.cumsum(np.cumsum(np.ones((M,N)),axis=0),axis=1) % 255

A: import numpy as np
from random import sample
def foo(M,N):
    #Create an np array of size M X N
    img = np.zeros((M,N))
    #Create a colour set within grayscale
    colours = set(range(255))
    #Iterate through the entire image pixel
    for i in range(M):
        for j in range(N):
            #img[i-1:i+2,j - 1:j + 2].flatten() : neighbouring pixel
            #including the current pixel
            #colours- set(img[i-1:i+2,j - 1:j + 2].flatten() : Colours not in the neighbouring pixel
            #sample(colours- set(img[i-1:i+2,j - 1:j + 2].flatten()),1)[0]: Select one from the above
            #and assign to the current pixel
            img[i,j] = sample(colours- set(img[i-1:i+2,j - 1:j + 2].flatten()),1)[0]
    return img

>>> foo(10,10)
array([[ 153.,  128.,   15.,  163.,  180.,  189.,  186.,  228.,   65.,
         140.],
       [  52.,  229.,  220.,   54.,   79.,  105.,   11.,  146.,   29.,
          70.],
       [ 244.,  119.,  188.,  147.,  230.,  157.,   28.,  243.,  105.,
          62.],
       [ 188.,  135.,  129.,  144.,  192.,   11.,   90.,  193.,   35.,
         149.],
       [  20.,  130.,  140.,  134.,  191.,   63.,   50.,  180.,   49.,
           4.],
       [  88.,  175.,  254.,  151.,  176.,   30.,  122.,  157.,   88.,
          82.],
       [  37.,  190.,   10.,  187.,  221.,   83.,    2.,  115.,  191.,
         148.],
       [  53.,   70.,  150.,  127.,  168.,  141.,  179.,   65.,  253.,
          59.],
       [  96.,    3.,  225.,  218.,   87.,   76.,   41.,  195.,  221.,
         192.],
       [  28.,   35.,  104.,  130.,  207.,   57.,  204.,  228.,   96.,
         174.]])

A: Since you mentioned that efficiency doesn't matter, try this:
  from numpy import array
  import random

  available = range(256)
  M=10
  N=5
  def generate():
    return random.choice(available)

  def get_neighbours(i,j):
    neighbours = []
    try:
      neighbours.append(matrix[i][j-1])
      neighbours.append(matrix[i][j+1])
      neighbours.append(matrix[i+1][j])
      neighbours.append(matrix[i-1][j])
      neighbours.append(matrix[i-1][j-1])
      neighbours.append(matrix[i-1][j+1])
      neighbours.append(matrix[i+1][j-1])
      neighbours.append(matrix[i+1][j+1])
    except:
      pass
    return neighbours

  def remove_neighbours(neighbours):
  available = range(256)
    for i in neighbours:
       try: available.remove(i)
       except: pass
    return available

  #First initialize a random matrix without any condition
  matrix = array([[generate() for i in range(M)] for j in range(N)])

  #Apply the condition and modify the matrix
  for i in range(N):
    for j in range(M):
      neighbours = get_neighbours(i,j)
      available = remove_neighbours(neighbours)
      matrix[i][j] = generate()

  print matrix

 [[215  91   6 110 166 214 189  63  89 107]
  [  5 136  85 200 216  87 105 223 132 112]
  [179 159 116  70   3  44 238  13  41 226]
  [ 48   0  37 248 209 162 211  61  50  40]
  [237 122 135 253 219 196  92 173 163  26]]


text:
Q: How sorted() function is able to sort with custom key in python? Below is my code for for sorting the list.
def sorthelper(x):
     return x[1]

ls=[('data2',1),('data1',3),('data3',2)]

print(sorted(ls,key=sorthelper))

Here I am able to define custom key and accordingly list is sorted  and got the expected result.
What keeps intriguing  me  that how sorted() function is working internally with key to sort the list ? How value of variable key is used for sorting ?
My understanding is sorthelper() (defined by me for returing key) is getting called multiple time and returning the key
Is variable key is maintaining some sort of list of all returned keys to sort original list ? If yes then requesting to explain the working as well.
I have tried to search as much as possible but didn't found any such explanation of my question.
Also Please bear with me for my bad English writing. Thanks for the understanding.