text:
Q: Click/Tap on text in Table to view image

                        ID: VXD7524W

                        RESULTS: CLICK ME<hover img src="/Images/results/rd.1.26.22.jpg"/>

                        STRAIN: SUPER LEMON HAZE

I'm trying to make the code for a table view an image on Click/tap when you click the text but I'm unfamiliar on how to do that in a table? and I cant find an answer here so I figured I would just ask.

A: Im not sure what you are exactly after but you can do something with a modal
Codepen
So yours will be something like this:
HTML:

  ×

   ID: VXD7524W

   RESULTS: CLICK ME

   STRAIN: SUPER LEMON HAZE

Css:
#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {transform:scale(0)}
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}

JS:
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

A: Hey there you just need to add javascript in your code that will help to change/call an image when you click. I just update some feature please check the code give below-

    ID: VXD7524W

    RESULTS: ><button onClick="changeImage()";>CLICK ME</button>
        >

    STRAIN: SUPER LEMON HAZE


text:
Q: How to set max or min values based on selected input I have selected input for set max or min values in another input field.
Selected Input
<select name="SelectedInput" required>
    <option value="a">A</option>
    <option value="b">B</option>
</select>

input field where max value will be set
<input type="number" name="price" id="price_id" min="0" step="0.01" required>

Conditions
If I select A option, I want to set max value in input field < 5000.
If I select B option, I want to set min value in input field >= 5000.

A: Selected Input :
<select name="SelectedInput" id="prooftype" required>
    <option value="a">A</option>
    <option value="b">B</option>
</select>

Input field where max value will be set :
<input type="number" name="price" id="price_id" min="0" step="0.01" required>

And then include javascript codes :
<script type="text/javascript">
var selectedopt;

$('#prooftype').change(function(){
   selectedopt=  $(this).val();

   //Add your condition here, and  check the selected option value:
  if(selectedopt== "a")
  {
   //Set input min and max value based on the selected option value.
   $('#price_id').attr('maxlength','4999');
  }
  elseif(selectedopt== "b")
  {
   $('#price_id').attr('minlength','5000');
  }
  // And so on........
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to 'loosely' check if string matches another string in list I have a long list of car ad titles and another list of all car makes and models, I am searching the titles to find a match in the makes/models list. I have this so far:
    for make in carmakes:
        if make in title:
            return make

but it doesn't work too well as the titles are human made and come with a lot of variations.
For example, if the title is 'Nissan D-Max' and i have 'dmax' in my makes/models list, the loop doesn't catch that as it doesn't match exactly. What's the best way to 'loosely' or 'dynamically' check for matches?

A: Once I came across a similar challenge, below is simplified solution:
import re

def re_compile(*args, flags: int =re.IGNORECASE, **kwargs):
    return re.compile(*args, flags=flags, *kwargs)

class Term(object):
    """"""
    def __init__(self, contain_patterns, *contain_args):
        self.matching_rules = []
        self.forbid_rules = []
        if isinstance(contain_patterns, str):
            self.may_contain(contain_patterns, *contain_args)
        else:
            for cp in contain_patterns:
                self.may_contain(cp, *contain_args)

    def __eq__(self, other):
        return isinstance(other, str) and self.is_alias(other)

    def is_alias(self, s: str):
        return (
            all(not f_rule(s) for f_rule in self.forbid_rules) and
            any(m_rule(s) for m_rule in self.matching_rules)
        )

    def matching_rule(self, f):
        self.matching_rules.append(f)
        return f

    def forbid_rule(self, f):
        self.forbid_rules.append(f)
        return f

    def must_rule(self, f):
        self.forbid_rules.append(lambda s: not f(s))
        return f

    def may_be(self, *re_fullmatch_args):
        self.matching_rules.append(re_compile(*re_fullmatch_args).fullmatch)

    def must_be(self, *re_fullmatch_args):
        fmatch = re_compile(*re_fullmatch_args).fullmatch
        self.forbid_rules.append(lambda s: not fmatch(s))

    def must_not_be(self, *re_fullmatch_args):
        self.forbid_rules.append(re_compile(*re_fullmatch_args).fullmatch)

    def may_contain(self, *re_search_args):
        self.matching_rules.append(re_compile(*re_search_args).search)

    def must_not_contain(self, *re_search_args):
        self.forbid_rules.append(re_compile(*re_search_args).search)

    def may_starts_with(self, *re_match_args):
        self.matching_rules.append(re_compile(*re_match_args).match)

    def must_not_starts_with(self, *re_match_args):
        self.forbid_rules.append(re_compile(*re_match_args).match)

In your case each car_model should be represented as Term instance with self regex rules (I do not know much about car brands, I invented some names):
if __name__ == '__main__':
    dmax = Term((r'd[ -._\'"]?max', r'Nissan DM'))
    dmax.may_contain(r'nissan\s+last\s+(year)?\s*model')
    dmax.must_not_contain(r'Skoda')
    dmax.must_not_contain(r'Volkswagen')

    @dmax.matching_rule
    def dmax_check(s):
        return re.search(r'double\s+max', s, re.IGNORECASE) and re.search(r'nissan', s, re.IGNORECASE)

    tg = Term(r'Tiguan')
    octav = Term(r'Octavia')

    titles = (
        'Dmax model',
        'd_Max nissan',
        'Nissan Double Max Pro',
        'nissan last model',
        'Skoda octavia',
        'skoda d-max',
        'Nissan Qashqai',
        'VW Polo double max'
    )

Your example:
for car_model in (dmax, tg, octav):
    print(car_model in titles)

Result:
True
False
True

Details:
print(' '*26, 'DMAX TIGUAN OCTAVIA')
for title in titles:
    print(title.ljust(26), (dmax == title), (tg == title), (octav == title))

Result:
                           DMAX TIGUAN OCTAVIA
Dmax model                 True False False
d_Max nissan               True False False
Nissan Double Max Pro      True False False
nissan last model          True False False
Skoda octavia              False False True
skoda d-max                False False False
Nissan Qashqai             False False False
VW Polo double max         False False False


text:
Q: Sass import doesn't work after using gulp-ruby-sass I was using gulp-sass to compile SCSS fine for my project. Then I decided to switch to .sass for its simplicity. I switched to gulp-ruby-sass, but then the import doesn't work. Here is what I have:
@import bootstrap/mixins

My directory structure:
|-- app
|   |-- app.js
|   |-- app.scss
|   |-- app_controller.js
|   |-- app_controller_test.js
|   |-- bootstrap
|   |   |-- _mixins.scss
|   |   |-- _normalize.scss
|   |   |-- _variables.scss

In my gulpfile:
gulp.task('css', function(){
gulp.src(['app.scss','./app/**/*.sass'])
    .pipe(plugins.rubySass())
    .pipe(plugins.concat('app.css'))
    .pipe(gulp.dest('./build'));
});

Then I got this error:
error ./main/main.sass (Line 1: File to import not found or unreadable: bootstrap/mixins.
Load paths:
/private/var/folders/kn/29d686ds16s31t8mp0957dt40000gn/T/gulp-ruby-sass

Please help me on this. Thanks!

A: Should it be gulp.src(['app.scss','./app/**/*.scss']) instead of gulp.src(['app.scss','./app/**/*.sass'])?

A: You need to define a load path:
gulp.task('css', function() {
  return gulp.src(['app.scss','./app/**/*.sass'])
    .pipe(plugins.rubySass({
      loadPath: [
        process.cwd() + '/app'
      ]
    }))
    .pipe(plugins.concat('app.css'))
    .pipe(gulp.dest('./build'));
});

You can add multiple load paths by comma seperating them. The function process.cwd() is used to get the path to your gulpfile.js


text:
Q: Fitting gaussian to a curve in Python II I have two lists .
import numpy
x = numpy.array([7250, ... list of 600 ints ... ,7849])
y = numpy.array([2.4*10**-16, ... list of 600 floats ... , 4.3*10**-16])

They make a U shaped curve.
Now I want to fit a gaussian to that curve.
from scipy.optimize import curve_fit
n = len(x)
mean = sum(y)/n
sigma = sum(y - mean)**2/n

def gaus(x,a,x0,sigma,c):
    return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c

popt, pcov = curve_fit(gaus,x,y,p0=[-1,mean,sigma,-5])

pylab.plot(x,y,'r-')
pylab.plot(x,gaus(x,*popt),'k-')
pylab.show()

I just end up with the noisy original U-shaped curve and a straight horizontal line running through the curve.
I am not sure what the -1 and the -5 represent in the above code but I am sure that I need to adjust them or something else to get the gaussian curve. I have been playing around with possible values but to no avail.
Any ideas?

A: First of all, your variable sigma is actually variance, i.e. sigma squared --- http://en.wikipedia.org/wiki/Variance#Definition.
This confuses the curve_fit by giving it a suboptimal starting estimate.
Then, your fitting ansatz, gaus, includes an amplitude a and an offset, is this what you actually need? And the starting values are a=-1 (negated bell shape) and offset c=-5. Where do they come from?
Here's what I'd do:

*

*fix your fitting model. Do you want just a gaussian, does it need to be normalized. If it does, then the amplitude a is fixed by sigma etc.

*Have a look at the actual data. What's the tail (offset), what's the sign (amplitude sign).

If you're actually want just a gaussian without any bells and whistles, you might not actually need curve_fit: a gaussian is fully defined by two first moments, mean and sigma. Calculate them as you do, plot them over the data and see if you're not all set.

A: p0 in your call to curve_fit gives the initial guesses for the additional parameters of you function in addition to x. In the above code you are saying that I want the curve_fit function to use -1 as the initial guess for a, -5 as the initial guess for c, mean as the initial guess for x0, and sigma as the guess for sigma. The curve_fit function will then adjust these parameters to try and get a better fit. The problem is your initial guesses at your function parameters are really bad given the order of (x,y)s.
Think a little bit about the order of magnitude of your different parameters for the Gaussian. a should be around the size of your y values (10**-16) as at the peak of the Gaussian the exponential part will never be larger than 1. x0 will give the position within your x values at which the exponential part of your Gaussian will be 1, so x0 should be around 7500, probably somewhere in the centre of your data. Sigma indicates the width, or spread of your Gaussian, so perhaps something in the 100's just a guess. Finally c is just an offset to shift the whole Gaussian up and down.
What I would recommend doing, is before fitting the curve, pick some values for a, x0, sigma, and c that seem reasonable and just plot the data with the Gaussian, and play with a, x0, sigma, and c until you get something that looks at least some what the way you want the Gaussian to fit, then use those as the starting points for curve_fit p0 values. The values I gave should get you started, but may not do exactly what you want. For instance a probably needs to be negative if you want to flip the Gaussian to get a "U" shape.
Also printing out the values that curve_fit thinks are good for your a,x0,sigma, and c might help you see what it is doing and if that function is on the right track to minimizing the residual of the fit.
I have had similar problems doing curve fitting with gnuplot, if the initial values are too far from what you want to fit it goes in completely the wrong direction with the parameters to minimize the residuals, and you could probably do better by eye. Think of these functions as a way to fine tune your by eye estimates of these parameters.
hope that helps

A: I don't think you are estimating your initial guesses for mean and sigma correctly.
Take a look at the SciPy Cookbook here
I think it should look like this.
x = numpy.array([7250, ... list of 600 ints ... ,7849])
y = numpy.array([2.4*10**-16, ... list of 600 floats ... , 4.3*10**-16])

n = len(x)
mean = sum(x*y)/sum(y)
sigma = sqrt(abs(sum((x-mean)**2*y)/sum(y)))

def gaus(x,a,x0,sigma,c):
   return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c

popy, pcov = curve_fit(gaus,x,y,p0=[-max(y),mean,sigma,min(x)+((max(x)-min(x)))/2])

pylab.plot(x,gaus(x,*popt))

If anyone has a link to a simple explanation why these are the correct moments I would appreciate it.  I am going on faith that SciPy Cookbook got it right.

A: Here is the solution thanks to everyone .
x = numpy.array([7250, ... list of 600 ints ... ,7849])
y = numpy.array([2.4*10**-16, ... list of 600 floats ... , 4.3*10**-16])

n = len(x)
mean = sum(x)/n
sigma = math.sqrt(sum((x-mean)**2)/n)

def gaus(x,a,x0,sigma,c):
    return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c

popy, pcov = curve_fit(gaus,x,y,p0=[-max(y),mean,sigma,min(x)+((max(x)-min(x)))/2])

pylab.plot(x,gaus(x,*popt))

A: Maybe it is because I use matlab and fminsearch or my fits have to work on much fewer datapoints (~ 5-10), I have much better results with the following starter values (as simple as they are):
a = max(y)-min(y);
imax= find(y==max(y),1);
mean = x(imax);
avg = sum(x.*y)./sum(y);
sigma = sqrt(abs(sum((x-avg).^2.*y) ./ sum(y)));
c = min(y);

The sigma works fine.


text:
Q: How do I send a django model to javascipt? How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.
def index(request):
    if Movie.objects.order_by('-stars').exists():
        movie = list(Movie.objects.order_by('-stars'))
    if TV.objects.order_by('-stars').exists():
        tv = TV.objects.order_by('-stars')
        print(tv)
    context = {
        'movie':movie,
    }
    return render(request, 'Movie/index.html',context)

fetchTrendingResults("all", "week")

        var mediaType = document.getElementById("media_type")
        mediaType.addEventListener("change", function(event) {
            fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day")
        })

        function fetchTrendingResults(media_type, time_window) {
            var trendingDiv = document.getElementById("trendings")
            trendingDiv.innerHTML = ""
            if (media_type == "score"){
                var js_list = {{movie}};
            }
            else{
            fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json"
                }}
                // todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。
                )
            .then(res => res.json())
            .then(data => {
                for (let i=0; i<data.results.length; i++) {
                    var mainDiv = document.createElement("div");
                    mainDiv.setAttribute("class", "card");
                    mainDiv.setAttribute("style", "width: 18rem;");
                    var img = document.createElement("img");
                    img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path);
                    img.setAttribute("class", "card-img-top");
                    img.setAttribute("alt", "...");
                    var body = document.createElement("div");
                    body.setAttribute("class", "card-body");
                    var title = document.createElement("h5");
                    title.setAttribute("class", "card-title");
                    if (data.results[i].name) {
                        title.innerHTML = data.results[i].name;
                    } else {
                        title.innerHTML = data.results[i].title;
                    }
                    //var text = document.createElement("p");
                    //text.setAttribute("class", "card-text");
                    //text.innerHTML = data.results[i].overview;
                    var link = document.createElement("a");
                    link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/");
                    link.setAttribute("class", "btn btn-primary");
                    link.innerHTML = "View Details";
                    body.appendChild(title);
                    //body.appendChild(text);
                    body.appendChild(link);
                    mainDiv.appendChild(img);
                    mainDiv.appendChild(body);
                    document.getElementById("trendings").appendChild(mainDiv);
                }
            })
        }
        }

How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.

A: You can send model data by just returning JsonResponse from the view (and for example creating JSON dict by forlooping QuerySet, or using model_to_dict Django built-in method) or by preserving your logic and sending html you need to override - even better - you can do both ways at the same time.
So, basically you write view like this:
from django.forms import model_to_dict
from django.http import Http404

def custom_ajax_view(request):
    if request.method != 'POST':
        raise Http404
    movies = Movie.objects.order_by('-stars')
    movie_dict = {}
    if movies.exists():
        movie_dict = {obj.id: model_to_dict(obj) for obj in movies}
    tv = TV.objects.order_by('-stars')
    tv_dict = {}
    if tv.exists():
        tv_dict = {obj.id: model_to_dict(obj) for obj in tv}
    context = {
        'movie': movie,
    }
    html = render_to_string(
        'Movie/index.html', context=context)
    return JsonResponse({
        'movies': movie_dict,
        'tvs': tv_dict,
        'html': html,
    })

And then you retrieve data via Ajax method (I prefer using jQuery for that) by writing:
$.ajax({
    url: CUSTOM_AJAX_URL,
    type: 'post',
    dataType: 'json',
    success: function (data) {
        // Here you retrieve your data and you can do something with it.
        console.log(data)
    }
});

You also can resolve your CUSTOM_AJAX_URL using template logic (post it at the end of template)
<script>
    const CUSTOM_AJAX_URL = "{% url 'custom_ajax_view' %}";
</script>
<script src="{% static 'your_script_name.js' %}"></script>

Then your script should see the CUSTOM_AJAX_URL (if you use script not directly by using inline method, but including script via script tag and placing it with static method in the code). If you place it directly, you can pass URL directly to the AJAX method.


text:
Q: NextJS script tag So I've been trying at this for quite some time now.
On this site I need to be able to place a script tag that will embed a contact form and newsletter sign up form etc to specific pages. So for example on the contact page the contact form script tag will live.
I've tried a bunch of different methods but I'm unable to get the result I'm after for what seems like a pretty basic thing to be able to do.
What I'm finding is initially it seems like it works fine, the script tag works and I see what I expect on the page. But then when you navigate away from the page and go back to it the script tag isn't displaying. It's only when I then refresh the page again will the stuff the script tag is supposed to output appear.
I'm assuming this is happening because with use of the Link tag the website doesn't reload between navigation, instead it all works like a SPA with no reload but it's that refresh that triggers the Script tag to execute.
In my research on this I've seen people recommend not using the Link tag and instead just using a tags so when navigating to the page it has to reload and force the Script tag to display. Only in my case it's not really an option because I am unable to tell which page the client has decided to output a script tag or not because the website is fully dynamic and able to be constructed all via the CMS.
I've tried:
Doing the dangerouslySetInnerHTML trick with the script. Unfortunately the same thing happens as I've described above
<div
  dangerouslySetInnerHTML={{__html: `<script src=""></script>`}}
/>

I've also tried using next's built in Script tag https://nextjs.org/docs/api-reference/next/script with all the different strategy props. Unfortunately the script content either didn't display at all or it acted the same as above.
I've also tried creating a helper function that uses the useEffect to instate the script tag only after navigating to the page, like so:
import { useEffect } from "react"

const useScript = (url) => {

  useEffect(() => {
    const script = document.createElement("script")

    script.src = url
    script.async = true

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])
}

export default useScript;

and then in the component output to a page:

    {useScript("...")}

This did work! Every time you navigate to the page with the script on it did output the contents of the script tag - not needing a page refresh. The only thing is the contents of the script tag was always output right at the bottom of the page, below the footer and everything. As opposed to where the actual useScript is put in the component.
I tried altering how the useEffect works by making it append the script into an already existing div in the component:
import { useEffect } from "react"

const useScript = (url) => {

  useEffect(() => {
    const script = document.createElement("script")

    script.src = url
    script.async = true
    script.defer = true

    document.getElementById('scriptEx').appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])
}

export default useScript;

But for some reason this doesn't act the same way as the previous setup. On navigation to the page the contents of the script tag don't display again.
The last method I found that does work every single time, but seems like a really ridiculous method to use is putting the script tag inside of an iFrame:
<iframe
    srcDoc={`
    <!doctype html>

    `}
/>

There's got to be a way to do this seemingly simple thing.
If anyone could help it'd be really appreciated!
Edit: Here is an example of what I am seeing using Next's Script tag: https://i.imgur.com/4JeiLFO.png
And here is the jsx that makes up that page:

import Script from "next/script";

const example = () => {
    return (

            The Nav is above this

Container for the form


text:
Q: Next Build failure with seemingly useless error message I was migrating a project over from Heroku to Vercel to take advantage of Next.js. This isn't my first time using Next, but I've never come across a bug like this before.
I was able to build it last night and it worked fine, but somewhere along the line I wound up getting this error message:
HookWebpackError: Unexpected '/'. Escaping special characters with \ may help.
    at makeWebpackError (/opt/homebrew/lib/node_modules/next/dist/compiled/webpack/bundle5.js:41630:9)
    at /opt/homebrew/lib/node_modules/next/dist/compiled/webpack/bundle5.js:25321:12
    at eval (eval at create (/opt/homebrew/lib/node_modules/next/dist/compiled/webpack/bundle5.js:140036:10), <anonymous>:48:1)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
-- inner error --
Error: Unexpected '/'. Escaping special characters with \ may help.
    at /Users/bigsexy/Desktop/currentProjects/portfolio_on_next/static/css/1ec7d2389c57fd3d.css:425:1
    at Root._error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:95188)
    at Root.error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:141043)
    at Parser.error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:103534)
    at Parser.unexpected (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:104020)
    at Parser.combinator (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:102267)
    at Parser.parse (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:109511)
    at Parser.loop (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:108916)
    at new Parser (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:95045)
    at Processor._root (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:111925)
    at Processor._runSync (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:112432)
caused by plugins in Compilation.hooks.processAssets
Error: Unexpected '/'. Escaping special characters with \ may help.
    at /Users/bigsexy/Desktop/currentProjects/portfolio_on_next/static/css/1ec7d2389c57fd3d.css:425:1
    at Root._error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:95188)
    at Root.error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:141043)
    at Parser.error (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:103534)
    at Parser.unexpected (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:104020)
    at Parser.combinator (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:102267)
    at Parser.parse (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:109511)
    at Parser.loop (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:108916)
    at new Parser (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:95045)
    at Processor._root (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:111925)
    at Processor._runSync (/opt/homebrew/lib/node_modules/next/dist/compiled/cssnano-simple/index.js:195:112432)

I dug through every single file and can not find what this is talking about, so I'm guessing it's coming from an npm package? Is there a way to save the build files from a failed build so I can examine the static/css/1ec...css file? ? I've tried running the build with the --debug flag and it doesn't provide anymore information.
I would post code snippets but I don't even know where to look, so here's the repo for anyone with any ideas.
https://github.com/igloo1505/portfolio_on_next
Thanks in advance!

A: It seems like you have a leftover closing comment tag here: https://github.com/igloo1505/portfolio_on_next/blob/main/css/App.css#L429


text:
Q: Accelerator in WinAPI with 2 alphabetical keys Is there a way to create an accelerator in WinAPI with two alphabetical keys? For example, Ctrl+A+S.
How a resource should look like in this case?

A: Win32 accelerators of this form are not supported. If you wish to support such key presses, you need to implement the input handling manually.


text:
Q: Reverse Minkowski (and related) Determinant Inequalities For positive semidefinite matrices $A,B,C \in \mathbb{R}^{n\times n}$, the following inequalities are well known:
$$(\det(A+B))^{1/n} \geq (\det A)^{1/n} + (\det B)^{1/n} $$
and
$$\det(A+B+C) + \det(C) \geq \det(A+C) + \det(B+C).$$
The first is, of course, Minkowski's determinant inequality.
I'm not sure whether the second has a name, but it can be found, e.g., here and here.
I would like to know whether anyone knows of any reverse forms of these inequalities.  To be more specific, I note that the Minkowski determinant inequality can be viewed as a consequence of the Entropy Power Inequality applied to Gaussian random vectors with covariance matrices $A$ and $B$. Applying similar reasoning to the entropy power inequality appearing in Theorem 4 of this paper, we may conclude that the following reverse counterparts to the above inequalities hold:
$$(\det(A+B))^{1/n} \leq (\det A)^{1/n}\left(\frac{\frac{1}{n}\operatorname{Tr}(B^{-1})}{(\det B^{-1})^{1/n}} \right) + (\det B)^{1/n}\left(\frac{\frac{1}{n}\operatorname{Tr}(A^{-1})}{(\det A^{-1})^{1/n}} \right),~~~~~(\star) $$
and
$$(\det(A+B+C) \det(C) )^{1/n} + (\det(A) \det(B) )^{1/n}  \leq (\det(A+C) \det(B+C) )^{1/n} .~~~(\star\star)$$
The first may be obtained from the second by taking $C = \varepsilon I$ and letting $\varepsilon \downarrow 0$.  I view $(\star)$ as a reverse counterpart to Minkowski's determinant inequality, since the ratio
$$\frac{\frac{1}{n}\operatorname{Tr}(B^{-1})}{(\det B^{-1})^{1/n}}\geq 1$$
by the AM-GM inequality applied to the eigenvalues of $B^{-1}$  (and similarly for the ratio involving $A^{-1}$), with near equality if the matrix $B$ has eigenvalues all roughly the same.
Has anyone seen these inequalities before, or does anyone have a direct proof of $(\star\star)$?

A: Inequality ($\star\star$) essentially follows from the original Minkowski plus an implication of Lidkskii's inequality (Fiedler's inequality, noted below).
$\newcommand{\da}{\downarrow} \newcommand{\ua}{\uparrow}$
Assume $C$ is strictly positive definite (otherwise, $\det C=0$ rendering ($\star\star$) trivial), and let $C^{1/2}$ denote the positive square root of $C$. Renaming the matrices $A \leftarrow C^{-1/2}A C^{-1/2}$ and $B \leftarrow C^{-1/2}B C^{-1/2}$, the original inequality reduces to showing that
\begin{equation*}
  \det(A+B+I)^{1/n} + [\det A\det B]^{1/n} \le [\det(I+A)\det(I+B)]^{1/n}.
\end{equation*}
Let $a^\da$ denote the eigenvalues of $A$ in decreasing order; similarly, define $b^\ua$ for $B$. Then, we have
\begin{equation*}
  \det(I+A)\det(I+B) = \prod_i(1+a_i^\da)\prod_i(1+b_i^\ua) = \prod_i(1+a_i^\da + b_i^\ua + a_i^\da b_i^\ua),
\end{equation*}
whence by the Minkowski inequality we get
\begin{equation*}
  [\det(I+A)\det(I+B)]^{1/n} \ge \prod_i(1+a_i^\da+b_i^\ua)^{1/n} + \prod_i(a_i^\da b_i^\ua)^{1/n}.
\end{equation*}
Now from Fiedler's (1971) determinantal inequality we know that
\begin{equation*}
  \prod_i(1+a_i^\da+b_i^\ua) \ge \det(I+A+B),
\end{equation*}
while clearly $\prod_i(a_i^\da b_i^\ua) = \det(A)\det(B)$. Thus, the inequality ($\star\star$) follows.


text:
Q: How to check general conditions? I have translated a code from Matlab (array orientation) to Java(OOP). The problem appeared when I have to translate this feature of Matlab:
min_omegaF_restricted=min(omegaF(p>cost));

Here, omegaF is a vector with the net worth of each firm.
p a vector of prices for each firm.
cost a vector of costs for each firm.
The above calculate the minimal net worth of survivor firms with demanded price higher than their costs.
In java can be translated to:
double min_omegaF_restricted=Double.POSITIVE_INFINITY;
for(int f=0; f<F; f++){
    Firm fo=firms.get(f);
    if(fo.p>fo.cost)
        min_omegaF_restricted=Math.min(min_omegaF_restricted, fo.omegaF);
}

Is there a option to generalize this kind of sentence to whatever condition (fo.p>fo.cost)?

A: Yes. Functional interfaces and lambdas in Java 8 make this simple and easy on the eyes. Create a Predicate which tests an object and returns a boolean value.
Predicate<Firm> predicate = firm -> firm.p > firm.cost;

Then you can defer to the predicate in the loop like so:
double min_omegaF_restricted=Double.POSITIVE_INFINITY;
for(int f=0; f<F; f++){
    Firm fo=firms.get(f);
    if(predicate.test(fo))
        min_omegaF_restricted=Math.min(min_omegaF_restricted, fo.omegaF);
}

What's more, with the new streaming API you can express the whole computation functionally without the explicit for loop.
double min_omegaF_restricted = firms.stream()
    .filter(predicate)
    .mapToDouble(f -> f.omegaF)
    .min()
    .orElse(Double.POSITIVE_INFINITY);


text:
Q: Can't Prove $T(x,0)=0$. Let $T : [0, 1]\times [0, 1] \rightarrow [0, 1]$. A $t$-norm is a function $T$ with properties:
$1. T (x, 1) = x$
$2.$ If $y\leq z$ then $T(x,y)\leq T(x,z)$
$3. T (x, y) = T (y, x) $
$4. T (x, T (y, z)) = T (T (x, y), z) $
Prove $T(x,0)=0$.
I'm trying to prove $T(x,0)\geq 0$ and $T(x,0)\leq 0$.
Obviously, $T(x,0)\geq 0$ because the definition of $T$.
But I can't prove $T(x,0)\leq 0$.
Any hint to prove it?

A: We have $T(0,1)=0$. Hence $0 \leq T(x,0)=T(0,x) \leq T(0,1)=0$.
I hope you can see what properties I have  used in each step of the argument.


text:
Q: How to Text Mining Specific Data I have a list of ID with lengthy descriptions separated with semicolons.  The following is an example of one ID with its description.
  ID      Description
O95831    activation of cysteine-type endopeptidase activity involved in apoptotic process; apoptotic DNA fragmentation; apoptotic process; cell redox homeostasis; chromosome condensation; DNA catabolic process; intrinsic apoptotic signaling pathway in response to endoplasmic reticulum stress; mitochondrial respiratory chain complex I assembly; NAD(P)H oxidase activity; neuron apoptotic process; neuron differentiation; oxidoreductase activity, acting on NAD(P)H; positive regulation of apoptotic process; regulation of apoptotic DNA fragmentation

Problem: Figure out a way to text mining the description in which the expression "mitochondria" or "mitochondrial" or "mitochondrion" is mentioned.  Would regex be useful to solve this problem? or what other ways that might be useful?
Expected Result: extraction of the description which the the phrase "mitochondrial" is mentioned
O95831    ;mitochondrial respiratory chain complex I assembly;

Your help is appreciated,

A: You can use a regex like
(\d+).*(.\s(?:mitochondria|mitochondrial|mitochondrion)[^;]+;)

The capture groups 1 and 2 will contain
O95831    ;mitochondrial respiratory chain complex I assembly;

Example : http://regex101.com/r/mR8xA7/1
Python code would be like
>>> re.findall(r"""(\d+).*(.\s(?:mitochondria|mitochondrial|mitochondrion)[^;]+;)""", str)
[('095831', '; mitochondrial respiratory chain complex I assembly;')]


text:
Q: 500 Internal Server Error Issue
My website is this. I've deleted all files from public html folder. Only cgi-bin lies in it. And now i'm facing 500 Internal Server Error.
I don't know how to handle this. Anyone like to help me out ????

A: You should delete .htaccess file since you have no folders there so I see no point in keeping an .htaccess files with rules. At the time of my answer I can see a wordpress site loading just fine using the URL that you have provided. I assume the problem is gone?!


text:
Q: Creating sub-classes of all external classes I am in a team developing Android applications in an enterprise corporate .One of team members suggested that we should create our own classes, so extending every classes of UI kit (Material Design).
So, if we are going to use a view called Button, we should create class MyPrefixButton extend Button.
It's a huge kit and creating all classes takes time and make project larger.
I don't understand the point of intercepting all classes even you are not going to make changes most of them?
Does it really neccessary to do that?
I would like to hear your opinions and suggestions.

A: This sounds like a clear violation of YAGNI (You aren't gonna need it). Do not develop features, or methods that you do not directly need. Basically only create what you know you are going to need, not what you might need in the future. Who knows you might choose to take an entirely different approach before you have the need.
Besides that, who says that the best way to customize is through the use of inheritance, it could just as well be through composition. Or through some other means of achieving the same.
I would challenge the need for extending all classes, and ask what value it would add to your project here and now. Even if you need the customization later on, you still want to depend on an abstraction any place you use the button.
So if you have the need for a button you depend on Button and not MyPrefixButton or any other specific implementation of the button. So creating a new customization, should not spawn a need for changing too many places in the code.
So based on YAGNI, and the general dependency inversion principle I do not recommend this approach.

A:
We may need to customize views in future if needed. Creating it earlier and using it makes less refactoring effort.

If this is an actual reason, you're using the wrong tools.
Imagine that at some point, you need to add a behavior to all of the buttons in your application, and for some reason, creating a base class is the most straightforward way to do it.
So, what's the problem? You just search the whole source code for the locations where the native button class is used, and you replace them by your own base class. Then you run the tests to check if you didn't break anything, and the change is done. As easy as that.
If you use an IDE (with autocompletion and all), it should have a way to show all the references to a class. Once those references replaced, the IDE can help by showing that now, you have only one reference to the native button class—the one from your own base class.
If you use a text-based editor where you can't search for references, plain text search should do the trick as well. One of the caveats may be the way the external packages are referenced. I don't know how things happen in the language used to develop Android applications, but in C#, for instance, one can fully qualify the name of a class (i.e. prefix it with the namespace), or use just the name of the class, or prefix it with a part of the namespace, or use an alias. This means that you have to do extra work here, which means that for this sort of refactoring, you should favor an IDE.

A: This is an argument you'll need to have with your colleagues. It's probably not necessary, but they might make a good case. Nevertheless, there are some reasons I would tend to avoid this - you will have to judge which ones apply:

*

*There's a good chance you won't need those changes down the line

*If you do, changing the existing uses probably won't be that hard

*It's quite likely that you'll have to change the call-site even if you do have a wrapper

*You may want to include updates from the library, which could force you to update your wrapper and the call site and get rid of something that conflicts with a new feature

*You're increasing the learning curve and invalidating a wealth of online documentation, examples, and support that you get for free by using an existing library

You would be delaying the initial delivery in order to maybe save a little time down the road. That might sound pretty good, but the feedback you can get from an early prototype is much more valuable.


text:
Q: pass json from controller to view Im trying to pass a list of json from my controller to my view but i am missing a big piece of the puzzle. This is the controller method:
 public ActionResult GetList()
        {
            var model = new ViewModel();
            model.Places = new List<Place>
            {

                new Place() {Id = 1, Catch = "Gädda", PlaceName = "Arboga", GeoLat = 59.394861, GeoLong = 15.854361},
                new Place() {Id = 2, Catch = "Aborre", PlaceName = "Fis", GeoLat = 59.394861, GeoLong = 15.845361}

            };

            return Json(model.Places, JsonRequestBehavior.AllowGet);
        }

This is the var in the view to which i am trying to send the list of json:
var data = [];

Any tips on how to go about this? I really have no idea where to start. Thanks!
For simplicitys sake, lets say I have a button in the view that calls GetList()
EDIT:
The code that querys the API:
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
                $.each(data, function (i, item) {
                    var marker = new google.maps.Marker({
                        'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
                        'map': map,
                        'title': item.PlaceName
                    });

(At this point I should add that this code comes from a tutorial:)
http://www.codeproject.com/Articles/629913/Google-Maps-in-MVC-with-Custom-InfoWindow

A: assuming jquery and ajax, then the following would work for you:
$(function(){
    $('#yourbuttonid').on('click', function(){
        $.ajax({
            // in a real scenario, use data-attrs on the html
            // rather than linking directly to the url
            url: '@Url.Action("GetList", "yourcontroller")',
            context: document.body
        }).done(function(serverdata) {
            data = serverdata;
            // as per your edit -now loop round the data var
            $.each(data, function (i, item) {...});
        });
    });
});

you'll have to tweak to suit, but basically, you're sending an ajax request to your controller and then passing the returned data into your data[] var.


text:
Q: Merge array with the same keys, array_merge doesn't work fine I have arrays with the same key like this:
Array1(
    [00] => green
    [10] => red
    [20] => yellow
)

Array2(
    [00] => avocado
    [10] => apple
    [20] => banana
)

I want this:
Array_result(
    [00] => Array(
            [0] => green
            [1] => avocado
        )

    [10] => Array(
            [0] => red
            [1] => apple
        )

    [20] => Array(
            [0] => yellow
            [1] => banana
        ))

Or [0], [1], [2], I do not mind the key, I try array_merge but it doesn't work fine.
EDIT: I don't know why, but array_merge_recursive prints this:
Array
(
    [00] => Array
        (
            [0] => green
            [1] => avocado
        )

    [0] => red
    [1] => apple
    [2] => yellow
    [3] => banana
)

A: You are looking for array_merge_recursive instead of array_merge.
<?php
$A = Array(00 => "green", 10 => "red", 20 => "yellow");
$B = Array(00 => "avocado", 10 => "apple", 20 => "banana");

$result = array_merge_recursive($A, $B);

print_r($result);?>

See it in action.

A: Try that:
function merge($arr){
$n = array();
if(!empty($arr)){
foreach($arr as $a){
if(!empty($a)){
foreach($a as $k => $v){
$n[$k][] = $v;
}}}}
return $n;
}

// use
$a = array('00' => 'green', '10' => 'red', '20' => 'yellow');
$b = array('00' => 'avocado', '10' => 'apple', '20' => 'apple');
print_r(merge(array($a, $b)));


text:
Q: Is there anyway to check the past logs in Drupal? I write a log function for one functionality, seems the logs message only for 24 hours, after that I couldn't see it.
Is there anyway to check the logs for past days in drupal?

A: If you're finding limitations with database logging, you might want to try enabling the core Syslog module (https://www.drupal.org/docs/8/core/modules/syslog/overview), which will send Drupal logs to your operating system's syslog file (e.g. /var/log/messages or /var/log/syslog) or a custom log file.


text:
Q: Print image files using python I generated some barcode files using python-barcode as png image files.
and I would like to know the best way to actually print those image files on actual paper using the system printer.
Bulk processing is the way for me.
Any hint would be much appreciated.

A: maybe it works pywin32 , sample document link
http://timgolden.me.uk/python/win32_how_do_i/print.html


text:
Q: How to change the "Apache/2.4.7 (Ubuntu) Server at localhost Port 80" line in Apache? When I open the browser and I go to localhost in my web-browser, and there is not an index.* file the Apache webserver will show a file browser.
At the end of the file browser, it posts this line:
Apache/2.4.7 (Ubuntu) Server at localhost Port 80

Is there any way to change this message, and if so, where can I find the configuration file that creates this message in Ubuntu 14.04.01?
I have searched on Google for some time but I can't find anything that points me in the correct direction.
Any help would be appreciated.

A: First of all set server signature to off, by setting:
ServerTokens ProductOnly
ServerSignature Off

in httpd.conf file. If you want a custom page than use ErrorDocument XXX /path/to/page.html to set different pages. For example: ErrorDocument 403 /error/denied.html


text:
Q: Automatically toggle RTS line (Delphi Prism SerialPort) I am using SerialPort under Delphi Prism. I am able to send bytes out to the serialport, but I can't receive data from outside, because the SerialPort Request to Send (RTS) line is always high or up. So, what setting do you set to automatically toggle the RTS line?
Here are the serialport properties I set:
SerialPort1 := new System.Io.Ports.SerialPort();
SerialPort1.BaudRate:=19200;
SerialPort1.DataBits:=8;
SerialPort1.DtrEnable:=true;
SerialPort1.Parity:=System.IO.Ports.Parity.Even;
SerialPort1.PortName:='COM1';//'/dev/ttyS0';
SerialPort1.ReadBufferSize:=3000;
SerialPort1.ReadTimeout:=1000;
SerialPort1.ReceivedBytesThreshold:=1;
SerialPort1.RtsEnable:=true;
SerialPort1.StopBits:=System.IO.Ports.StopBits.One;
SerialPort1.WriteTimeout:=1000;
SerialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(@MySerialData);
SerialPort1.Open;

I do have DTR set. Request to Send line is how you control when to read and write data to the serial. RTS is high then you can only write and if RTS is low you can only read. We have checked the communication line on the oscilloscope and the RTS line is always high, which means our program can only send bytes but not able to read any bytes or data from outside. That is the main reason why the DataReceived Event never gets to execute, because it never sees any incoming bytes or data.
So, after looking at my serial port setting, can you tell me what I am missing.

A: RTS is output so it doesn't have anything to do with receiving. Try turning on DTR and/or CTS.
EDIT:
Try removing the RTS enabled line and adding handshaking for RTS/CTS (not sure what exactly it is in Delphi). I know what the pins are for and what they are supposed to do. Do you have the pinouts showing how this is wired. I assume 2 & 3 are crossed, DTR to DSR both directions, RTS to CTS both directions.


text:
Q: Switch to, and from, Preview, with 1 keyboard shortcut? I tried using textInputFocus && !inputFocus && editorLangId == 'markdown' and textInputFocus && editorReadonly && editorLangId == 'markdown' in When Expression for markdown.showSource, with relevant respective versions for markdown.showPreview .
But the shortcut still doesn't work when the Preview has Focus .

A: If you look at the markdown.showSource in the Keybindings Shortcuts you will see it has no context/when clause.  It must just find the matching resource and go to it.
Also when a preview is active, you will see that the language ID in the bottom right corner disappears, so editorLangId == markdown will presumably always fail.
If you want a when clause to prevent keybinding conflicts, try:
  {
    "key": "alt+e",
    "command": "markdown.showSource",
    "when": "markdownPreviewFocus"
  }

Learn about the Developer: Inspect Context Keys command, see inspect context keys utility.  That is how I found the markdownPreviewFocus clause.


text:
Q: How to implement a search in multiple fields in API Platform and Sylius? I'm implementing a product search in Sylius 1.8.5 (based on API Platform 2.5.7 and Symfony 4.4.16).
The basic variant for the search in the product.translations.name (see the code below) is working. But now I want to be able to search in multiple fields, e.g. in product.translations.name, product.translations.description, and product.translations.short_description. The problem is, that adding of further criteria will just make the filtering stricter, because the logic behind it, implemented in the ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter, only knows the AND connector and uses the andWhere(...) internally.
Sure, as workaround I can simply override the API Platform's SearchFilter by a custom one and change the logic how I want. But maybe there is a more elegant / built-in solution for this case? I have the feeling, it should be, since the scenario I want to implement is a very common one and probably needed in nearly every (shop) application with a (product) search functionality.
What is a proper way to implement a (product) search in multiple properties / fields in API Platform / Sylius?

services.yaml
imports:
    - { resource: "filters.yaml" }

filters.yaml
<?xml version="1.0" ?>
...
<resources ...>
    <resource class="%sylius.model.product.class%" shortName="Product">
        <collectionOperations>
            <collectionOperation name="admin_get">
                ...
            </collectionOperation>
            <collectionOperation name="shop_get">
                <attribute name="method">GET</attribute>
                <attribute name="path">/shop/products</attribute>
                <attribute name="filters">
                    <attribute>sylius.api.product_order_filter</attribute>
                    <attribute>sylius.api.product_taxon_code_filter</attribute>
                    <attribute>sylius.api.translation_order_name_and_locale_filter</attribute>
                    <attribute>shop.product_search_filter</attribute> <-- added
                </attribute>
            </collectionOperation>
            <collectionOperation name="admin_post">
                ...
            </collectionOperation>
        </collectionOperations>
    </resource>
</resources>

filters.yaml
services:
    # Filter Services
    shop.product_search_filter:
        autowire: false
        autoconfigure: false
        public: false
        parent: 'api_platform.doctrine.orm.search_filter'
        arguments: [ { translations.name: 'partial', translations.locale: 'exact' } ]
        tags: [ name: 'api_platform.filter' ]


text:
Q: Is it possible to use Cygwin on Windows to develop Node.js apps with Yarn? I would like to get started with, and use yarn.
I am using cygwin on windows, I launch and type:
$yarn init

and I get:
$ yarn init
yarn init v1.12.3
error An unexpected error occurred: "Can't answer a question unless a user TTY".
info If you think this is a bug, please open a bug report with the information provided in "C:\\home\\code\\repos\\pwa\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/init for documentation about this command.

What does means: "Can't answer a question unless a user TTY"?
Am I prevented from using a bash shell provided by cygwin with yarn?  I could not find any document telling me what terminal/shell I should download and use.
I need to be productive using my bash shell with scripts, aliases, command line completion, and have access to a full range of gnu commands for scripting and so therefore a DOS command prompt or powershell is not an option.

A: Yes!
TL;DR: Update to the latest yarn version. Skip to the end to see how to get the latest version. It is NOT as simple as it sounds.
I believe it could be done in yarn 1.x if you modify the /c/Program Files/nodejs/yarn file to work correctly with cygwin. I don't get why that script was written the way it was, but I can see why it wouldn't work on the cygwin terminal: for some paths, it converts them to windows paths, then appends linux paths to the end of it. I bet if you modify that to use linux (i.e., cygwin) paths, yarn 1.x will run correctly.
But, this is not a great answer because it's all hypothetical. Luckily, there's an even simpler solution that isn't hypothetical: upgrade to the latest yarn. Once I did this, cygwin worked correctly. They probably fixed a bug in the older versions.
You may be saying to yourself, "I just ran npm install yarn so I already have the latest version." That doesn't mean you have the latest yarn. For some reason, that installs the latest version of 1.x. The latest version of yarn is 3.x.
Also, to go from 1.x to latest, you need to run some ad-hoc commands -- as opposed to npm installing something else.
Here is the guide to go from yarn 1.x to latest:

*

*Run npm install -g yarn to update the global yarn version to latest v1

*Go into your project directory

*Run yarn set version berry to enable v2

*If you used .npmrc or .yarnrc, you'll need to turn them into the new format

*Add nodeLinker: node-modules in your .yarnrc.yml file
I don't know what step 4 means. But my current .yarnrc looks like this:
yarnPath: ".yarn/releases/yarn-berry.cjs"
nodeLinker: node-modules

*Commit the changes so far (yarn-X.Y.Z.js, .yarnrc.yml, ...)

*Run yarn install to migrate the lockfile

*Use yarn the way you normally would.


text:
Q: Background image for a webpage I'm new for the ASP.NET. I need to know how to add a background image for my webpage?

A: You can do this with CSS, you don't need to do anything with ASP here.
Add the following code to your Style.css file and make sure you change the path to your background image to your real image.
body {
    background-image: url(images/myImage.png);
}

Now, no matter how many pages you have, you have your background image defined in only one place.  In the future, you can change the background image for all of your web pages (that reference your CSS file) by changing this one line.

A: If its an image you want to be repeated horizontal of vertical,
you can use repeat-x or repeat-y
body {
background-image: url(images/photo1.png);
background-repeat: repeat-y;
}


text:
Q: Creating a printable/downloadable PDF of a web application I have been searching for an answer to this problem now for several weeks. I also previously tried to research this a few years ago to no avail.
Problem Summary:
My company has developed a web-based data analytics suite for a major beverage distributor. They have recently asked for a feature that allows the user to print or download a visually pleasing version of the rendered app as a PDF. I have had no luck in finding a solid, controllable, or reliable method to do this. I was hoping the stack community might be able to point me in the right direction.
Current Tech Stack:

*

*Plack servers

*Perl base on the Dancer framework

*Standard web dev front-ends: HTML5, CSS3, Javascript, Jquery/UI

*Client is using IE9/10 and Chrome.

Attempted Solutions Summary:
Obviously I started with the window.print() and tried to control what printed using classes and a specialized print.css but the output was still awful.
I looked in to pdfmachine and pdfbox and even contacted Adobe's acrobat development team directly to see if they had an out of the box solution our company could purchase. I was informed that such a product would be counter intuitive to their desired business model of putting an acrobat subscription on each client computer rather than a single server side application.
I have extensively searched the stack articles but did not feel that the articles I found covered what I was looking for.
At present, I am all out of ideas and am hoping somebody out there has had better luck at this than I have.
tl;dr = I need a pdf version of the rendered output of a complex reporting app.
Thanks for your time stack, I appreciate it.

A: A solution I have used in the past is to use PhantomJS running on a server to generate the PDF for download/email. Usually if the content is sensitive the server (that handles authentication) would provide a single use viewing token that is then passed to a PhantomJS process. It loads the URL with the viewing token then saves as a PDF.
Further info on Phantoms screen cap API can be found here on GitHub.
https://github.com/ariya/phantomjs/wiki/Screen-Capture

A: Is it something you can create in Perl using PDF::API2 or PDF::Create?  You can load and modify and existing PDF (handy if you want standard headers and footers), and then insert the relevant content.  The learning curve can be a bit steep, but simple reports should be easy enough.
See PDF::TextBlock and PDF::Table too - they are great little helpers.

A: Consider this service http://pdfmyurl.com/ . I try to use many perl modules, but they dont satisfy my problems.


text:
Q: How restrict the drag element between one boundary in Angular Material 7 CDK? For my current project am trying to implement the drag element one position to another position inside one div. For this I am using the Angular Material 7 CDK drag and drop features. it dragging all over the page but want to only drag inside particular div. But I didn't see any option to control the boundary in Angular Material 7 CDK drag and drop.
Can anyone tell me how to control boundary in material or suggestion some other plugins which is compactable for angular 7. ?
Thanks.

A: You can use cdkDragBoundary which will be useful to prevent the user from being able to drag an element outside of another element.
You can use it as following:

    I can only be dragged within the dotted container

You can read more about it from here Angular Material Restricting movement within an element


text:
Q: Problems with display nav properly
*

*I'm having trouble with adding space to the hovered "home" right/left.

*Adding proper spacing so after the hovered section of "home" appears that about and the other pages would follow.

CSS:
nav {
    width:460px;
    height:50px;
    background-color:#0066ff;
    float: left;
    margin: 15px 0 0 324px;
    position: fixed;
}

nav ul {
    margin: 0;
    padding: 0;
    position: fixed;
    width:493px;
    border: 1px solid green;
}

nav li {
        float: left;
    text-align: left;
    margin:0;
    padding: 0 0 0 24px;
    display: block;
    width: 51px;
    height: 50px;
}

nav li:first-child {
    float: left;
    text-align: left;
    margin:0;
    padding: 0 15px 0 0;
    display: block;
    height: 50px;
}

nav a:first-child {
    margin: 0;
    padding: 0;
    height: 50px;
    min-width:51px;
    display:block;
    position: fixed;
    line-height:50px;
    float: left;
    text-align: center;
}

nav a {
    margin: 0;
    padding: 0;
    height: 50px;
    min-width:51px;
    display:block;
    position: fixed;
    line-height:50px;
    float: left;
    text-align: center;
}

nav ul li a:link, nav ul li a:visited {
    text-decoration: none;
    color:#fff;
    display:block;
}

nav ul li a:hover, nav ul li a:active {
    background: #929292;
    text-decoration: none;
    display:block;
}

This problem has been giving me headaches for hours.

Link Update

The blue space beside about can't happen.

A: Nick, your issue is in the li:first-child selector. Specifically the padding attribute, where it clears the padding, where you're missing the spacing.

*

*Many of your :first-child selectors are redundant, and don't need to be re-specified.

*Mixing position:fixed with float:left is generally not a good idea as your CSS will be fighting layout structure.

*You only need a position:fixed for the main container, the rest the nav's children will be relative to that.

*There's a lot of unnecessary padding and such, you should use your browser's DOM inspector to play with the layout.

Check this JSFiddle that's cleaned it up.

A: A lot of the time, a small
 is placed to the left of the "home" link to push it over like so:
#fillerdiv{
width:20px;
background-color:#0066ff;
}

then you could place it like so:

 Home

About

Work

Services

Clients

Contact

That produces this:

Or you could give the "home" button a specific class and add extra padding for it alone.
#home{
     padding-left:20px;
}

And the HTML:

 Home

About

Work

Services

Clients

Contact

A: I played around your code a bit and tried to simplify it. I hope you don't mind.
JSFiddle
/* styles.css */
nav {
    float: left;
   background: #0066ff;
    border: 1px solid green;
}

nav ul {
    margin: 0;
    padding: 0;
}

nav li {
    float: left;
    display: block;
}

nav a {
    margin: 0;
    padding: 0;
    padding:20px;
color:#fff;
    text-align: center;
}

nav ul li a:link, nav ul li a:visited {
    text-decoration: none;
    display:block;
}

nav ul li a:hover, nav ul li a:active {
    background: #929292;
    text-decoration: none;
    display:block;
}


text:
Q: Concerning the values on the boundary and the value in a open set I bring up this question because in many reference books this result is always directly used without any explanation, which might be kind of confusing for a beginner.
If we assume |f(z)| $\lt$ M in an arbitrary disk D, if f analytic, then |f| $\le$ M on $\partial D$. This stems from the continuity.
Now, 1. is this statement correct?
In other words, if we know a bound for the interior points, we also know this can be a bound for values on the boundary. (provided f analytic in a region including the disk)
2.When we took the region to be the maximum region that f can be analytic, I thought this statement no longer holds since then there must be a pole on the boundary, which causes trouble in every sense.

A: Yes, the statement is correct. If $|f(z_0)|>M$ for some $z_0\in\partial D$, then there is some $\delta>0$ such that $|z-z_0|<\delta\implies|f(z)-f(z_0)|>|f(z_0)|-M\implies|f(z)|>M$. And the disk $D(z_0,\delta)$ contains points of $D$.


text:
Q: Angular 2: Programmatically to position inside div overlay I've customized a PrimeNg TabView and wrapped it inside a custom component in order to achieve this:

As you can see the tabview content has overflow-x: hidden so it can look better, to allow users to navigate between tabs that are hidden I've add two buttons, one on each side of the tabview.
Now I am trying to develop those buttons click functionality and I dont know how I can achieve that.
This is how my component looks like:

 chevron_left

 chevron_right

linha-tempo .wrapper {
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  -moz-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  -o-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  -webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  position: fixed;
  top: 55px;
  width: 100%;
}

linha-tempo .tab-container {
  border: none !important;
  margin: 0 auto;
  width: calc(100% - 80px);
  border-radius: 0px;
 }

linha-tempo #back, linha-tempo #forward {
  width: 40px;
  position: fixed;
  top: 55px;
  line-height: 33px;
  text-align: center;
  cursor: pointer;
}

linha-tempo #back {
  left: 0px;
}

linha-tempo #forward {
  right:0px;
}

linha-tempo #back i, linha-tempo #forward i {
  line-height: 2;
  color: white;
}

linha-tempo .ui-tabview-panel {
  display: none !important;
}

linha-tempo .ui-tabview-nav, linha-tempo .ui-tabview-nav > li.ui-state-active {
  border-bottom: none !important;
  background-color: transparent !important;
  line-height: 1.8;
}

linha-tempo .ui-tabview-nav {
  color: rgba(255, 255, 255, 0.6);
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

linha-tempo .ui-tabview-nav > li {
  border: none !important;
  width: 150px;
  border-radius: 0px 0px 0px 0px !important;
  -webkit-border-radius: 0px 0px 0px 0px !important;
  -moz-border-radius: 0px 0px 0px 0px !important;
}

linha-tempo .ui-tabview-nav > li.ui-state-active {
  color: white;
}

linha-tempo .ui-tabview-nav a {
  color: rgba(255, 255, 255, 0.7) !important;
  width: 100%;
  box-sizing: border-box;
  text-align: center;
  display: block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

linha-tempo .ui-tabview-nav > li.ui-state-active a {
  color: white !important;
  border-bottom: 2px solid white;
  cursor: default !important;
}

body .ui-tabview .ui-tabview-nav > li.ui-state-hover {
  background-color: transparent !important;
}

Any help is welcome

A: I have tried scrolling left and right for a div on click.
You can do the same for tabs as well.
Kindly look into the following link for detailed reference
http://www.w3schools.com/code/tryit.asp?filename=FAB7S70J7UZD
Please let me know in case of any query.


text:
Q: nodejs foreach swig and ejs I'm trying to convert some code from swig to ejs, but are facing an issue with a "for" loop.
The problem is that the loop inside the swig file is looping trough the content from the config.json file correctly. However when i try to implement similar code in ejs i cant get it to work and need some guidance.
I have a config.json file i'm looping trough:
{
  "server" : {
    "port" : 3000,
    "ssl" : false,
    "ssl_cert" : "/home/pi/lirc_web/server.cert",
    "ssl_key" : "/home/pi/lirc_web/server.key",
    "ssl_port" : 3001
  },
  "repeaters": {
    "lg": {
      "KEY_VOLUMEUP": true,
      "KEY_VOLUMEDOWN": true
    }
  },
  "macros": {
    "TESTTV": [
      [ "lg", "KEY_VOLUMEUP" ],
      [ "lg", "KEY_VOLUMEUP" ],
      [ "lg", "KEY_VOLUMEDOWN" ]
    ]
  },
  "commandLabels": {
    "lg": {
      "KEY_VOLUMEUP": "Volume Up",
      "KEY_VOLUMEDOWN": "Volume Down"
    }
  },
  "remoteLabels": {
     "lg": "LG TV"
  },
  "blacklists": {
  }
}

The route.js file contains (code snippet):
config = require('../config.json');

app.get('/profile', isLoggedIn, function(req, res)
{
    app.get('/remotes.json', function (req, res) {
        res.json(refineRemotes(lircNode.remotes));
    });

    var refinedRemotes = refineRemotes(lircNode.remotes);
        res.render('remotes.ejs', {
        macros: macrostwo,
        remotes: refinedRemotes,
        macros: config.macros,
        repeaters: config.repeaters,
        labelForRemote: labelFor.remote,
        labelForCommand: labelFor.command,
      });

      console.log('DEBUG: ConfigFile Macros: \n', macrostwo);
});

The swig file, which is working contains:

  {% for macro in macros %}
    {% set macroName = loop.key %}

<button class="btn btn-wide btn-large btn-warning macro-link" href="/macros/{{ macroName|url_encode }}">{{ macroName }}</button>

  {% endfor %}

The ejs file im working on have below code:

    <% macros.forEach(function(macro){ %>

<button class="btn btn-wide btn-large btn-warning macro-link" href="/macros/<%=macro.name%>">  <%=macro.name%> </button>

    <% }) %>

If i change my routes.js file to pass in below code to ejs view the foreach loop is working correctly
var macrostwo = [
{ name: 'Nathan Explosion', message: 'Dethklok rules' },
{ name: 'William Murderface', message: 'Bass is the heart of the band' },
{ name: 'Dr. Rockso', message: 'Where is my friend Toki?' }
];

app.get('/profile', isLoggedIn, function(req, res)
{
    app.get('/remotes.json', function (req, res) {
        res.json(refineRemotes(lircNode.remotes));
    });

    var refinedRemotes = refineRemotes(lircNode.remotes);
        res.render('remotes.ejs', {
        macros: macrostwo,
        remotes: refinedRemotes,
        macros: macrostwo,              //config.macros,
        repeaters: config.repeaters,
        labelForRemote: labelFor.remote,
        labelForCommand: labelFor.command,
      });

      console.log('DEBUG: ConfigFile Macros: \n', macrostwo);
});

EDIT1:
I have been trying to get he object.keys but i just get "1" when printing to the console. I know i use macros.name in the ejs file, which is "non" existing in the config.json. The issue is that i dont know how to get the key names when looping trough.
/Thomas

A: Found a solution:
route.js:
app.get('/profile', isLoggedIn, function(req, res)
{
    app.get('/remotes.json', function (req, res) {
        res.json(refineRemotes(lircNode.remotes));
    });

    console.log('=============\n');

    var keys = Object.keys(config.macros);
    console.log(keys);

    console.log('\n=============\n');

    var refinedRemotes = refineRemotes(lircNode.remotes);
    res.render('remotes.ejs',{
        remotes: refinedRemotes,
        macros: keys, //config.macros,
        repeaters: config.repeaters,
        labelForRemote: labelFor.remote,
        labelForCommand: labelFor.command,
    });
});

ejs file:

    <% macros.forEach(function(macro){ %>

<button class="btn btn-wide btn-large btn-warning macro-link" href="/macros/<%=macro%>">  <%=macro%> </button>

    <% }) %>


text:
Q: git rebase -i presents an empty MacVim file I'm trying to rebase a commit. However, any time I run git rebase -i f83eff3ffc8, for example, a MacVim window opens, that's empty (there is no information in the file). Then once I write and close the file (even though it's empty), I get a Successfully rebased and updated refs/heads/clicktocall-hotfix message.
The file name is .git/rebase-merge/git-rebase-todo. I also tried running it with sudo but this didn't make a difference.
What could be the problem? I've never successfully completed a rebase.

A: I was using Macvim and needed to run mvim with the -f option, as documented here: GIT_EDITOR not working with macvim

A: For atom I was able to fix by adding the wait flag to gitconfig (reference https://help.github.com/articles/associating-text-editors-with-git/)
[core]
    editor = atom --wait

A: I was using Atom and run into this problem. I set my default editor like this:
export VISUAL=vim
export EDITOR="$VISUAL"

Now everything is working great.
TL;DR; Use Vim.

A: Ran into this as well in VS Code, and the issue was that I had forgotten the "wait" flag in my editor config.
Solved by running:
git config --global core.editor "code --wait"

A: You should not even have to look at the git-rebase-todo file. Vim should display a noop line and some comments. After saving that, you should get "Successfully rebased and updated ".
You are either using an old version of git, you have a broken git install or you have touched the .git folder in some way to cause it to behave this way.


text:
Q: margin-top property in CSS Why does margin-top value not work in IE?
Works fine in FF and Safari. Here's the link
Thanks

A: *

*Collapsing Margins

A: I see your #papertop is empty. Try adding some   inside to see if that does the trick.
Edit: forget it; this doesn't work.

A: For a quick workaround this will achive the same thing.
#papertop {
background:transparent url(images/paper_top.png) no-repeat scroll right bottom;
height:250px;
position:relative;
z-index:300;
}


text:
Q: sklearn and weka kNN predictions exactly same for all except for one data point I wrote a code for kNN using sklearn and then compared the predictions using the WEKA kNN. The comparison was done using the 10 test set predictions, out of which, only a single one is showing a high difference of >1.5 but all others are exactly the same. So, I am not sure about if my code is working fine or not. Here is my code:
df = pd.read_csv('xxxx.csv')
X = df.drop(['Name', 'activity'], axis=1)
y = df['activity']
Xstd = StandardScaler().fit_transform(X)
x_train, x_test, y_train, y_test = train_test_split(Xstd, y, test_size=0.2,
shuffle=False, random_state=None)
print(x_train.shape, x_test.shape)
X_train_trans = x_train
X_test_trans = x_test
for i in range(2, 3):
    knn_regressor = KNeighborsRegressor(n_neighbors=i, algorithm='brute',
weights='uniform', metric='euclidean', n_jobs=1, p=2)

    CV_pred_train = cross_val_predict(knn_regressor, X_train_trans, y_train,
n_jobs=-1, verbose=0, cv=LeaveOneOut())
    print("LOO Q2: ", metrics.r2_score(y_train, CV_pred_train).round(2))

    # Train Test predictions
    knn_regressor.fit(X_train_trans, y_train)
    train_r2 = knn_regressor.score(X_train_trans, y_train)
    y_train_pred = knn_regressor.predict(X_train_trans).round(3)
    train_r2_1 = metrics.r2_score(y_train, y_train_pred)
    y_test_pred = knn_regressor.predict(X_test_trans).round(3)
    train_r = stats.pearsonr(y_train, y_train_pred)

    abs_error_train = (y_train - y_train_pred)
    train_predictions = pd.DataFrame({'Actual': y_train, 'Predcited':
    y_train_pred, "error": abs_error_train.round(3)})
    MAE_train = metrics.mean_absolute_error(y_train, y_train_pred)

    abs_error_test = (y_test_pred - y_test)
    test_predictions = pd.DataFrame({'Actual': y_test, 'predcited':
    y_test_pred, 'error': abs_error_test.round(3)})

    test_r = stats.pearsonr(y_test, y_test_pred)
    test_r2 = metrics.r2_score(y_test, y_test_pred)
    MAE_test = metrics.mean_absolute_error(y_test, y_test_pred).round(3)
    print(test_predictions)

The train set statistics are almost same in both sklearn and WEKA kNN.
the sklearn predictions are:
Actual  predcited  error
6.00      5.285 -0.715
5.44      5.135 -0.305
6.92      6.995  0.075
7.28      7.005 -0.275
5.96      6.440  0.480
7.96      7.150 -0.810
7.30      6.660 -0.640
6.68      7.200  0.520
***4.60      6.950  2.350***

and the weka predictions are:
actual  predicted      error
6          5.285     -0.715
5.44       5.135     -0.305
6.92       6.995      0.075
7.28       7.005     -0.275
5.96       6.44       0.48
7.96       7.15      -0.81
7.3        6.66      -0.64
6.68       7.2        0.52
***4.6        5.285      0.685***

parameters used in both algorithms are: k =2, brute force for distance calculation, metric: euclidean.
Any suggestions for the difference?


text:
Q: PSQL Error: function does not exist I have made a function in postgres
CREATE OR REPLACE FUNCTION foobar(
    x TEXT,
    y TEXT,
    z REAL
) RETURNS BOOLEAN AS $func$
.
.
.
$func$ LANGUAGE plpgsql;

When I do \df i get the following:
+----------+--------+------------------+------------------------+---------+
|  Schema  |  Name  | Result data type |  Argument data types   |  Type   |
+----------+--------+------------------+------------------------+---------+
| mySchema | foobar | boolean          | x text, y text, z real | normal  |
+----------+--------+------------------+------------------------+---------+

But when I try to use it I get [42883] ERROR: function foobar(text, text, real) does not exist. Hint: No function matches the given name and argument types. You might need to add explicit type casts. The call I'm doing is:
SELECT * FROM myTable WHERE foobar(column1::text, 'hello'::text, 7.2::real);

To me it seems like the function exists and the types match, I'm struggling to figure out what's wrong.

A: As a_horse_with_no_name mentioned in his comment, the solution is prefix the function with the schema.
Wrong:   SELECT * FROM myTable WHERE foobar(column1::text, 'hello'::text, 7.2::real);
Correct: SELECT * FROM myTable WHERE mySchema.foobar(column1::text, 'hello'::text, 7.2::real);


text:
Q: Is there a function to see how long a script takes to run? I have a python script than can sort files and i want to know how long it takes to run.
i searched for a module that's names time but it didnt work and it asked me to put a real time.

A: You can calculate execution time like that:
import time

start_time = time.time()

# your script here

end_time = time.time()
execution_time = end_time - start_time

print("Execution time:", execution_time, "seconds")

A: I prefer to use time.perf_counter() if we are talking about timing code:
from time import perf_counter

# Get the start 'time'
t1 = perf_counter()

# Some complex time-consuming function
for i in range(10**9):
    pass

# Get the end 'time'
t2 = perf_counter()

# Now you subtract the start time from the end time and you have your elapsed time:
print("Elapsed time:",t2-t1)

Check the documentation here: https://docs.python.org/3/library/time.html#time.perf_counter


text:
Q: PendingIntent scheduled using AlarmManager.RTC type is still invoked in the sleep mode Here is the code that I used to set an alarm for my widget:
 private static void setAlarm(Context context) {
    Intent myIntent = new Intent(context, Widget.class);
    myIntent.setAction(AUTO_UPDATE);
    PendingIntent pendingIntent =
            PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 8);
    alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
            pendingIntent);
}

but the problem is that even in the sleep mode, onReceive() is still triggered by the intent.
Although after using setInexactRepeating instead of setRepeating, the delays between calls get increased up to 1 minute in sleep mode, but that's still battery consuming.

A: I believe you are setting the alarm to trigger 8 seconds after the Calendar's time, which you have set 8 seconds ahead of the current time .. so you are setting the alarm to trigger instantly.
I don't see any reason you need a Calendar here. The calendar is just used to track the time 8 seconds in the future here:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 8);

The alarm is created to trigger every 8 seconds here:
alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
        pendingIntent);

The alarm continues to trigger every eight seconds.
I would try changing:
alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
        pendingIntent);

To:
alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), 8000,
        pendingIntent);

If you continue having problems, then maybe the interval is the problem. Try changing setRepeating() to set() to see if that's the case.


text:
Q: FreeSync fails in Ubuntu 16.04 LTS, tearing with a Radeon video adapter My PC has an MSI AMD Radeon RX 580 display adapter, an AMD Ryzen 7 1800X CPU, and an AOC Gaming G2460PF 24" display. The same thing happens on Ubuntu 16.04.4 and Kubuntu 18.04 beta 2: DISPLAY=:0 xrandr --prop tells nothing about the FreeSync (from the AMD's manual), i.e. there are no freesync_capable and freesync parameters at all. Installing the AMDGPU-PRO driver didn't help. Tried on the DP, DVI-D, and HDMI ports.
There is a very strong tearing when just scrolling in Chrome or playing a game (especially on Ubuntu 16.04 which is officially supported by AMD), and the Dota 2 client shows "Failed to initialize Vulkan".

A: xrandr --output DisplayPort-0 --set TearFree on

Worked for me with the "scroll tearing".
Hope it helps ^_^

A: Thanks it works for me, xubuntu 16.04.5 with AMD RX 580.
Should highlight that --output parameter may be different, depends where your monitor is connected. To list all available outputs you may run:
xrandr

In my case it was HDMI 1 port, so command was following:
xrandr --output HDMI-A-1 --set TearFree on


text:
Q: $scope is not updated in AngularJS I have integrated pagination and sorting in my AngularJS project. I want to show the data according to page per item using user's choice. When I integrate this thing I got problem of updating the scope variable. Here is my code:

{{partners.name}}

{{partners.website}}

{{partners.location}}

{{partners.service}}

{{partners.connection}}

{{partners.action}}

I have include the file for pagination and for item per page:
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="templates/dashboard/dirPagination.tpl.html"></dir-pagination-controls>

This is the dirPagination.tpl.html file:
<select class="filterSelect"  ng-options="limits.value as limits.value for limits in availableLimits" ng-model="limits"  ng-change="selectLimit()">

                    </select>

Controller code:
    $scope.currentPage = 1;
    $scope.limitData = 1;
    $scope.selectLimit = function ()
    {
         //console.log($scope.limits);
         var limits = $scope.limits
         $scope.limitData = limits;
    };

A: Please, refer this code. It's working fine.
http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview
function MyController($scope) {

  $scope.currentPage = 1;
  $scope.pageSize = 10;
  $scope.meals = [];

  var dishes = [
    'noodles',
    'sausage',
    'beans on toast',
    'cheeseburger',
    'battered mars bar',
    'crisp butty',
    'yorkshire pudding',
    'wiener schnitzel',
    'sauerkraut mit ei',
    'salad',
    'onion soup',
    'bak choi',
    'avacado maki'
  ];
  var sides = [
    'with chips',
    'a la king',
    'drizzled with cheese sauce',
    'with a side salad',
    'on toast',
    'with ketchup',
    'on a bed of cabbage',
    'wrapped in streaky bacon',
    'on a stick with cheese',
    'in pitta bread'
  ];
  for (var i = 1; i <= 100; i++) {
    var dish = dishes[Math.floor(Math.random() * dishes.length)];
    var side = sides[Math.floor(Math.random() * sides.length)];
    $scope.meals.push('meal ' + i + ': ' + dish + ' ' + side);
  }

  $scope.pageChangeHandler = function(num) {
      console.log('meals page changed to ' + num);
  };
}

A: It is the problem of scope inheritance in Angular or in Javascript. Read more on this here.
To fix your problem, first define an object like this:
$scope.modelData = {};
$scope.modelData.currentPage = 1;
$scope.modelData.limitData = 1;

$scope.selectLimit = function() {
     $scope.modelData.limitData = $scope.limits;
};

Now, update your views to use the new object $scope.modelData (I'm writing it at one place, you can fix this at other places if any):

Defining an object $scope.modelData and using it all the places will eliminate the problem of nested scope which is being created by the repeat expression.

A: Are you missing an ";" in the end of var limits = $scope.limits ? Sometimes JS drives you crazy with these types of errors.


text:
Q: OpenERP - Can I just get city name in my form field with "res.better.zip"? I have a custom form that inherit city from "res.better.zip", this is the python code:
city= fields.Many2one('res.better.zip', 'City:')

but when I search for a city, it autofill with "zip code, city, state and country", can I only get the "city" in this field?
P.D. this is the field in the .xml
<field name="city" class="oe_no_button" placeholder="p. ej. Madrid" options="{"no_open": True}" attrs="{'readonly': [('city','=',True)]}"/>

A: If i understand your question correctly, what you need to do is define _rec_name on your res.better.zip model, like:
_rec_name = 'city'

Note that will change default name for whole model res.better.zip.


text:
Q: python conda environment install package order Creating an environment conda (anaconda/miniconda python) from a package list file (see bottom of message).
I've specified matplotlib version to 3.0.2, after creating env, I run python then:
Python 3.7.9 (default, Aug 31 2020, 12:42:55)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.__version__
'3.3.2'

I've to conda uninstall matplotlib then conda install matplotlib=3.0.2 to have then good version of matplotlib.
I think basemap package enter in conflict with matplotlib that's why this happens.
How can I do a clean environment creation without having to uninstall/install matplotlib ?
# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: linux-64
_libgcc_mutex=0.1=main
basemap=1.2.0=py37h856778e_4
blas=1.0=mkl
bzip2=1.0.8=h7b6447c_0
ca-certificates=2020.10.14=0
certifi=2020.6.20=pyhd3eb1b0_3
cftime=1.2.1=py37heb32a55_0
curl=7.71.1=hbc83047_1
cycler=0.10.0=py37_0
dbus=1.13.18=hb2f20db_0
expat=2.2.10=he6710b0_2
fontconfig=2.13.0=h9420a91_0
freetype=2.10.4=h5ab3b9f_0
geos=3.8.0=he6710b0_0
glib=2.66.1=h92f7085_0
gst-plugins-base=1.14.0=hbbd80ab_1
gstreamer=1.14.0=hb31296c_0
hdf4=4.2.13=h3ca952b_2
hdf5=1.10.4=hb1b8bf9_0
icu=58.2=he6710b0_3
intel-openmp=2020.2=254
jpeg=9b=h024ee3a_2
kiwisolver=1.3.0=py37h2531618_0
krb5=1.18.2=h173b8e3_0
lcms2=2.11=h396b838_0
ld_impl_linux-64=2.33.1=h53a641e_7
libcurl=7.71.1=h20c2e04_1
libedit=3.1.20191231=h14c3975_1
libffi=3.3=he6710b0_2
libgcc-ng=9.1.0=hdf63c60_0
libgfortran-ng=7.3.0=hdf63c60_0
libnetcdf=4.7.3=hb80b6cc_0
libpng=1.6.37=hbc83047_0
libssh2=1.9.0=h1ba5d50_1
libstdcxx-ng=9.1.0=hdf63c60_0
libtiff=4.1.0=h2733197_1
libuuid=1.0.3=h1bed415_2
libxcb=1.14=h7b6447c_0
libxml2=2.9.10=hb55368b_3
lz4-c=1.9.2=heb0550a_3
matplotlib-base=3.3.2=py37h817c723_0
mkl=2020.2=256
mkl-service=2.3.0=py37he904b0f_0
mkl_fft=1.2.0=py37h23d657b_0
mkl_random=1.1.1=py37h0573a6f_0
ncurses=6.2=he6710b0_1
netcdf4=1.5.3=py37hbf33ddf_0
numpy=1.19.2=py37h54aff64_0
numpy-base=1.19.2=py37hfa32c7d_0
olefile=0.46=py37_0
openssl=1.1.1h=h7b6447c_0
pcre=8.44=he6710b0_0
pillow=8.0.1=py37he98fc37_0
pip=20.2.4=py37h06a4308_0
proj4=5.2.0=he6710b0_1
pyparsing=2.4.7=py_0
pyproj=1.9.6=py37h14380d9_0
pyqt=5.9.2=py37h05f1152_2
pyshp=2.1.2=py_0
python=3.7.9=h7579374_0
python-dateutil=2.8.1=py_0
pytz=2020.1=py_0
qt=5.9.7=h5867ecd_1
readline=8.0=h7b6447c_0
setuptools=50.3.0=py37h06a4308_1
sip=4.19.8=py37hf484d3e_0
six=1.15.0=py_0
sqlite=3.33.0=h62c20be_0
tk=8.6.10=hbc83047_0
tornado=6.0.4=py37h7b6447c_1
wheel=0.35.1=py_0
xz=5.2.5=h7b6447c_0
zlib=1.2.11=h7b6447c_3
zstd=1.4.5=h9ceee32_0
matplotlib=3.0.2=py37h5429711_0


text:
Q: cd into an application Mystery solved...
[nemo@Saturn.local /Applications/AppsUser/System]$ ls -l | grep ExpanDrive
-rw-r--r--@  1 nemo  admin         0 Nov 16  2010 ExpanDrive.app
[nemo@Saturn.local /Applications/AppsUser/System]$ file ExpanDrive.app
ExpanDrive.app: empty

Works fine for other apps. Now what, do I delete this question seeing as how it's invalid?

I'm trying to get a little binary inside an application bundle to run from the commandline, like
$ ./ExpanDrive.app/Contents/Resources/expan

('expan' is the binary inside ExpanDrive's application bundle)
This doesn't work, ("Not a directory"), nor can I cd into it, or list its contents. Are there toggles for cd and ls that allow this, or other utilities?
To clarify, this is what happens:
[nemo@Saturn.local /Applications/AppsUser/System]$ cd ExpanDrive.app
-bash: cd: ExpanDrive.app: Not a directory
[nemo@Saturn.local /Applications/AppsUser/System]$ ExpanDrive.app/Contents/Resources/expan
-bash: ExpanDrive.app/Contents/Resources/expan: Not a directory

Is it possible that this does not work because I'm logged in over SSH?

A: You can usually just specify the full path:
/Applications/ExpanDrive.app/Contents/Resources/expan

This would also work:
cd /Applications/
ExpanDrive.app/Contents/Resources/expan

./ is only needed for running executables in the current folder.
cd /Applications/ExpanDrive.app/Contents/Resources/
./expan


text:
Q: Cloud Composer non interactive authentication I've tried a lot before posting this question, I'm not against down votes, at least let me know WHY you are down voting.
I have built an Airflow plugin to fetch data from Cloud composer Airflow environment and accessing the cloud composer is working great from browsers as it needs the user to sign in before accessing any of the Airflow endpoints.
In my use case, I need to trigger the endpoints via code. Is there a way in which I can do this.
Below is the Airflow-Flask plugin being used
from datetime import datetime
import json
import os
import six
import time

from flask import Blueprint, request, Response
from sqlalchemy import or_
from airflow import settings
from airflow.exceptions import AirflowException, AirflowConfigException
from airflow.models import DagBag, DagRun
from airflow.utils.state import State
from airflow.utils.dates import date_range as utils_date_range
from airflow.www.app import csrf

airflow_api_blueprint = Blueprint('airflow_api', __name__, url_prefix='/api/v1')

class ApiInputException(Exception):
    pass

class ApiResponse:

    def __init__(self):
        pass

    STATUS_OK = 200
    STATUS_BAD_REQUEST = 400
    STATUS_UNAUTHORIZED = 401
    STATUS_NOT_FOUND = 404
    STATUS_SERVER_ERROR = 500

    @staticmethod
    def standard_response(status, payload):
        json_data = json.dumps({
            'response': payload
        })
        resp = Response(json_data, status=status, mimetype='application/json')
        return resp

    @staticmethod
    def success(payload):
        return ApiResponse.standard_response(ApiResponse.STATUS_OK, payload)

    @staticmethod
    def error(status, error):
        return ApiResponse.standard_response(status, {
            'error': error
        })

    @staticmethod
    def bad_request(error):
        return ApiResponse.error(ApiResponse.STATUS_BAD_REQUEST, error)

    @staticmethod
    def not_found(error='Resource not found'):
        return ApiResponse.error(ApiResponse.STATUS_NOT_FOUND, error)

    @staticmethod
    def unauthorized(error='Not authorized to access this resource'):
        return ApiResponse.error(ApiResponse.STATUS_UNAUTHORIZED, error)

    @staticmethod
    def server_error(error='An unexpected problem occurred'):
        return ApiResponse.error(ApiResponse.STATUS_SERVER_ERROR, error)

@airflow_api_blueprint.before_request
def verify_authentication():
    authorization = request.headers.get('authorization')
    try:
        api_auth_key = settings.conf.get('AIRFLOW_API_PLUGIN', 'AIRFLOW_API_AUTH')
    except AirflowConfigException:
        return

    if authorization != api_auth_key:
        return ApiResponse.unauthorized("You are not authorized to use this resource")

def format_dag_run(dag_run):
    return {
        'run_id': dag_run.run_id,
        'dag_id': dag_run.dag_id,
        'state': dag_run.get_state(),
        'start_date': (None if not dag_run.start_date else str(dag_run.start_date)),
        'end_date': (None if not dag_run.end_date else str(dag_run.end_date)),
        'external_trigger': dag_run.external_trigger,
        'execution_date': str(dag_run.execution_date)
    }

def find_dag_runs(session, dag_id, dag_run_id, execution_date):
    qry = session.query(DagRun)
    qry = qry.filter(DagRun.dag_id == dag_id)
    qry = qry.filter(or_(DagRun.run_id == dag_run_id, DagRun.execution_date == execution_date))

    return qry.order_by(DagRun.execution_date).all()

@airflow_api_blueprint.route('/dags', methods=['GET'])
def dags_index():
    dagbag = DagBag()
    dags = []

    for dag_id in dagbag.dags:
        payload = {
            'dag_id': dag_id,
            'full_path': None,
            'is_active': False,
            'last_execution': None,
        }

        dag = dagbag.get_dag(dag_id)

        if dag:
            payload['full_path'] = dag.full_filepath
            payload['is_active'] = (not dag.is_paused)
            payload['last_execution'] = str(dag.latest_execution_date)

        if request.args.get('dag_id') is not None:
            if request.args.get('dag_id') not in payload['dag_id']:
                continue
        dags.append(payload)

    return ApiResponse.success({'dags': dags})

@airflow_api_blueprint.route('/dag_runs', methods=['GET'])
def get_dag_runs():
    dag_runs = []

    session = settings.Session()

    query = session.query(DagRun)

    if request.args.get('state') is not None:
        query = query.filter(DagRun.state == request.args.get('state'))

    if request.args.get('external_trigger') is not None:
        # query = query.filter(DagRun.external_trigger == (request.args.get('external_trigger') is True))
        query = query.filter(DagRun.external_trigger == (request.args.get('external_trigger') in ['true', 'True']))

    if request.args.get('prefix') is not None:
        query = query.filter(DagRun.run_id.ilike('{}%'.format(request.args.get('prefix'))))

    if request.args.get('dag_id') is not None:
        query = query.filter(DagRun.dag_id.ilike('{}%'.format(request.args.get('dag_id'))))

    runs = query.order_by(DagRun.execution_date).all()

    for run in runs:
        dag_runs.append(format_dag_run(run))

    session.close()

    return ApiResponse.success({'dag_runs': dag_runs})

@csrf.exempt
@airflow_api_blueprint.route('/dag_runs', methods=['POST'])
def create_dag_run():
    # decode input
    data = request.get_json(force=True)

    # ensure there is a dag id
    if 'dag_id' not in data or data['dag_id'] is None:
        return ApiResponse.bad_request('Must specify the dag id to create dag runs for')
    dag_id = data['dag_id']

    limit = 500
    partial = False
    if 'limit' in data and data['limit'] is not None:
        try:
            limit = int(data['limit'])
            if limit <= 0:
                return ApiResponse.bad_request('Limit must be a number greater than 0')
            if limit > 500:
                return ApiResponse.bad_request('Limit cannot exceed 500')
        except ValueError:
            return ApiResponse.bad_request('Limit must be an integer')

    if 'partial' in data and data['partial'] in ['true', 'True', True]:
        partial = True

    # ensure there is run data
    start_date = datetime.now()
    end_date = datetime.now()

    if 'start_date' in data and data['start_date'] is not None:
        try:
            start_date = datetime.strptime(data['start_date'], '%Y-%m-%dT%H:%M:%S')
        except ValueError:
            error = '\'start_date\' has invalid format \'{}\', Ex format: YYYY-MM-DDThh:mm:ss'
            return ApiResponse.bad_request(error.format(data['start_date']))

    if 'end_date' in data and data['end_date'] is not None:
        try:
            end_date = datetime.strptime(data['end_date'], '%Y-%m-%dT%H:%M:%S')
        except ValueError:
            error = '\'end_date\' has invalid format \'{}\', Ex format: YYYY-MM-DDThh:mm:ss'
            return ApiResponse.bad_request(error.format(data['end_date']))

    # determine run_id prefix
    prefix = 'manual_{}'.format(int(time.time()))
    if 'prefix' in data and data['prefix'] is not None:
        prefix = data['prefix']

        if 'backfill' in prefix:
            return ApiResponse.bad_request('Prefix cannot contain \'backfill\', Airflow will ignore dag runs using it')
        # ensure prefix doesn't have an underscore appended
        if prefix[:-1:] == "_":
            prefix = prefix[:-1]

    conf = None
    if 'conf' in data and data['conf'] is not None:
        if isinstance(data['conf'], six.string_types):
            conf = data['conf']
        else:
            try:
                conf = json.dumps(data['conf'])
            except Exception:
                return ApiResponse.bad_request('Could not encode specified conf JSON')

    try:
        session = settings.Session()

        dagbag = DagBag('dags')

        if dag_id not in dagbag.dags:
            return ApiResponse.bad_request("Dag id {} not found".format(dag_id))

        dag = dagbag.get_dag(dag_id)

        # ensure run data has all required attributes and that everything is valid, returns transformed data
        runs = utils_date_range(start_date=start_date, end_date=end_date, delta=dag._schedule_interval)

        if len(runs) > limit and partial is False:
            error = '{} dag runs would be created, which exceeds the limit of {}.' \
                    ' Reduce start/end date to reduce the dag run count'
            return ApiResponse.bad_request(error.format(len(runs), limit))

        payloads = []
        for exec_date in runs:
            run_id = '{}_{}'.format(prefix, exec_date.isoformat())

            if find_dag_runs(session, dag_id, run_id, exec_date):
                continue

            payloads.append({
                'run_id': run_id,
                'execution_date': exec_date,
                'conf': conf
            })

        results = []
        for index, run in enumerate(payloads):
            if len(results) >= limit:
                break

            dag.create_dagrun(
                run_id=run['run_id'],
                execution_date=run['execution_date'],
                state=State.RUNNING,
                conf=conf,
                external_trigger=True
            )
            results.append(run['run_id'])

        session.close()
    except ApiInputException as e:
        return ApiResponse.bad_request(str(e))
    except ValueError as e:
        return ApiResponse.server_error(str(e))
    except AirflowException as e:
        return ApiResponse.server_error(str(e))
    except Exception as e:
        return ApiResponse.server_error(str(e))

    return ApiResponse.success({'dag_run_ids': results})

@airflow_api_blueprint.route('/dag_runs/<dag_run_id>', methods=['GET'])
def get_dag_run(dag_run_id):
    session = settings.Session()

    runs = DagRun.find(run_id=dag_run_id, session=session)

    if len(runs) == 0:
        return ApiResponse.not_found('Dag run not found')

    dag_run = runs[0]

    session.close()

    return ApiResponse.success({'dag_run': format_dag_run(dag_run)})

A: For programmatic auth to Composer's Airflow webserver, you will have to authenticate through IAP.
https://cloud.google.com/composer/docs/how-to/using/triggering-with-gcf contains a js example of this.
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iap/make_iap_request.py is a Python example, but note that it is missing a timeout on the final IAP request (https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1812).


text:
Q: Cassandra migration I have Cassandra 0.8.0 running with data on server 1, and a clean install of Cassandra 1.0.3 on server 2.
Is it possible to just copy some files from server 1 to server 2? Or do i have to write my own import/export code?
Both servers can be taken down, restarted, etc.

A: Why would you not upgrade server1? Upgrade details here (either way read this first):
http://svn.apache.org/viewvc/cassandra/branches/cassandra-1.0/NEWS.txt?view=markup
But if you do want to change machines, follow the procedures for 'nodetool snapshot' as detailed here:
http://wiki.apache.org/cassandra/Operations#Backing_up_data
Re-create the schema on the new node, then add the snapshots to the data directory (as described above), restart cassandra then issue a nodetool scrub.

A: Thanks zznate it had to do with hardware.
Here some links i found useful:
http://jonathanhui.com/cassandra-data-maintenance-backup-and-system-recovery
http://wiki.apache.org/cassandra/StorageConfiguration
http://www.memonic.com/user/pneff/folder/database/id/1bZvk
If it looks like nothing happened after migrating make sure you create the column family's on the new node using CassandraCli.