text:
Q: Redirect with htaccess on apache I am trying to create a virtualhost and allow a htaccess to redirect (it is for a laravel project).
I am my environment is: ubuntu16.04 apache2.4.18 php7.0.4
And here is my /etc/apache2/sites-available/sub.domain.com.conf
<VirtualHost *:80>
    ServerName eatec.es
    ServerAlias webs.eatec.es

    ServerAdmin eloy@eatec.es
    DocumentRoot /var/www/html/sub.domain.com/public
    <Directory "/var/html/sub.domain.com/public">
            Options FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>
    #ErrorLog ${APACHE_LOG_DIR}/error.log
    #CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Things that I tried (and remember).
 1. The line of Directory I tried removing the quotes.
 2. The line of Directory I used too this  (removing the subdomain sub -with and without the quotes-).
 3. I move the Directory block from this file to /etc/apache2/apache2.conf (I paste the last of this type of blocks).
 4. I change the AllowOverride option on the  block (on the apache2.conf -with my Directory block in apache.conf but too on sub.domain.com.conf-).
 5. There was more micro changes, sure... but I don´t remember.
One more thing I tried was a2enmod rewrite but it doesn´t work (though I see mod_rewrite on the loaded modules if I make a phpinfo()).
This is my .htaccess content:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

It is the default htaccess file on a laravel project. It is supposed to redirect the index.php on the same folder. My folder structure is the next:
/var/www/html/sub.domain.com-------------> All The Project
/var/www/html/sub.domain.com/public---> htaccess and index.php
Any suggestion?? Thanks.


text:
Q: Monaco: saving preferences to localStorage In the editor you can resize the completions dropdown with a drag handle - this is important to me because the completion items can have wildly different widths.
The new width persists for the duration of that editor, but if you reload the page it's reset to the default.
I can implement this interface as suggested on https://github.com/microsoft/monaco-editor/issues/2241#issuecomment-764694521. However I would like to just rely on the default implementation but simply persist all settings to localStorage. It seems like that would be such a common case that there would be a simpler way of doing this without reimplementing storage.ts.
Is there a way of delegating to the default impl, or adding a listener for changes without overriding the default impl?

A: See an example of implementing monaco-editor with localstorage on Anglo
Check settings button (top right): https://sekedus.github.io/anglo/
or, you can test this basic example:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weird white gaps and horizontal scrolling issue It seems I'm having an issue with a design I'm working on. I'm using the kickstart HTML framework but I have a couple issues.
Firstly is that there is a very large white gap between the top of my page (logo, navbar) and the text.
Secondly I've tried to overlay the logo over the the navbar by using z-index. However it causes a negative horizontal scroll. I've tried to hide it by hiding overflow-x but it just doesn't seem like the best solution.
You can see the issues at http://jkr.me.uk/problem.html
Thanks,
John

A: Using position: relative on the logo makes it take up space that you're refferring to.
Instead, use float: right, or position it with position: absolute;

A: The issue with the white gap is the image. If you disable the position:relative property the image bottom will be touching the top margin of the fist header tag. A dirty fix for this would be something like margin-top: -200px on the first header or alternatively margin-bottom: -200px on the logo image. You could also use the method from the previous answerer.
As for the logo image overlaying the navbar, it does for me in both Chrome and IE 9.


text:
Q: hiding content on an MVC view after postback I have an MVC password reset form where the user enters their email and a password reset link is sent to them.
What I want to achieve is that when the email has successfully been sent then in the view I want to hide the email input box and display a message to say that an email has been sent.
What would be the best way to go about this?
Thanks

A: I used this in the end: -
@if (ViewBag.okay == "true"){

    @:Thanks, a password reset link Has been emailed to you.

}else{
    <form method="post">
        Please enter your email address <input type="text" name="email" id="email" style="width: 200px;" /> <input type="submit" value="Send Password Reset Link" />
    </form>
}

A: It would be argued that you should send a user to a completely different view once the email has been sent.
So in your code, once you have posted the form to your Controller, return the View of a confirmation page.
e.g.
if ( email.sent) {
    Return View("Confirmation");
}
else{
    Return View(emailModel);
}


text:
Q: What do you call the artwork you first see upon entering a place
*

*When you open the front doors of a building and enter, you would be greeted by this statue or painting.

*After you enter a campus by car, you would encounter this sculpture or fountain.

*An building's vestibule, or foyer would often have this prominent statue or painting.

*A cemetery would have a statue right behind its front gates.

*In the Museum of Natural History, Washington, D.C., it would be the elephant.

What would you call this artwork or decoration placement?

A: According to my wife, who is trained in Art History, this is a marquee piece from the word marquee meaning a sign placed at the entrance of a building.

A: Consider the term "centerpiece"

(n.) an item or issue intended to be a focus of attention: the tower is the centerpiece of the park.

Definition from New Oxford American Dictionary

The Fénykövi Elephant is the centerpiece of the Museum of Natural History.

A: If this piece of art puts you in the right mood for the rest of the exhibits, if it has the same functions as a starter course in a meal you could say:

The Fénykövi Elephant is the tone setter art piece of the Museum of Natural History.
Tone setter a person or thing that establishes the quality or
  character that is to be followed subsequently

or,  more figuratively, borrowing from music and drama:

The Fénykövi Elephant is the opening act of the Museum of Natural History.

A: I think that this artworks  usually  located in important parts of buildings so that they can be very visible and attract the attention of guests or visitors can be called: high spots or focal points.

A: How about the word frontispiece?

A: Centerpieces have specific names:

Nef is an extravagant table ornament and container used in the Middle Ages and Renaissance, made of precious metals in the shape of a
  ship
Pergne is a type of table centerpiece, usually made
  of silver, but may be made of any metal or glass or porcelain.

A collectors piece is generally prominently exhibited


text:
Q: Why is PCA sensitive to outliers? There are many posts on this SE that discuss robust approaches to principal component analysis (PCA), but I cannot find a single good explanation of why PCA is sensitive to outliers in the first place.

A: One of the reasons is that PCA can be thought as low-rank decomposition of the data that minimizes the sum of $L_2$ norms of the residuals of the decomposition. I.e. if $Y$ is your data ($m$ vectors of $n$ dimensions), and $X$ is the PCA basis ($k$ vectors of $n$ dimensions), then the decomposition will strictly minimize
$$\lVert Y-XA \rVert^2_F = \sum_{j=1}^{m} \lVert Y_j - X A_{j.} \rVert^2  $$
Here $A$ is the matrix of coefficients of PCA decomposition and $\lVert
 \cdot \rVert_F$ is a Frobenius norm of the matrix
Because the PCA minimizes the $L_2$ norms (i.e. quadratic norms) it has the same issues a least-squares or fitting a Gaussian by being sensitive to outliers. Because of the squaring of deviations from the outliers, they will dominate the total norm and therefore will drive the PCA components.


text:
Q: Проблема с чтением бинарных данных Всем привет. Возникла проблема при чтении бинарных данных( *.wav файл ) из stdin.
При чтении массива данных размером 65536(запись производится ровно такого размера), корректно читается только 4412 байт, после чтение прерывается так как приходит символ eof. Следовательно отсюда вопрос: каким образом это можно обойти ?
Cборка идёт под ОС WIN 10 x64
компилятор: msvc13
Привожу краткий код чтения и записи:
    std::array<char, SoundVector::Buffer::size> buf
    std::vector<char> input;

    std::memset(buf.data(), 0x00, buf.size());

    std::ifstream is(stdin);
    is.setf(std::ifstream::binary | std::ifstream::in);

    size_t ssize = is.read(buf.data(),buf.size()).gcount();

Запись:
std::ofstream of(stdout);
of.setf(std::ofstream::binary | std::ofstream::out);

std::array<char, SoundVector::Buffer::size> buf;
std::memset(buf.data(), 0x0, buf.size());
std::memcpy(buf.data() + offset, vectorSound.data(), sizeData);
of.write(buf.data(), buf.size());

vectorSound представляет из себя std::vector<short> c данными

P.S. Если записывать буффер, всебайты которого заполнены 0xff, то всё проходит хорошо.

A: Решение оказалось на уровне функций ОС.
Необходимо использовать конструкцию вида:
#if defined(WIN32) || defined(WIN64)
    if (_setmode(_fileno(stdin), _O_BINARY) == -1){
        sMode = false;
    }
#else
    if (setmode(fileno(stdin), O_BINARY) == -1){
        sMode = false;
    }
#endif

для чтения бинарного ввода данных.
Полный пример кода :
#if defined(WIN32) || defined(WIN64)
    if (_setmode(_fileno(stdin), _O_BINARY) == -1){
        sMode = false;
    }
#else
    if (setmode(fileno(stdin), O_BINARY) == -1){
        sMode = false;
    }
#endif

if ( !sMode ){
    throw std::runtime_error("*** ERROR *** Can not set binary mode read ");
}

std::array<uint8_t, sound::size> buf;
std::ifstream in(stdin);
in.read(reinterpret_cast<char*>(buf.data()), buf.size());
in.close();


text:
Q: I want to add all the images stored in a folder to a website in django How can I loop through images in a folder and add them to the website?
I want to make a website in which users can upload their photos and every other user can access it.
I want to create a website in which all the users can upload their images and every other user can access that image. All the uploaded images are stored in a media folder. What I want is to add all those images to the html file so that other users can access those images.
Please help me on displaying the images on the browser (html file)
Suppose I have a photo folder called image_post which stores the photos that users upload.
So, I just want to display all those images in a html file, and for that I think I should use a for loop:
{% extends 'basic_app/base.html' %}
{% block body_block %}
{% load static %}

{% if user.is_authenticated %}

this is the explore page

Go to the home page to post more images

  {% for images in post_images %}

      {{ images.title }}

  {% endfor %}
{% else %}

Please login first to have a look at all the images which are
posted by other users.

{% endif %}

{% endblock %}

I'm not sure if the above method is correct because we cannot use a for loop in html file to loop through the images of a folder.
Is there any method by which I can add the images to the html, like the google photos site where all the images are displayed?


text:
Q: How do I convert existing DOM element text to HTML element? I have an element that is already present on the page with HTML as a string.
How can I take the text from that element and convert it into HTML and re-inject it back into the existing element?
Everything I try re-renders the elements innerhtml as text.
window.current_element_content=window.current_element.previousElementSibling.innerHTML;
window.current_element.previousElementSibling.getElementsByTagName('div').innerHTML = window.current_element_content;

Example of the text when printed on the console.

            9:00 AM - 4:00 PM

            9:00 AM - 4:00 PM

            9:00 AM - 4:00 PM

            9:00 AM - 4:00 PM

            9:00 AM - 4:00 PM

            Closed

            Closed

A: You can see how to decode HTML entities from here: Unescape HTML entities in Javascript?
After that you can inject your code into a given element using .innerHTML property:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

$(document).ready(function(){
    var s = '<input type=button value="Inserted Button">';
    document.getElementById('my_place').innerHTML = htmlDecode(s);
});

In the above code jQuery is used only to trigger on document.ready.

A: You need to read out the textContent instead of the innerHTML, and then write that to innerHTML like you had it:
var element = current_element.previousElementSibling.querySelector('div');
element.innerHTML = element.textContent;

Note also that getElementsByTagName returns a NodeList which does not have innerHTML. Instead use querySelector.


text:
Q: Showing random divs using Jquery I have a list if divs which contain images. I need to randomly show 4 of these each time the page loads. Here's the code I'm starting with.

All of these will start as display:none, I'd like to take 4 of the divs at random and set them to display:block. I'm assuming I need to use "Math.random()" in there somewhere but not sure how JQuery does this. Any pointers would be appreciated.

A: This does what you need: http://www.jsfiddle.net/Yn2pn/1/
$(document).ready(function() {
    $(".Image").hide();

    var elements = $(".Image");
    var elementCount = elements.size();
    var elementsToShow = 4;
    var alreadyChoosen = ",";
    var i = 0;
    while (i < elementsToShow) {
        var rand = Math.floor(Math.random() * elementCount);
        if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
            alreadyChoosen += rand + ",";
            elements.eq(rand).show();
            ++i;
        }
    }
});

A: jQuery(function($){
  var sortByN = function(a,b){ a=a.n; b=b.n; return ab?1:0 };
  $.each( $('div.Image').map(
    function(){ return { div:this, n:Math.random() }; }
  ).get().sort(sortByN), function(i){
    if (i<4) $(this.div).show();
  });
});

Note that this will always show the divs in the same order as the original. Is that acceptable?

A: I find sorting them randomly then showing the first 4 to be the easiest, like this:
var divs = $("div.Image").get().sort(function(){
            return Math.round(Math.random())-0.5; //so we get the right +/- combo
           }).slice(0,4);
$(divs).show();

You can test it out here.  If you want to also randomize the order (not just which are shown), you already have them sorted so just append them to the same parent in their new order by changing this:
$(divs).show();
//to this:
$(divs).appendTo(divs[0].parentNode).show();

You can test that version here.


text:
Q: REST API - HTTP Status 415 - Cannot consume content type I have a javax.ws.rs.* REST endpoint which I am trying to upload a file with.  So the endpoint receives a document and a list of parameters.
It gets the following error:

HTTP Status 415 - Cannot consume content type

Question
Any ideas what I am doing wrong and how do I change my code to consume the document and paramaters?
Here is my code:
@POST
@Path("override")
@ApiOperation(value="Receives the override info for a trip ('overrideConclusion':'Approved'/'Reject').")
@ApiResponses({
        @ApiResponse(code=200, message="Success"),
        @ApiResponse(code=404, message="Not Found")
})
@Consumes(MediaType.MULTIPART_FORM_DATA)
//@Consumes({"text/*","application/*"})
@Produces(MediaType.APPLICATION_JSON)
public Response override(@HeaderParam("Authorization") String token, @Context HttpServletRequest request,
                         @ApiParam(required = true) byte[] data, @ApiParam(required = true) @QueryParam("tripId") Long tripId, @QueryParam("overrideReason") String overrideReason,
                         @QueryParam("overrideConclusion") String overrideConclusion, @QueryParam("authorizedApproverPersonId") Long authorizedApproverPersonId, @QueryParam("fileName") String fileName) {

I use Postman to test it:
The file to upload

The parameters

Full error:

HTTP Status 415 - Cannot consume content type

type Status report

message Cannot consume content type

description The server refused this request because the request entity is in a format not supported by
            the requested resource for the requested method (Cannot consume content type).

JBoss Web/7.0.1.Final


text:
Q: strlen doesn't work even with #include  in C Does it not return an int or something?
This is a snippet of my code:
int wordlength(char *x);

int main()
{
    char word;
    printf("Enter a word: \n");
    scanf("%c \n", &word);
    printf("Word Length: %d", wordlength(word));
    return 0;
}

int wordlength(char *x)
{
    int length = strlen(x);
    return length;
}

A: Change this part:
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);

to:
char word[256];       // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
                      // Note also that you don't need an & for a string,
                      // and note that %255s prevents buffer overflow if
                      // the input string is too long.

You should also know that the compiler would have helped you with most of these problems if you had enabled warnings (e.g. gcc -Wall ...)

Update: For a sentence (i.e. a string including white space) you would need to use fgets:

char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);

A: Function strlen is applied to strings (character arrays) that have the terminating zero. You are applying the function to a pointer to a single character. So the program has undefined behaviour.


text:
Q: Open a dialog from a hyperlink on text view - Android There is a way to put a link in some words on a textView and when i click on this word, a dialog is open.
Ex.: TextView --> Word A - Word B - Word C
When i click on Word A, show a Dialog with some options, and when i click on Word C open another dialog with another options.
i checked this link but my problem dont fits.
Open a popup/alert before opening a link in the browser when clicked on a textview
Anyone can help?

A: Suppose you are given a "this is a test" String and you wish to show dialog A for the substring "this" and dialog B for the substring "test". Consider the following method:
private static void applySpan(SpannableString spannable, String target, ClickableSpan span) {
  final String spannableString = spannable.toString();
  final int start = spannableString.indexOf(target);
  final int end = start + target.length();
  spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

The method takes a spannable, searches for the first target occurrence in it and applies the span to it. To show the spannable in a TextView, say from an Activity, you could do the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final SpannableString spannable = SpannableString.valueOf("this is a test");
    applySpan(spannable, "this", new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // show dialog A
        }
    });
    applySpan(spannable, "test", new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // show dialog B
        }
    });

    final TextView textView = new TextView(this);
    textView.setText(spannableString);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    setContentView(textView);
}

This is just a crude example, but it hopefully demonstrates a way to solve your problem.


text:
Q: Remove leading space from columns I have a spreadsheet with ( 99| 100) in the first cell(A2).
Using =(split(A2," ( | ) ",true)) in cell B2 I am getting 99 and using =CONTINUE(A2, 1, 2) i am getting 100 in cell C2.
There is a leading space in both B2 and C2 how do i remove it, i need to perform a few calculations on B2 and C2.
I've tried using trim but it isn't working.
=trim(split(B248," ( | ) ",true))
For testing purposes i have the following code in cell D2 value(B2) and i get the error Cannot parse text
https://docs.google.com/spreadsheet/ccc?key=0AmZqKT8_r5b_dDJxSnh2Y09ndzhGWm10clp0TXpYT3c&usp=sharing

A: I've tried to use the REGEXREPLACE function to get rid off the white spaces. It turns out that the ASCII character 160 isn't considered to be a white space but a  "Non-breaking space".
Therefore I used the CODE function to reveal the empty space (remove the open bracket first). For your particular setting, the following will work:
=SPLIT(SUBSTITUTE(B1,CHAR(160),""),"(|)")

A: I did a quick test and was able to get A2 and B2 to add without a problem.  Please see:
https://docs.google.com/spreadsheet/ccc?key=0AvRseCY0-3SVdEJybVU5U1pZYzdxX3NzNEVOekxFOVE&usp=sharing
Perhaps there is some column formatting on your values?


text:
Q: How can I choose "at least n" of each type of item in an ordered list I have a list of results (see JSON below), and I need to choose the top 10.  Here they're in json but I'm json_decoding them into an array like $coureValues["BUS1067"] == 117.1
I use arsort($courseValues) to get them in order like JSON below.
I need to choose the top 10, but I need to enforce a constraint of at least 4 "BUS", at least 2 "CMP", and at least 1 SAF.   So for example, if there is no SAFxxxx in the top 10, but there are 6 BUS and 2 CMP, I want to remove the lowest scoring BUS and add the highest scoring SAF.  In the end, all I want is a php array with the top 10, taking into consideration the constraints.
JSON
{
    "BUS1067": 117.1,
    "BUS1057": 86.06,
    "BUS1073": 79,
    "BUS1068": 74.08,
    "BUS1077": 74,
    "BUS1001": 71,
    "BUS1066": 68,
    "BUS1076": 67.05,
    "BUS1011": 64,
    "BUS1054": 64,
    "BUS1006": 63,
    "CMP1091": 62,
    "BUS1000": 60,
    "CMP1083": 59,
    "SAF1007": 58,
    "CMP1073": 56,
    "CMP1044": 55,
    "CMP1029": 55,
    "CMP1082": 53,
    "CMP1089": 50,
    "CMP1042": 48,
    "CMP1070": 46,
    "CMP1074": 45,
    "BUS1074": 31,
    "BUS1009": 20,
    "BUS1003": 10,
    "BUS1058": 1.09,
    "BUS1061": 1.07,
    "BUS1056": 1.04,
    "CMP1081": 1.03,
    "SAF1021": 1.01,
    "CMP1064": 0,
    "CMP1039": 0,
    "CMP1047": 0,
    "SAF1045": 0,
    "SAF1047": 0,
    "CMP1063": 0,
    "SAF1020": 0,
    "SAF1043": 0,
    "SAF1032": 0,
    "SAF1038": 0,
    "BUS1075": 0,
    "SAF1002": 0,
    "CMP1037": 0,
    "BUS1040": 0,
    "CMP1078": 0,
    "BUS1013": 0,
    "CMP1080": 0,
    "BUS1002": 0,
    "BUS1048": 0,
    "BUS1071": 0,
    "CMP1072": 0,
    "CMP1088": 0,
    "CMP1084": 0,
    "BUS1031": 0,
    "BUS1055": 0,
    "BUS1063": 0,
    "BUS1072": 0,
    "SAF1013": 0,
    "BUS1012": 0,
    "SAF1006": 0,
    "CMP1049": -20,
    "CMP1048": -20,
    "CMP1050": -20,
    "CMP1075": -20,
    "CMP1038": -925,
    "CMP1041": -929,
    "CMP1079": -933.98
    }

what I'm looking for is a simple, elegant way to do that.  I could "get it done", but the code that comes to mind is messy and unclear, and it seems that there's some general "algorithm" or sorting function that I should be using.
UPDATE: CODE:
as requested, here is my awful code to do a simple thing
<?php

$jsonWeights='{ "BUS1067": 117.1, "BUS1057": 86.06, "BUS1073": 79, "BUS1068": 74.08, "BUS1077": 74, "BUS1001": 71, "BUS1066": 68, "BUS1076": 67.05, "BUS1011": 64, "BUS1054": 64, "BUS1006": 63, "CMP1091": 62, "BUS1000": 60, "CMP1083": 59, "SAF1007": 58, "CMP1073": 56, "CMP1044": 55, "CMP1029": 55, "CMP1082": 53, "CMP1089": 50, "CMP1042": 48, "CMP1070": 46, "CMP1074": 45, "BUS1074": 31, "BUS1009": 20, "BUS1003": 10, "BUS1058": 1.09, "BUS1061": 1.07, "BUS1056": 1.04, "CMP1081": 1.03, "SAF1021": 1.01, "CMP1064": 0, "CMP1039": 0, "CMP1047": 0, "SAF1045": 0, "SAF1047": 0, "CMP1063": 0, "SAF1020": 0, "SAF1043": 0, "SAF1032": 0, "SAF1038": 0, "BUS1075": 0, "SAF1002": 0, "CMP1037": 0, "BUS1040": 0, "CMP1078": 0, "BUS1013": 0, "CMP1080": 0, "BUS1002": 0, "BUS1048": 0, "BUS1071": 0, "CMP1072": 0, "CMP1088": 0, "CMP1084": 0, "BUS1031": 0, "BUS1055": 0, "BUS1063": 0, "BUS1072": 0, "SAF1013": 0, "BUS1012": 0, "SAF1006": 0, "CMP1049": -20, "CMP1048": -20, "CMP1050": -20, "CMP1075": -20, "CMP1038": -925, "CMP1041": -929, "CMP1079": -933.98 }';

$courseValues=json_decode($jsonWeights,true);
arsort($courseValues);

$minRequired=array("BUS"=>4, "CMP"=>2, "SAF"=>1);
$pathLength=10;
$selected=array();

//get top results to satisfy minimum required
foreach ($minRequired as $courseType => $min) {
    foreach($courseValues as $key => $val){
        if(substr($key, 0, 3) == $courseType && $min)
        {
            $selected[$key]=$val;
            $min--;
            if($min==0)
                break;
        }
    }
}

//fill in the remaining with the top results
foreach($courseValues as $k=>$v){
    if(count($selected)<$pathLength)
    {
        if(!array_key_exists($k, $selected))
            $selected[$k]=$v;
    }
    else
        break;
}

arsort($selected);

foreach($selected as $k=>$v)
    echo "$k: $v<br>";

?>

A: $topten = array_keys( array_slice( arsort( $courseValues ), 0, 10) ); ?
okay, sorry for not reading the question thoroughly :)

A: I would start with creating a php array that has the prefixes as keys and the number needed as values like so:
$prefixes = array("BUS" => 4, "CMP" => 2, "SAF" => 1);

Then, since you need 10 elements and the sum of the values is 7, you pick 3 elements from any category. The loop then should be something like this:

Basic idea:
While you don't have 10 elements from the sorted list:
Get element.
Extract prefix.
If (the prefix exists in the prefix array, and the corresponding value is greater than 0),
    or (the sum of the remaining prefix values is less than the number of elements needed), then add it to your result.

In code:
$results = array();
foreach ($courseValues as $course => $courseValue) {
    $prefix = substr($course, 0, 3);
    if (isset($prefixes[$prefix]) && $prefixes[$prefix--] >= 0) {
        $results[$course] = $courseValue;
    }
    else if (array_sum($prefixes) < 10 - count($results)) {
        $results[$course] = $courseValue;
    }

    if (count($results) == 10) {
        break;
    }
}

Note: this is assuming $courseValues is sorted by $courseValue

A: MY SOLUTION:
Ok, I've got it down to one foreach loop.  here's the full solution:
$jsonWeights='{ "BUS1067": 117.1, "BUS1057": 86.06, "BUS1073": 79, "BUS1068": 74.08, "BUS1077": 74, "BUS1001": 71, "BUS1066": 68, "BUS1076": 67.05, "BUS1011": 64, "BUS1054": 64, "BUS1006": 63, "CMP1091": 62, "BUS1000": 60, "CMP1083": 59, "SAF1007": 58, "CMP1073": 56, "CMP1044": 55, "CMP1029": 55, "CMP1082": 53, "CMP1089": 50, "CMP1042": 48, "CMP1070": 46, "CMP1074": 45, "BUS1074": 31, "BUS1009": 20, "BUS1003": 10, "BUS1058": 1.09, "BUS1061": 1.07, "BUS1056": 1.04, "CMP1081": 1.03, "SAF1021": 1.01, "CMP1064": 0, "CMP1039": 0, "CMP1047": 0, "SAF1045": 0, "SAF1047": 0, "CMP1063": 0, "SAF1020": 0, "SAF1043": 0, "SAF1032": 0, "SAF1038": 0, "BUS1075": 0, "SAF1002": 0, "CMP1037": 0, "BUS1040": 0, "CMP1078": 0, "BUS1013": 0, "CMP1080": 0, "BUS1002": 0, "BUS1048": 0, "BUS1071": 0, "CMP1072": 0, "CMP1088": 0, "CMP1084": 0, "BUS1031": 0, "BUS1055": 0, "BUS1063": 0, "BUS1072": 0, "SAF1013": 0, "BUS1012": 0, "SAF1006": 0, "CMP1049": -20, "CMP1048": -20, "CMP1050": -20, "CMP1075": -20, "CMP1038": -925, "CMP1041": -929, "CMP1079": -933.98 }';
$courseValues=json_decode($jsonWeights,true);
arsort($courseValues);

$required=array("BUS"=>4, "CMP"=>2, "SAF"=>1,"Total" => 10);
$selected=array();
foreach($required as $type => $min)
    foreach($courseValues as $key => $val)
        if(count($selected)<$required['Total']
        &&($type=='Total'||(substr($key,0,3)==$type && $min-->0)))
            $selected[$key]=$val;

I'll leave it open in case anyone has a better idea


text:
Q: Running Hadoop/Storm tasks on Apache Marathon I recently came across Apache Mesos and successfully deployed my Storm topology over Mesos.
I want to try running Storm topology/Hadoop jobs over Apache Marathon (had issues running Storm directly on Apache Mesos using mesos-storm framework).
I couldn't find any tutorial/article that could list steps how to launch a Hadoop/Spark tasks from Apache Marathon.
It would be great if anyone could provide any help or information on this topic (possibly a Json job definition for Marathon for launching storm/hadoop job).
Thanks a lot

A: Thanks for your reply, I went ahead and deployed a Storm-Docker cluster on Apache Mesos with Marathon. For service discovery I used HAProxy. This setup allows services (nimbus or zookeeper etc) to talk to each other with the help of ports, so for example adding multiple instances for a service is not a problem since the cluster will find them using the ports and loadbalance the requests between all the instances of a service. Following is the GitHub project which has the Marathon recipes and Docker images: https://github.com/obaidsalikeen/storm-marathon

A: Marathon is intended for long-running services, so you could use it to start your JobTracker or Spark scheduler, but you're better off launching the actual batch jobs like Hadoop/Spark tasks on a batch framework like Chronos (https://github.com/airbnb/chronos). Marathon will restart tasks when the complete/fail, whereas Chronos (a distributed cron with dependencies) lets you set up scheduled jobs and complex workflows.
While a little outdated, the following tutorial gives a good example.
http://mesosphere.com/docs/tutorials/etl-pipelines-with-chronos-and-hadoop/


text:
Q: How to iterate through files and delete those older than x days but NOT in use So, I've been able to figure out bits of this myself but am having trouble piecing them together. I have a task I need to automate - I have folders filled with gigabytes of obsolete files, and I want to purge them if they meet two criteria.

*

*Files must not have been modified in the past 14 days - for this, I'm using find -

find /dir/* -type f -mtime +14

*And the files cannot be in use, which can be determined by

lsof /dir/*
I don't know bash quite well enough yet to figure out how to combine these commands. Help would be appreciated. I think I essentially want to loop through each line of output from find, check if it is present in output from lsof, and if not, rm -f -- however, I am open to alternative methodologies if they accomplish the goal!

A: The following should work:
for x in `find <dir> -type f -mtime +14`; do lsof "$x" >/dev/null && echo "$x in use" || echo "$x not in use" ; done

Instead of the echo "$x not in use" command, you can place your rm "$x" command.
How does it work:

*

*find files, last modified 14 days or longer ago:

find <dir> -type f -mtime +14

*

*loop over items in a list:

for x in <list>; do <command>; done

*

*execute command 2 if result of lsof is 0, else execute command 1:

lsof "$x" && <command 1> || <command 2>
This relies on the lazy evaluation of Bash to execute command 1 or command 2.
On my system (Ubuntu 14.04) this works with file names with spaces in them and even for file names with ? and * in them.
This is however no guarantee that it will work with every shell on any system. Please test before replacing the echo command with the rm command.

A: Use the -exec action in find to execute a command for each file. This executes a program with arguments; if you need a more complex command (with variable expansion, conditionals, etc.) then you need to invoke a shell explicitly:
find /dir/* -type f -mtime +14 -exec sh -c '
  if …; then
    rm "$0"
  fi
' {} \;

To test whether a file is currently open, the most straightforward way is to call fuser.
find /dir/* -type f -mtime +14 -exec sh -c '
  if ! fuser "$0" >/dev/null 2>/dev/null; then
    rm "$0"
  fi
' {} \;

Beware that just because a file hasn't been modified in a long time and isn't currently open doesn't mean that it isn't useful. I recommend at least testing that the file hasn't been read in a while; this can be tested with the access time, but beware that Linux systems don't update the access time reliably. (Whether they do, and how often, depends on the kernel version, on the mount options, and on how the access time compares with the modification time.)
I recommend reviewing the files before deleting them.
find /dir/* -type f -mtime +14 -atime +14 -exec sh -c '
  if ! fuser "$0" >/dev/null 2>/dev/null; then
    echo "$0"
  fi
' {} \; >files-to-delete-potentially.txt

Review the file names, and erase the ones you want to keep. Then to remove them all, assuming none of the file names contains a newline character, you can use
<files-to-delete-potentially.txt tr '\n' '\0' | xargs -0 rm

A: Instead of using lsof which has a nightmare tangle of options and interesting ouput to parse, I suggest using the -atime or -amin options to find.  These let you specify the file access time in days or seconds, respectively.
Instead of using another process to find out if a file is currently "in use", you can check to see if was accessed within the last N seconds or days.
The following command lists all files which were modified more than 14 days a ago and accessed less than 60 seconds ago.
find "$dir" -type f -mtime +14 -amin -60

To remove the files that match this criteria, you can use find's -exec command ; command.  The strange thing about this is that you specify each command argument separately to find and terminate with a semicolon (;).  If {} appears in any argument, it is replaced by the name of the name of the file being processed.
This command removes all files created more than 14 days ago, and not accessed within the last 60 minutes:
find "$dir" -type f -mtime +14 -amin -60 -exec rm '{}' \;


text:
Q: HttpWebRequest.EndGetRequestStream issue in Silverlight I am using HTTPWebRequest to post data to a webserver in Silver light 3.0, here is my code
    public void MakePostRequest()
    {

            // Create a new HttpWebRequest object.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mywebsite.com/somepage.php");

            // Set the ContentType property.
            request.ContentType="application/x-www-form-urlencoded";
            // Set the Method property to 'POST' to post data to the URI.
            request.Method = "POST";

            // Start the asynchronous operation.
            request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);

           // Keep the main thread from continuing while the asynchronous
            // operation completes. A real world application
            // could do something useful such as updating its user interface.
            allDone.WaitOne();

            // Get the response.

            request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
    }

    private static void ResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = resp.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        // Close the stream object.
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse.
        resp.Close();
    }

    private static void ReadCallback(IAsyncResult asynchronousResult)
    {
            IDictionary<string, string> objDictionary = new Dictionary<string, string>();
            objDictionary.Add("action", "login");
            objDictionary.Add("login", "myid@yahoo.com");
            objDictionary.Add("password", "pass123");

            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the operation.
            // This line of code making the blocking call???
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            Stream memStream = new System.IO.MemoryStream();

            byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            foreach (KeyValuePair<string, string> entry in objDictionary)
            {
                string key = entry.Key;
               string value = entry.Value;
                string formitem = string.Format(formdataTemplate, key, value);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);

        //Writing the name value pair
        postStream.Write(tempBuffer, 0, tempBuffer.Length);

        memStream.Close();
        postStream.Close();

}

The problem I am facing is that the line Stream postStream = request.EndGetRequestStream(asynchronousResult); is making some blocking call, and whole of my application seems to be hanged.. however I can open the same webpage from the browser... Why it is so?

A: Remove your use of the Wait handle allDone.  Instead move your call to BeginGetResponse to the end of the ReadCallback method.  In effect you chain the calls:-
BeginGetRequest->ReadCallback->BeginGetResponse->ResponseCallback

BTW, You are using a Content-Type of "application/x-www-form-urlencoded". However you appear to be attempting to encode a Multipart entity body in which case your content type should be "multipart/form-data".

A: It seems that this isn't all of your code since there is this:
 allDone.WaitOne();

That would be the source of your blocking call most likely.

A: If all you want to do is POST and name/value pair collection to the server, just use WebClient. In two lines of code you can achieve what you want.
Of course, it wont give you fine grained control, like being able to implement async, but in the end, it will get the job done.

A: seems or might be, you are going to get access to an URL that need 'permission'. The Web browser store 'cookie' or any to reside your access permission, but your application are not. Once you get login to that URL using browser, you get that access permission only for your browser application, and cannot derived to another application.


text:
Q: Simple html link wont work I'm having difficulty pinpointing whats preventing the following link from working.
I chose a random link (w3schools) to test it before I linked it to what its meant for.
I thought the problem may have to do with the CSS.

ul {
  font-family: 'Montserrat';
  font-size: 15px;
  color: #994f00;
}

#innerNav {
  /*adding a relative or absolute here will break sticky*/
  background-color: black;
  color: white;
  left: 0px;
  overflow: hidden;
  height: 1300px;
  width: 150px;
  z-index: -1;
  white-space: nowrap;
  list-style-type: none;
}
<!DOCTYPE html>

The Door

Mr Pointy

Block Rain

But even when I comment out the last line of the innerNav, the link still doesn't work (clicking it doesn't open anything).
Any ideas?
also my git files for this is:
Portfolio

A: The problem has nothing to do with the link and everything to do with the fact that you have the z-index of your #innerNav set to -1.  So you are covering your navigation up with the .wrapper.  So just remove the z-index from the innerNav completely or just set it to 1.
PS the markup for this is invalid as well you may want to look up the correct markup for an unordered list it should be as follows:

For some reason you have it backwards with
 nested inside of
 it should be the other way around.


text:
Q: Destroy SWF DOM in swfupload I am using swfupload for uploading files and I have this problem:

*

*In Internet Explorer, I have to use destroy(). Otherwise it crashes
http://demo.swfupload.org/Documentation/#destroy

*In Firefox, if I use destroy(), it crashes.
So the solution is to detect browser type and only destroy in Internet Explorer. Is it how it works? Or did I do something wrong? I mean is the destroy() function only for IE??

A: I know this is late but try wrapping the SWF in another element and destroy that element.


text:
Q: Centering 2 elements inside Bootstrap column So if i have only one element, in my case a button, i just add the .center-block class to that element and it is centered.

        <button type="submit" class="btn btn-primary center-block">Element 1</button>

But what if i have two elements? I tried to wrap them in a div and added a .center-div class like so:
HTML:

            <button type="submit" class="btn btn-primary">Element 1</button>
            <button type="submit" class="btn btn-primary">Element 2</button>

CSS:
.center-div {
    display: inline-block;
    margin-right: auto;
    margin-left: auto;
}

.center-div is almost the same as .center-block except that i used display: inline-block; instead of display: block; so that it fits the contents size.
Sadly it doesn't work. Unless i change it to display: block; and assing it a fixed width like 200px.
What am i missing here?

A: Margin right and left set to auto only works if the width of the element is fixed.
As your center-div is now an inline-block, you need a text-align: center property on its container.

I used a style attribute for convenience in this example

A: see if this helps:
.center-div {
width: 50%;
border: 1px solid black;
display: inline-block;
margin:0 auto;
text-align: center;
}
body{
text-align: center;
}


text:
Q: Populate empty attribute table from constantly growing CSV in QGIS I have a Python script running that will generate a line feature from a point depending on a degree of rotation around that point. I have a non-spatial CSV setup to get fed this rotation data from another source. The CSV will be constantly updating and generating new data, and will generate new lines in QGIS as they arrive.
As you might have inferred, I want this CSV to effectively act as a dynamic attribute table for this line feature class, but I'm having trouble figuring out the right way to perform a table join on the line feature. I have an "ID" and a "LOB" (rotation) field set up in both the CSV and the empty attribute table, so my expectation was that the tables would join and the CSV data would carry over and appear in the table. But this is not the case, as I somehow need to get the number of rows in both "ID" columns to match prior to the join. But this doesn't seem like a solution, as the number of columns will be rapidly changing.
Are there any reasonable solutions to this dilemma? This is very easy to do with spatial text-delimited point layers, but mind boggling with non-spatial data for lines.
Below is a screenshot for reference. The top table is the CSV, the bottom is the attribute table it's "joined" to. I need the number of rows in the attribute table to match that of the CSV.


text:
Q: Why does UITextFIeld return optional value in Swift? Im using a UITextField to enter numbers but when I enter the first number it ends up printing nil. Then when I enter other numbers it prints out the number I inputed but with an optional return type. Why does that happen?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //convert string into number
    let input = (numberLabel.text! as NSString).integerValue

    //find answer to label when added by 1111
    let answer = input + 1111
    print(answer)

    let numberText = Int(numberField.text!)
    print("This is number text: \(numberText)

    if answer == numberText {
        print("correct")
        //if user gets answer correct
    } else {
        //if user gets answer incorrect
    }
}

A: The reason is probably because you're using shouldChangeCharactersIn which doesn't indicate the change in the character until the second character.  Ideally you want the user to be notified of the correct answer after they complete the answer and submit it, in which case you want to use something like textFieldDidEndEditing:
class MyVC: UIViewController, UITextFieldDelegate {
    let textField = UITextField()
    var numberLabel: UILabel {
        let label = UILabel()
        label.text = "100"
        return label
    }
    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(textField)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            textField.widthAnchor.constraint(equalToConstant: 200),
            textField.heightAnchor.constraint(equalToConstant: 100)
        ])
        textField.delegate = self

        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        button.tag = 1
        button.backgroundColor = .black
        button.setTitle("Answer", for: .normal)
        self.view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.leadingAnchor.constraint(equalTo: textField.trailingAnchor),
            button.widthAnchor.constraint(equalToConstant: 200),
            button.heightAnchor.constraint(equalToConstant: 100)
        ])

    }

    @objc func buttonPressed(_ sender: UIButton!) {
        if case let tag = sender.tag, tag == 1 {
            textField.resignFirstResponder()
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        //convert string into number
        let input = (numberLabel.text! as NSString).integerValue

        //find answer to label when added by 1111
        let answer = input + 1111
                print(answer)

        if let numberText = Int(textField.text ?? "0") {
            print("This is number text: \(numberText)")

            if answer == numberText {
                //if user gets answer correct
                print("correct")
            } else {
                //if user gets answer incorrect
                print("wrong")
            }
        }
    }

}

A: UITextFied text property will never return nil. Its default value is an empty string. What is returning nil is the Int string initializer. Regarding text property optionality IMO is intentional to allow you to assign an optional string without the need to unwrap it first.
let numberText = Int(textField.text!) ?? .zero


text:
Q: I would appreciate a little help in understanding the error in pine script I'm trying to get a value of 5 if the chart is in a 5 minute time frame and every hour the clock shows 5 minutes, For example: 13:05, 14:05
I wrote this line:
res=  (timeframe.period == '5') and (minute == '5') ? 5 :na

This is the error I am getting :

Cannot call 'operator ==' with argument 'expr1'='5'. An argument of
'literal string' type was used but a 'series int' is expected

I tried to write it that way too:
res=  (timeframe.period == '5') ? (minute == '5') ? 5 :na

And I got this error:

Mismatched input 'end of line without line continuation' expecting ':'

I would like to know if it is possible to write it differently and if it is even possible?

A: Have you tried res= (timeframe.period == '5') and (minute == 5) ? 5 :na?
It seems to be that you're trying to compare with a string a value of an int array

A: minute returns an int and not a string.

minute(time) → series int

So, you should be doing res=  (timeframe.period == '5') and (minute == 5) ? 5 :na
Always consult with the reference manual when in doubt.


text:
Q: Java TicTacToe game does not display correctly OK, so I'm writing a game of Tic Tac Toe. I've got the whole program written, but I can't understand why it's not displaying correctly?
import java.util.Scanner;

public class TicTacToeGame {

        //constants for game options
        static final int STANDARD_GAME = 0;
    static final int QUIT = -1;

    //constants for the number of rows and columns in a standard TicTacToe grid
    static final int STANDARD_GRID_ROWS = 3;
    static final int STANDARD_GRID_COLUMNS = 3;

    //two dimensional array to represent a TicTacToe grid
    static char[][]grid = new char[STANDARD_GRID_ROWS][STANDARD_GRID_COLUMNS];

    //Scanner for input
    static Scanner keyboard = new Scanner(System.in);

//***RUN STANDARD GAME******************************************************

    static void runStandardGame() {

        int position = QUIT;
        char playerChar = 'X';
        boolean isGameOver = false;

        fillPosition();

        System.out.println("Choose a position to play.\n");

        displayGrid();

        do {
            System.out.print("Player " + playerChar +
             " (Enter a position or " + QUIT + " to resign): ");
            position = keyboard.nextInt();

            System.out.println("Choose a position to play.\n");

            displayGrid();

            if(isWin()) {
                System.out.print("\nPlayer " + playerChar +"WINS!!!\n");
                isGameOver = true;
            }
            else if (isTie()) {
                System.out.print("\nTIE.\n");
                isGameOver = true;
            }
            else {
                //switch players because one of the players has just played
                //and not won;, so, it is the other player's turn
                if (playerChar == 'X') {
                    playerChar = 'O';
                }
                else{
                    playerChar = 'X';
                }
            }
           }while(!isGameOver && position != QUIT);

    }//end of runStandardGame

//***PLAY*******************************************************************

    static void play(int cell, char playerChar) {
        //the player has entered a number 1 through 9 for the position they want
        //to play, so, figure out which row and which column of the array this     is
        //For example, if the player wants to play 'X' in position 7, this means
        //the 'X' must go into row 2, column 0 of the array
        int row = 0;
        int column = 0;

        if (cell > 0 && cell <= (STANDARD_GRID_ROWS * STANDARD_GRID_COLUMNS)){
            row = (cell - 1) / STANDARD_GRID_ROWS;
            column = (cell - 1) % STANDARD_GRID_COLUMNS;
            grid[row][column] = playerChar;
        }
    }

//***IS WIN*****************************************************************

    static boolean isWin() {
        boolean isWin = false;

        if (isRowWin() || isColumnWin() || isDiagonalWin()){
            isWin = true;
        }

        return isWin;
    }

//***IS TIE*****************************************************************

    static boolean isTie() {
        boolean isTie = false;

                if(!isRowWin() || !isColumnWin() || !isDiagonalWin()){

        int count = 9;

        for (int row = 0; row < 3; row ++){

            for (int column = 0; column < 3; column ++){
                if (grid[row][column] == 0)
                    count --;
                }
        }

        if (count == 0)
            {
            System.out.println("\nSorry, this game is tied.  Better luck next time!");
            return true;
            }
        }
        return isTie;
    }

//***IS ROW WIN**********************************************************

    static boolean isRowWin() {

        boolean isRowWin = false;
        int column = 0 ;

        for (int row = 0;row < STANDARD_GRID_ROWS && !isRowWin; row++) {

            //if the three array elements on the same row are equal,
            //then one of the players has either three 'X's on that
            //row, or three 'O's, and therefore, has won
            if (grid[row][column] == grid[row][column+1] &&
                grid[row][column+1] == grid[row][column+2]){
                    isRowWin = true;
                }
        }

        return isRowWin;

    }

//***IS COLUMN WIN**********************************************************

    static boolean isColumnWin() {

        boolean isColumnWin = false;

        int row = 0 ;

        for (int column = 0;column < STANDARD_GRID_COLUMNS && !isColumnWin;      column++) {

            //if the three array elements on the same row are equal,
            //then one of the players has either three 'X's on that
            //row, or three 'O's, and therefore, has won
            if (grid[row][column] == grid[row+1][column] &&
                grid[row+1][column] == grid[row+2][column]){
                    isColumnWin = true;
                }
        }

        return isColumnWin;

    }

//***IS DIAGONAL WIN********************************************************

    static boolean isDiagonalWin() {

        boolean isDiagonalWin = false;
        int row = 0;
        int column = 0;
        if(
                (grid[row][column] == grid[row+1][column+1] &&
            grid[row+1][column+1] == grid[row+2][column+2])||
            (grid[row][column+2] == grid[row+1][column+1] &&
            grid[row+1][column+1] == grid[row+2][column])){
                isDiagonalWin = true;
            }

        return isDiagonalWin;

    }

//***GET USER CHOICE********************************************************

    static int getUserChoice() {
        int choice;

        System.out.print("Please enter your choice: ");
        choice = keyboard.nextInt();

        return choice;

    }

//***FILL POSITIONS*********************************************************

    static void fillPosition(){

        char position = '1';

                for (int row = 0; row < STANDARD_GRID_ROWS; row++) {
                    for (int column = 0; column < STANDARD_GRID_COLUMNS; column++) {
                         grid[row][column] = (char) ('1' + row*STANDARD_GRID_COLUMNS + column);
                    }
                }

        }

//***DISPLAY GRID***********************************************************

    static void displayGrid() {

    System.out.println((grid[0][0]) + " | " + (grid[0][1]) + " | " + (grid[0][2]));
    System.out.println("---------");
    System.out.println((grid[1][0]) + " | " + (grid[1][1]) + " | " + (grid[1][2]));
    System.out.println("---------");
    System.out.println((grid[2][0]) + " | " + (grid[2][1]) + " | " + (grid[2][2]));

    }

//***END********************************************************************

}//end of class

In the game, I want it to display the board as:
 1 | 2 | 3
-----------
 4 | 5 | 6
-----------
 7 | 8 | 9

Regardless of what I choose, or where, it repeatedly ask me to make a choice...Even though I will purposely make one win, or make them tie to get it to end, it's neverending...is that a logical error?
ALSO, I deleted some of the code that I know is correct so it will be easier to read and understand.

A: The do-while loop in fillPosition only gets executed once. In the condition row<4 && column<4 && position<10, the boolean position<10 will initially be false. Because position is a char,
position < 10

is interpreted as
(int)position < 10

(int)position = (int)'2' = 49 (position is '2' after the first loop iteration), which is not less than 10, so this condition is false, meaning the entire loop-condition is also false - and hence the loop ends.
So, the '1' gets placed correctly but nothing else does (it's a do-while loop, so it executes at least once regardless of its condition).

A: You are trying to compare a char (column) with 10 which is a number, the ascii number for the character '1' is bigger than then, so the loop is breaking

A: Your fillPosition() method is not correct. It should look sth like this:
    static void fillPosition(){
        for (int row = 0; row < STANDARD_GRID_ROWS; row++) {
            for (int column = 0; column < STANDARD_GRID_COLUMNS; column++) {
                grid[row][column] = (char) ('1' + row*STANDARD_GRID_COLUMNS + column);
            }
        }

    }

A: You're fillPosition do-loop's exit condition is wrong...
I'd also advise against using character arithmetic, better to use an int and Interger.toString(int), but that's just me.
Take a loop at using compound for loops to fill the grid array, the outer begin used for the rows and the inner for the columns, for example


text:
Q: using a service into another service I wrote a service for a custom confirmation dialog for delete items from database and page. also i have an another service for the CRUD operations.
my confirmation service:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AlertService {
  subject = new Subject<any>();
  constructor() {}
  confirmThis(message: string, siFn: () => void, noFn: () => void, className) {
    this.setConfirmation(message, siFn, noFn, className);
  }
  setConfirmation(message: string, siFn: () => void, noFn: () => void,    className) {
    const that = this;
    this.subject.next({ type: 'confirm',
       text: message,
       siFn: function(){
          that.subject.next(); // this will close the modal
          siFn();
       },
       noFn: function(){
          that.subject.next();
          noFn();
       }
    });
  }
  getMessage(): Observable<any> {
     return this.subject.asObservable();
  }
}

and in my component:
confirmDeleteContent(id, i) {
const that = this;
this.alertService.confirmThis('Are you sure?', function(){
  alert('Yeap');
  that.deleteContent(id, i);
}, function(){ alert('No'); }, this);
}

and deleteContent function:
deleteContent(id, i) {
this.service.deleteContent(id)
  .subscribe(
    (response) => {
      this.contents.splice(i, 1);
      console.log(JSON.stringify(response));
    },
    (error) => {
      console.log(error);
    }
  );
}

the problem is when i call confirmDeleteContent function i give this error in console:
EXCEPTION: Error in ./AlertComponent class AlertComponent - inline template:16:14 caused by: this is undefined  error_handler.js:54
ORIGINAL EXCEPTION: this is undefined

How can i handle this?
thanks!


text:
Q: (Js puro) função que filtre array de maneira que retorne arrays unicos com elementos distintos var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

Ex: os arrays abaixo todos seriam eliminados pois possuem elementos repetidos dentro
[3,4,7,9,4]
[3,6,4,7,7]
[6,7,9,4,9]
[6,7,9,5,6]

Nos casos abaixo os elementos são distintos porem eles se repetem com posicionamento diferente em um outro array, nesse caso um seria eliminado e outro permaneceria se tornando unico dentro do array principal
[3,6,4,7,9]
[3,4,7,9,6]

[3,6,4,8,7]
[3,6,4,7,8]

A: Acho que isso resolve o seu problema:

var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

// Eliminando arrays com elementos repetidos
let withoutDuplicates = list.filter(l => (new Set(l)).size === l.length)

// Função diff (traz a diferença entre 2 arrays)
Array.prototype.diff = function (a) {
  return this.filter((i) => a.indexOf(i) === -1)
}

let duplicatedKeys = []

// Percorrendo os arrays restantes
withoutDuplicates.forEach((a, i) => {
  // Fazendo outro loop para percorrer os arrays restantes novamente
  withoutDuplicates.forEach((b, x) => {
    // Checando se os elementos comparados não são o mesmo elemento
    // e checando se a diferença entre eles é igual a 0 (se for significa
    // que eles possuem os mesmo valores, mesmo em posições diferentes)
    if(i !== x && a.diff(b).length === 0) {
        // Verifica se o elemento a e b não foram incluídos no array duplicatedKeys
        if(duplicatedKeys.indexOf(a) === -1 && duplicatedKeys.indexOf(b) === -1) {
            // Armazena o elemento no array duplicatedKeys
            duplicatedKeys.push(a)
        }
    }
  })
})

// Removendo as chaves duplicadas que foram armazenadas no array duplicatedKeys
withoutDuplicates = withoutDuplicates.filter(a => duplicatedKeys.indexOf(a) === -1)

console.log(withoutDuplicates)

Quando chegar em casa edito e tento explicar melhor o que foi feito...

A:

var lista = [
  [3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
  [3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
  [3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
  [3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
  [3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
  [3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
  [3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
  [6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
  [6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
  [6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
  [6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
  [6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
  [6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
  [6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
]

// 1º Passo - Remover os arrays com itens repetidos.
lista = lista.filter(function (sublista) {
  return sublista.every(function (item, indice) {
    return sublista.indexOf(item) == indice
  })
})

// 2º Passo - não é possivel comparar dois Objetos por valor no JavaScript.
// desta forma, [1, 2, 3] != [1, 2, 3]. porém como se trata de um array de numeros,
// é possivel converter o mesmo para uma string de base64 com a função btoa
// para que que a string base64 para arrays com os mesmos numeros seja igual,
// devemos ordenar os arrays com a função sort, antes de obter a string base64.
// por exemplo, [3, 4, 5, 7, 9] será convertido para "Myw0LDUsNiw4"
var indices = {}
var binarios = lista.map(function (sublista, indice) {
  return { indice: indice, binary: btoa(sublista.sort()) }
})

// 3º Passo - obtendo o indice da primeira ocorrencia de cada array,
// assim como a quantidade de ocorrencias de arrays com os mesmo elementos.
binarios.forEach(function (item, indice) {
  if (indices[item.binary]) {
    indices[item.binary].total++
  } else {
    indices[item.binary] = { indice: indice, total: 1 }
  }
})

// 4º Passo - Filtrar os arrays, para exibir apenas os arrays cujo a conjunto numerico é unico.
lista = Object.values(indices).filter(function (item) {
  return item.total == 1
}).map(function (item) {
  return lista[item.indice]
})

console.log(lista)

A: Ao fazer o teste de mesa, resulta nas seguintes arrays:
[3,4,7,9,5]
[3,4,7,9,8]
[3,6,4,7,5]
[3,6,4,8,5]
[3,6,4,8,7]
[6,7,9,3,4]
[6,7,9,3,8]
[6,7,9,4,8]
[6,7,9,5,3]
[6,7,9,5,4]
[6,7,9,5,8]

O código abaixo filtra da forma que deseja, substituindo a array original list com os elementos filtrados:

var list =[
[3,4,7,9,4],[3,4,7,9,5],[3,4,7,9,6],[3,4,7,9,7],
[3,4,7,9,8],[3,4,7,9,9],[3,4,8,3,3],[3,4,8,3,4],
[3,4,8,3,5],[3,4,8,3,6],[3,4,8,3,7],[3,4,8,3,8],
[3,4,8,3,9],[3,6,4,6,7],[3,6,4,6,8],[3,6,4,6,9],
[3,6,4,7,3],[3,6,4,7,4],[3,6,4,7,5],[3,6,4,7,6],
[3,6,4,7,7],[3,6,4,7,8],[3,6,4,7,9],[3,6,4,8,3],
[3,6,4,8,4],[3,6,4,8,5],[3,6,4,8,6],[3,6,4,8,7],
[6,7,8,8,7],[6,7,8,8,8],[6,7,8,8,9],[6,7,8,9,3],
[6,7,8,9,4],[6,7,8,9,5],[6,7,8,9,6],[6,7,8,9,7],
[6,7,8,9,8],[6,7,8,9,9],[6,7,9,3,3],[6,7,9,3,4],
[6,7,9,3,5],[6,7,9,3,6],[6,7,9,3,7],[6,7,9,3,8],
[6,7,9,4,5],[6,7,9,4,6],[6,7,9,4,7],[6,7,9,4,8],
[6,7,9,4,9],[6,7,9,5,3],[6,7,9,5,4],[6,7,9,5,5],
[6,7,9,5,6],[6,7,9,5,7],[6,7,9,5,8],[6,7,9,5,9],
];

var list2 = list.map(function(v){ return v.join('') });

for(var item in list2){
   list2[item] = list2[item].split('').sort().join('')+" "+item;
}

for(var item in list2){
   var m = list2[item].match(/^\d+/)[0];
   for(var x=0; x<m.length; x++){
      var r = m.match( new RegExp(m[x], 'g') ).length;
      if(r > 1){
         list2[item] = list2[item].replace(m+' ','');
         break;
      }
   }
}

var list2_str = list2.join(); // converto para string

for(var item of list2){
   var padrao = item.match(/^\d+\s/);
   var m = list2_str.match( new RegExp(padrao, 'g') );
   if(m){
      for(var x=1; x<m.length; x++){
         list2_str = list2_str.replace(m[x], '');
      }
   }
}

list2_str = list2_str.split(','); // converto para array

list2_str.filter(function(v){
   if(v.length < 7) list[v] = null;
});

list = list.filter(function(v){ return v; });

// daqui pra baixo apenas para mostrar na div
var div = document.querySelector("#resultado");

for(var item in list){
    div.innerHTML += item+": ["+list[item]+"]
";
}


text:
Q: Calendar calculation problems My code is bellow, the problem is i need it to be able to make the calendar as if it was real for whatever input the user says, so if the users says i want it to start on Monday, in the year 1776, then it will work for that. How it works now is, it is only able to start on Sunday and every month start on Sunday so if the month before ends on Monday the calendar should begin the next month on Tuesday but it goes back to Sunday if thats what the user input anyone got a fix for this?
package calendaryear;
import java.util.Scanner;
public class calendaryear {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String month;
    String day;
    Scanner userinput = new Scanner(System.in);
    //enter the day!
    System.out.print("Enter day [0 is for Sunday, 1 is for moneday continued]:");
    int d = userinput.nextInt();
    //enter a year!
    System.out.print("Enter a year:");
    int y = userinput.nextInt();
    // for loop for 12 months!
    for (int m = 1; m <= 12; m++){
        switch (m) {
            case 1:
                month = "\n\t January";
                break;
            case 2:
                month = "\n\t February";
                break;
            case 3:
                month = "\n\t March";
                break;
            case 4:
                month = "\n\t April";
                break;
            case 5:
                month = "\n\t May";
                break;
            case 6:
                month = "\n\t June";
                break;
            case 7:
                month = "\n\t July";
                break;
            case 8:
                month = "\n\t August";
                break;
            case 9:
                month = "\n\t September";
                break;
            case 10:
                month = "\n\t October";
                break;
            case 11:
                month = "\n\t November";
                break;
            case 12:
                month = "\n\t December";
                break;
            default:
                month ="";
                }

        System.out.printf("%" + (34 + month.length()) / 2 + "s %s\n", month, y);
        System.out.println(String.format("%39S", "").replace(' ', '-'));
        System.out.printf("%-6s%-6s%-6s%-6s%-6s%-6s%-6s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

        int l = 30 + ((m + (int)(m / 8.0)) % 2);
        if (m == 2) {
            if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)){
                l = 29;
            }else {
                l = 28;
            }
        }
        d = (d) % 7;
        switch (d) {
            case 0:
                day = "Sunday";
                break;
            case 1:
                day = "Moneday";
                break;
            case 2:
                day = "Tuesday";
                break;
            case 3:
                day = "Wednesday";
                break;
            case 4:
                day = "Thursday";
                break;
            case 5:
                day = "Friday";
                break;
            case 6:
                day = "Saturday";
                break;
            default:
                day = "";
        }
        if (d != 0) {
            System.out.print(String.format("%" + 6 * d + "s", ""));

        }

for (int i = 1; i <= l; i++)
{
System.out.printf("%-6d", i);
if (i % 7 == 0)  //<-- this part
{
   System.out.println();
}
day += 1;
}
        System.out.print("");

    }
}

}

A: Your logic was partly correct. There were a few problems:

*

*To simplify, I replaced the modulus(%) operator with a counter.

*day += 1  is incorrect. That concatenates. You want d += 1

*You need to print the correct number of blank days before you print Day 1

Here's the corrected program:
    public static void main(String[] args) {
    String month;
    String day;
    Scanner userinput = new Scanner(System.in);
    //enter the day!
    System.out.print("Enter day [0 is for Sunday, 1 is for moneday continued]:");
    int d = userinput.nextInt();
    //enter a year!
    System.out.print("Enter a year:");
    int y = userinput.nextInt();
    // for loop for 12 months!
    for (int m = 1; m <= 12; m++){
        switch (m) {
        case 1:
            month = "\n\t January";
            break;
        case 2:
            month = "\n\t February";
            break;
        case 3:
            month = "\n\t March";
            break;
        case 4:
            month = "\n\t April";
            break;
        case 5:
            month = "\n\t May";
            break;
        case 6:
            month = "\n\t June";
            break;
        case 7:
            month = "\n\t July";
            break;
        case 8:
            month = "\n\t August";
            break;
        case 9:
            month = "\n\t September";
            break;
        case 10:
            month = "\n\t October";
            break;
        case 11:
            month = "\n\t November";
            break;
        case 12:
            month = "\n\t December";
            break;
        default:
            month ="";
        }

        System.out.printf("%" + (34 + month.length()) / 2 + "s %s\n", month, y);
        System.out.println(String.format("%39S", "").replace(' ', '-'));
        System.out.printf("%-6s%-6s%-6s%-6s%-6s%-6s%-6s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

        int l = 30 + ((m + (int)(m / 8.0)) % 2);
        if (m == 2) {
            if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)){
                l = 29;
            }else {
                l = 28;
            }
        }
        //d = (d) % 7;  ***** REMOVED *****
        switch (d) {
        case 0:
            day = "Sunday";
            break;
        case 1:
            day = "Moneday";
            break;
        case 2:
            day = "Tuesday";
            break;
        case 3:
            day = "Wednesday";
            break;
        case 4:
            day = "Thursday";
            break;
        case 5:
            day = "Friday";
            break;
        case 6:
            day = "Saturday";
            break;
        default:
            day = "";
        }
        if (d != 0) {
            //System.out.print(String.format("%" + 6 * d + "s", ""));   ***** REMOVED *****

        }

        /* print leading blank days (if any) */
        int daysprinted = 0;
        for (int k = 0; k < d; k++) {
            System.out.printf("%-6s", "");
            daysprinted++;
        }

        for (int i = 1; i <= l; i++)
        {
            System.out.printf("%-6d", i);
            daysprinted++;

            if (daysprinted == 7)  //<-- this part   ***** CHANGED *****
            {
                System.out.println();
                daysprinted = 0;
            }

            d += 1;     //***** day += 1 is INCORRECT; use d here *****
            if (d > 6)
                d = 0;  //WRAP AROUND

        }
        System.out.print("");
    }
}


text:
Q: override CSS nested attribute Simple question regarding overriding a CSS attribute that is nested.
I've tried going up to the source of this gallery style sheet to get to the base of it but I just can't seem to work my way around it.
I am simply trying to change the max-width and width of
body.gallery .asset.is-landscape img

to a new value but It seems to not work even when attributed !important
here is the CSS in question I am aiming to make make the above mentionned change to:
body.gallery .asset.is-landscape img, body.gallery .asset.is-square img, body.nested_gallery .asset.is-landscape img, body.nested_gallery .asset.is-square img {
    max-width: 550px;
    width: 80%;
}

Here is the whole style sheet which i thoroughly tried changing the elements I thought could affect the nested body gallery, but without success. Bare in mind I am obviously not expert, this might be something easy to resolve.
/*
------------------------------------------------------------------
Gallery Styles
------------------------------------------------------------------
*/
html.is-changing body.gallery .main, html.is-changing body.nested_gallery .main {
  transform: translate3d(20px, 0, 0);
  opacity: 0; }

body.gallery, body.nested_gallery {
  overflow-y: hidden;
  position: relative;
  height: 100%; }
  body.gallery .page-name-small, body.nested_gallery .page-name-small {
    opacity: 1 !important;
    pointer-events: auto !important;
    top: -2px; }
  body.gallery .breadcrumb-link.bottom, body.nested_gallery .breadcrumb-link.bottom {
    -webkit-transition: opacity 250ms ease;
    transition: opacity 250ms ease;
    display: none;
    position: fixed;
    bottom: 10px;
    left: 20px;
    z-index: 96; }
    body.gallery .breadcrumb-link.bottom.hidden, body.nested_gallery .breadcrumb-link.bottom.hidden {
      opacity: 0; }
  body.gallery .overview-icon-bottom, body.nested_gallery .overview-icon-bottom {
    -webkit-transition: opacity 250ms ease;
    transition: opacity 250ms ease;
    display: none;
    cursor: pointer;
    position: fixed;
    bottom: 9px;
    right: 100px;
    z-index: 96; }
    body.gallery .overview-icon-bottom.hidden, body.nested_gallery .overview-icon-bottom.hidden {
      opacity: 0;
      pointer-events: none; }
  body.gallery .assets-container, body.nested_gallery .assets-container {
    -webkit-overflow-scrolling: touch;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow-x: auto;
    overflow-y: hidden; }
    body.gallery .assets-container.is-draggable .asset.img img, body.nested_gallery .assets-container.is-draggable .asset.img img {
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none; }
    body.gallery .assets-container.is-draggable.is-dragging, body.nested_gallery .assets-container.is-draggable.is-dragging {
      cursor: grabbing !important;
      cursor: -moz-grabbing !important;
      cursor: -webkit-grabbing !important; }
  body.gallery .main, body.nested_gallery .main {
    -webkit-transition: opacity 250ms ease, -webkit-transform 250ms ease;
    transition: opacity 250ms ease, -webkit-transform 250ms ease;
    transition: opacity 250ms ease, transform 250ms ease;
    transition: opacity 250ms ease, transform 250ms ease, -webkit-transform 250ms ease;
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    opacity: 1; }
    body.gallery .main .assets-container, body.nested_gallery .main .assets-container {
      display: flex;
      height: 100vh; }
  body.gallery .title-element, body.nested_gallery .title-element {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 50vw; }
    body.gallery .title-element .text, body.nested_gallery .title-element .text {
      position: relative;
      max-width: 500px;
      padding: 20px;
      width: 80%; }
    body.gallery .title-element img, body.nested_gallery .title-element img {
      max-width: 600px;
      width: 80%; }
  body.gallery .cover-image, body.nested_gallery .cover-image {
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 50vw; }
    body.gallery .cover-image.is-landscape img, body.gallery .cover-image.is-square img, body.nested_gallery .cover-image.is-landscape img, body.nested_gallery .cover-image.is-square img {
      max-width: 600px;
      width: 80%; }
    body.gallery .cover-image.is-portrait img, body.nested_gallery .cover-image.is-portrait img {
      max-height: 600px;
      height: 80vh; }
  body.gallery .caption, body.nested_gallery .caption {
    max-width: 80%;
    margin-top: 20px;
    position: relative; }
    body.gallery .caption p, body.nested_gallery .caption p {
      margin: 0; }
    body.gallery .caption p + p, body.nested_gallery .caption p + p {
      margin-top: 1em; }
  body.gallery .asset, body.nested_gallery .asset {
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 50vw; }
    body.gallery .asset.is-landscape img, body.gallery .asset.is-square img, body.nested_gallery .asset.is-landscape img, body.nested_gallery .asset.is-square img {
      max-width: 550px;
      width: 80%; }
    body.gallery .asset.is-portrait img, body.nested_gallery .asset.is-portrait img {
      -o-object-fit: contain;
      object-fit: contain;
      max-height: 700px;
      height: 64vh; }
    body.gallery .asset.image img, body.gallery .asset.video img, body.nested_gallery .asset.image img, body.nested_gallery .asset.video img {
      cursor: pointer; }
    body.gallery .asset.video .video-thumb-container, body.nested_gallery .asset.video .video-thumb-container {
      position: relative;
      width: 80%;
      max-width: 600px; }
      body.gallery .asset.video .video-thumb-container .vimeo_cont, body.gallery .asset.video .video-thumb-container .youtube_cont, body.nested_gallery .asset.video .video-thumb-container .vimeo_cont, body.nested_gallery .asset.video .video-thumb-container .youtube_cont {
        width: 100%; }
      body.gallery .asset.video .video-thumb-container .video-play-icon, body.nested_gallery .asset.video .video-thumb-container .video-play-icon {
        -webkit-transition: all 250ms ease;
        transition: all 250ms ease;
        opacity: 0.9;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -23px;
        margin-left: -23px; }
      body.gallery .asset.video .video-thumb-container:hover .video-play-icon, body.nested_gallery .asset.video .video-thumb-container:hover .video-play-icon {
        -webkit-transform: scale(1.08);
        -ms-transform: scale(1.08);
        transform: scale(1.08);
        opacity: 1; }
    body.gallery .asset.text .text-content, body.nested_gallery .asset.text .text-content {
      max-width: 500px;
      padding: 20px;
      position: relative;
      width: 80%; }
  body.gallery .next-nested-page, body.nested_gallery .next-nested-page {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    width: 50vw; }
    body.gallery .next-nested-page .nexted-nested-page-title, body.nested_gallery .next-nested-page .nexted-nested-page-title {
      padding-left: 20px;
      padding-right: 110px; }
      body.gallery .next-nested-page .nexted-nested-page-title .title, body.nested_gallery .next-nested-page .nexted-nested-page-title .title {
        color: #ffffff;
        font-family: "Miller Banner Black", "Miller Banner Black", serif;
        font-size: 19px;
        font-weight: normal; }
      body.gallery .next-nested-page .nexted-nested-page-title .see-more, body.nested_gallery .next-nested-page .nexted-nested-page-title .see-more {
        color: rgba(40, 40, 40, 0.75);
        font-size: 14px; }
    body.gallery .next-nested-page.is-landscape img, body.gallery .next-nested-page.is-square img, body.nested_gallery .next-nested-page.is-landscape img, body.nested_gallery .next-nested-page.is-square img {
      max-width: 600px;
      width: 80%; }
    body.gallery .next-nested-page.is-portrait img, body.nested_gallery .next-nested-page.is-portrait img {
      max-height: 400px;
      height: 80vh; }
    body.gallery .next-nested-page .nexted-nested-page-cover-image, body.nested_gallery .next-nested-page .nexted-nested-page-cover-image {
      transition: opacity 250ms ease;
      transform: translate(100%, -50%);
      opacity: 0.5;
      position: absolute;
      top: 50%;
      right: 90px; }
    body.gallery .next-nested-page:hover .nexted-nested-page-cover-image, body.nested_gallery .next-nested-page:hover .nexted-nested-page-cover-image {
      opacity: 1; }
  body.gallery .caption, body.nested_gallery .caption {
    color: #282828;
    font-size: 20px;
    line-height: 2;
    font-family: "Miller Banner Roman", "Miller Banner Roman", serif; }
  body.gallery .gallery-zoom-container, body.nested_gallery .gallery-zoom-container {
    -webkit-transition: all 250ms ease;
    transition: all 250ms ease;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    pointer-events: none;
    opacity: 0;
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 97; }
    body.gallery .gallery-zoom-container .vimeo_cont, body.gallery .gallery-zoom-container .youtube_cont, body.nested_gallery .gallery-zoom-container .vimeo_cont, body.nested_gallery .gallery-zoom-container .youtube_cont {
      width: 85vw; }
    body.gallery .gallery-zoom-container img.fit-h, body.nested_gallery .gallery-zoom-container img.fit-h {
      width: 100vw !important;
      height: auto !important; }
    body.gallery .gallery-zoom-container img.fit-v, body.nested_gallery .gallery-zoom-container img.fit-v {
      width: auto !important;
      height: 100vh !important; }
    body.gallery .gallery-zoom-container.landscape img, body.nested_gallery .gallery-zoom-container.landscape img {
      width: auto;
      height: 100vh; }
    body.gallery .gallery-zoom-container.portrait img.is-landscape, body.nested_gallery .gallery-zoom-container.portrait img.is-landscape {
      width: 100vw;
      height: auto; }
    body.gallery .gallery-zoom-container.portrait img.is-portrait, body.nested_gallery .gallery-zoom-container.portrait img.is-portrait {
      width: auto;
      height: 100vh; }
    body.gallery .gallery-zoom-container.active, body.nested_gallery .gallery-zoom-container.active {
      opacity: 1;
      pointer-events: auto; }
  body.gallery .gallery-counter, body.nested_gallery .gallery-counter {
    -webkit-transition: opacity 250ms ease;
    transition: opacity 250ms ease;
    position: fixed;
    bottom: 20px;
    left: 0;
    text-align: center;
    width: 100%;
    z-index: 96; }
    body.gallery .gallery-counter.hidden, body.nested_gallery .gallery-counter.hidden {
      opacity: 0; }
  body.gallery .gallery-overview-overlay, body.nested_gallery .gallery-overview-overlay {
    background: rgba(255, 255, 255, 0.75);
    -webkit-transition: all 250ms ease;
    transition: all 250ms ease;
    pointer-events: none;
    opacity: 0;
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 97; }
    body.gallery .gallery-overview-overlay .gallery-overview-inner, body.nested_gallery .gallery-overview-overlay .gallery-overview-inner {
      -webkit-overflow-scrolling: touch;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -ms-flex-wrap: wrap;
      flex-wrap: wrap;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      padding: 20px; }
    body.gallery .gallery-overview-overlay.active, body.nested_gallery .gallery-overview-overlay.active {
      opacity: 1;
      pointer-events: auto; }
      body.gallery .gallery-overview-overlay.active .gallery-overview-inner, body.nested_gallery .gallery-overview-overlay.active .gallery-overview-inner {
        overflow-y: auto; }
    body.gallery .gallery-overview-overlay .overview-asset, body.nested_gallery .gallery-overview-overlay .overview-asset {
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      min-height: 500px;
      margin: 40px;
      padding: 50px;
      width: calc(33.3333% - 80px); }
      body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content {
        cursor: pointer;
        position: relative;
        max-height: 100%;
        width: 100%; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-left, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-left {
          left: -50px;
          margin-right: auto; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-right, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-right {
          left: 50px;
          margin-left: auto; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-top, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-top {
          -ms-flex-item-align: start;
          align-self: flex-start; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-bottom, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-bottom {
          -ms-flex-item-align: end;
          align-self: flex-end; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-h-center, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-h-center {
          margin-left: auto;
          margin-right: auto; }
        body.gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-v-center, body.nested_gallery .gallery-overview-overlay .overview-asset .overview-asset-content.flush-v-center {
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-self: center; }
      body.gallery .gallery-overview-overlay .overview-asset.text .text-content, body.nested_gallery .gallery-overview-overlay .overview-asset.text .text-content {
        background: #ffffff;
        border: 2px solid #282828;
        padding: 50px 30px; }
    body.gallery .gallery-overview-overlay .close-overview, body.nested_gallery .gallery-overview-overlay .close-overview {
      font-size: 4rem;
      color: #282828;
      cursor: pointer;
      position: absolute;
      bottom: 20px;
      left: 50%;
      margin-left: -1rem; }

.is-changing .gallery-counter {
  opacity: 0; }

Thanks to whoever takes the time to answer and explain where I did my wrongs :)

A: You could use web inspection tool to check whether your style is overridden. If so you can append one more class or include another HTML element to your tag and it will override the gallery styles.
Example -
body.gallery.one_more_class  .asset.is-landscape img
body.gallery .wrapper HTML .asset.is-landscape img


text:
Q: Injecting a reference bean from jar file, No bean named *** is defined exception is thrown <bean id="org.sakaiproject.vidyayug.tool.SakaiStyleSelectorInterceptor"
class="org.sakaiproject.vidyayug.tool.SakaiStyleSelectorInterceptor">
<property name="worksiteManager">
<ref bean="org.sakaiproject.metaobj.worksite.mgt.WorksiteManager"/>
</property>
</bean>

I am injecting ref bean from a jar file..
Exception is:
Cannot resolve reference to bean 'org.sakaiproject.metaobj.worksite.mgt.WorksiteManager' while setting bean property 'worksiteManager';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.sakaiproject.metaobj.worksite.mgt.WorksiteManager' is defined

A: You must add a
<bean id="org.sakaiproject.metaobj.worksite.mgt.WorksiteManager" class="org.sakaiproject.metaobj.worksite.mgt.WorksiteManager"/>

in your application context.
Bean id and class name are not the same thing, even if you're giving them the same value.
The bean id should be a "handy" name you use to refer to a bean isntance, while the class is the actual fully qualified class name to load the bean from the classpath (jar or your class folder or whatever).

A: do like that, give a bean id, and then call the reference by calling that id.
  <bean id="Order" class="com.classes.OrderPizza">
    <property name="pizzaTemp" ref="ChickenPizza"></property>
  </bean>

<bean id="ChickenPizza" class="com.classes.ChickenPizza"></bean>
<bean id="PaneerPizza" class="com.classes.PaneerPizza"></bean>

A: The problem is that you are referencing a bean without instantiating it. Correct your code this way:
<bean id="org.sakaiproject.vidyayug.tool.SakaiStyleSelectorInterceptor" class="org.sakaiproject.vidyayug.tool.SakaiStyleSelectorInterceptor">
    <property name="worksiteManager">
        <bean class="org.sakaiproject.metaobj.worksite.mgt.WorksiteManager"/>
    </property>
</bean>

NOTE You also have to be sure the jar is deployed in your project binaries.


text:
Q: Delete particular word from string I'm extracting twitter user's profile image through JSON. For this my code is:
$x->profile_image_url

that returns the url of the profile image. The format of the url may be "..xyz_normal.jpg" or "..xyz_normal.png" or "..xyz_normal.jpeg" or "..xyz_normal.gif" etc.
Now I want to delete the "_normal" part from every url that I receive. How can I achieve this in php? I'm tired of trying it. Please help.

A: Php str_replace.
str_replace('_normal', '', $var)

What this does is to replace '_normal' with '' (nothing) in the variable $var.
Or take a look at preg_replace if you need the power of regular expressions.

A: The str_ireplace() function does the same job but ignoring the case
like the following
<?php
echo str_ireplace("World","Peter","Hello world!");
?>

output : Hello Peter!

for more example you can see

A: The str_replace() function replaces some characters with some other characters in a string.
try something like this:
$x->str_replace("_normal","",$x)

A: $s = 'Posted On jan 3rd By Some Dude';

echo strstr($s, 'By', true);

This is to remove particular string from a string.
The result will be like this
 'Posted On jan 3rd'

A: Multi replace
$a = array('one','two','three');
$var = "one_1 two_2 three_3";
str_replace($a, '',$var);

A: string erase(subscript, count)
    {
     string place="New York";
     place erase(0,2)
  }


text:
Q: Why do the navigation borders ignore my anchor tags when I reduce screen width? I'm just building a mini test project in an online HTML/CSS course I'm doing for beginners and I don't understand why my navbar content doesn't respond to screen width. The header border goes right through my content if you keep reducing screen width (I've left borders on so you can see that happening).
I have copied my code and the course instructor's code below so that so you guys can tell me why his works but mine doesn't. The only major difference I see is that I used anchor tags whereas he used button tags for navigation but I still don't get why that is a problem (I set my anchor tags to display:block; in case their inline display was the issue).
My code:

/*mycss.css*/

* {
  margin: 0;
  border: 0;
  padding: 0;
  box-sizing: border-box;
}

header {
  border: 1px solid hotpink;
  height: 100vh;
  width: 10vw;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  border-right: 1px solid #D7DBDD;
}

div#top-nav {
  border: 5px solid green;
  height: 25%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

ul {
  border: 1px solid gold;
  list-style-type: none;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

li {
  border: 1px solid red;
  width: 100%;
  /* text-align: center; */
}

li a {
  border: 1px solid blue;
  display: block;
  padding: 20px 0 20px 20px;
  text-decoration: none;
  color: #16A2D7;
  font-size: font-size: 2vw;
}

li a:hover {
  background-color: #EEF3F5;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Title</title>

Inbox

Contact

Accounts

Legal

Instructor's code:

/*main.css*/
html,
body,
div,
nav,
button {
  padding: 0;
  border: 0;
  margin: 0;
  box-sizing: border-box;
}

html {
  color: #16A2D7;
  font-size: 2vw;
}

#sidebar {
  height: 100vh;
  /* arrange child elements */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /* format */
  border-right: 1px solid #D7DBDD;
  width: fit-content;
  /*the width*/
}

.sidebar-child {
  /* arrange child elements */
  display: flex;
  flex-direction: column;
}

.sbc-top {
  /* format */
  padding-top: 2rem;
}

.sbc-btm {
  padding-bottom: 2rem;
}

button {
  /* format */
  color: inherit;
  background-color: white;
  font-size: 1rem;
  height: 3rem;
  width: 10rem;
  /*the width*/
  text-align: left;
  padding-left: 2rem;
  cursor: pointer;
}

button:hover {
  background-color: #EEF3F5;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Sidebar Menu</title>

      <button>Inbox</button>
      <button>Contact</button>
      <button>Accounts</button>

      <button>Legal</button>

A: The chief thing that is causing you issues is this rule:
header {
  width: 10vw;
}

This means, no matter what, make my  have width equal to 10% of the width of the viewport.  This doesn't account for size of the content within.  Take a look at your professor's rule for the #sidebar, it uses width: fit-content which doesn't limit the size of the container.
An additional issue is that you are using:
li a {
  display: block;
}

Which means the  are going to try and eat as much space as they.  Normally, they are inline which causes them not to try to fill out width.  Depending on what presentation you are trying to make, you should remove the width: 10vw; and the display: block; to start.


text:
Q: Update and remove cached image using Liipimaginebundle I'm using liipimaginebundle and everything work fine except for deletion and update cached images when I update the original image. I would to know How can I do this
config.yml
liip_imagine:
resolvers:
   default:
      web_path: ~

filter_sets:
    cache: ~
    travel_75_55:
        quality: 80
        filters:
            thumbnail: { size: [75, 55], mode: outbound }

    travel_270_161:
        quality: 75
        filters:
            thumbnail: { size: [270, 161], mode: outbound}

And this is Entity: Image
/**
 * Image
 *
 * @ORM\HasLifecycleCallbacks
*/
class Image
{
//.................

public $file;

public function setFile($file)
{
    $this->file = $file;

    if (null !== $this->url) {
    $this->tempFilename = $this->url;

    $this->url = null;
    $this->alt = null;
    }
}

public function getFile()
{
    return $this->file;
}

private $tempFilename;

/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
    if (null === $this->file) {
    return;
    }

$this->url = $this->file->guessExtension();

$this->alt = $this->file->getClientOriginalName();
}

/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
    if (null === $this->file) {
    return;
    }

    if (null !== $this->tempFilename) {
    $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;

        if (file_exists($oldFile)) {
            unlink($oldFile);
        }
    }

    $this->file->move(
    $this->getUploadRootDir(),
    $this->id.'.'.$this->url
    );
}

/**
* @ORM\PreRemove()
*/
public function preRemoveUpload()
{
    $this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}

/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
    if (file_exists($this->tempFilename)) {
    unlink($this->tempFilename);
    }
}

public function getUploadDir()
{
    return 'uploads/img/travels';
}

protected function getUploadRootDir()
{
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

public function getWebPath()
{
    return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}

}

A: Here is a solution that works fine
services:
    project.cacheimage_listener:
        class: Project\DashboardBundle\Listener\CacheImageListener
        arguments: ["@liip_imagine.cache.manager"]
        tags:
            - { name: doctrine.event_listener, event: postUpdate }
            - { name: doctrine.event_listener, event: preRemove }

create the listener
namespace Project\DashboardBundle\Listener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Project\DashboardBundle\Entity\Image;

class CacheImageListener
{
protected $cacheManager;

public function __construct($cacheManager)
{
    $this->cacheManager = $cacheManager;
}

public function postUpdate(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    if ($entity instanceof Image) {
        // clear cache of thumbnail
        $this->cacheManager->remove($entity->getUploadDir());
    }
}

// when delete entity so remove all thumbnails related
public function preRemove(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    if ($entity instanceof Image) {

        $this->cacheManager->remove($entity->getWebPath());
    }
}
}