text:
Q: Use `robots.txt` in a multilingual site Having to manage a multilingual site, where users are redirected to a local version of site, like
myBurger.com/en // for users from US, UK, etc..
myBurger.com/fr // for users from France, Swiss, etc...

How should be organized the robots.txt file in pair with the sitemap?
myBurger.com/robots.txt // with - Sitemap: http://myBurger.com/??/sitemap
OR
myBurger.com/en/robots.txt  // with - Sitemap: http://myBurger.com/en/sitemap
myBurger.com/fr/robots.txt  // with - Sitemap: http://myBurger.com/fr/sitemap

kwnowing that en and fr sites are in fact independent entities not sharing common content, even if similar appearance.

A: You need to put one robots.txt at the top level.

The robots.txt file must be in the top-level directory of the host,
  accessible though the appropriate protocol and port number.

https://developers.google.com/webmasters/control-crawl-index/docs/robots_txt

A: Put the robots.txt at the root: myBurger.com/robots.txt and register your sitemaps in the robots.txt file using the sitemap: directive (see an example I maintain if necessary).


text:
Q: How to efficiently load large csv file into html table using flask? I'm wondering what would be the best practice to load csv data (over 60,000 rows) into html table using flask (I'm flask beginner).
I'm able to load data to html table, but it takes a very long time for the page to load in my browser. Would someone be able to recommend a better, more robust solution for my scenario? Thank you in advance!
My code so far:
app.py:
@app.route('/')
def weather_dashboard():
    filename = '/path/to/my/data.csv'
    data = pandas.read_csv(filename, header=0)
    myData = list(data.values)
    return render_template('home.html', myData=myData)

home.html:

      date
      ID
      Items
      Sold Items

    {% for value in myData%}

      {{ value[0] }}
      {{ value[1] }}
      {{ value[2] }}
      {{ value[3] }}

    {% endfor %}

Thanks in advance!

A: Here's a way to improve performance at the cost of resource usage (RAM).  It will only update when the file's content hash changes.
import csv
import hashlib
from pathlib import Path

import flask

class Cache:
    template = '''

{% for v in data %}

    {{ v[0] }}
    {{ v[1] }}
    {{ v[2] }}
    {{ v[3] }}

{% endfor %}

'''
    csv_file = Path(__file__).parent / 'data.csv'

    def __init__(self, app: flask.Flask):
        self._app = app
        self._cache = None
        self._filehash = None
        self()  # first-time initialization

    def __call__(self):
        filehash = self._hash_file()
        if filehash != self._filehash:
            self._filehash = filehash
            self._cache = self._render()

        return self._cache

    def _hash_file(self) -> str:
        with self.csv_file.open('rb') as f:
            md5 = hashlib.md5()
            while data := f.read(65536):  # 64kb chunks
                md5.update(data)
            return md5.hexdigest()

    def _render(self):
        with self.csv_file.open(newline='') as f:
            reader = csv.reader(f)
            next(reader)  # skip header

            with self._app.app_context():
                return flask.render_template_string(self.template, data=reader)

app = flask.Flask(__name__)
cache = Cache(app)

@app.route('/')
def weather_dashboard():
    return flask.render_template('home.html', table_body=cache())

A: Change your app.py like this code.
@app.route('/')
def weather_dashboard():
    filename = '/path/to/my/data.csv'
    data = pandas.read_csv(filename, header=0)
    myData = data.values
    return render_template('home.html', myData=myData)

A: Try with pandas.to_html:
@app.route('/')
def weather_dashboard():
    filename = '/path/to/my/data.csv'
    data = pandas.read_csv(filename, header=0)
    data.columns=['date','ID','Items','Sold Items']
    data.to_html(open('data.html', 'w'))
    return render_template('data.html')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zurb Foundation Accordion not expanding I am using Foundation 6.7.4.
I am trying to set up an accordion like the one in their example here https://get.foundation/sites/docs/accordion.html
I have my accordion set up as such:

                  My Title

                   My content

When I click the A tag I can see the Accordion expand for a fraction of a second before closing. I can also see the CSS classes and attributes change in the inpector.
But I'm unsure why none of these are sticking and what's causing the accordion to revert its's self.
Would anyone know why?

A: Turned out this was because I had 2 foundation.js files referenced.


text:
Q: How to modify regrex expression to deal with whitespaces import re
def addMultiplication(input1):
    return re.sub(r'([^-+*/])\(', r'\1*(', input1)

I have a function that will take an string and add multiplication symbols whenever there are parenthesis symbolizing multiplication.
Some examples here (that work):

*

*"4(3)" -> "4*(3)"

*"(4)(3)" -> "(4)*(3)"

*"4*2 + 9 -4(-3)" - > "4*2 + 9 -4*(-3)"

*"(-9)(-2)   (4)" -> "(-9)*(2) *(4)"

*"4^(3)" -> "4^(3)"

*"(4-3)(4+2)" -> "(4-3)*(4+2)"

*"(Aflkdsjalkb)(g)" -> "(Aflkdsjalkb)*(g)"

*"g(d)(f)" -> "g*(d)*(f)"

*"(4) (3)" -> "(4)*(3)"

Here are some examples I am failing (because of added whitespace) the arrow points to my code's output the farthest right and in bold is what I want:

*

*"(4)* (3)" -> "(4) * * (3)" | "(4)*(3)"

*"(4-3* (2)" -> "4-3* *(2)"   | 4-3 * (2)"
Note I had to add some extra spaces in the two above examples because otherwise it kept italicizing and formatting. So basically if I get rid of the white space in my above two examples, it works, but when I leave a whitespace after the asterisk, it malfunctions.
How would I incorporate the extra whitespace in my regrex expression? I tried using \s but I'm not sure how it works.

A: One way to look at this is that you want to put a * between any character, digit or closing parenthesis ()) which is followed by an opening parenthesis ((), or any closing parenthesis which is followed by a character, digit or opening parenthesis; with some number of spaces in the middle. You can use lookaheads for that purpose, capturing the initial character/digit/parenthesis in group 1:
([a-z0-9)](?= *\()|\)(?= *[a-z0-9(]))

You can then replace this with \1*. Note you should use the re.IGNORECASE (case-insensitive, also re.I) flag so that it works for expression such as A(B).
Demo on regex101
In python:
def addMultiplication(input1):
    return re.sub(r'([a-z0-9)](?= *\()|\)(?= *[a-z0-9(]))', r'\1*', input1, 0, re.IGNORECASE)


text:
Q: how to locate an element using UIAutomater when same thing is shared by two element
Both the Camera picture and All photos have same element locator then how can we click All pictures, i have explained everything in picture description

A: Appium interprets page as an XML, so there are no two elements with the same locator. So you can locate by the folder names for example.
def cameraPicturesLocatorBy = By.xpath("//*[@text='Camera pictures']")
and
def allPhotosLocatorBy = By.xpath("//*[@text='All photos']")

A: Looking at the screenshots, you could use ids. in Python:
driver.find_element_by_id('your id')


text:
Q: Is there a simple means of adding an aspect to an existing VB.NET method? I know there are numerous aspect-oriented frameworks for VB.NET.  It's a little heavy to pull an entire framework into play in order to add an aspect to a couple methods.  Does VB.NET offer a simple means (via some sort of metaprogramming/reflection) in which to layer an aspect over an existing method in a class/object?
Basically, the goal is intercept a method's incoming message to invoke it and add side effects or to manipulate the request, just as one would normally do in standard AOP.
Are there any plans to integrate aspects directly into the language?

A: Is polymorphism not an option in this case?  I think you'll find that, outside of an AOP framework of some kind, there is no way in VB to change the functionality of an existing class.  You can inherit and override base members, or you can use extension methods to add additional functionality to an existing class, but there's no way to alter existing functionality in an existing class.
It is possible to create a new library that mimics another existing library and trick existing code into thinking your new library is the original one, but unless absolutely necessary, this is a bad idea.  Chances you just need to rethink your design in a standard OOP way rather than thinking in AOP terms.

A: How about the decorator (or proxy) pattern?  Since it's only a few methods, then you only need one or two decorator classes. If you discover later that it's not just one or two methods, then you can consider bringing in an AOP tool.
Here's an example in C# that should translate pretty easily to VB.NET


text:
Q: How can i replace daily x-axis labels with months but keep chart showing daily values? I want to draw a chart from my dataframe (which has got daily data) and want the xlables to show up as months (covering all the daily data period).
For example if i have data from 2010-01-01 till 2010-12-31, i want 365 days data points, but in the x-axis i want just Jan, Feb, Mar, etc... each of those month covering the exact period of the corresponding days. Strugglling in getting this...
This is the DataFrame:
    Daily CP ROI S2     positive    Month   Day
Date
2008-01-02  100087.000  True    January     2
2008-01-03  101967.000  True    January     3
2008-01-04  102167.000  True    January     4
2008-01-07  104004.000  True    January     7
2008-01-08  105192.000  True    January     8

pl_plot = pl_plot.set_index('Date')
figure(num=None, figsize=(20, 8), dpi=80, facecolor='w', edgecolor='k')
plt.ylabel('USD', fontsize=18)
plt.rc('ytick',labelsize=16)
final_value = new_df_test.iloc[ei-2]['Daily_Compound_ROI']
roi = round(((final_value - very_init_budget)/very_init_budget)*100,3)
roi_s=str(roi)
plt_title_s = new_title+'\nPeriod: '+y_init_s+'-'+y_end_s+', (ROI: '+roi_s+'%)'
plt.title(plt_title_s, fontsize=24)
pl_plot['positive'] = pl_plot['Daily_Compound_ROI'] > 100000
pl_plot['Daily CP ROI S2'].plot(kind='bar', color=pl_plot.positive.map({True: '#5cb85c', False: 'r'}))
ax1 = plt.axes()
plt.rc('xtick',labelsize=14)
x_axis = ax1.axes.get_xaxis()
x_axis.set_visible(True)

I want to get something like the below (keep red color when value is below 100000 otherwise green color for the bar), but in the x-axis would like to see Jan, Feb, Mar, etc... without any separation between the months (and dont want to see each single day as i see right now).
enter image description here

A: IIUC you could give seaborn a try.
If you add a month- and day-column to your dataframe, you can make a barpot with monthly separated blocks of bars per day.

Example:
# import pandas as pd
# import numpy as np

# df = pd.DataFrame(index=pd.date_range('15.8.2019', '27.11.2019'))
# df['Value'] = np.random.random(len(df))
# df['Month'] = df.index.month_name()
# df['Day'] = df.index.day

#                Value     Month Day
# 2019-08-15  0.813130    August  15
# 2019-08-16  0.850873    August  16
# 2019-08-17  0.728416    August  17
# 2019-08-18  0.326072    August  18
# 2019-08-19  0.880385    August  19
#              ...       ...  ..
# 2019-11-23  0.771801  November  23
# 2019-11-24  0.638811  November  24
# 2019-11-25  0.824542  November  25
# 2019-11-26  0.451075  November  26
# 2019-11-27  0.151469  November  27

given this dataframe, you could do
import seaborn as sns

sns.catplot(kind='bar', x='Month', y='Value', hue='Day', data=df, color='b', legend=False)

results in

A: That looks quite strange as i am answering my own question.
Anyway i found the way:
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
sns.set(font_scale=1.5, style="whitegrid")
fig, ax = plt.subplots(figsize=(20, 8))
ax.bar(df.index.values, df['Daily CP ROI S2'].values, width=1, color=pl_plot.positive.map({True: '#5cb85c', False: 'r'}))
ax.set(#xlabel="Period", ylabel="USD", title=title1)
ax.title.set(fontsize=24)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(DateFormatter("%b"))
plt.show()

the above fixes the problem and what i get is the below:
Chart as i wanted it
The only problem left is now i need to fit the title within the chart :) Will look after this, but if any suggestions, please go ahead! Thanks.


text:
Q: error al activar un script con formsubmit El siguiente es el email que recibí ante la falla al completar el formulario por primera vez.
Tu secuencia de comandos, Formulario de consultas y trámites, no se ha ejecutado correctamente. A continuación incluimos un resumen de los errores. Para configurar los activadores de la secuencia de comandos o cambiar la configuración para recibir futuras notificaciones de errores, haz clic aquí.
El documento Formulario de consultas y trámites utiliza la secuencia de comandos.
Estoy obteniendo este error:

Inicio:   18/10/17 12:34   Función:   showQuestionNumber   Mensaje de
  error:    No se puede usar FormApp.getUi() desde este contexto. (línea 5,
  archivo "Código") Activación: formSubmit   Fin: 18/10/17 12:34
  Atentamente,
Google Apps Script

El código del script es muy sencillo:
function showQuestionNumber() {

      var questionnumber=5

      FormApp.getUi().alert('Su consulta tramitará con el número:    '+ questionnumber)
    }

Les agradezco que me ayuden a solucionar este inconveniente.
Saludos
Salvador

A: Como lo indica el mensaje de error FormApp.getUI() sólo se puede usar cuando se ejecuta el script en el contexto del editor de formularios de Google, no es posible llamarlo usando el activador "al enviar formulario" así como tampoco es posible ejecutar scripts en la vista para responder formularios.


text:
Q: View Asynchronous JavaScript calls I've upgraded the tracking script for Google Analytics to the Asynchronous version. The only issue I have is being able to debug the calls. I was able to track the older version in Firebug using the approach outlined on this site, but now cannot view the gaq.push calls. Is there way to view this in Firebug or another tool?
This is my sample test page I'm trying to track:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Google Analytics Event Tracking</title>
    <script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-13250000-1']);
        _gaq.push(['_trackPageview']);

        (function() {
            var ga = document.createElement('script');
            ga.type = 'text/javascript';
            ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(ga, s);
        })();
    </script>
</head>
<body>
Lorem ipsum dolor sit amet....<br />
<script type="text/javascript">
    _gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);
</script>
</body>
</html>

I'm trying to confirm that "_gaq.push" is actually working.

A: I just ran into the same issue, and so I did a google search and ended up on this stack overflow question.. I too thought that this would just show up as a xhr request in firebug as that would be the simple way to track an event. Turns out they are using a 1x1 pixel gif to do the tracking! If you look in the Net > All tab in Firebug you will see a GET request made looking similar to this:
https://ssl.google-analytics.com/__utm.gif?utmwv=5.2.4&utms=28&utmn=1818843630&utmhn=dev-marketplace.asos.com&utmt=event&utme=5(my-home*sub-nav-click*blog-posts)&utmcs=UTF-8&utmsr=1920x1080&utmvp=1920x618&utmsc=24-bit&utmul=en-gb&utmje=0&utmfl=11.1%20r102&utmdt=Build%20%23%20Developer%20Live%20Feed%20ASOS%20Marketplace&utmhid=1950484512&utmr=-&utmp=%2Flivefeed%2Fblogposts&utmac=UA-23521416-1&utmcc=__utma%3D159014575.706813547.1328542287.1328542287.1328604985.2%3B%2B__utmz%3D159014575.1328542287.1.1.utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B&utmu=6AAAAAAAAAAAAAAAQ~

These are the params sent in the request
utmac   UA-23521416-1
utmcc   __utma=159014575.706813547.1328542287.1328542287.1328604985.2;+__utmz=159014575.1328542287.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
utmcs   UTF-8
utmdt   Build # Developer Live Feed ASOS Marketplace
utme    5(my-home*sub-nav-click*blog-posts)
utmfl   11.1 r102
utmhid  1950484512
utmhn   dev-marketplace.asos.com
utmje   0
utmn    1818843630
utmp    /livefeed/blogposts
utmr    -
utms    28
utmsc   24-bit
utmsr   1920x1080
utmt    event
utmu    6AAAAAAAAAAAAAAAQ~
utmul   en-gb
utmvp   1920x618
utmwv   5.2.4

A: The TamperData plugin for Firefox is very handy. It lets you see all HTTP traffic, with filtering etc.  It also has a facility that lets you modify headers before the browser starts the HTTP transaction, which seems pretty awesome but I've never used it.

A: I do this by looking at the Resources tab in Chrome Developer Tools:
http://drktd.com/45VJ (notice the yellow 'XHR' -- that means XMLHttpRequest, which is the kind of call you're likely looking for)
If you need an in-depth view of each request into/out of your system, you should really install Charles Proxy.  It is the best of breed for this kind of stuff.

A: If you do not see the requests happening in FireBug, then they are not happening. Google Analytics is not somehow sidestepping the browser's ability to track what HTTP requests it is making, your code is simply not making them.


text:
Q: Date format on client browser I am getting a date from the server as a javascript string(GMT) or unix timestamp(GMT).
I can convert it to a javascript date object with
var date = new Date(string) or var date = new Date(string)
This gives me the date variable with proper system time-zone's time.
Currently I am displaying this- date.toLocaleString()
Which gives me a nicely formatted date/time according to my system locale and time zone.
I am using this to automatically accomodate for DST if the client browser follows it.
Previously I was required to display this date only in EST, but when the US time started following EDT, I was told to display it in EST. I think this approach would simplify displaying the time/date acoording to user's system time setting.
Is there any disadvantage or possible bug accociated with this approach?
If yes, what would be the best way to display this date in the browser, so that it displays correctly according to the timezone(accomodating DST if any) in which the user(cient browser) is?

A: As pointed out in the comments, the output may be different depending on the users settings. A more reliable and flexibe solution is moment.js, which is a great library.
moment("2013-04-04", "YYYY-MM-DD").format("MMM Do YY"); //"Apr 4th 13"


text:
Q: Uploading a directory to AWS S3 I want to upload a directory to AWS S3 based on AWS documentation here
  TransferUtility directoryTransferUtility =
                new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.USEast1));

    directoryTransferUtility.UploadDirectory(directoryPath,
                                                     existingBucketName);

In order to use above API i need RegionEndPoint and BucketName.  Lets say i have path in the following format
https://mybucketname.s3-us-west-2.amazonaws.com/mykey/
How do i upload a directory to this path?
I know I can parse the path and get RegionEndPoint and BucketName and use those values in the API. But i was wondering is there any API method available which takes the above path and uploads the objects to that path? The path already contains bucketname and regionendpoint.

A: Yes, you can use the below object to do that. It returns Bucket, IsPathStyle, Key and Region.
Amazon.S3.Util.AmazonS3Uri

For more information click on http://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html?page=S3/TS3UtilS3Uri.html&tocid=Amazon_S3_Util_AmazonS3Uri


text:
Q: I want to check 2 file names in powershell I want to check 2 files names 1 XYZyymmddhhmmss.dat
2 XYZyymmddhhmmss.complete
In a mention path
I try with regex but fail to get output
Anyone can help me?
Thanks in advance.


text:
Q: Returns a specific species based on the id I'm trying to return a specific species based on the id. The objects themselves aren't present. But here's my code thus far:
function findById (data, id) {
  const result = null

  for (var i = 0; i < data.length; i++) {
    var bug = data[i]
    if (bug.id = id) {
      return bug
    }
  }

  return result
}

It keeps kicking back the error: AssertionError: expected { Object (species, id, ...) } to deeply equal { Object (species, id, ...) }

A: Try using == or === instead of = in your if statement:
function findById (data, id) {
  const result = null

  for (var i = 0; i < data.length; i++) {
    var bug = data[i]
    if (bug.id === id) {
      return bug
    }
  }

  return result
}


text:
Q: How are Web API access tokens validated on the server? Once a WebAPI access token is generated, how does WebAPI validate that token for the next request? I wonder if I can use an [Authorize] attribute, it must compare the token sent by the client with the token at the server side, if stored somewhere. Does it just check if token is present and not its value?

A: Once access token is generated, client must include the access token inside Header for each request.
Client may set the access token inside Authorization HTTP Header.
On the server side, you should create class to handle the Authorization, which is a derived class from System.Web.Http.AuthorizeAttribute, something like below :
public class AuthorizationHandlerAttribute : AuthorizeAttribute
{
    string AccessTokenFromRequest = "";
    if (actionContext.Request.Headers.Authorization != null)
    {
        // get the access token
        AccessTokenFromRequest = actionContext.Request.Headers.Authorization.Parameter;
    }

    string AccessTokenStored = "";
    // write some code to get stored access token, probably from database
    // then assign the value to a variable for later use

    // compare access token
    if (AccessTokenFromRequest != AccessTokenStored)
    {
        // if the token is not valid then return 401 Http Stasus
        // or simply call base method
        base.HandleUnauthorizedRequest(actionContext);
    }
}

Then you use the newly created class and attach it on controller or action you wished to protect from unauthorized access.
public class UsersController : ApiController
{
    [AuthorizationHandler]
    public User Get(int id)
    {
        // only request with valid access token will reach this
    }
}

A: The secret key is transmitted in the header of the request from the client to the server, and the contents are validated at the server at each request where the [Authorize] attribute is used.
You can use a tool like Fiddler from Telerik (free) to see the data being transported, but not the content (since its encrypted). Inspecting raw web traffic is invaluable when working with MVC / WebAPI, so I highly recommend it. Here's a link to Fiddler, although other similar tools exist as well.
http://www.telerik.com/fiddler
To answer the second part of your question, the server absolutely checks the contents of the secret key before allowing the request to proceed as authorized.

A: Bearer token
First of all, your Identity Provider or Token Provider which issues the authorization tokens needs to have the same machine key settings as the Web Api application for encryption/decryption:

<machineKey
  decryptionKey="B7EFF1C5839A624ED0268917EDE82F408D2ECBFAC817"
  validation="SHA1"
  validationKey="C2B8DF31AB9624D8066DFDA1A479542825F3B48865C4E47AF6A026F22D853DEC2B3248DF268599BF89EF78B9E86CA05AC73577E0D5A14C45E0267588850B"
  />   </system.web>

Because under the hood Bearertoken uses MachineKey encryption.
In other words if you dont have the same settings, your web api won't be able to decrypt the token (validate it).
This is done automatically by:

Microsoft.Owin.Security.OAuth.dll

using middleware.
You can use the Authorize Attribute on your web api controllers/actions if you want simple authorization with Usernames or roles like this:
[Authorize(Roles="Administrators,Managers",Users ="Mike,Laura")]

If you want custom authorization, then you have to implement a custom authorization attribute which will handle the custom authorization in your web api. If the user is not allowed to pass you will return a 401 UnAuthorized Response:
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add("WWW-Authenticate","Bearer location='http://localhost:8323/account/login'");

For example:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class CustomAuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
{
    public RulesExampleEnum[] Rules { get; set; }
    public string Id { get; set; }
    .....
// Summary:
//     Calls when a process requests authorization.
//
// Parameters:
//   actionContext:
//     The action context, which encapsulates information for using System.Web.Http.Filters.AuthorizationFilterAttribute.
public virtual void OnAuthorization(HttpActionContext actionContext);
public virtual Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken);

and register it in your webApiConfig.cs
config.Filters.Add(new CustomAuthorizeAttribute());

and apply it on Web Api controller or action:
[CustomAuthorize(Id = "AnyId", Rules = new RulesExampleEnum[] { RulesExampleEnum.Rule1, RulesExampleEnum.Rule3 })]
public IEnumerable<object> Get()
{...


text:
Q: C# Dictionary with Simultanous Reading/Writing functionalty Is there a data structure or an algorithm to implement following functionalty?

Data is being received continously into the application in multiple
  threads and being written to a dictionary type structure.
  If someone wants to read the dictionary while it is being written to, instead of
  using locking, the values available right before value updation
  started will be provided.

A: You'd use the ConcurrentDictionary<,>


text:
Q: What is the purpose of the PhotoStreamsData folder? The folder PhotoStreamsData contains the same photos as the DCIM folder, only with a slightly lower resolution. Why create (almost exact) duplicates? Is it only to save some space on iCloud? Can I safely delete it to free up some space? Would deletion make any difference to the iCloud sync?
(iOS 9.0.2, iPhone 5c)

A: In general, deleting files that an application stores internally is a bad idea. This goes double for iOS since the presumption that users won't be idly deleting things is more realistic across the user-population of an app. The reasons for not deleting things are:

*

*the app (or the system) has a database for tracking what's placed where. Deleting the file without cleaning up the reference at best means you end up with another file. At worst, you have crashes and slowdowns caused by the app/system having to sanity check all the files it has placed on the storage.

*the files will appear again as the app re-does the work you've undone.

The reasons to place files in different spaces allows the system to reclaim storage space in the even that a cached file can be cleared to make way for other content. It also is baked in to how Photos works - when you run low on storage space, the app can be more aggressive about compressing the local cached copy of the photo. One setting won't be appropriate for people with 128 GB of storage and 16 GB of storage not to mention as you fill up your storage with other items over time. Also, I bet Apple is only backing up the files that are "authoritative" and not thumbnail or resampled versions of the iCloud originals. That saves bandwidth if backing up to the cloud and storage space on the backup and time to complete a backup.
So, I'd recommend making other changes like deleting large apps, large video files and let Photos be photos with storing multiple copies of images and multiple resolutions in different places.
Your DCIM folder is where the photos taken on that device live - so use care not to delete the authoritative copy of a file until it's backed up elsewhere.


text:
Q: numpy.ndarray sent as argument doesn't need loop for iteration? In this code np.linspace() assigns to inputs 200 evenly spaced numbers from -20 to 20.
This function works. What I am not understanding is how could it work. How can inputs be sent as an argument to output_function() without needing a loop to iterate over the numpy.ndarray?
def output_function(x):
    return 100 - x ** 2

inputs = np.linspace(-20, 20, 200)
plt.plot(inputs, output_function(inputs), 'b-')
plt.show()

A: numpy works by defining operations on vectors the way that you really want to work with them mathematically.  So, I can do something like:
a = np.arange(10)
b = np.arange(10)
c = a + b

And it works as you might hope -- each element of a is added to the corresponding element of b and the result is stored in a new array c.  If you want to know how numpy  accomplishes this, it's all done via the magic methods in the python data model.  Specifically in my example case, the __add__ method of numpy's ndarray would be overridden to provide the desired behavior.

A: What you want to use is numpy.vectorize which behaves similarly to the python builtin map.
Here is one way you can use numpy.vectorize:
outputs = (np.vectorize(output_function))(inputs)

You asked why it worked, it works because numpy arrays can perform operations on its array elements en masse, for example:
a = np.array([1,2,3,4]) # gives you a numpy array of 4 elements [1,2,3,4]
b = a - 1 # this operation on a numpy array will subtract 1 from every element resulting in the array [0,1,2,3]

Because of this property of numpy arrays you can perform certain operations on every element of a numpy array very quickly without using a loop (like what you would do if it were a regular python array).


text:
Q: Trouble sending email on behalf of another person in a cakephp 2.0 application I have a form where users enter their email and the email of a friend. If the email validates, my controller uses the email class to send a message to the friend. I would like to have the friend receive an email that was "from" the user but can not get it work. I can only get emails to send successfully if I set the sender to something static, like "myname@mydomain.com" Here's my form:
<?php
    echo $this->Form->create('User', array( 'action' => 'invite',
                                    'controller' => 'users')
                                    );
    echo $this->Form->input('User.from', array('label'=>"Your email",'value'=>'your email','class'=>"",'type'=>'email'));
    echo $this->Form->input('User.to', array('label'=>"Your friend's", 'value'=>"your friend's email",'class'=>"",'type'=>'email'));
    echo $this->Form->end(array('label'=>'Invite', 'class'=>'special-button use-transition'));
?>

My Users controller then handles the form. This works successfully in that I can get the app to send email messages to valid email addresses. However, if I try to set $from to the user's email address, it doesn't send anything. How can I send this email from the email address entered by a user? Here are the pertinent sections of user controller:
// tell app to use Cake Email
App::uses('CakeEmail', 'Network/Email');

public function invite(){
    if ($this->request->is('post')) {
        // Get data from the form and send an email
        $to = $this->request->data['User']['to'];
        $from = $this->request->data['User']['from'];
        $subject = "Some text for the subject line";
        $message = "Some text for the message";
        // I use this data to send an email but it won't work unless
        // I change $from to something static like so:
        $from = "myemail@mydomain.com";
        $this->send($to, $from, $subject, $message);
        // redirect on success not shown...
    }
}

// Send function takes the to/from/subject/message and sends it
public function send($to, $from, $subject, $msg) {
    $email = new CakeEmail();
    $email->template('welcome')
          ->emailFormat('html')
          ->from($from)
          ->to($to)
          ->subject($subject);
    if ($email->send($msg)){
        return true;
    }

}

A: I suggest you try to Collect the Sender's Name too and add to the from Field.
So your form should be like:
<?php
    echo $this->Form->create('User', array( 'action' => 'invite',
                                'controller' => 'users')
                                );
 echo $this->Form->input('User.fromName', array('label'=>"Your Name", 'value'=>"your name",'class'=>""));
echo $this->Form->input('User.from', array('label'=>"Your email",'value'=>'your email','class'=>"",'type'=>'email'));
echo $this->Form->input('User.to', array('label'=>"Your friend's", 'value'=>"your friend's email",'class'=>"",'type'=>'email'));
echo $this->Form->end(array('label'=>'Invite', 'class'=>'special-button use-transition'));
?>

And in your invite function let the $formMail be like this:
 $fromMail = array($this->request->data['User']['from'] => $this->request->data['User']['fromName']);

Hope this gets it work


text:
Q: More than an acquaintance, less than a friend? Is there currently, in English, a word which describes the following kind of relationship:
A person who you know you could be close friends with (this feeling maybe even being mutual and/or outspoken) but who you never even become friends with due to, for instance, scheduling issues, distance, etc.
I'll also take colloquialisms, suggestions, etc.

A:
Mate

In Australia this word does not mean precisely that, but is probably pretty close.

He has a lot of mates and a few close friends.

Is "mate" more of a friend than acquaintance? I would say yes. You don't necessarily like an acquaintance, or even enjoy their company - but people who you are "mates" with are definitely people who you like to be around even if you are not that close, say work buddies. In fact, perhaps in an American context:

Buddy

A: I was thinking on this recently with a friend, and came up with "supraquaintance," to indicate a level above acquaintances but (implicitly) not yet at the level of friendship.

A: Whether or not (ˈkĭndrəd) kindred souls ever meet or have time for each other is up to fate.

(idiomatic) Someone with the same feelings or attitudes as oneself; kindred spirit.

A: according to Random House Kernerman Webster's College Dictionary, © 2010 K Dictionaries Ltd...
ac•quaint•ance -- 1250–1300; Middle English < Old French]
syn:  acquaintance, associate, companion, friend refer to a person with whom one is in contact. An acquaintance is a person one knows, though not intimately: a casual acquaintance at school. An associate is a person who is often in one's company, usu. because of some work or pursuit in common: a business associate. A companion is a person who shares one's activities or fortunes; the term usu. suggests a familiar relationship: a traveling companion; a companion in despair. A friend is a person with whom one is on intimate terms and for whom one feels a warm affection: a trusted friend.


text:
Q: Wordpress permalinks and javascript redirection I need to use javascript redirection in one of my scripts. With /%postname%/ WP permalinks structure redirection works like it should but with default it always redirects to home page.
/%postname%/ structure script:
window.location.replace(encodeURIComponent("http://www.url.com/customposttype/postslug"));

default permalinks structure script:
window.location.replace(encodeURIComponent("http://www.url.com/?customposttype=postslug"))

A: The issue is that your script is doing a replace, but really what you want is to set the window location:
Change your redirects from:
window.location.replace(encodeURIComponent("http://www.url.com/?customposttype=postslug"))

to
window.location = "http://www.url.com/?customposttype=postslug";

And it should work properly.


text:
Q: spring:bind throws error when used in a list I have a list containing users. I am trying to print it in JSP but some how I am not able to get it to print it using spring:bind. I get an exception. The reason I am trying to use spring:bind is to invole @Formatting annotation.
Code in JSP
<c:forEach items="${users}" var="user" varStatus="status">
   <spring:bind path="users[${status.index}].name">
      <c:out value="${status.value}" />
   </spring:bind>
</c:forEach>

Controller
ModelAndView modelAndView = new ModelAndView("go_some_JSP_page");
List<UserEntity> users = userManager.getAllObjects();
modelAndView.addObject("users", users);

BTW, UserEntity has name field. If I remove the binding and try to print the user.name using <c:out value="user.name" /> it prints the value
A test sample code exists at https://github.com/hth/StatusInvoke.git
Please take a look at landing.jsp line 35
Let me know if you face any problem deploying it.

A: The only way I could get this to work is if the bean path that you are binding to is within the base command bean.  In my case I am using MyForm which has a getter and setter for users.  The spring bind tag does not seem to work outside of the base form command bean.
So your controller method needs to change to .
@RequestMapping(method = RequestMethod.GET)
public ModelAndView loadForm() {
    ModelAndView modelAndView = new ModelAndView("landing");
    MyForm myForm = new MyForm();
    myForm.setUsers(populate());
    modelAndView.addObject("myForm", myForm);
    return modelAndView;
}

In your jsp have the following.
<form:form commandName="myForm">
    <c:forEach var="user" items="${myForm.users}" varStatus="status">

            <spring:bind path="users[${status.index}].loginName">
                    <c:out value="${status.value}" />
                </spring:bind>
            <spring:bind path="users[${status.index}].balance">
                    <c:out value="${status.value}" />
                </spring:bind>

    </c:forEach>
</form:form>

A: The correct answer to invoke @NumberFormat annotation is by using spring:eval expression tag
<spring:eval expression="user.balance" />


text:
Q: How to get values from checkboxes to php array on button click? I have a problem. I want to get checked values from checkboxes and add them to a php array but i have no clue on how to do it. I can do it in javascript but i want a php array and i don't know how to convert js array to php array. I am gonna use the array in next php file and search rows from database with those values. I would appreciate if anybody suggests something on how to do it as i have no clue.
while ($row = mysqli_fetch_array($search)) {
            $category = $row["Category"];
            echo<inputtype=\"checkbox\"name=\"category\"value=\"$category\"required/>$kategoria</input>

";
}

<button>Answer to questions!</button>

This is how i make the checkboxes and then on button click i move to the next file

A: add attribute action=questions.php, method="post" to form instead of using  and place  in form and use extract($$__REQUEST) at very first line of questions.php use print_r(extract($_REQUEST)) to print extracted data from form to associative array.

A: Use this for your form:
<form method="POST" action="questions.php">
    <input type="checkbox" name="myInput" id="myInput" value="checked" />
    Checkbox

    <input type="submit" value="Submit values" />
</form>

Then in questions.php, all your values are added to the variable $_POST:
// Foreach item in the POST array.
foreach ($_POST as $item => $value) {

    // The value will be stored in $value
}

If the checkbox is checked, the $value variable will be checked. Otherwise it will be empty.
Source: PHP: Foreach in a multidimensional array


text:
Q: How to find minimal boolean expression segregating multiple more complex boolean expressions Let's say there are some triggers T1, T2, …, Tn each guarded by a boolean expression and a user defined list L containing boolean variables, bound to values.
Against this list all trigger expressions are evaluated and where the guard evaluates to true the trigger is executed.
Is there a way to calculate the minimal sub expression E (if it exists) that prevents one certain trigger from being executed but no others, such that if L satisfies E, L is rejected before any trigger expressions are evaluated?
E.g. for the following triggers preventing the list to contain k && m would disable T1 but not the others.
T1 = ((k && (e || f)) && m) || ((a || b) && k && m)
T2 = k || m && (x || y || z)
T3 = m || n


text:
Q: How to trigger event when 5 list
* items have been added to my dynamically generated
* list? I have a list in html (like a to-do list) and I want a button to appear when the user adds 5 items to that list.
I wrote this in js but it is not working:
function addButton(){
const glist = document.querySelectorAll('.gratitude_container > ul > li')
const gratListArray = Array.from(glist);
if (gratListArray === 4) {
    FortuneButton.classList.remove('hidden')

}
my html is:
    <form>
        <input type="text" placeholder="Enter it here..." class="gratitude_input" />
        <button class="gratitude_button" type="submit">

        </button>
    </form>

Any ideas?

A: Can you recreate this issue in a demo on code pen?
Looking at the code you provided, the JS should never hit, since you don't have any li's in your ul. But that might just be what you pasted.
If you can make a demo w/ this same issue, it will be easier to help you out.

A: probably you should use gratListArray.length in your IF statement.

A: enter code here

      function showButton() {
        const list = document.getElementsByClassName("gratitude_list")[0];
        let items = list.getElementsByTagName("li");
        const button = document.getElementById("newButton");

        if (items.length >= 5) {
          button.style.display = "block";
        } else {
          button.style.display = "none";
        }
      }

      showButton();

1

2

3

4

5

      <button id="newButton">Button</button>

A: Assuming you're getting your array as expected, my solution would be to add an event listener to your function.
Based on the code you shared I dont see what is triggering your current function.
all functions need to be declared by an event eg. page load, timer, or user interaction... to name a few. With an event listener each time there is a click the array is updated and the if statement is tested.
document.querySelector("button").addEventListener("click", () => {
    const glist = document.querySelectorAll('.gratitude_container > ul > li')
    const gratListArray = Array.from(glist);
    if (gratListArray.length === 4) {
    FortuneButton.classList.remove('hidden')
})

hope that helped and have fun coding.


text:
Q: Retrieving mail items with Id and Outlook REST API Given a list of Ids (aka ItemIds) how can we efficiently retrieve the emails with OutlookREST Api?
I tried to forge the following request.
https://outlook.office365.com/api/beta/me/MailFolders/<somefolderId>/messages?$filter=((Id eq 'firstId') or (Id eq 'secondId') or (Id eq 'thirdId'))

But I received a BadRequest 400 error: "The property 'Id' does not support filtering" which is very clear.
As a workaround I use the InternetMessageId (I do not care which "copy" of the email is returned). Is there a way to use the Id to achieve better performance ?

A: You could do up to 20 individual GET requests for each ID in a batch request. This is only available on the beta endpoint right now.
Something like:
POST https://outlook.office.com/api/beta/$batch HTTP/1.1

Authorization: Bearer aGFwcHlnQGRr==
Host: outlook.office.com
Content-Type: multipart/mixed; boundary=batch_myBatchId

--batch_myBatchId
Content-Type: application/http
Content-Transfer-Encoding: binary

GET  /api/beta/me/messages/{id1}    HTTP/1.1

--batch_myBatchId
Content-Type: application/http
Content-Transfer-Encoding: binary

GET  /api/beta/me/messages/{id2}    HTTP/1.1

--batch_myBatchId--


text:
Q: trim between two particular character in php I want to trim space between two special character in a string in PHP. I mentioned my string given below.
$string= "{102)The quick brown fox{201}   {501}jumbs over the{102}lazydog{201} {501}

I need to remove the space between these }  { character in this string.
the result should be like this:
$string= "{102)The quick brown fox{201}{501}jumbs over the{102}lazydog{201}{501}

A: If the number of spaces between the characters is variable, you probably need to use a regex like the following
$str = preg_replace('/}\s+{/', '}{', $str);

A: If it's always a single space, why not just do:
$str = str_replace('} {', '}{', $str);

A: One way (and probably most efficient way in your case) is to use the built-in str_replace function to do the replacing for you.
For example:
$output=str_replace('} {','}{',$string);


text:
Q: How to get row with last day of month in Sql Server query Given a table with a single row for each day of the month, how can I query it to get the row for the last day of each month?

A: Try adapting the following query. The SELECT statement within the IN clause choses the dates for the outer query to return.
SELECT *
FROM myTable
WHERE DateColumn IN
(
    SELECT MAX(DateColumn)
    FROM myTable
    GROUP BY YEAR(Datecolumn), MONTH(DateColumn)
)

A: You need to select from your table where the YourDateColumn field of the record equals the last date of the month YourDateColumn belongs to:
SELECT CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0, YourDateColumn )+1,0)) AS DATE)

A: Try to make use of below query:
    DECLARE @Dates Table (ID INT, dt DATE)
    INSERT INTO @Dates VALUES
    (1,'2017-02-01'),
    (2,'2017-02-03'),
    (3,'2017-02-04'),
    (4,'2017-03-03'),
    (5,'2017-04-03'),
    (6,'2017-04-04')

    SELECT MAX(dt) AS LastDay FROM @Dates GROUP BY DATEPART(MONTH,dt)

OUTPUT
LastDay
2017-02-04
2017-03-03
2017-04-04

OR
SELECT DATEPART(MONTH,dt) AS [MONTH],MAX(DATEPART(DAY,dt)) AS LastDay FROM @Dates GROUP BY DATEPART(MONTH,dt)

MONTH   LastDay
   2    4
   3    3
   4    4


text:
Q: html objects layering with  (oder of objects) I am currently creating an image that has a svg overlay which interacts via mouseover. My problem is, that I need to assign the title (in
) a link - as well as assign links to the menu items that are created via < button>.
If I assign this link to the first- tag however it supercedes all the links I can assign to the buttons. (every click will lead to the link assigned to the first -tag. I tried using z-index to have the buttons be on top, but my guess is the svg element is on top of the buttons, thus making it impossible to click on the links assigned to the < button> tags.
Any idea on how to assign the title a clickable link as well as have the links on the buttons work? (If I remove the href on the first -tag the links on the buttons work no problem.)
Thanks a lot for any ideas!

                    <img src="<?php echo esc_url( $stylesheet_directory_uri . '/images/picture.jpg'); ?>"/>
                    <svg viewBox="0 0 180 320" fill="#0092AB" preserveAspectRatio="none"><path d="m 181,170.17857 -56.52362,0.17222 c -45.694531,0.36942 -8.05082,49.60726 -62.096437,47.69861 L 0,218 0,0 181,0 Z"/></svg>

<?php echo $title[$menu_display_item]; ?>

<?php echo $slogan[$menu_display_item]; ?>

                        <?php foreach ( (array) $menu_items as $key => $menu_item ) {
                            if ($menu_item->menu_item_parent == $menu_display_item) echo '<button style="onclick="window.location=\'' . $url[$key] . '\';">' . $title[$key] . '</button>';
                        } ?>


text:
Q: Improving performance for large volume of simultaneous reads/writes on Percona 8 A general description of the environment and the use case:
Technical:

*

*We're running a distributed application with a single server and ~25 clients; each client is running ~75 threads.

*At one connection per thread, this results in up to ~1900 always-on connections from all client threads to the one server that continuously read, write, and delete data.

*The server machine that's hosting the database has 32G RAM and 8 cores, running Linux.

Tables involved (obfuscated but otherwise unmodified, to make this question as generic and as useful as possible, while also retaining the relevant information):
CREATE TABLE `input` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `user` varchar(191) COLLATE utf8mb4_0900_bin DEFAULT NULL,
  `domain` varchar(191) COLLATE utf8mb4_0900_bin DEFAULT NULL,
  `mail_hash` varchar(191) COLLATE utf8mb4_0900_bin DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `f12` (`field1`,`field2`),
  KEY `field1` (`field1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;

CREATE TABLE `output` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `field1` varchar(191) COLLATE utf8mb4_0900_bin DEFAULT NULL,
  `field2` varchar(191) COLLATE utf8mb4_0900_bin DEFAULT NULL,
  [...various other output fields],
  `dt` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `f12` (`field1`,`field2`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;

Application:

*

*The main process for a typical job lasts several days. It involves reading batches of up to 99,999 records from an input table that contains between ~100M and 200M rows, processing them, then writing the output to a table that is now at ~500M rows (holding data from older jobs).

*The input data consists of exactly two fields, field1, field2, which are also part of the output. There is a relation of one-to-many between field1 and field2.

*The query for reading data from the input table is of the form SELECT * FROM input WHERE field1 = ? LIMIT 99999 and could plausibly return between 1 and 99,999 rows per each value of field1.

*Processing each record takes between a few milliseconds and a few seconds, and after it is processed it is removed from the input table in batch (DELETE FROM input WHERE field1 = ? AND field2 IN(?, ..., ?);

*Prior to processing the data, the process will check the output table to see if the same data hasn't already been processed; the query for this is SELECT ... FROM output WHERE field1 = ? AND field2 IN(?, ..., ?); with up to 1,000 elements in the IN() construct at once.

*Writes to the output table use REPLACE INTO output [all fields], and may or may not overwrite existing data (we are also looking at changing the REPLACE INTO with INSERT ... ON DUPLICATE KEY UPDATE, as we are not modifying the primary key).

We recently upgraded from Percona 5.7 to Percona 8.0, and we noticed a significant drop in performance, as well deadlocks, which we had not experienced before. The slow query log says some data may take up to 40 seconds to be read from the input table. The output table got locked when performing a version of the query described at point 5 above (SELECT ... FROM output WHERE field1 = ? AND field2 IN(?, ..., ?) AND dt > ?; with ~15K of elements inside IN(). To fix this, we had to chunk it to multiple requests limited to 1,000 each and remove the dt > ? (we're now filtering on date in the application), because this would take minutes.
The only other change apart from the upgrade we did was to change the default table CHARSET from utf8 to utf8mb4 (we read that performance issues were eliminated in version 8; using it 5.7 would grind the processing to a halt).
Here's the configuration we ended up with after tweaking my.cnf for the past few hours to at least get the application to run without locking up:
[mysqld]

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

secure_file_priv   = ""
bind-address       = 0.0.0.0
loose-local-infile = 1
local-infile = 1
skip-name-resolve
disable-log-bin

max_allowed_packet      = 128M
max_connections         = 2048
transaction-isolation   = READ-UNCOMMITTED
open_files_limit        = 2048
table_open_cache        = 2048
innodb_open_files       = 2048
thread_cache_size       = 2048
join_buffer_size        = 128M
sort_buffer_size        = 16M
read_rnd_buffer_size    = 2M
max_prepared_stmt_count = 20000
thread_handling         = pool-of-threads
max_heap_table_size     = 8G
tmp_table_size          = 4G
key_buffer_size         = 1G
read_buffer_size        = 1M

[InnoDB]
innodb_file_per_table          = 1
innodb_log_file_size           = 2G
innodb_log_buffer_size         = 512M
innodb_undo_tablespaces        = 2
innodb_locks_unsafe_for_binlog = 1
innodb_buffer_pool_size        = 8G
innodb_buffer_pool_instances   = 8
innodb_use_native_aio          = 1
innodb_io_capacity             = 250
innodb_io_capacity_max         = 500
innodb_purge_threads           = 1
innodb_adaptive_hash_index     = 0
innodb_page_cleaners           = 4
innodb_lru_scan_depth          = 256

I'd greatly appreciate any hints as to what could make the same application that worked in Percona 5.7 suddenly grind to a halt in Percona 8.0. Should we go back to utf8? Also, if anything looks out of place in the configuration, do not hesitate to point it out. Thank you!

A:
~1900 always-on connections

What the heck are they doing?  What is the value of SHOW GLOBAL STATUS LIKE 'Threads_running';?  Check that number several times; if it gets above, say, 20, you could be having contention issues.  Normally lots of "idle" threads is not a problem.
UNIQUE KEY `f12` (`field1`,`field2`),
KEY `field1` (`field1`)  -- This is redundant and can be dropped.

How is ROW_FORMAT=COMPRESSED treating you?  (I'm not a fan of it.)

lasts several days

Would summary tables help out?
... input ...
PRIMARY KEY (`id`),
UNIQUE KEY `f12` (`field1`,`field2`),

If you don't need id, toss it and promote the UNIQUE to PRIMARY.
LIMIT 99999

Will you be using OFFSET?  If so, there is a performance issue we should discuss.
(DELETE FROM input WHERE field1 = ? AND field2 IN(?, ..., ?);

I don't know where the inflection point is, but 99999 items in an IN list will probably choke the processing.  In other situations, I have found the optimal chunking to be somewhere between 100 and 1000, not 99999.  More discussion:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks
REPLACE INTO with INSERT ... ON DUPLICATE KEY UPDATE

Yes.  IODKU does the Insert or Update is a single "step".  REPLACE is two significant steps:  DELETE, then INSERT.  Note that that means the AUTO_INCREMENT` value will change even if the other columns are unchanged.

deadlocks

Would you like to share one?  SHOW ENGINE=InnoDB STATUS;

2048

Since you are talking about ~1900 connections, be aware that a connection is likely to need multiple entries in the table_open_cache, etc.  That is, the rest of the things set to 2048 may be set too low.

join_buffer_size        = 128M
max_heap_table_size     = 8G
tmp_table_size          = 4G

Many settings are "per connection".  This one, for example could hugely blow up if certain queries happened 'simultaneously' in many of your 1900 connections.  Lower it.

key_buffer_size         = 1G

MySQL 8 does not handle MyISAM; lower this value to 10M.
If you would like more analysis of your settings and/or of the slowlog, see http://mysql.rjweb.org/doc.php/mysql_analysis

A: Your my.cnf should NOT have stray section name
[innodb]
remove it, please.
First easily identified problem, then after stop/start, 24 hours of instance uptime provide requested data for workload analysis.
Thanks

A: Rate Per Second = RPS
Suggestions to improve performance for your my.cnf for your 8.0.26-16 Percona instance
innodb_lru_scan_depth=100  # from 256 to minimize CPU cycles used every second
thread_pool_size=6  # from 8 to better allow sharing of 8 available cpu's
read_rnd_buffer_size=96K  # from 2M to reduce handler_read_rnd_next RPS of 6,545
net_buffer_length=96K  # from 16K to reduce packet count required when busy
innodb_buffer_pool_size=16G  # from 8G to reduce innodb_data_reads RPS of 6,168

Many more opportunities exist.
Observations, It appears general_log_file and slow_query_log_file are not available - meaning you have no recorded critical files - OR the SHOW GLOBAL VARIABLES; results were not completely posted for analysis.
ROW_FORMAT=COMPRESSED should be reconsidered.  Every row READ requires decompression, every second when used for any table.


text:
Q: Operating System on SSD but can't access files on HDD
Possible Duplicate:
Can't delete files on Windows 7 (permission)

Just upgraded from Windows XP to Windows 7 and added a SSD. The Windows 7 & Office is in the SSD.
I can see the HDD and my old files but everytime I try to access them e.g., word files,
It says I'm not authorised to.
I did not delete Windows  XP from the HDD ( dont know how to ).
Can someone help me out please? Thank you.

A: Take ownership of the files & then reset the ACLs.
Open the command prompt, type:
<your hdd drive letter>:
takeown /r /dY
icacls * /reset /c /q /t

A: When you open Microsoft Word, try opening it with Right Click and Run As Administrator. When Microsoft Word starts up, try and open the document using File->Open.
If that works, you can right click on the Microsoft Word shortcut, go to the Compatibility tab and check Run As Administrator in order to run it every time without right clicking.
Hope that helps.
(Also, you can right click on your files or folders, go to the Security tab and check which users have Full Control, Press Edit to edit the users and add yourself with full control if you are not in there)


text:
Q: adding image to library in iphone simulator I've done some research on this issue for the past hour. It should be an easy issue, but I still can't get it to work. I've added an image called IMG_0000.JPG in ~/Library/Application Support/iPhone Simulator/4.1/Media/DCIM/100APPLE and ~/Library/Application Support/iPhone Simulator/User/Media/DCIM/100APPLE. People say the easy way out is to drag an image from safari to the library. I did that and it opens the image in safari, but when I try again the image is not there. What should I do?

A: When they are talking about adding the image from Safari, it is actually adding it in Safari from the simulator.
Open Safari on your iPhone simulator, go open the image you want and make a long press on the image. An option to save the image should appear.


text:
Q: Setting up routing for Cakephp application on AWS cloudfront and elastic load balance (using beanstalk) I'd like to ask for your help how to setup routing properly for a Cakephp web application on AWS. I got Cakephp running on AWS Elastic Beanstalk, using PHP configuration, and then I set an A record for my domain (e.g. foo.com) linking to Cloudfront CDN that was linked to the default ELB of Beanstalk. Everything was working fine, until I found out all redirections handled by Cakephp will redirect to the default public DNS of ELB (elb-abc123.elb.amazonaws.com/page/) instead of foo.com/page/. I know there's something called CName for elb, but I couldn't get it working (http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-domain-names-with-elb.html?). And I'm not sure if this is something with .htaccess.
Here's the route 53 setting of my domain:
foo.com. A ALIAS examplecode.cloudfront.net (examplecode...)
www.foo.com. A ALIAS examplecode.cloudfront.net (examplecode...)

And CouldFront settings:
Alternative Domain Names (CName): foo.com, www.foo.com

Okay, and here's an example of what I'm facing:
Schema: client->cloudfront->elb(beanstalk)->EC2
1. Everything works fine when A client type foo.com or www.foo.com in his/her browser.
2. The Cakephp asks for login when client is attempting to request a secure page foo.com/account/index (e.g. account page), so the redirection is handled by cakephp controller: $this->redirect(array('controller' => 'secure', 'action' => 'login'));.
3. The expecting landing url should be foo.com/secure/login/ bur what turns out is elb-abc123.elb.amazonaws.com/secure/login.
Can someone help me, thanks.

A: Check the return value of env('HTTP_HOST'), that's what CakePHP uses for the base URL by default. It will probably return elb-abc123.elb.amazonaws.com.
If you cannot change that behavior, then, depending on your CakePHP version, use FULL_BASE_URL, App.fullBaseUrl or Router::fullBaseURL() to define the proper base URL on your own.
$s = null;
if (env('HTTPS')) {
    $s = 's';
}
$fullBaseUrl = 'http' . $s . '://foo.com';

In your index.php
define('FULL_BASE_URL', $fullBaseUrl);
Configure::write('App.fullBaseUrl', FULL_BASE_URL);

Or at anytime (assuming the Router class is available):
Router::fullBaseUrl($fullBaseUrl);


text:
Q: How to centre this SVG word Trying to figure out how to centre this SVG text horizontally and vertically in the viewport
(The element needs to remains central across different viewport sizes)
Tried using the viewbox panning but I can't get everything aligned - part of the SVG remains cut off/incorrectly scaled
Also looking to set the font size to the same rem value as other standard text elements on the page.
SVG text is used as there's a 'slice' GSAP animation happening to it.
<div class="stage">
<svg id="demo" xmlns="http://www.w3.org/2000/svg" width="2000" height="800" viewBox="0 0 1000 800">
<defs>
  <pattern id="slicePattern" patternUnits="userSpaceOnUse" width="3000" height="800" x="0" y="0"><text transform="translate(500 400)" text-anchor="middle" font-size="220" fill="#fff">SLICE</text>
  </pattern>
</defs>

<g fill="url(#slicePattern)">
  <polygon id="slide1" points="0,150 551,150 201,400 0,400" />
  <polygon id="slide2" points="549,150 1000,400 999,400 1000,150" />
  <polygon points="200,400 550,150 1000,400" />
</g>

<line x1="550" y1="150" x2="200" y2="400" stroke-width="1" stroke="white"/>
<line x1="550" y1="150" x2="1000" y2="400" stroke-width="1" stroke="white"/>

  </svg>
</div>

The standard text to match to is 2.5em. Setting the SVG text to that it doesn't size the same. Also can't correctly pan the viewbox to centre the svg text in the viewport. I need this to be responsive centering also.
In short, I don't understand the effect the text transform properties are having on the element, or how this relates to the viewport/viewbox values.

A: For making the whole svg responsive:
svg{
    width:100%;
    height:auto
}

For the text, It has already text-anchor set to middle which is correct. You need to specify the position of the text by setting x and y values.
<text text-anchor="middle" x="50" y="0">The Text</text>

The font-size in svg has nothing to do with the default font-size of the css. It's relative to the viewBox of your svg. SVG functions as a separate image file. But you can have access to its style attributes by css.


text:
Q: laravel 5.1 : how can i have two wherePivot in eloquent? I need check two where conditions on a pivot table. I know that I can check one condition with this:
$dis = $user->discounts()->wherePivot('used_for_id', '=', null)

However, I want two where conditions. When I use orWherePivot, the two where conditions are ORed together, but I want them to be ANDed together.
$whereData = [
    ['id', "=", $discountId],
    ['used_for_id', "=", null]
];

A: The wherePivot function definition is given below. So u can use $boolean variable as 'or' and 'and' for joining condition
public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') {
  //code
}

 $dis = $user->discounts()->wherePivot('column', '=', null,'and')
        ->wherePivot('column', '=', null,'or')
        ->wherePivot('column', '=', null,'and')
        ->get();

A: wherePivot() works the same as a normal where() method; you can just chain on the second wherePivot() condition and it will be ANDed with the previous conditions:
$dis = $user
    ->discounts()
    ->wherePivot('id', '=', $discountId)
    ->wherePivot('used_for_id', '=', null)
    ->get();


text:
Q: Why does a solution of a linear homogenous ODE with constant coefficient must be infinitely differentiable? Let $y_0$ be a solution to the ODE: $$y^{(n)} + a_{n-1} y^{(n-1)} + \dots + a_0 y = 0$$
In this note (part 2), it is claimed that $y_0$ must be infinitely differentiable because we can write $y^{(n)}$ in terms of derivatives with lower order.
My understanding is that since $y^{(n)} = -a_{n-1} y^{(n-1)} - \dots - a_0 y$, differentiating both sides will give you a formula of $y^{(n + 1)}$ in terms of derivatives with lower order. Continuing this process gives us formula for derivative of arbitrarily high order. My problem with this is that why are allowed to differentiate on both sides? Aren't we allow to differentiate only if $y^{(n)}$ is differentiable?

A: Yes, but $y^{(n)}$ is differentiable because

*

*$y$ is $n$ times differentiable, since it is a solution of the differential equation.

*$y^{(n)} = -a_{n-1}\,y^{(n-1)} - \dots - a_0\, y$, and each $y^{(k)}$, $0\le k<n$, is differentiable.

A: You have the well-known regularity result:  $$\text{if }f\in \mathcal{C}^k \text{ then each solution of } y^{(n)}=f(t,y(t),...,y^{(n-1)})\text{ is } \mathcal{C}^{n+k}.$$ In the case of the homogenous ODE with constant coefficient, we have  $$f(t,u_1,...,u_n)=-a_{n-1} u_n - \dots - a_0 u_1,$$ which is infinitely differentiable on $\mathbb{R}\times\mathbb{R}^n$; so $y$ is infinitely differentiable on $\mathbb{R}$.


text:
Q: Possible to filter row values using DataStax python cassandra-driver? I need to process about 4,000 cassandra queries. I convert each query ResultSet into a generator to keep the memory footprint low. Within each row of the generator, I'm only concerned with a few fields of about 50 present.
I know that I can't filter directly on value fields in CQL but does the DataStax Python Cassandra driver have something built in that does this? or would it make more sense to just do this when I build the generator i.e
def make_gen(response):
    for row in response:
        yield row.value.field1, row.value.filed2

I am issuing direct queries at the moment but will move to model based approach later with concurrent queries and prepared statements.  The code that is issuing the request is very basic
sess = connect_cas(env)
for user in users:
    q = 'select * from table ' + \
        'where key1 = {} and '.format(key_1) + \
        'key2 = {} and '.format(key_2) + \
        'sample_time > {} '.format(t1) + \
        'sample_time < {} '.format(t2)
   resp_gen = make_gen(sess.execute(q)) # just a yield json.loads(Row.value)
   for resp in resp_gen:
       if field in resp:
           // process data from this field

I only care about rows where this "field" is present. I've since updated my generator to only yield data when this condition is true, however, if there is something built into the DataStax driver that does this more efficiently, at 4,000 queries the savings will add up.

A: Are you showing that you only process rows where field1 or field2 are set to a particular value?
It's not exactly built for this purpose, but you could use a custom row_factory to achieve this filtering at a lower level and avoid conversions between named tuple, tuple, and additional generator.


text:
Q: Repeating/Cloning DOM elements with HTML and CSS only Given an HTML template with the following structure:

etc, is there any way to generate the child  elements in HTML without manually adding them for each user?  I will not have access to Javascript or PHP in this environment, only a basic HTML form and an inline style sheet.


text:
Q: Set with lower bound but without an infimum w.r.t. $\subseteq$ I'm looking for a set $M$ which is partially ordered by $\subseteq$. $M$ should have a lower bound but no infimum. Is that possible?
A lower bound is an element $x \in N$ with $M \subset N$ such that for all elements $y \in M$, $x \subseteq y$ holds.
An infimum is a maximal lower bound with respect to $\subseteq$.

A: It doesn't make sense to say that $M$ has a lower bound but no infimum if $M$ is the partially ordered set, so I'm assuming that you want a set $N$ partially ordered by $\subseteq$ in which there is a subset $M$ with a lower bound but no infimum. (This is now clear from the revised version of your question.)
That is possible. Let $N=\{(x,\to):x\in\Bbb Q\}$, the set of all open rays unbounded on the right; $N$ is even linearly ordered by $\subseteq$. Let $M=\{(x,\to)\in N:x>\sqrt2\}$.


text:
Q: Delegate hookup to receive shouldStartLoadWithRequest in Cocoa-Applescript? I'm trying to receive the shouldStartLoadWithRequest message from a WebView in an applescript/objective-c OSX application.
The applescript I would like to receive the message with:
on webView_shouldStartLoadWithRequest_(request, navigation_type)
    log "should start!"
    return yes
end webView_shouldStartLoadWithRequest_

I am led to believe that I have the wrong delegate connections in the IntefaceBuilder, but I've tried everything which looks plausible and still no luck.
downloadDelegate --> MyApp App Delegate
frameLoadDelegate --> MyApp App Delegate
resourceLoadDelegate --> MyApp App Delegate
UIDelegate --> MyApp App Delegate

No luck so far. However, I have other messages working correctly (e.g. webView_didStartProvisionalLoadForFrame_ works fine).
What do I need to connect or add to receive this event? I'm very new to this type of programming, so apologies if I'm missing something obvious.
Thanks so much!

A: You're probably doing everything right, but the message isn't being received because it isn't being sent. webView:shouldStartLoadWithRequest: is not a method in any web view delegate protocol on OS X. (It does exist on iOS.)
I'm not at all familiar with those various delegate protocols, but depending on what you're trying to accomplish, it seems that either webView:resource:willSendRequest:redirectResponse:fromDataSource: or possibly webView:decidePolicyForNavigationAction:request:frame:decisionListener: may be useful.


text:
Q: Delphi: How do I translate this C code, which performs low-level access to IEEE floating-point number? The following C function is from fastapprox project.
static inline float
fasterlog2 (float x)
{
  union { float f; uint32_t i; } vx = { x };
  float y = vx.i;
  y *= 1.1920928955078125e-7f;
  return y - 126.94269504f;
}

I know that C union can be translated to Delphi variant record, but I still experienced difficulty in translating such low-level C code to Delphi. I hope Delphi experts here are willing to help.
More Information
I add this section later, which is not a part of the question. This section gives information to readers that expect better accuracy.

*

*In fastapprox, fasterlog2() was deliberately designed to be simpler, faster but less accurate Log2 function. Anyone who expect better accuracy can use the more-accurate function they provide, namely fastlog2().

*They included a Mathematica notebook with an explanation of their algorithms as well as the origin of some mysterious values, e.g.126.94269504. Mathematica website provides a free viewer for the .nb files.

*See also: Why the IEEE-754 exponent bias used in this C code is 126.94269504 instead of 127?

A: I think I'd code it by using pointer casts to effect a reinterpret cast:
function fasterlog2(x: single): single;
const
  c1: Single = 1.1920928955078125e-7;
  c2: Single = 126.94269504;
var
  y: single;
begin
  y := PCardinal(@x)^;
  Result := y * c1 - c2;
end;

Note that I used typed constants of type single to ensure an exact match with the C code.
I don't really see any need for a variant record in a Delphi implementation.
Or you could use a pure asm approach. The x86 version looks like this:
function fasterlog2asm(x: single): single;
const
  c1: Single = 1.1920928955078125e-7;
  c2: Single = 126.94269504;
asm
  FILD    DWORD PTR [ESP+$08]
  FMUL    c1
  FSUB    c2
  FWAIT
end;

For x64 the SSE implementation would be
function fasterlog2asm64(x: single): single;
const
  c1: double = 1.1920928955078125e-7;
  c2: double = 126.94269504;
asm
  CVTDQ2PD  xmm0, xmm0
  MULSD     xmm0, c1
  SUBSD     xmm0, c2
  CVTSD2SS  xmm0, xmm0
end;

In x64 the assembly version is only about twice as performant as the pure pascal function.  The x86 assembly version is over five times as performant - this is entirely due to the higher cost of type conversion (integer/single/double) in SSE vs x87.
The reason that this approach can be used is that floating point numbers are represent as
significand * base^exponent

and a value of 2 is used as the base.

A: How about this:
function fasterlog2(x: Single): Single; inline;
const
  f1: Single = 1.1920928955078125e-7;
  f2: Single = -126.94269504;
var
  i: Cardinal absolute x;
begin
  Result := i * f1 + f2;
end;

A: A possible translation is:
function fasterlog2(x: Single): Single;
type
  TVx = record
    case Byte of
      0: (f: Single);
      1: (i: UInt32); // Or Cardinal, depending on version
  end;
const
  C1: Single = 1.1920928955078125e-7;
  C2: Single = 126.94269504;
var
  y: Single;
  vx: TVx;
begin
  vx.f := x;
  y := vx.i;
  y := y * C1;
  Result := y - C2;
end;

I assume this somehow uses knowledge of the bit patterns of the Single. I am not sure if it really gives you a faster log, but that is what the C routine is doing.

A: Try this (literal translation):
function fasterlog2(x : Single): Single; inline;
type
  TX = record
    case boolean of
      false: (f : Single);
      true:  (i : Cardinal);
  end;
const
  f1 : Single = 1.1920928955078125e-7;
  f2 : Single = -126.94269504;
var
  vx: TX absolute x;
  y: Single;
begin
  y := vx.i;
  y := y * f1;
  Result := y + f2;
end;

WriteLn(fasterlog2( 1024.0));
WriteLn(Math.Log2( 1024.0));

Outputs:
 1.00573043823242E+0001
 1.00000000000000E+0001

Or a oneliner (similar to Davids example):
function fasterlog2(x : Single): Single; inline;
const
  f1 : Single = 1.1920928955078125e-7;
  f2 : Single = -126.94269504;
begin
  Result := PCardinal(@x)^ * f1 + f2;
end;


text:
Q: How to activate ActionEvent inside JMenu to show new panel on the frame?(Basic) I just started to learn swing by myself, I'm little bit confused why my event does not work here:
1.I'm trying to delete everything from my panel if the user click menu bar -> load but it force me to change the panel to final because i'm using it inside the event!
2.I have defined new panel in my event and defined two more container to add to that panel and then add it to the main frame but it seems nothing happening!
Please help me if you can find out what is wrong.
Sorry in advance for messy code.
I appreciate any hints.
public class SimpleBorder {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                myFrame frame = new myFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

class MyFrame extends JFrame {

    public MyFrame()
    {

        setSize(500,500);
        JPanel panel = new JPanel();

        panel.setLayout(null);
        JLabel label = new JLabel("my name is bernard...");
        Color myColor = new Color(10, 150, 80);
        panel.setBackground(myColor);
        label.setFont(new Font("Serif", Font.PLAIN, 25));
        Dimension size = label.getPreferredSize();
        Insets insets = label.getInsets();
        label.setBounds(85+insets.left, 120+insets.top , size.width, size.height);

        panel.add(label);

        JMenuBar menu = new JMenuBar();
        setJMenuBar(menu);

        JMenu col = new JMenu("Collection");
        menu.add(col);

        JMenu help = new JMenu("Help");
        menu.add(help);

        Action loadAction = new AbstractAction("Load")//menu item exit goes here
        {
            private static final long serialVersionUID = 1L;
            public void actionPerformed(ActionEvent event)
            {
                JTextArea text = new JTextArea(10, 40);
                JScrollPane scrol1 = new JScrollPane(text);
                String[] items = {"A", "B", "C", "D"};
                JList list = new JList(items);
                JScrollPane scrol2 = new JScrollPane(list);
                JPanel panel2 = new JPanel(new BorderLayout());
                panel2 = new JPanel(new GridLayout(1, 2 ));
                panel2.add(scrol1,BorderLayout.WEST);
                panel2.add(scrol2,BorderLayout.EAST);
                add(panel2);
            }
        };
        JMenuItem load = new JMenuItem(loadAction);
        col.add(load);
        add(panel);

    }

}

A: Call revalidate()/repaint() on your JFrame instance after adding the new panel:
JPanel panel2 = new JPanel(new BorderLayout());
// panel2 = new JPanel(new GridLayout(1, 2 ));//why this it will overwrite the above layout
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
revalidate();
repaint();

Also call pack() on you JFrame instance so all components are spaced by the layoutmanager. As said in a comment dont extend the JFrame class, create a variable of the frame and initiate all that you need on the frames instance, and dont set a layout to null, unless you love hard work :P
Alternatively as mentioned by mKorbel, a CardLayout may be more what you want, it will allow you to use a single JPanel and switch between others/new ones:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";

//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...

//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);

//add card panel to frame
frame.add(cards);

//swap cards
CardLayout cl = (CardLayout)(cards.getLayout());//get layout of cards from card panel
cl.show(cards, TEXTPANEL);//show another card


text:
Q: Join object values into a string with dynamic key names In an Angular app, I have an HTTP response from the server as a JSON object with some errors. I want to join them all into a string and show them as a message to the user.
At the moment, I have done this:
if ( "errors" in emsg.error ) {
   let msg = emsg.error.map(o => o.name).join(', ');
}

However, I need to write it for every different case of return with different key names. An example of my response is this one:
{
   "error":{
      "message":"422 Unprocessable Entity",
      "errors":{
         "id":[
            "The id has already been taken."
         ],
         "name":[
            "The name has already been taken."
         ]
      },
      "status_code":422
   }
}

So, my response can have dynamic object names and each of them may have more than one error. Is there any way to transform the above to a generic code that will handle all the responses of the same format?

A:

var emsg = {
   "error":{
      "message":"422 Unprocessable Entity",
      "errors":{
         "id":[
            "The id has already been taken."
         ],
         "name":[
            "The name has already been taken."
         ]
      },
      "status_code":422
   }
}, array = [];

// push all error values into array
for (var key in emsg.error.errors) {
    Array.prototype.push.apply(array, emsg.error.errors[key]);
}

console.log(array.join(', '));

If you can use lodash, you can use flatMap to do it more elegantly,
_.flatMap(emsg.error.errors).join(', ');

A: get the object keys and iterate the keys array. If the keys exist then join the values

var emsg = {
   "error":{
      "message":"422 Unprocessable Entity",
      "errors":{
         "id":[
            "The id has already been taken."
         ],
         "name":[
            "The name has already been taken."
         ]
      },
      "status_code":422
   }
}
 var keys = Object.keys(emsg.error.errors);
 let msg = keys.map(o =>emsg.error.errors[o] ).join(', ');
 console.log(msg)


text:
Q: How to avoid Spring Boot Controller catching request for favicon? I have the following Controller
@Controller
public class MyController {

    @GetMapping({"/", "/{name}"})
    public String hello(@PathVariable(required = false) String name) {
        System.out.println("Name: " + name);
        return "hello";
    }
}

and this directory structure
- resources
    - static
        - favicon.ico
    - templates
        - hello.html

When I GET http://localhost:8080/ through the browser, my application prints:
Name: null
Name: favicon.ico

So the request for /favicon.ico goes was caught by my controller, but instead I want that Spring handles this request and returns the favicon.ico placed here resources/static/favicon.ico
I think there should be a way without adding a handful of lines of configuration.

A: One approach you could take is to disable favicon resolution via this property:
spring.mvc.favicon.enabled=false

A: I had to include <link rel="icon" type="image/x-icon" href="images/favicon.ico"> in my html head, and it worked. The images prefix isnt necessary, but I moved the icon into their because I was allowing any unauthenticated request to /images so I dont need a extra rule for the favicon.ico. Thats my current directory strucutre:
- resources
    - static
        - images
            - favicon.ico
    - templates
        - hello.html

s/o to Ajay Kumar for helping.


text:
Q: kotlin android "OnbackPressed" overrides nothing I know this already asked a few times, but I still don't get anything after all (I'm quite new in android development).
So i set up my back button in the MainActivity.kt like this:
    class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        val navController = this.findNavController(R.id.myNavHostFragment)

        NavigationUI.setupActionBarWithNavController(this, navController)

        supportActionBar?.setDisplayHomeAsUpEnabled(false)

    }

        // Set up the back button on action bar
        override fun onSupportNavigateUp(): Boolean {
            val navController = this.findNavController(R.id.myNavHostFragment)

            return navController.navigateUp()
        }
    }

What I want is that this back button is disabled in some fragments, so I tried to override the onBackPressed() function (It is what most people on the internet told) in one of the fragments:
    class DashboardFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        // Declare that this fragment has menu
        setHasOptionsMenu(true)

        // Set action bar title to "Main Dashboard"
        (activity as AppCompatActivity).supportActionBar?.title = "Main Dashboard"

        // Binding object for this fragment and the layout
        val binding: FragmentDashboardBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_dashboard, container, false)

        //Some codes here//

        return binding.root
    }

        // This is where the error occured
        override fun onBackPressed() {
            super.onBackPressed()
        }

        override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
            super.onCreateOptionsMenu(menu, inflater)
            inflater?.inflate(R.menu.nav_overflow_menu, menu)
        }
    }

But it returns an error saying:

"OnBackPressed" overrides Nothing

Am I missing something? I'm already searching for the solutions but still confused over this.

A: Who knew... onSupportNavigateUp() works only on 4.0 and above. For below onNavigateUp() is called.
so
    override fun onNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.myNavHostFragment)

        return navController.navigateUp()
    }

A: What you could do is set your nonbackbutton fragments to backstack when inserting them, which is done by
val transaction = supportFragmentManager.beginTransaction()
transaction.addToBackStack(null)
transaction.replace(R.id.frame, fragment) //or add, whatever you use
transaction.commit()

(if you want back button functionality, just skip the addtoBackStack line)
Then, also in your activity, you override the onBackPressed() and check whether the backstack is empty or full. If it is empty, which is checked by
if(supportFragmentManager.backStackEntryCount() == 0)

then you are, for example, on a fragment that supports back button, and just do super.onBackPressed().
On the other hand, if it has something, you can do the navController.navigateUp() part, and when done, pop it using supportFragmentManager.popBackStackImmediate().
I think you could make something like this work, try it, and let us know :)


text:
Q: Calling C++ function from a C file gives an "undefined reference" compiler error I have the following files - main.c, RULE_MINE.h and RULE_MINE.cpp
main.c
#include "RULE_MINE.h"
int main()
{
  checker();
}

RULE_MINE.h
#ifndef HEADER_FILE
#define HEADER_FILE

#ifdef __cplusplus

extern "C"
{

#endif

//declare functions here
  void checker();

#ifdef __cplusplus

}

#endif

#endif

and RULE_MINE.cpp
#include <bits/stdc++.h>
#include "RULE_MINE.h"

using namespace std;

void checker()
{
  cout<<"whaaat?"<<endl;
}

I am compiling the following way
$ g++ RULE_MINE.h
$ g++ -c RULE_MINE.cpp
$ g++ main.c

For this, I get a compiler error
main.c:(.text+0x1947): undefined reference to 'checker'
collect2: error: ld returned 1 exit

I am unable to find what the error is. But suppose in the main.c file if I include #include "RULE_MINE.cpp" , then it is running properly and gives an output.
Can you please explain why I am getting this error?

A: Replace void checker() with extern "C" void checker in you cpp file to ensure correct linkage (C or cdecl linkage).

Your compilation commands are incorrect, you don't compile header files. Use:
$ g++ RULE_MINE.cpp main.c

And perhaps more flags (-W -Wall -O2 for example)
or
$ g++ -c RULE_MINE.cpp
$ g++ -c main.c # or gcc -c main.c
$ g++ RULE_MINE.o main.o

A: Your implementation needs extern too :
extern "C" void checker()
{
  cout<<"whaaat?"<<endl;
}


text:
Q: Opening .scmp file in Visual Studio 2015 opens as XML and not as comparison UI I'm opening a Database Schema Comparison (.scmp) file and the file opens in Visual Studio as XML. However, the need is for the file to open in the Server Data Tools tab.
I have tried opening from Visual Studio and Windows Explorer.
Using Visual Studio Professional 2015 with Update 3.

A: Silly me. I didn't notice that SQL Server Data Tools (SSDT) had been corrupted and wasn't showing as installed. Installing SSDT solved the issue.

A: The .scmp file is a XML file essentially. It is stored in the Schema Comparison folder of the project system by default.  When you double click the .scmp file in the Visual Studio, the Select Source/ Target Schema page appears, on which shows the comparison settings and options that you have set. When you click the OK button on that page, SchemaCompare1.scmp file (for example) shows in the edit explorer.
However, you may not open a .scmp file by double-clicking it on the disk. It may be because the .scmp file is used to save comparison settings and options between usage sessions (any combination of a project, database, and .dbschema file), it associates with a solution so you can open it by double-clicking it in the Visual Studio.


text:
Q: facebook keeps freezing Chrome and Windows Hı, everyone. I am a Windows 7 and Chrome user.
Lately (since past few months) my Chrome has been freezing, taking down whole operating system with it, leaving resetting the computer the only choice. Recently I discovered that the issue was with facebook tabs, and when I close those tabs (if it's not too late!), I can save Chrome and Windows from a complete crash.
This is very annoying. Is there a solution for this problem? Maybe uninstalling/reinstalling some plugins? Please help. Thanks.
PS: Let me know if for helping me with this issue you need to know the list of extensions I have installed. I'll provide it in as an addendum.

A: You can try these two methods; try the first one first, and if it hasn't worked try the second one:

*

*Delete browser cache to the time before you've started having the problems (Chrome has options for 1 hour, 1 day, 4 weeks, all. Pick the nearest).

*Disable chrome's built in flash player plugin. You can access the plugins page by typing about:plugins in the address bar.
If you see multiple flash versions, look at the location displayed along with it and disable the one that has chrome in its path.
If you have your chrome connected to a google account like I have, disconnect your google account first before you follow method no 1 (from chrome:settings), and reconnect later, that way you won't lose your history/passwords/search etc.
This has worked for me on multiple occasions on both Mac and Windows.

A: This works for me

*

*Type about:plugins into the address bar of chrome.

*After you press enter, you'll see a list of all the plugins installed in Chrome. Look for the Flash entry and expand the details of these files by toggling the label [+] Details, found in the upper right-hand corner of the browser.

*Click the Disable option for Chrome's internal installation of Flash. (Make sure you disable the file located in Chrome's AppData folder and not the stand-alone Flash installation).

You'll now be using the Flash installed on your operating system. Now ensure that you have the latest version of Flash!


text:
Q: Send Post Request over Cordova InAppBrowser I am developing a cordova hybrid app (currently for android) and using the InAppBrowswer-Plugin.
I want to open a web page and login there using a post request (as it is currently done via Java in an actual Android application).
Somehow this does not work though and I cannot figure out why. This is the code I am using:
var ref = cordova.InAppBrowser.open("www.thesite.dummy", "_blank", "location=yes");

var postAsString = 'var xhttp = new XMLHttpRequest();'+
    'xhttp.open("POST", "'+url+'", true);'+
    'xhttp.onreadystatechange = function() {if (xhttp.readyState == 4 && xhttp.status == 200) {alert("it worked")}};'+
    'xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");'+
    'xhttp.send("username=dummyUser&password=dummyPW")'
console.log(postAsString);

ref.executeScript({"code":postAsString});

As you can see I also console.log my "postAsString". If I copy this string and execute it in the console of www.thesite.dummy it actually works, but not in the InAppBrwoser

A: Just to help anyone who find this question through Google, the solution is described at that answer as said in the question comments.
The code, changing values for the specific context is below:
var pageContent = '<form id="loginForm" action="www.thesite.dummy" method="post">' +
'<input type="hidden" name="username" value="dummyUser">' +
'<input type="hidden" name="password" value="dummyPW">' +
'</form> ';
var pageContentUrl = 'data:text/html;base64,' + btoa(pageContent);

var browserRef = window.cordova.InAppBrowser.open(
    pageContentUrl ,
    "_blank",
    "hidden=no,location=no,clearsessioncache=yes,clearcache=yes"
);


text:
Q: Representation that is semisimple passing to algebraic closure Let $G$ be a group, $k$ be a field of characteristic $0$, $k^a$ be an algebraic closure of $k$, $V$ be a finite dimensional $k$-representation of $G$. If the base change representation $V_{k^a}$ is  semisimple, then is $V$ semisimple?
For example, continuous real representations of compact groups are semisimple. It somehow leads me to ask the precedent question (since it is well-known that complex representations are semisimple, but of couse this conclusion is also direct for real case).

A: Fact: Let $G$ be a group, $L/K$ be a field extension. If $V/K$ is a finite dimensional representation of $G$ such that $V_L$ is a semisimple $G$-representation, then $V$ is a semisimple $G$-representation.
The proof is taken from Bourbaki Algèbre Ch.8, Sec.7, no.4, Théorème 2.
Proof: For every $G$-subrepresentation $W\subset V$, $W_L$ is a $G$-subrepresentation of $V_L$. By semisimplicity of $V_L$, there is a $G$-equivariant projection $p:V_L\to W_L$. There is a $K$-linear map $h:L\to K$ with $h(1)=1$. Then $Id_W\otimes h:W\otimes_KL\to W\otimes_KK$ is $G$-equivariant and $K$-linear. The map $q:V\to W$ defined by $q(v)=(Id_W\otimes h)[p(v\otimes 1)]$ is a $G$-equivariant $K$-linear map. Therefore, $\ker(q)$ is a $G$-subrepresentation of $V$.
For every $w\in W$, $p(w\otimes 1)=w\otimes 1$ and $q(w)=w$. That is $q|_W=Id_W$, so $\ker(q)\oplus W=V$ as $G$-representation. This show that $V$ is semisimple.


text:
Q: segment condition in sobolev space In Adam's "Sobolev Spaces", he defines "segment condition" in 3.21 which describes the properties of a domain:

we say that a domain $\Omega$ satisfies the segment condition if every $x\in \text{bdry}\Omega$ has a neighborhood $U_x$ and a non-zero vector $y_x$ such that if $z\in \bar{\Omega}\cap U_x$, then $z+ty_x\in\Omega$ for $0<t<1$.

I'm confused about the definition above, in 3.20 he defines $\Omega_1:=\{(x,y)\in\mathbb
R^2|0<|x|<1,0<y<1\}$ and says $\Omega_1$ doesn't satisfy the segment condition but $\Omega_2:=\{(x,y)\in\mathbb
R^2|-1<x<1,0<y<1\}$ satisfies the segment conditon.
For $\Omega_2$, take $x=(0,1)$, then the only choice of $y_x$ in my mind is $(0,-\varepsilon)$.  Take $U_x$ to be the semi-disc of radius $1/2$, then when $z$ is close to $(-1/2,1)$, certainly $z+ty_x\notin \Omega_2$.
the author concludes that " the domain cannot lie on both sides of any part of its boundary " and I don't know how to get it.

A: Your assertion "when $z$ is close to $(-1/2,1)$, certainly $z+ty_x\notin \Omega_2$" is not true.
Proof. Assume that $z=(-1/2+\delta_1,1-\delta_2)$ with $\delta_1,\delta_2\geq 0$ small enough so that $z\in\overline{\Omega_2}\cap U_x$. Then $z+ty_x$ belongs to the interior of the segment $[z,(-1/2+\delta_1,1/2-\delta_2)]\subset\Omega_2$.
The author concludes that "the domain cannot lie on both sides of any part of its boundary" and I don't know how to get it.
Geometric ideia in $\mathbb R^2$: If the domain lie on both sides of some part of its boundary, then $[z,z+y_x]\cap\text{bdry}\Omega\neq\varnothing$ for some $z\in U_x$, i.e., $z+ty_x\notin \Omega$ for some $t$.


text:
Q: jQuery Odd Even is Adding Even to an Odd Element jQuery('li.has-sub ul li:even').addClass('even');
jQuery('li.has-sub ul li:odd').addClass('odd');

The classes are being added to a drop down menu.  In one drop down menu the classes are added correctly but the another dropdown is adding class even to odd elements.  I think that jquery might be counting all of the list items together, which still doesnt explain why it is counting 1 as even.  You can see the problem on this url:
The menu with the yellow background starting with rafting trips.
http://bit.ly/XAEmh7
I have tried adding this in an attempt to make jQuery count only the ul in question but no luck.

A: jQuery is behaving correctly given your code:
jQuery('li.has-sub ul li:even').addClass('even');
jQuery('li.has-sub ul li:odd').addClass('odd');

If you change it to:
jQuery('li.has-sub').each(function(){
   jQuery('ul li:even',this).addClass('even');
   jQuery('ul li:odd',this).addClass('odd');
});

Should work.

A: :ODD/:EVEN selectors are 0 based index so it will high-light Second,fourth,etc rows as odd (index 1,3, etc.)
Also, for improving performance you should use .filter as below:
$(document).ready(function() {
    $('li ul').filter(':even').addClass('even').end()
              .filter(':odd').addClass('odd');
});

Please refer the jQuery documentation : http://api.jquery.com/odd-selector/


text:
Q: Adjacent sibling selector not working with dynamically added class in IE7/8 span1
span2
<button id='btn'>select span1</button>

#span1.selected + span {
    background-color:red;
}

$('#btn').click(function() {
    $('#span1').addClass('selected');
});

http://jsfiddle.net/xSGh5/
I'm using adjacent sibling selector to style checkbox with the custom image, so I don't want to abandon this selector. Any workarounds?

A: Well, this is a known bug, see the section about + selector here: http://www.quirksmode.org/css/contents.html


text:
Q: JQuery element CLICK function IF (for each css_attribute = value) then change css value I'm a JQuery NEWB trying to figure out why this doesn't work.
HTML:

div 0

div 1

div 2

<button>

click

</button>

SCRIPT:
$(".button").click(function() {
    $('.box').each(function(i) {
        var color = $(this).css('background-color');
        if (color == 'rgb(0, 0, 255)') {
            $("div#box").css ({'background-color':'rgb(255, 0, 0)'});
        }
    });
});

The actual over all problem is much more complex and this is NOT the actual code, but this is an equivalent based from what solutions I could find on here.

A: In your case change your js part to below. then it will solve the problem.

$(".button").click(function() {
    $('.box').each(function(i) {

         var color = $(this).css('background-color');
         if (color == 'rgb(0, 0, 255)') {
            $(this).css ({'background-color':'rgb(255, 0, 0)'});
        }
    });
});

or else this is how you can do it. refer the working demo and the example code. hope this will help to your.

<!DOCTYPE html>

 <title></title>

div 0

div 1

div 2

<button>

click

</button>


text:
Q: Windows 10: How to disable this notification? This insanely annoying notifications keeps up showing up daily:

How could I please disable it? I remember doing something with regedit about this, but it didn't work apparently.
There is no such option to disable it on the menus.
I don't want the computer to ever reboot by itself or remind me of the active hours, I will reboot it manually or just let it apply the update when I turn it off.
Windows 10 version: Enterprise LTSC 1809

A: The message is telling you the computer will restart OUTSIDE of active hours, not inside active hours (when you have defined when you will be using the computer).
The update has been installed and you cannot stop  this message.
Be certain Active Hours have been properly set and work for you.
You can pause the restart for several days (I am not certain how many) but you cannot install anything else in the meantime because of the pending restart.
Best approach is the set Active Hours and then let restarts happen outside of your active hours.

A: Microsoft has decided users cannot delay restarts past a certain time.
In the advanced options, you can 'schedule' it for up to seven days out, but then this notification will come back, and will reboot next night.

A: Open "Edit Group Policy"

*

*Go to: Computer configuration and click Administrative templates.

*Go to: Windows components > Windows Defender Security Center > Notifications

*Open the Hide non-critical notifications setting and set it to Enabled. Click OK.
source material here