text:
Q: Boost Geometry: assertion_failed error C++ I have the following header file in order to use boost geometry types:
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>

using namespace boost::geometry;
using namespace detail::assign;

typedef model::d2::point_xy<double> point_xy;
typedef model::polygon<point_xy> polygon;
typedef model::multi_polygon<polygon> multi_polygon;
typedef model::box<point_xy> box;

When compiling a file that attempts to use these types, I get a massive compiler error:
In file included from src/geometry.cpp:11:
In file included from src/../include/geometry.hpp:9:
In file included from /usr/local/include/boost/geometry.hpp:17:
In file included from /usr/local/include/boost/geometry/geometry.hpp:26:
In file included from /usr/local/include/boost/geometry/core/coordinate_dimension.hpp:23:
/usr/local/include/boost/geometry/core/point_type.hpp:45:5: error: no matching function for call to 'assertion_failed'
    BOOST_MPL_ASSERT_MSG
    ^~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/mpl/assert.hpp:454:51: note: expanded from macro 'BOOST_MPL_ASSERT_MSG'
#   define BOOST_MPL_ASSERT_MSG( c, msg, types_ ) \
                                                  ^
/usr/local/include/boost/mpl/assert.hpp:440:9: note: expanded from macro '\
BOOST_MPL_ASSERT_MSG_IMPL'
        boost::mpl::assertion_failed<(c)>( BOOST_PP_CAT(mpl_assert_arg,counter)::assert_arg() ) \
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/mpl/assert.hpp:60:58: note: expanded from macro '\
BOOST_MPL_AUX_ASSERT_CONSTANT'
#   define BOOST_MPL_AUX_ASSERT_CONSTANT(T, expr) enum { expr }
                                                         ^~~~
/usr/local/include/boost/geometry/core/point_type.hpp:65:30: note: in instantiation of template class
      'boost::geometry::traits::point_type<std::__1::vector<float, std::__1::allocator<float> > >' requested here
            typename traits::point_type<Geometry>::type
                             ^
/usr/local/include/boost/geometry/core/coordinate_type.hpp:58:22: note: in instantiation of template class 'boost::geometry::core_dispatch::point_type<void,
      std::__1::vector<float, std::__1::allocator<float> > >' requested here
    typedef typename point_type<GeometryTag, Geometry>::type point_type;
                     ^
/usr/local/include/boost/geometry/core/coordinate_type.hpp:88:37: note: in instantiation of template class 'boost::geometry::core_dispatch::coordinate_type<void,
      std::__1::vector<float, std::__1::allocator<float> > >' requested here
    typedef typename core_dispatch::coordinate_type
                                    ^
/usr/local/include/boost/geometry/core/access.hpp:269:17: note: in instantiation of template class 'boost::geometry::coordinate_type<std::__1::vector<float,
      std::__1::allocator<float> > >' requested here
inline typename coordinate_type<Geometry>::type get(Geometry const& geometry
                ^
/usr/local/include/boost/geometry/algorithms/detail/convert_point_to_point.hpp:42:74: note: while substituting deduced template arguments into function template
      'get' [with Dimension = 0, Geometry = std::__1::vector<float, std::__1::allocator<float> >]
        set<Dimension>(destination, boost::numeric_cast<coordinate_type>(get<Dimension>(source)));
                                                                         ^
/usr/local/include/boost/geometry/algorithms/detail/convert_point_to_point.hpp:58:76: note: (skipping 3 contexts in backtrace; use -ftemplate-backtrace-limit=0
      to see all)
    point_to_point<Source, Destination, 0, dimension<Destination>::value>::apply(source, destination);
                                                                           ^
/usr/local/include/boost/geometry/algorithms/append.hpp:129:45: note: in instantiation of member function
      'boost::geometry::detail::append::append_range<boost::geometry::model::ring<boost::geometry::model::d2::point_xy<double, boost::geometry::cs::cartesian>,
      true, true, vector, allocator>, std::__1::vector<std::__1::vector<float, std::__1::allocator<float> >, std::__1::allocator<std::__1::vector<float,
      std::__1::allocator<float> > > > >::apply' requested here
            append_range<ring_type, Range>::apply(
                                            ^
/usr/local/include/boost/geometry/algorithms/append.hpp:296:51: note: in instantiation of member function
      'boost::geometry::detail::append::range_to_polygon<boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double,
      boost::geometry::cs::cartesian>, true, true, std::vector, std::vector, std::allocator, std::allocator>, std::__1::vector<std::__1::vector<float,
      std::__1::allocator<float> >, std::__1::allocator<std::__1::vector<float, std::__1::allocator<float> > > > >::apply' requested here
        dispatch::append<Geometry, RangeOrPoint>::apply(geometry,
                                                  ^
/usr/local/include/boost/geometry/algorithms/append.hpp:371:22: note: in instantiation of function template specialization
      'boost::geometry::resolve_variant::append<boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double, boost::geometry::cs::cartesian>,
      true, true, std::vector, std::vector, std::allocator, std::allocator> >::apply<std::__1::vector<std::__1::vector<float, std::__1::allocator<float> >,
      std::__1::allocator<std::__1::vector<float, std::__1::allocator<float> > > > >' requested here
                   ::apply(geometry, range_or_point, ring_index, multi_index);
                     ^
/usr/local/include/boost/geometry/algorithms/assign.hpp:75:15: note: in instantiation of function template specialization
      'boost::geometry::append<boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double, boost::geometry::cs::cartesian>, true, true,
      std::vector, std::vector, std::allocator, std::allocator>, std::__1::vector<std::__1::vector<float, std::__1::allocator<float> >,
      std::__1::allocator<std::__1::vector<float, std::__1::allocator<float> > > > >' requested here
    geometry::append(geometry, range, -1, 0);
              ^
src/geometry.cpp:213:5: note: in instantiation of function template specialization
      'boost::geometry::assign_points<boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double, boost::geometry::cs::cartesian>, true, true,
      std::vector, std::vector, std::allocator, std::allocator>, std::__1::vector<std::__1::vector<float, std::__1::allocator<float> >,
      std::__1::allocator<std::__1::vector<float, std::__1::allocator<float> > > > >' requested here
    assign_points(poly, shape.border);
    ^
/usr/local/include/boost/mpl/assert.hpp:83:5: note: candidate function not viable: no known conversion from 'boost::mpl::failed
      ************(boost::geometry::traits::point_type<std::__1::vector<float, std::__1::allocator<float> >
      >::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE::************)(types<std::__1::vector<float, std::__1::allocator<float> > >)' to 'typename assert<false>::type'
      (aka 'mpl_::assert<false>') for 1st argument
int assertion_failed( typename assert<C>::type );
    ^
In file included from src/geometry.cpp:11:
In file included from src/../include/geometry.hpp:9:
In file included from /usr/local/include/boost/geometry.hpp:17:
In file included from /usr/local/include/boost/geometry/geometry.hpp:28:
/usr/local/include/boost/geometry/core/coordinate_type.hpp:43:5: error: no matching function for call to 'assertion_failed'
    BOOST_MPL_ASSERT_MSG
    ^~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/mpl/assert.hpp:454:51: note: expanded from macro 'BOOST_MPL_ASSERT_MSG'
#   define BOOST_MPL_ASSERT_MSG( c, msg, types_ ) \

I have seen this post in which they did not register tuples - however, I am not using tuples or any special kind of point - I am just attempting to use the built in geometry types. Why is this error still occurring?

A: As you can see, the code posted is not a problem per se: Live On Coliru.
So,there must be something else interfering. I have three hunches:

*

*It's somewhere else in your code that you didn't post. The cause of the error is in ../src/geometry.cpp (not Boost library):
assign_points(poly, shape.border);

That gives you good ideas on how to reduce to a MCVE.

*You have preprocessor issues. Try pre-processing your sources and see whether any of the code appearing in the error messages looks suspect.
A classical example of this would be if some other included header defines tokens like #define min(a,b) ... or other commonly used words.

Side note: this is about code-hygiene. A related note is the appearance of using namespace in your shown code snippet. This just begs namespace collisions or unintended effects.

*Slightly related: the source of the interference could have to do with pre-compiled headers. Try disabling those or making sure you know what is in the PCH header (especially on MSVC (commonly using stdafx.h) precompiled headers have some potentially surprising effects)
UPDATE
I think I spotted it: the offending code at src/geometry.cpp:213:5 calls:
assign_points(poly, shape.border);

With the types: poly is
boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double, boost::geometry::cs::cartesian>, true, true, std::vector, std::vector, std::allocator, std::allocator>,

That's the polygon typedef you show above. But shape.border is:
std::__1::vector<std::__1::vector<float, std::__1::allocator<float>>, std::__1::allocator<std::__1::vector<float, std::__1::allocator<float>>>>>

That's just vector<std::vector<float> >. That's not a supported Geometry.


text:
Q: input field as drop down I am trying to make an input field a drop-down list as well. I have seen a few examples of what to do but yet when I mimic them I still have 2 separate fields for the data to go. I also have a problem with the datalist not displaying properly. Any ideas or routes to try would be greatly appreciated.
<div class="input-group">
     <label class="input-group-addon tc-group-addon" data-translate="" title="{{$tcore.tcoreTranslations.TRANSLATIONS.elementList.ThinClient_TIS.translation_184}}">
         TRANSLATIONS.elementList.ThinClient_TIS.translation_184
     </label>
     <input list="valueLists" ng-model="vm.selectedValue" class="form-control tc-tis-form-control" ng-change="vm.changeValue()" ng-disabled="vm.readOnly">

     <datalist id="valueLists" ng-model="vm.selectedValue" class="form-control tc-tis-form-control" ng-change="vm.changeValue()" >
          <option ng-repeat="item in vm.valueList" value="{{item}}">{{item}}</option>
     </datalist>

What I am trying to mimic is this functionality where you can type inside the box or you can choose a predetermined value I want to mimic this

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you stop a GUI window from re-opening? For some reason the GUI window function restarts when it reaches the end of the code?
Here is the main code:
import dash
from dash import dcc
from dash import html
import plotly.express as px
import pandas as pd
import File_Select_GUI as fsg

#running GUI window
fsg.FSG_Window()

#selecting dataframe
datafile = fsg.selection
df = pd.read_csv(datafile)

Then some code to make graphs:
defend_fig = px.bar(defend_df,
             x='Player',
             y='Touches',
             color='Player')...

Then finally setting up the Dashboard:
app = dash.Dash()

app.layout = html.Div(children=[
    html.Div([
        html.H1('Defenders'),
        dcc.Graph(id="Defenders", figure=defend_fig...

#server link output
if __name__ == "__main__":
    app.run_server(debug=True)


text:
Q: Good way to use hook : useSelector() I used to use stackoverflow a lot to check things, but that's my first time asking a question :)
I'm starting help a friend with an app he's creating.
I've never used react-native before and I'm trying to make some clean-up in his code.
we're using a reducer :
in a file credentials.js, we got :
export const INITIAL_CREDENTIALS = {
  configReload: false,
  dataReload: false,
  dataReloadAuto: false,
  imgSetup: false,
  imgSetupAdd: false,
  imgSetupRemove: false,
  // ... et bien d'autres ...
}

const creditentialsReducer = (state = INITIAL_CREDENTIALS, action) => {
  switch (action.type) {
    case 'SET_CREDENTIALS': {
      return {
        ...state,
        ...action.value,
      };
    }
    default:
      return state;
  }
};

export default creditentialsReducer;

which is updated on a store by a dedicated event:
store.dispatch({ type: 'SET_CREDENTIALS', value: appProfil });

until here, we're good :)
I'd then like to use those data to display or hide few items on screen.
What is currently done :
on file screens/preferences.js
return (
    <ScrollView style={{ backgroundColor: 'transparent' }}>
      <View style={[styles.card, { backgroundColor: theme.colors.bgColor, borderRadius: theme.roundness }]}>
        {prefDataCred &&
          <List.Item
            title={t("Data management")}
            left={() => <List.Icon icon="database-settings" color={theme.colors.primary} />}
            right={() => <List.Icon icon="chevron-right" color={theme.colors.text} />}
            onPress={() => { props.navigation.navigate('PrefDataManager'); }}
          />
        }
      </View>
    </ScrollView>
);

prefDataCred is today defined as follow  :
  const credConfigReload = useSelector(state => state.creditentialsReducer.configReload);
  const credDataReload = useSelector(state => state.creditentialsReducer.dataReload);
  const credDataReloadAuto = useSelector(state => state.creditentialsReducer.dataReloadAuto);
  const credImgSetup = useSelector(state => state.creditentialsReducer.imgSetup);
  const credClearCache = useSelector(state => state.creditentialsReducer.clearCache);
  const credSystemSetup = useSelector(state => state.creditentialsReducer.systemSetup);

  const prefDataCred = (
    credConfigReload ||
    credDataReload ||
    credDataReloadAuto ||
    credImgSetup ||
    credClearCache ||
    credSystemSetup
  );

15 lines of code to define only 1 item : that's too much for me, not talking about the fact that it's not even very readable
And I have another 15 items to defined the way based on several items coming from creditentialsReducer, so it make lines and lines of declaration "for nothing". I'd like to find a way to factorize all of it
I had in mind to use that way of doing it : (the final aim is to know if there is at least one item set to 'true', and also be abble to get notify on update that could occur at any time)
const prefDataCred = (
    getCredentials('configReload', 'dataReload', 'dataReloadAuto', 'imgSetup', 'clearCache', 'systemSetup')
  );

with the generic function avec la fonction getCredentials defined in an Helper file as follow  :
export const getCredentials = (...creds) => {
    var crendential = false;
    creds.forEach(function (item) {
        crendential = crendential || useSelector(state => state.creditentialsReducer[item]);
    });

    return crendential;
}

and here starts the issue ...!
My friend just tells me "don't do that. you try to call a hook (useSelector) in a conditionnal way, that's forbidden !"
any thoughts on this ?
Am I doing it wrong ? any idea on how to do it the good way ?
Thanks for you help !


text:
Q: Is there a way to check if a workflow is completed using Javascript? I created a form that start a workflow automatically when an item is created, and I redirect to html page that shows a message like "Processing... please wait.", and I wait 3 seconds and so redirect to a page with results of the workflow.
Instead of wait 3 seconds, I want to create a javascript that check if the workflow is completed, then redirect to results page.
I am using SharePoint 2010 Foundation
Is there way?

A: I haven't tried this method, but I think it should work. If you use the Lists web service to query for the particular item, you should be able to retrieve the workflow status column and see it's value. It should give you In Progress/Complete. In your code, you'd just need to check that status and wait/recheck in a few seconds or redirect to your page based on the results.
Edit:
I tried using SPServices and it does work:
$().SPServices({
    operation: "GetListItems",
    async: false,
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='WFColumn' /></ViewFields>",
    listName: "MyList",
    completefunc: function (xData, Status) {
        $(xData.responseXML).SPFilterNode("z:row").each(function() {
            if ($(this).attr("ows_WFCol" === 5)){
                console.log("It's complete");
          }
        });
    }
});

A: You can use the Dom/debug in the browser(press F12) then find the 'name =" "' atribute  of the column. Then use that name with Spservcies. For my example I trigger my wf by updating a column then returning a workflow status colmn value:
 function CopyStrategyDocuments(StrategyDocID, StrategyDocLocation){

                                $().SPServices({
                                        operation: 'UpdateListItems',
                                        listName: 'Case Attachments',
                                        ID: StrategyDocID,
                                        valuepairs: [['Copy_x002d_Document','Yes'],['Copy_x002d_To',StrategyDocLocation]],
                                                                        completefunc: function(xData, Status) {

                                              var test = $(xData.responseXML).SPFilterNode("z:row").attr("ows_CopyDocu");
                                               alert(test)
                                        //

                                        }
                                });

      };


text:
Q: Custom fonts not loading in iframe
*

*I have an iframe, and none of the custom fonts that I'm applying via the stylesheet are loading (the font is correctly applied in the stylesheet, it just doesn't work).

*I'm trying to add the styles in the actual iframe, not from the parent page

*The font is being correctly defined in the stylesheet (and I'm applying the various different font types e.g. .eot .otf .woff and .svg).

*I've also correctly configured the mime types for the font in my web.config, and the fonts are on the server in the correct location (I'm hosting the actual fonts).

*There are no errors in the 'console' of the browser

*In the 'net' tab in Firefox, there are no failed loads for any files

*The fonts don't load on any browser

Any ideas what's going on or anything else I should check?
Here's the font declaration in the stylesheet:
@font-face {
    font-family: 'TradeGothicLTBdCondTwenty';
    src: url('../fonts/lte50543.eot');
    src: url('../fonts/lte50543.eot') format('embedded-opentype'),
         url('../fonts/lte50543.woff') format('woff'),
         url('../fonts/lte50543.ttf') format('truetype'),
         url('../fonts/lte50543.svg#TradeGothicLTBdCondTwenty') format('svg');
}

and here's the staticContent section of the web.config that allows the file types:
<staticContent>
    <!-- HTML5 Web font MIMEtypes -->
    <remove fileExtension=".eot" />
    <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
    <remove fileExtension=".otf" />
    <mimeMap fileExtension=".otf" mimeType="font/otf" />
    <remove fileExtension=".woff" />
    <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    <!-- Proper SVG Serving -->
    <remove fileExtension=".svg" />
    <mimeMap fileExtension=".svg" mimeType="image/svg+xml"/>
    <remove fileExtension=".svgz" />
    <mimeMap fileExtension=".svgz" mimeType="image/svg+xml"/>
</staticContent>

A: Fixed this.  We're using the TFS (Team Foundation Server) build system to deploy the site, and the TFS build action for the fonts wasn't set to 'copy if newer', so when the site was redeployed, the fonts had actually been removed from the server (I'd previously had to deploy them manually for testing purposes on the server).


text:
Q: Downloading .csv from Express backend to Angularjs I have seen this same question
here, however the solution is not working in my case and inputting the code snipped that was used
$('<form action="'+ url +'" method="'+ ('post') +'">'+inputs+'</form>')
           .appendTo('body').submit().remove();

returns an error that Reference $ is not defined
I have a download request that looks like this:
controller.js

$http.put('/download' {file:$scope.inputInfo.name.$modelValue+'.csv'}).success(function(data,status,headers){
        console.log(status);
        console.log(data);

    })

app.js
app.put('/download', function(req,res){
    console.log(req.body.file)
    res.download(__dirname +'/'+ 'req.body.file, function(err){
      if(err){console.log(err)}
   })

})
My controller.js is returning the raw file output as data and not initiating the download from the page.  Is there something I am missing to initiate this file download in angular?
Any help would be greatly appreciated.

A: Seth you totally set me in the right direction with the lack of jQuery on my page.
Here is my finished code that I added to controllers.js in place of the $http.put():
$('<form action="'+ "/download" +'" method="'+ ('post') +'">'+'<input type="hidden" name="file" value="'+$scope.inputInfo.name.$modelValue+'"'+'/></form>')
           .appendTo('body').submit().remove();

Thanks again for your help with this.


text:
Q: How to add product description in quick view section in bigcommerce? I would like to add product description in a quick view section of my big commerce store. So please any one how can i achieve this?
I have already tried to add this panel %%Panel.ProductDescription%% in to my Quickview.html file.but no luck.
Please any one..

A: There is a BC variable that can be used to display the Product Description excerpt in quick view: %%GLOBAL_QuickViewProductDescription%% add it to QuickViewContent.html

A: I have done some Ajax script call
you need to add below script inside "Panels/QuickViewContent.html" Panel.
it will fetch the description from it's product Page.
function processData(item){

    return function(data){

      var desc = jQuery(data).find("#ProductDescription .ProductDescriptionContainer").text();
    desc = desc.substr(0,450);
    jQuery("#QuickViewContent").find('.PriceRow').after("
"+desc+"...more
");

  }
}

jQuery(document).ready(function(){

        var path = '%%GLOBAL_QuickViewProductURL%%';

        if(path!="") {
        path = path.replace("http://","//").replace("https://","//");

        var item = path;
        $.ajax({
          url: path,
          type: "GET",
           async: true,
             success: processData(item)
        });
        }

});


text:
Q: What does the "comma" syntax mean when calling a function in stripe? I am attempting to create a new customer in Stripe. I am successful but confused about how their documentation styles the function call.
I cannot seem to find any information on their official docs.
https://stripe.com/docs/api/customers/create?lang=node
For example:
stripe.customers.create({
  description: 'Customer for jenny.rosen@example.com',
  source: "tok_visa" // obtained with Stripe.js
}, function(err, customer) {
  // asynchronously called
});

I am assuming it is similar to ".then((err, customer) =>{}', but cannot seem to use the function call with this syntax.
Any explanation would be helpful!

A: What you know are Promises, and they are the preferred way to do async today. Stripe's API is using the callback (also called errback) style, which predates Promises.
It is similar to
.then(customer => ...).catch(err => ...)

However, Stripe's Node library returns promises as well, so you can convert your example to:
stripe.customers.create({
  description: 'Customer for jenny.rosen@example.com',
  source: "tok_visa" // obtained with Stripe.js
})
.then(customer => ...)
.catch(err => ...);

A: The comma means the same as it does in any other function call. It separates arguments.
The second argument just happens to be a function.
var first_argument = {
  description: 'Customer for jenny.rosen@example.com',
  source: "tok_visa" // obtained with Stripe.js
};

var second_argument = function(err, customer) {
  // asynchronously called
};

stripe.customers.create(first_argument, second_argument);


text:
Q: Knockout: foreach not working with asp.net mvc I know this might be easy but somehow I'm unable to implement foreach for a knockout binding. The code is as below:
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts
{

}

First name	Last name

And the rendered HTML is as follows:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

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

                </button>
                Application name

Home

About

Contact

First name	Last name

© 2014 - My ASP.NET Application

The problem is that the foreach doesn't work as implemented in the code. The error I get is (debugged using Knockout context):

ExtensionError: TypeError message: "Object.getOwnPropertyNames called
on non-object" stack: (...) get stack: function () { [native code] }
set stack: function () { [native code] }
proto: Error info: "Please select a dom node with ko data."
Uncaught TypeError: undefined is not a function

I have trying this for a while now but with no success.
Thanks.

A: So I solved it!
The problem was that knockout 2.0 has a line of code:
var elems = jQuery['clean']([html]);
But the jQuery 1.10 that I was using deprecated the clean method.
So I upgraded my knockout to 3.0 and it worked!
Thanks to @Boaz for answering this question on stackoverflow


text:
Q: What does a Weapons Technologist do? So I was travelling around, and I came across a person with the same symbol as an Engineer but he was titled as a Weapons Technologist. I noticed that I could hire him.
What is a Weapons Technologist? What does he do?

A:
A Weapons Technologist is employed on a station to monitor and improve the efficiency of technical production processes using various technical components. Products improved by their services include: Missiles, EM-Spectrometer, Scanning Array and Warheads.

http://forum.egosoft.com/viewtopic.php?t=347620


text:
Q: Adding JavaScript tags dynamically - type tag receives random string of characters I'm dynamically adding some JavaScript tags to a page (header and footer) and each tag ends up getting injected with a random string of characters in the type field. This happens on every JavaScript tag that gets dynamically added.
For example, this tag:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX" type="text/javascript"></script>

Becomes this when it's dynamically added to the page:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX" type="588dfae21373a29f8ed97bdf-text/javascript"></script>

This random string of characters gets added prior to text/javascript - 588dfae21373a29f8ed97bdf - can this be avoided or prevented?


text:
Q: Работа со стилем в приложение Есть 2 окна: 1-ое окно оно главное, 2-ое это выводится пользовательские настройки. Так вот как сделать чтобы стиль не применялся во втором окне, а только был на первом? Буду очень благодарен!
код: main.py
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from options import Themes
import sys
import os

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self);

        # создание файла для сохранения натроек
        self.CONFIG_FILE_NAME = 'settings\\config.ini'

        self.centralWidget = QtWidgets.QWidget() # создаём центральный виджет
        self.setCentralWidget(self.centralWidget)
        self.mainLayout = QtWidgets.QVBoxLayout(self.centralWidget)

        # settings
        self.setFixedSize(620, 640)
        self.setWindowTitle(" B U G ")

        # делаем сборку
        self.widget_main = self.createPage()
        self.mainLayout.addWidget(self.widget_main)
        self.createMenuBar()

        # условия для тем (чтобы задать стиль обьектов)
        if self.view_theme_1.isChecked() == True:
            Themes.set_theme_number_1(self)

        elif self.view_theme_2.isChecked() == True:
            Themes.set_theme_number_2(self)

        # вывод информации на строку состояния
        self.label_1 = QtWidgets.QLabel("v 1.0")
        self.label_1.setStyleSheet("font-size: 18px; color: black;")

        self.status_1.addPermanentWidget(self.label_1)

        self.status_1.showMessage("Добро пожаловать", msecs = 4000)

        self.setStatusBar(self.status_1)

    def createPage(self):
        """создание страницы в основном окне """

        self.widget_page = QtWidgets.QWidget()

        # создание обьектов
        self.button_1 = QtWidgets.QPushButton("Перейти к поиску телефонных\
                                            \nномеров и электронных почт")

        self.formbox = QtWidgets.QGridLayout()

        # добавление в box и в окно
        self.formbox.addWidget(self.button_1)
        self.formbox.setSpacing(20)
        self.widget_page.setLayout(self.formbox)

        # сделать главным комонентом
        return self.widget_page

    def createMenuBar(self):

        # создание панели-меню и строки состоянии
        self.menu = QtWidgets.QMenuBar()
        self.status_1 = QtWidgets.QStatusBar()

        # создание категорий меню и функционал в ней
        self.menu_options = QtWidgets.QMenu("Опции")
        self.menu_view = QtWidgets.QMenu('Вид')
        self.menu_help = QtWidgets.QMenu("Справка")

        # просто настройки
        self.sub_menu_options = QtWidgets.QMenu("Настройки")

        self.user_settings = QtWidgets.QAction("Пользовательские настройки")

        self.sub_menu_options.addAction(self.user_settings)

        self.menu_options.addMenu(self.sub_menu_options)

        # настройка тем
        self.sub_menu_view_themes = QtWidgets.QMenu("Цветовая схема")

        self.view_theme_1 = QtWidgets.QAction("Тёмно-синяя тема")
        self.view_theme_1.setCheckable(True)
        self.view_theme_2 = QtWidgets.QAction("Светло-серая тема")
        self.view_theme_2.setCheckable(True)
        self.view_theme_2.setChecked(True)

        self.group_action_5 = QtWidgets.QActionGroup(self.sub_menu_view_themes)

        self.group_action_5.addAction(self.view_theme_1)
        self.group_action_5.addAction(self.view_theme_2)

        self.sub_menu_view_themes.addAction(self.view_theme_1)
        self.sub_menu_view_themes.addAction(self.view_theme_2)

        self.menu_view.addMenu(self.sub_menu_view_themes)

        # добавляем отдельное меню в главное меню
        self.menu.addMenu(self.menu_options)
        self.menu.addMenu(self.menu_view)
        self.menu.addMenu(self.menu_help)

        # датчики
        self.user_settings.triggered.connect(self.clickedActionUser)
        self.view_theme_1.triggered.connect(self.clickedActionViewTheme)
        self.view_theme_2.triggered.connect(self.clickedActionViewTheme)

        # добавляем в окно
        self.setMenuBar(self.menu)

    # методы для датчиков
    def clickedActionViewTheme(self):
        if self.view_theme_1.isChecked() == True:
            Themes.set_theme_number_1(self)

        elif self.view_theme_2.isChecked() == True:
            Themes.set_theme_number_2(self)

    def clickedActionUser(self):
        My_WindowSettings = WindowSettings(self)
        My_WindowSettings.show()

class WindowSettings(QtWidgets.QWidget):
    """Класс реализующий пользовательские настройки
       в виде выводящего окна """

    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self, parent)
        self.parent = parent

        # settings
        self.setFixedSize(500, 550)
        self.setWindowTitle("Пользовательские настройки")
        self.setWindowFlags(QtCore.Qt.Dialog)
        self.setWindowModality(QtCore.Qt.WindowModal)

        # делаем сборку
        self.createPage()

    def createPage(self):

        self.gridBox = QtWidgets.QGridLayout()

        self.tabWidget = QtWidgets.QTabWidget()
        self.button_save = QtWidgets.QPushButton("Применить")

        self.gridBox.addWidget(self.tabWidget, 0, 0)
        self.gridBox.addWidget(self.button_save, 1, 0, alignment = QtCore.Qt.AlignRight)
        self.setLayout(self.gridBox)

        # сборка tab-виджетов
        self.createTabWidget_Search()

    def createTabWidget_Search(self):
        self.tabWidget_1 = QtWidgets.QWidget()
        self.tabWidget.addTab(self.tabWidget_1, "настройки поиска")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MainWindow()
    MainWindow.show()
    sys.exit(app.exec_())

стили: options.py
from PyQt5 import QtWidgets
from PyQt5 import QtGui

class Themes():

    def set_theme_number_1(self):

        self.setStyleSheet("QPushButton {background: #29293d; color: white; font-size: 18px;}\
                            QPushButton:hover {background: #3d3d5c;}\
                            QPushButton:pressed {background: #1f1f2e}\
                            \
                            QMenuBar {background: #a9a9c2;}\
                            \
                            QLabel {color: white; font-size: 20px;}\
                            QTextEdit {background: #b3b3cc; font-size: 20px; border: 0px solid black;}\
                            QLineEdit {background: #b3b3cc; font-size: 23px; border: 0px solid black;}\
                            QStatusBar {background: #a9a9c2; font-size: 17px; font-style: oblique;}\
                            QComboBox {background: #a9a9c2; font-size: 16px;}\
                            QToolBar {background: #a9a9c2;}\
                            \
                            QToolButton {font-style: italic;}\
                            QToolButton:hover {background: #7575a3;}\
                            QToolButton:pressed {background: #5c5c8a;}\
                            \
                            QTabWidget {background: #29293d;}\
                            "
                            )

        self.palet = QtGui.QPalette()
        self.palet.setColor(QtGui.QPalette.Window, QtGui.QColor("#34344c"))
        self.setPalette(self.palet)

    def set_theme_number_2(self):

        self.setStyleSheet("QPushButton {background: #666666; color: white; font-size: 18px;}\
                            QPushButton:hover {background: #a6a6a6;}\
                            QPushButton:pressed {background: #333333;}\
                            \
                            QLabel {color: white; font-size: 20px;}\
                            QTextEdit {background: #d9d9d9; font-size: 20px; border: 0px solid black;}\
                            QLineEdit {background: #d9d9d9; font-size: 23px; border: 0px solid black;}\
                            QStatusBar {background: #bfbfbf; font-size: 17px; font-style: oblique;}\
                            QComboBox {background: #bfbfbf; font-size: 16px;}\
                            QToolBar {background: #bfbfbf;}\
                            \
                            QToolButton {font-style: italic;}\
                            QToolButton:hover {background: #a6a6a6;}\
                            QToolButton:pressed {background: #737373;}\
                            "
                            )

        self.palet = QtGui.QPalette()
        self.palet.setColor(QtGui.QPalette.Window, QtGui.QColor("#8c8c8c"))
        self.setPalette(self.palet)

A: не надо передавать родителя:
    def clickedActionUser(self):
#        My_WindowSettings = WindowSettings(self)                           # - self
#        My_WindowSettings.show()
        self.My_WindowSettings = WindowSettings()                           # +++  <<<======<
        self.My_WindowSettings.show()

import sys
import os
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

#from options import Themes
class Themes():

    def set_theme_number_1(self, parent):                                          # + parent
#       vvvvvv
        parent.setStyleSheet("QPushButton {background: #29293d; color: white; font-size: 18px;}\
                            QPushButton:hover {background: #3d3d5c;}\
                            QPushButton:pressed {background: #1f1f2e}\
                            \
                            QMenuBar {background: #a9a9c2;}\
                            \
                            QLabel {color: white; font-size: 20px;}\
                            QTextEdit {background: #b3b3cc; font-size: 20px; border: 0px solid black;}\
                            QLineEdit {background: #b3b3cc; font-size: 23px; border: 0px solid black;}\
                            QStatusBar {background: #a9a9c2; font-size: 17px; font-style: oblique;}\
                            QComboBox {background: #a9a9c2; font-size: 16px;}\
                            QToolBar {background: #a9a9c2;}\
                            \
                            QToolButton {font-style: italic;}\
                            QToolButton:hover {background: #7575a3;}\
                            QToolButton:pressed {background: #5c5c8a;}\
                            \
                            QTabWidget {background: #29293d;}\
                            "
                            )

        parent.palet = QtGui.QPalette()
        parent.palet.setColor(QtGui.QPalette.Window, QtGui.QColor("#34344c"))
        parent.setPalette(parent.palet)

    def set_theme_number_2(self, parent):                                          # + parent
#       vvvvvv
        parent.setStyleSheet("QPushButton {background: #666666; color: white; font-size: 18px;}\
                            QPushButton:hover {background: #a6a6a6;}\
                            QPushButton:pressed {background: #333333;}\
                            \
                            QLabel {color: white; font-size: 20px;}\
                            QTextEdit {background: #d9d9d9; font-size: 20px; border: 0px solid black;}\
                            QLineEdit {background: #d9d9d9; font-size: 23px; border: 0px solid black;}\
                            QStatusBar {background: #bfbfbf; font-size: 17px; font-style: oblique;}\
                            QComboBox {background: #bfbfbf; font-size: 16px;}\
                            QToolBar {background: #bfbfbf;}\
                            \
                            QToolButton {font-style: italic;}\
                            QToolButton:hover {background: #a6a6a6;}\
                            QToolButton:pressed {background: #737373;}\
                            "
                            )

        parent.palet = QtGui.QPalette()
        parent.palet.setColor(QtGui.QPalette.Window, QtGui.QColor("#8c8c8c"))
        parent.setPalette(parent.palet)

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self);

        # создание файла для сохранения натроек
        self.CONFIG_FILE_NAME = 'settings\\config.ini'

        self.centralWidget = QtWidgets.QWidget() # создаём центральный виджет
        self.setCentralWidget(self.centralWidget)
        self.mainLayout = QtWidgets.QVBoxLayout(self.centralWidget)

        # settings
        self.setFixedSize(620, 640)
        self.setWindowTitle(" B U G ")

        # делаем сборку
        self.widget_main = self.createPage()
        self.mainLayout.addWidget(self.widget_main)

        self.view_theme_1 = None  # +
        self.view_theme_2 = None  # +

        self.createMenuBar()

        self.themes = Themes()                                                   # +++

        # условия для тем (чтобы задать стиль обьектов)
        if self.view_theme_1.isChecked() == True:
            self.themes.set_theme_number_1(self)                                 # + self.themes

        elif self.view_theme_2.isChecked() == True:
            self.themes.set_theme_number_2(self)                                 # + self.themes

        # вывод информации на строку состояния
        self.label_1 = QtWidgets.QLabel("v 1.0")
        self.label_1.setStyleSheet("font-size: 18px; color: black;")

        self.status_1.addPermanentWidget(self.label_1)

        self.status_1.showMessage("Добро пожаловать", msecs = 4000)

        self.setStatusBar(self.status_1)

    def createPage(self):
        """создание страницы в основном окне """

        self.widget_page = QtWidgets.QWidget()

        # создание обьектов
        self.button_1 = QtWidgets.QPushButton("Перейти к поиску телефонных\
                                            \nномеров и электронных почт")

        self.formbox = QtWidgets.QGridLayout()

        # добавление в box и в окно
        self.formbox.addWidget(self.button_1)
        self.formbox.setSpacing(20)
        self.widget_page.setLayout(self.formbox)

        # сделать главным комонентом
        return self.widget_page

    def createMenuBar(self):

        # создание панели-меню и строки состоянии
        self.menu = QtWidgets.QMenuBar()
        self.status_1 = QtWidgets.QStatusBar()

        # создание категорий меню и функционал в ней
        self.menu_options = QtWidgets.QMenu("Опции")
        self.menu_view = QtWidgets.QMenu('Вид')
        self.menu_help = QtWidgets.QMenu("Справка")

        # просто настройки
        self.sub_menu_options = QtWidgets.QMenu("Настройки")

        self.user_settings = QtWidgets.QAction("Пользовательские настройки")

        self.sub_menu_options.addAction(self.user_settings)

        self.menu_options.addMenu(self.sub_menu_options)

        # настройка тем
        self.sub_menu_view_themes = QtWidgets.QMenu("Цветовая схема")

        self.view_theme_1 = QtWidgets.QAction("Тёмно-синяя тема")
        self.view_theme_1.setCheckable(True)
        self.view_theme_2 = QtWidgets.QAction("Светло-серая тема")
        self.view_theme_2.setCheckable(True)
        self.view_theme_2.setChecked(True)

        self.group_action_5 = QtWidgets.QActionGroup(self.sub_menu_view_themes)

        self.group_action_5.addAction(self.view_theme_1)
        self.group_action_5.addAction(self.view_theme_2)

        self.sub_menu_view_themes.addAction(self.view_theme_1)
        self.sub_menu_view_themes.addAction(self.view_theme_2)

        self.menu_view.addMenu(self.sub_menu_view_themes)

        # добавляем отдельное меню в главное меню
        self.menu.addMenu(self.menu_options)
        self.menu.addMenu(self.menu_view)
        self.menu.addMenu(self.menu_help)

        # датчики
        self.user_settings.triggered.connect(self.clickedActionUser)
        self.view_theme_1.triggered.connect(self.clickedActionViewTheme)
        self.view_theme_2.triggered.connect(self.clickedActionViewTheme)

        # добавляем в окно
        self.setMenuBar(self.menu)

    # методы для датчиков
    def clickedActionViewTheme(self):
        if self.view_theme_1.isChecked() == True:
            self.themes.set_theme_number_1(self)                            # + self.themes

        elif self.view_theme_2.isChecked() == True:
            self.themes.set_theme_number_2(self)                            # + self.themes

    def clickedActionUser(self):
#        My_WindowSettings = WindowSettings(self)                           # - self
#        My_WindowSettings.show()
        self.My_WindowSettings = WindowSettings()                           # +++  <<<======<
        self.My_WindowSettings.show()

class WindowSettings(QtWidgets.QWidget):
    """Класс реализующий пользовательские настройки
       в виде выводящего окна """

    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self, parent)
        self.parent = parent

        # settings
        self.setFixedSize(500, 550)
        self.setWindowTitle("Пользовательские настройки")
        self.setWindowFlags(QtCore.Qt.Dialog)
        self.setWindowModality(QtCore.Qt.WindowModal)

        # делаем сборку
        self.createPage()

    def createPage(self):
        self.gridBox = QtWidgets.QGridLayout()

        self.tabWidget = QtWidgets.QTabWidget()
        self.button_save = QtWidgets.QPushButton("Применить")

        self.gridBox.addWidget(self.tabWidget, 0, 0)
        self.gridBox.addWidget(self.button_save, 1, 0, alignment = QtCore.Qt.AlignRight)
        self.setLayout(self.gridBox)

        # сборка tab-виджетов
        self.createTabWidget_Search()

    def createTabWidget_Search(self):
        self.tabWidget_1 = QtWidgets.QWidget()
        self.tabWidget.addTab(self.tabWidget_1, "настройки поиска")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MainWindow()
    MainWindow.show()
    sys.exit(app.exec_())


text:
Q: How can I resolve this issue with Flutter? Can anyone help me solve this issue?

I'm a beginner with Flutter.
Here is the code that I've written:
   File?croppedImage=await ImageCropper().cropImage(
        sourcePath:filePath,maxHeight:1080,maxWidth:1080
    );

And I'm facing this error:
croppedFile can't be assigned to a variable of type file?

How can I fix it?

A: The type of cropImage is CroppedFile
CroppedFile? croppedFile = await ImageCropper().cropImage(sourcePath:filePath,maxHeight:1080,maxWidth:1080 );


text:
Q: Why should we avoid using class variables @@ in rails? Why should we avoid using class variables @@ in rails? Is there any security loopholes with that. Please answer as I am new with rails. and I am much using instance variable @variable_name . I tried once @@variable_name .
I know only about class variable is, Class variable is sharable between object
But I really would like to know  Why should we avoid using class variables @@ in rails?

A: Simply because they are not thread safe. Many rails=capable servers are multi-threaded. That means there may be multiple running instances of your application at any given time and any request by one of your users is going to be arbitrarily assigned to one of them. Class variables are not shared between processes so there is a possibility that your class variable will be different in a subsequent request.
Even if you deliberately manage to run your app in a single threaded server, there is no guarantee that your app won't be restarted between requests, losing your class variable.
If you want functionality similar to what class variables provide, I strongly recommend that you look into key-value stores such as Memcached or Redis.


text:
Q: Matplotlib to set the frequency on xaxis I would like to set the frequency of the x axis of my chart with the following code:
fig, ax = plt.subplots()
fig = plt.figure(figsize=(4,3))
plt.plot(vol['BTC'], 'b-', vol['ETH'], 'r-', vol['XRP'], 'g-', vol['BCH'], 'y-')
plt.legend(labels= ['BTC','ETH','XRP','BCH'], fontsize="xx-small")
plt.xticks(rotation=30, horizontalalignment='right')
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 20))
plt.rcParams.update({'font.size': 3})

However, nothing changes and it remains like a bulk of ink as the labels overlaps.
I would like to lower the frequency of display and reduce the size of the labels.
Any help would be appreciated.
EDIT:
I tried the following but the chart is empty.
My new code:

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
days = mdates.DayLocator()  # every day
years_fmt = mdates.DateFormatter('%Y-%m-%d')
vol_index = vol.index

fig, ax = plt.subplots()
ax.plot(np.array(vol.index), np.array(vol['BTC']))

# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(days)

# round to nearest years.
datemin = pd.to_datetime(np.datetime64(vol.index[0], 'D')).strftime('%Y-%m-%d')
datemax = pd.to_datetime(np.datetime64(vol.index[-1], 'D') + np.timedelta64(1, 'D')).strftime('%Y-%m-%d')
ax.set_xlim(datemin, datemax)

# format the coords message box
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = lambda x: '$%1.2f' % x  # format the price.
ax.grid(True)

fig.autofmt_xdate()

This code use the following input:
np.array(vol['BTC']):
[0.05498711 0.03454131 0.03454131 0.02293731 0.02191053 0.02191053
 0.01688648 0.02828462 0.02828462 0.02828462 0.03188105 0.03054535
 0.02955679 0.0270898  0.0281818  0.02866918 0.02710031 0.02668099
 0.03404319 0.03670357 0.05311734 0.08663729 0.08663729 0.08339912
 0.08831546 0.08063601 0.07522458 0.06043395 0.06280006 0.06543079
 0.06543079 0.0444152  0.0444152  0.03575803 0.03575803 0.03575803
 0.02870328 0.02870328 0.02870328 0.02870328 0.02835626 0.02263508
 0.02263508 0.02514882 0.0332816  0.02463769 0.0385677  0.0427951
 0.04329788 0.04329788 0.04329788 0.05240083 0.05883257 0.05883257
 0.03162634 0.02906886 0.02765406 0.024522   0.02352016 0.01756594
 0.02030382 0.02030382 0.03326152 0.03601441 0.03601441 0.03250479
 0.04571088 0.06313575 0.07639834 0.07639834 0.0555884  0.05133794
 0.0493664  0.03279575 0.05379169 0.05431873 0.05431873 0.04422756
 0.04649411 0.04825915 0.04584981 0.02741382 0.02741382]

vol.index:
Index(['2019-11-01 23:59:08', '2019-11-02 23:59:08', '2019-11-03 23:59:04',
       '2019-11-04 23:59:12', '2019-11-05 23:59:03', '2019-11-06 23:59:08',
       '2019-11-07 23:59:04', '2019-11-08 23:59:07', '2019-11-09 23:59:06',
       '2019-11-10 23:59:05', '2019-11-11 23:59:03', '2019-11-12 23:59:04',
       '2019-11-13 23:59:06', '2019-11-14 23:59:06', '2019-11-15 23:59:05',
       '2019-11-16 23:59:12', '2019-11-17 23:59:03', '2019-11-18 23:59:10',
       '2019-11-19 23:59:09', '2019-11-20 23:59:06', '2019-11-21 23:59:11',
       '2019-11-22 23:59:05', '2019-11-23 23:59:06', '2019-11-24 23:59:09',
       '2019-11-25 23:59:05', '2019-11-26 23:59:03', '2019-11-27 23:59:04',
       '2019-11-28 23:59:05', '2019-11-29 23:59:04', '2019-11-30 23:59:02',
       '2019-12-01 23:59:06', '2019-12-02 23:59:11', '2019-12-03 23:59:02',
       '2019-12-04 23:59:07', '2019-12-05 23:59:07', '2019-12-06 23:59:08',
       '2019-12-07 23:59:07', '2019-12-08 23:59:06', '2019-12-09 23:59:06',
       '2019-12-10 23:59:06', '2019-12-11 23:59:11', '2019-12-12 23:59:05',
       '2019-12-13 23:59:04', '2019-12-14 23:59:08', '2019-12-15 23:59:07',
       '2019-12-16 23:59:13', '2019-12-17 23:59:10', '2019-12-18 23:59:12',
       '2019-12-19 23:59:09', '2019-12-20 23:59:10', '2019-12-21 23:59:06',
       '2019-12-22 23:59:07', '2019-12-23 23:59:07', '2019-12-24 23:59:13',
       '2019-12-25 23:59:10', '2019-12-26 23:59:11', '2019-12-27 23:59:04',
       '2019-12-28 23:59:05', '2019-12-29 23:59:06', '2019-12-30 23:59:07',
       '2019-12-31 23:59:09', '2020-01-01 23:59:06', '2020-01-02 23:59:02',
       '2020-01-03 23:59:06', '2020-01-04 23:59:03', '2020-01-05 23:59:08',
       '2020-01-06 23:59:07', '2020-01-07 23:59:08', '2020-01-08 23:59:06',
       '2020-01-09 23:59:03', '2020-01-10 23:59:10', '2020-01-11 23:59:02',
       '2020-01-12 23:59:07', '2020-01-13 23:59:04', '2020-01-14 23:59:07',
       '2020-01-15 23:59:04', '2020-01-16 23:59:06', '2020-01-17 23:59:03',
       '2020-01-18 23:59:09', '2020-01-19 23:59:04', '2020-01-20 23:59:04',
       '2020-01-21 23:59:08', '2020-01-22 23:59:04'],
      dtype='object', name='timestamp')

vol:
                      BTC       ETH       XRP       BCH
timestamp
2019-11-01 23:59:08  0.054987  0.040244  0.029715  0.082026
2019-11-02 23:59:08  0.034541  0.029485  0.026469  0.078933
2019-11-03 23:59:04  0.034541  0.027006  0.026571  0.057731
2019-11-04 23:59:12  0.022937  0.027006  0.026571  0.052057
2019-11-05 23:59:03  0.021911  0.026792  0.023252  0.040931
...                       ...       ...       ...       ...
2020-01-18 23:59:09  0.046494  0.086220  0.066950  0.162209
2020-01-19 23:59:04  0.048259  0.084283  0.066950  0.157251
2020-01-20 23:59:04  0.045850  0.081700  0.064228  0.149919
2020-01-21 23:59:08  0.027414  0.041858  0.042955  0.092721
2020-01-22 23:59:04  0.027414  0.041858  0.042955  0.092721

A: You need a tick locator:
import matplotlib.ticker as ticker

# ...
ax.xaxis.set_major_locator(ticker.MultipleLocator(20))

And you can do this, if you want, instead of modifying the rcParams:
ax.tick_params(axis='x',which='major',labelsize=3)

A: This is an alternative approach where you specify the number of ticks you want instead of the frequency, but you may still find it useful:
import pandas as pd
import matplotlib.pyplot as plt

x = np.arange('2017-01', '2020-01', dtype='datetime64[D]')
y = np.random.random(len(x))

df = pd.DataFrame({'x': x, 'y': y})

plt.scatter(df['x'].values, df['y'].values)
ticks = np.arange(x[0], x[-1], (x[-1] - x[0]).astype('timedelta64[D]') / 15)
plt.xticks(ticks, ticks)
plt.gca().tick_params('x', labelrotation=45, labelsize=10)
plt.show()

Which gives

instead of

 Edit
Here is a complete example which uses the given data,
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

BTC = np.array([0.05498711,0.03454131,0.03454131,0.02293731,0.02191053,0.02191053,
                0.01688648,0.02828462,0.02828462,0.02828462,0.03188105,0.03054535,
                0.02955679,0.0270898, 0.0281818, 0.02866918,0.02710031,0.02668099,
                0.03404319,0.03670357,0.05311734,0.08663729,0.08663729,0.08339912,
                0.08831546,0.08063601,0.07522458,0.06043395,0.06280006,0.06543079,
                0.06543079,0.0444152, 0.0444152, 0.03575803,0.03575803,0.03575803,
                0.02870328,0.02870328,0.02870328,0.02870328,0.02835626,0.02263508,
                0.02263508,0.02514882,0.0332816, 0.02463769,0.0385677, 0.0427951,
                0.04329788,0.04329788,0.04329788,0.05240083,0.05883257,0.05883257,
                0.03162634,0.02906886,0.02765406,0.024522,  0.02352016,0.01756594,
                0.02030382,0.02030382,0.03326152,0.03601441,0.03601441,0.03250479,
                0.04571088,0.06313575,0.07639834,0.07639834,0.0555884, 0.05133794,
                0.0493664, 0.03279575,0.05379169,0.05431873,0.05431873,0.04422756,
                0.04649411,0.04825915,0.04584981,0.02741382,0.02741382])

idx = np.array(['2019-11-01 23:59:08', '2019-11-02 23:59:08', '2019-11-03 23:59:04',
                '2019-11-04 23:59:12', '2019-11-05 23:59:03', '2019-11-06 23:59:08',
                '2019-11-07 23:59:04', '2019-11-08 23:59:07', '2019-11-09 23:59:06',
                '2019-11-10 23:59:05', '2019-11-11 23:59:03', '2019-11-12 23:59:04',
                '2019-11-13 23:59:06', '2019-11-14 23:59:06', '2019-11-15 23:59:05',
                '2019-11-16 23:59:12', '2019-11-17 23:59:03', '2019-11-18 23:59:10',
                '2019-11-19 23:59:09', '2019-11-20 23:59:06', '2019-11-21 23:59:11',
                '2019-11-22 23:59:05', '2019-11-23 23:59:06', '2019-11-24 23:59:09',
                '2019-11-25 23:59:05', '2019-11-26 23:59:03', '2019-11-27 23:59:04',
                '2019-11-28 23:59:05', '2019-11-29 23:59:04', '2019-11-30 23:59:02',
                '2019-12-01 23:59:06', '2019-12-02 23:59:11', '2019-12-03 23:59:02',
                '2019-12-04 23:59:07', '2019-12-05 23:59:07', '2019-12-06 23:59:08',
                '2019-12-07 23:59:07', '2019-12-08 23:59:06', '2019-12-09 23:59:06',
                '2019-12-10 23:59:06', '2019-12-11 23:59:11', '2019-12-12 23:59:05',
                '2019-12-13 23:59:04', '2019-12-14 23:59:08', '2019-12-15 23:59:07',
                '2019-12-16 23:59:13', '2019-12-17 23:59:10', '2019-12-18 23:59:12',
                '2019-12-19 23:59:09', '2019-12-20 23:59:10', '2019-12-21 23:59:06',
                '2019-12-22 23:59:07', '2019-12-23 23:59:07', '2019-12-24 23:59:13',
                '2019-12-25 23:59:10', '2019-12-26 23:59:11', '2019-12-27 23:59:04',
                '2019-12-28 23:59:05', '2019-12-29 23:59:06', '2019-12-30 23:59:07',
                '2019-12-31 23:59:09', '2020-01-01 23:59:06', '2020-01-02 23:59:02',
                '2020-01-03 23:59:06', '2020-01-04 23:59:03', '2020-01-05 23:59:08',
                '2020-01-06 23:59:07', '2020-01-07 23:59:08', '2020-01-08 23:59:06',
                '2020-01-09 23:59:03', '2020-01-10 23:59:10', '2020-01-11 23:59:02',
                '2020-01-12 23:59:07', '2020-01-13 23:59:04', '2020-01-14 23:59:07',
                '2020-01-15 23:59:04', '2020-01-16 23:59:06', '2020-01-17 23:59:03',
                '2020-01-18 23:59:09', '2020-01-19 23:59:04', '2020-01-20 23:59:04',
                '2020-01-21 23:59:08', '2020-01-22 23:59:04'], dtype='datetime64[s]')

df = pd.DataFrame({'BTC': BTC})
df.index = pd.DatetimeIndex(idx)

x = df.index.values.astype('datetime64[D]')
y = df['BTC']

plt.figure(figsize=(8,4))
plt.plot(x, y)
ticks = np.arange(x[0], x[-1], (x[-1] - x[0]).astype('timedelta64[D]') / 15)
plt.xticks(ticks, ticks)
plt.gca().tick_params('x', labelrotation=90, labelsize=10)
plt.show()

This will give you


text:
Q: Help verifying proof about tensor fields in Abraham, Marsden, Ratiu, Manifolds, Tensor Analysis, and Applications This question is apropos of a comment I received in the question: Lang Fundamentals of Differential Geomety definition of covariant derivative of a tensor field. The comment referred to a proposition in Abraham, Marsden, Ratiu, Manifolds, Tensor Analysis, and Applications (hereafter AMR). In the second edition, it is Proposition 5.2.20 and in the third edition it is Proposition 6.2.20. A complete
understanding of the AMR proposition would be useful in addressing the referred to
question.
Proposition. Let $M$ be a finite-dimensional manifold or be modeled on a Banach space
with norm $C^\infty$ away from the origin. Then $\mathcal{T}^r_s(M)$ is isomorphic to
$\mathfrak{T}^r_s(M)$ regarded as $\mathcal{F}(M)$-modules and as real vector spaces. In particular $\mathfrak{X}^*(M)$ is isomorphic to $\mathcal{X}^*(M)$.
[Before citing the proof, here are the definitions given just before the proposition:
$$L_{\mathcal{F}(M)}(\mathfrak{X}(M),\mathcal{F}(M))=\mathcal{X}^*(M)$$
the $\mathcal{F}(M)$-linear mappings on $\mathfrak{X}(M)$, and similarly
\begin{equation*}
  \mathfrak{T}^r_s(M)=L^{r+s}_{\mathcal{F}(M)}(\mathcal{X}^*(M),\dots,\mathfrak{X}(M);
  \mathcal{F}(M))
\end{equation*}
the $\mathcal{F}(M)$-multilinear mappings.
I'm pretty certain there is a typo (theirs, not mine) in that last display. It would make far more sense if the definition was
\begin{equation*}
  \mathfrak{T}^r_s(M)=L^{r+s}_{\mathcal{F}(M)}(\mathfrak{X}^*(M),\dots,\mathfrak{X}(M);
  \mathcal{F}(M))
\end{equation*}
where all I did was change the font from calligraphic to fraktur on the first of the
$r+s$ elements listed. This same typo exists in both the second and third editions. I'll assume this latter display is the correct one.]
Proof. Consider the map $\mathcal{T}^r_s(M)\to\mathfrak{T}^r_s(M)$ given by
\begin{equation*}
  \ell(\alpha^1,\dots,\alpha^r,X_1,\dots,X_s)(m)=\ell(m)(\alpha^1(m),\dots,X_s(m)).
\end{equation*}
[EDIT: It seems to me that it would make more sense notationally
if the right hand side $\ell$ was actually $t$.]
This map is clearly $\mathcal{F}(M)$-linear. To show it is an isomorphism, given such
a multilinear map $\ell$, define $t$ by
\begin{equation*}
  t(m)(\alpha^1(m),\dots,X_s(m))=\ell(\alpha^1,\dots,X_s)(m).
\end{equation*}
To show that $t$ is well-defined we first show that, for each $v_0\in T_mM$, there is
an $X\in\mathfrak{X}(M)$ such that $X(m)=v_0$, and similarly for dual vectors. Let
$(U,\phi)$ be a chart at $m$ and let $T_m\varphi(v_0)=(\varphi(m),v_0')$.
Define $Y\in\mathfrak{X}(U')$ by $Y(u)=(u',v_0')$ on a neighborhood $V_1$ of
$\varphi(m)$, where $w=\varphi(n)$. [I have to believe there are a couple of AMR
typos there. I think the $w=\varphi(n)$ was probably supposed to be $u'=\varphi(u)$,
but in any case, it should not be needed, since $Y$ is supposed to be defined on
$U'$, which I assume is $\varphi(U)$, so the definition of $Y$ should, I believe,
read $Y(u')=(u',v_0')$.] Extend $Y$ to $U'$ so $Y$ is zero outside $V_2$, where
$\mathrm{cl}(V_1)\subset V_2$, $\mathrm{cl}(V_2)\subset U'$, by means of a bump
function. Define $X$ by $X_\varphi=Y$ on $U$, and $X=0$ outside $U$. Then $X(m)=v_0$.
The construction is similar for dual vectors.
As in Theorem 4.2.16 [same number in both second and third editions],
$\mathcal{F}(M)$-linearity of $\ell$ shows that the definition of $t(m)$ is
independent of how the vectors $v_0$ (and corresponding dual vectors) are extended
to fields.
The proof goes on from there to prove smoothness and to give a simplification in
the finite-dimensional case.
I have two problems with this proof:

*

*I don't see how to show that the definition of $t$ (given $\ell$) is independent of
the choice of chart $(U,\varphi)$. The referenced 4.2.16 only gives an example of how to
prove that a particular definition is independent of the specifics of the bump function
used to define it. It doesn't deal with independence from the choice of chart.

*I don't see how to show that $t(m)$ is continuous (multilinear). The multilinear
part is easy; it's the continuous part that I can't figure out.

EDIT: It occurs to me that if this proposition is going to be true,
then the meaning of
$L^{r+s}_{\mathcal{F}(M)}(\mathfrak{X}^*(M),\dots,\mathfrak{X}(M);\mathcal{F}(M))$ has to be more than the stated
"$\mathcal{F}(M)$-multilinear mappings". It seems that from the forward
direction of the isomorphism we are going to have that
\begin{equation*}
  |\ell(\alpha^1,\dots,X_s)(m)|
  =|(t(m))(\alpha^1(m),\dots,X_s(m))|
  \leq||t(m)||\,||\alpha^1(m)|| \cdots ||X_s(m)||
\end{equation*}
so I think this condition should be part of the definition of
$L^{r+s}_{\mathcal{F}(M)}(\mathfrak{X}^*(M),\dots,\mathfrak{X}(M);\mathcal{F}(M))$. That is, I think we should define
\begin{equation*}
  \begin{split}
  L^{r+s}_{\mathcal{F}(M)}(&\mathfrak{X}^*(M),\dots,\mathfrak{X}(M);\mathcal{F}(M))=\\
  &\{\mathcal{F}(M)\text{-multilinear }\mathcal{F}(M)\text{-valued}\,\ell:
  \forall m\in M,\exists c(m)\geq 0\text{ such that}\\
  &|(\ell(\alpha^1,\dots,X_s))(m)|\leq c(m)||\alpha^1(m)||\cdots||X_s(m)||\}.
  \end{split}
\end{equation*}
Of course, we will have to specify, for each $m$, a norm of $T_m(M)$
and for $(T_m(M))^*$. I think this will take care of question 2. That
still leaves question 1: showing chart-independence.


text:
Q: Web API2 How to log user actions with friendly names with an Annotation I'm working on a greenfield Web API and need to log users' actions in a friendly way. I can see its easy to gather the logged in user, the controller, the action, and parameters like this post
What I am looking for is away to give human readable friendly messages like:

*

*"Paul Logged in" + timestamp

*"Paul Created a new product (some product metadata)" + timestamp

*"Paul Deleted Product xyz" + timestamp

I could adapt the answer here and then use a lookup table on the controller and action to translate to my human readable string with some token replacements but I can see that being a maintenance overhead when new actions are added. It also means a developer might forget to put the call in and we miss auditing.
Is there a way I can use an annotation on the action to specify what my human readable log message will be? (possibly with tokens)
Has anybody done this in a generic manner without the code becoming totally custom to that application?

A: I would look into an Aspect oriented programming framework to cross cut your application in a way that's maintainable. Having a strong typed annotation on every action specific to a logging mechanism will be readable and maintainable provided you are happy that to add a the logging capability, you will require a re-compilation. You could switch these on or off using a config setting easily.
I have used and would recommend PostSharp here, its awesome and free (for basic aspects).
A good example is:
http://doc.postsharp.net/example-trace
I have implemented a modified version of this with log4net and it works really well in a production environment.
Generally speaking i am not a fan of AOP as its surprise factor can be disconcerting, but in cases like this the maintenance overhead reduction is worth the trade off.

A: I think that trying to accomplish this at the UI layer is the wrong place.  If I hit the url foo.com/product/delete/1 does that mean that I deleted the product?  I would say no.

*

*What happens if that user didn't have permission?

*What happens if the product didn't exist?

*What happens if the product failed to delete?

I think the correct place to do this kind of auditing is at the repo layer of your code.  Have a method something like this:
public void DeleteProduct(int productID, string username) {
   _db.Products.Delete(productID); //pseudo code
   _auditService.AddAuditRecord($"Product ID {productID} was deleted by {username}");
}

This way, you only audit the data change if it was successful.


text:
Q: Show/hide select values based on previous select choice I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:

   <select name="discipline" class="discipline">
      <option value=" " selected></option>
      <option value="access">ACCESS</option>
      <option value="inbraak">INBRAAK</option>
      <option value="brand">BRAND</option>
      <option value="cctv">CCTV</option>
      <option value="airphone">AIRPHONE</option>
      <option value="perimeter">PERIMETER</option>
   </select>

<select name="article" class="input-article">
   <?php
      $articleselect = $dbh->prepare('SELECT * FROM articles');
      $articleselect->execute();
         while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
   ?>
      <option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
   <?php
      }
   ?>
</select>

I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?

A: jQuery for the change event and AJAX
$(document).ready(function(e) {
    $('select.discipline').change(function(e) { // When the select is changed
        var sel_value=$(this).val(); // Get the chosen value
        $.ajax(
        {
            type: "POST",
            url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
            data: {selected_option: sel_value}, // Send the slected option to the PHP page
            dataType:"HTML",
            success: function(data)
            {
                $('select.input-article').append(data); // Append the possible values to the second select
            }
        });
    });
});

In your AJAX.php
<?php
if(isset($_POST['selected_option']))
    $selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent

$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic

// Process your query

$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
    $options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>

Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.

A: First give both of the selects an unique ids...

   <select name="discipline" class="discipline" id="discipline">
      <option value="" selected></option>
      <option value="access">ACCESS</option>
      <option value="inbraak">INBRAAK</option>
      <option value="brand">BRAND</option>
      <option value="cctv">CCTV</option>
      <option value="airphone">AIRPHONE</option>
      <option value="perimeter">PERIMETER</option>
   </select>

<select name="article" class="input-article" id="article">
   <option value="" selected></option>
</select>

Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...

Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
  <option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
  }
?>

Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.

A: This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...

// select box for state starts

  State

    <select class="form-control input-sm" name="statename" id="stateid">
      <option value="">---- Select ----</option>
      <?php

                        $state=sql::readResultArray("Your Query To select State`");
                        foreach($state as $s){
                            ?>
      <option  value="<?php echo $s?>"> <?php echo $s ?> </option>
      <?php
                            }
                        ?>
    </select>

  Colleges

    <select class="form-control input-sm" name="mycollegename">
      <option value="">--- Select --- </option>
    </select>

// further code for from in form.php..

Script to find the state and then pass the value to find the respective colleges in that state

Call this file through ajax .. Code on this file
mycollege.php
 <?php

require('db.php'); // call all function required, db files or any crud files

$type=$_GET['type'];

if(!empty($type)){

$r=sql::read("Your Query To call all teh college list");

?>

<select name="mycollegename">
  <option value="">Select One</option>
  <?php

        foreach($r as $r){

            echo "<option  value=\"$r->collegename\">$r->collegename  </option>";

        }

?>
</select>
<?php }else{ ?>
<select name="mycollegename">
  <option value="">Select State</option>
</select>
<?php } ?>


text:
Q: Flash Builder iPhone app size I have a mobile Flex project which I am deploying to iPhone/iPod and Android. I'm having an issue getting my app under the 20 MB 3g size limit. I am including some images and a video which amount to 1.5 MB. The swf for the build is 2.8 MB and the resulting ipa is 9.7 MB with the app file being 22.4MB. The app store shows the final size as 21.1 MB, though I understand Apple needs to add additional things to the package is it really supposed to grow that significantly? What started as 3.3 MB has now grown to over 20 MB.
I've seen people say that all that matters is the ipa size, which is obviously not what is happening here. Any thoughts?

A: ipa is a compressed format and the download size is uncompressed. In other words, users don't download the ipa file in it's compressed state to their iPhone/iPod/iPad. If you rename ipa to zip and unzip it this is what you want to try and get below 20 mb. I'm having the exact same problem as you since the AIR overhead eats up a significant part of that 20 mb. Hope this explanation helps - good luck!
-Tom


text:
Q: Regex match substring ignoring occurencies inside HTML I need to remove a code of digits, preceeded by an underscore in strings that may or may not be cointained in an HTML tag, that may or may not containt the same substring.
Example: remove _1234 from following strings:
this is my string_1234

this is my html nested string_1234

I just do:
$regex = '#\_(\d+)$#';
$name = preg_replace($regex, '', $name);

but I'm removing also the part inside the HREF, so I would like to generally exclude the any occurency that may happen inside the html tag.
EDIT: 1 thing I can be sure, the eventual HTML tag will always be a link... is there a way to ignore with regex anything inside  and ?

A: Perhaps not exactly what you're after but work based on quotes.
This contains a negative lookahead for a quote (or digit, stops it matching simply a smaller amount of inside the href) and a negative lookbehind in the same way. The word aspect is still matched and stored in group 1.
That can then be used as the replacement value.
$regex = '(?<!"|\w)(\w+)_\d+(?!"|\d)';
$name = preg_replace($regex, '$1', $name);

https://regex101.com/r/2agOwr/1


text:
Q: Laravel 5 - can't get parameters from redirect::route I have this code in a controller:
$id = 1;
$name = 'Phil';
return Redirect::route('myroute')->with('id',$id)->with('name',$name);

Then in my routes file I have the following:
Route::get('test/{id}/{name}',array('as' => 'myroute', 'uses' => 'MyController@myFunction'));

And finally the function in MyController:
 public myFunction($id,$name) {
        return $name;
 }

Instead of getting the content of the variable name printed 'Phil', I get the string '{name}'.

What am I doing wrong?
Thanks in advance

A: Pass the route parameters as the second argument to route():
return Redirect::route('myroute', ['id' => $id, 'name' => $name]);

->with() puts the items in the Input for the next request, rather than being route parameters.


text:
Q: Is it possible to read each line of a file on command in javascript In short I have a video playing on the canvas:
vid1.addEventListener('play', function() {
  var $this = this; //cache
  (function loop() {
    if (!$this.paused && !$this.ended) {
      ctx1.drawImage($this, 0, 0);
      setTimeout(loop, 1000 / 30); // drawing at 30fps
    }
  })();
}, 0);

On each run of the function loop I would like to read a line from a text file. The file is 50 mb so I am tempted to steer away from loading the whole file into an array before starting but i have yet to find a solution that would allow me to read each line of the file with out doing that. Thank you.


text:
Q: Android AudioRecord return twice more data on read I have strange situation with recording on Android. I created AudioRecorder with sample rate 8kHz, Mono, PCM 16 bit. But when i call read, it return twice more samples that needed. For example i rite 2 seconds on microphone, which must give 16k samples, but instead it gives 32k samples.
the code running in thread and pretty simple:
numSamples = audioRecord.read(buf, 0, SIMPLE_RECORDER_BUFFER_SIZE);
writer.write(stereo, 0, numSamples)

Does anyone had this issue?


text:
Q: Not well formed error in firefox when using getScript I do many search in stackoverflow and google, but I cannot found a logical way !
I use getScript to load a js file, I get "Not Well Formed" error in Firefox error console.
I trying to comment all lines of my code in js file, and again I get that error !
Timestamp: 04/25/2012 02:02:32 PM
Error: not well-formed
Source File: file:///G:/ct/main/main.js?_=1335346352617
Line: 1, Column: 1
Source Code:
/*

I use $.ajax too, I get exactly that error.
Note: my included JS code work without any problem and everything is OK (when my code is not commented), but I want to know why my user should get this error in Firefox ?!
Sorry for my bad English.
EDIT:
var ulWidth = 0;
$('.carousel_links ul li').each(function(){
  ulWidth += $(this).outerWidth();
});

$('.carousel_links ul').css({
   'width' : ulWidth+'px'
});

UPDATE:
I found this way:
How do I include a JavaScript file in another JavaScript file?
I use this and I think this way is better than $.getScript because I don't get any error and all of my JavaScript code work fine.

A: I think it must be do do with the mime type of the requested document.
If it's running on your server, make sure that it knows what to do with .js files. It should return text/javascript.
If not then it should definitely work when requested like this:
var req = new XMLHttpRequest();
req.open("GET", "filename.js");
req.overrideMimeType("text/javascript");
req.send(null);


text:
Q: Using Safari to list all contents of a folder/path Is there a way I can use Safari to list the contents of a folder? More like of an "index" page where you get to see the files and sub-folders inside a path/folder. Like this one:
When I use Chrome, I just type the tilde "~" character on the address bar, which many of us know, represents the "home directory" of the OS. It's easy for me because Chrome just lists all the files under that directory in a list format inside the browser. I can just click the HTML files or any file/folder for that matter to view its content.
I know this can be done just by using Finder to navigate your directories and files, but it's much easier to just click around files where you know it will still end up displaying in the browser.
As I have tested, when typing the path or even "~" in the address bar, what it does is either do a web search or open that folder in Finder. Just not what I want.

A: I don't think this is possible. I looked at a list of Safari Extensions, and no extension I found has this ability.
NOTE: If you put the actual URL path description in the Safari address bar, ex: file:///Users/Panoy, Safari will open a Finder window to that path, not display the path in the browser window itself.


text:
Q: (Basic) Get order number of an Object in Array - Javascript ES6 i have a basic question about Javascript ES6, Hope your helps!
I want to get order number of an Object in Array:
[
  { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 11, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 67, "image": "http://localhost:8000/media/users/1/2_27.jpg"}
]

I have params.id: 11, I want to print order_object = 2

A: You are looking for findIndex
var order_object = arr.findIndex( s => s.pk == 11 ) + 1;

Demo

var arr  = [
  { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 11, "image": "http://localhost:8000/media/users/1/2_27.jpg"},
  { "pk": 67, "image": "http://localhost:8000/media/users/1/2_27.jpg"}
];

var order_object = arr.findIndex( s => s.pk == 11 ) + 1;

console.log( order_object );

A: You can use [].findIndex() to find the first index of a matching predicate.


text:
Q: Ng2-smart-table doesn't display date time values in IE i am using ng2-smart-table in my angular 7 application,
I have used owl-datetime picker in the table. the values are getting added in the db.
i am getting the values from back end in an array which is getting populated in the table.
but the datetime value is not getting displayed in the box, it is giving me
 "InvalidPipeArgument : 'Unable to convert "2019-12-24 13:00:00" into a date' for pipe DatePipe'.
I can't share any code as this'll is my office based application...
any help would be appreciated...

A: use moment like this

public date : string = '2019-12-24 13:00:00';
public newDate;

this.newDate =  moment(this.date).format('MMM Do YYYY');

than binding this.newDate

<h2> {{newDate}}</h2>


text:
Q: How to apply an effect depending on mouse move / position? I have 3 buttons in position absolute :
.micro {
position:absolute;
}

#micro_1 {
left:1165px;
top:176px;
}

#micro_2 {
left:800px;
top:300px;
}

#micro_3 {
left:300px;
top:400px;
}

I would like to fade these 3 elements when the mouse move and come closer to one of the images.
If mouse comes closer to image 1, images 1 is fading in. Images 2 and images 3 are fading out.
And so on.
I can use jQuery to know the mouse position :
$('body').mousemove(function(e){
    $('#mouse_position').html("mouse position: x=" + e.pageX + "; y=" + e.pageY);

So i guess i can do some math to apply the effect.
What i've done :
$('body').mousemove(function(e){
        $('#mouse_position').html("mouse position: x=" + e.pageX + "; y=" + e.pageY);
        if (e.pageX > 394 && e.pageX < 533) {
            $('#lueur_video_1').fadeIn('slow');
            $('#lueur_video_2').fadeOut('slow');
            $('#lueur_video_3').fadeOut('slow');
        }

        if (e.pageX > 533 && e.pageX < 722) {
            $('#lueur_video_2').fadeIn('slow');
            $('#lueur_video_1').fadeOut('slow');
            $('#lueur_video_3').fadeOut('slow');
        }

        if (e.pageX > 722 && e.pageX < 1116) {
            $('#lueur_video_3').fadeIn('slow');
            $('#lueur_video_1').fadeOut('slow');
            $('#lueur_video_2').fadeOut('slow');
        }

A: You can compare the mouse position (e.pageX / e.pageY) to the center of the image and set the opacity based on that.  You can check where the elements are on the page with $("#micro_3").offset().
You will need to decide on the minimum and maximum distance for the fading on your own.  When it's out of the maximum distance, opacity is 0 and inside the minimum, opacity is 1.  For anything in between calculate the opacity by (Range - CurrentDistance) / Range.


text:
Q: How to instantiate a javascript class in another js file? Suppose if I define a class in file1.js
function Customer(){
    this.name="Jhon";
    this.getName=function(){
        return this.name;
    };
};

Now if I want to create a Customer object in file2.js
var customer=new Customer();
var name=customer.getName();

I am getting exception: Customer is undefined, not a constructor.
But when i create a customer object in file2.js and pass it to file1.js then its working .
file1.js

    function Customer(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        }
    }
    function customer(){
        return new Customer();
    }

file2.js

    var customer=customer();
    var name=customer.getName();

but i want to create a customer object in file1.js using new Customer(). How can i achieve that?

A: You can export your methods to access from other files like this:
file1.js
var name = "Jhon";
exports.getName = function() {
  return name;
}

file2.js
var instance = require('./file1.js');
var name = instance.getName();

A: It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js is loaded before file2.js:
<script src="file1.js"></script>
<script src="file2.js"></script>

In node.js, the recommended way is to make file1 a module then you can load it with the require function:
require('path/to/file1.js');

It's also possible to use node's module style in HTML using the require.js library.

A: If you are using javascript in HTML, you should include file1.js and file2.js inside your html:
<script src="path_to/file1.js"></script>
<script src="path_to/file2.js"></script>

Note, file1 should come first before file2.

A: Make sure the dom is loaded before you run your code in file2... If you're using jQuery:
$(function(){
  var customer=customer();
  var name=customer.getName();
});

Then it doesn't matter what order the files are in, the code won't run until all of the files are loaded.

A: // Create Customer class as follows:
export default class Customer {
   getName() {
     return 'stackoverflow';
   }
}

// Import the class
// no need for .js extension in path cos it gets inferred automatically
import Customer from './path/to/Customer';
// OR
const Customer = require('./path/to/Customer')

// Use the class
var customer = new Customer();
var name = customer.getName();

A: Possible Suggestions to make it work:
Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...} it should be this.getName=function(){...};)
function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}

(This might be one of the problem.)
and
Make sure U Link the JS files in the correct order
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

A: It is saying the value is undefined because it is a constructor function, not a class with a constructor. In order to use it, you would need to use Customer() or customer().
First, you need to load file1.js before file2.js, like slebetman said:
<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>

Then, you could change your file1.js as follows:
export default class Customer(){
    constructor(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        };
    }
}

And the file2.js as follows:
import { Customer } from "./file1";
var customer=new Customer();

Please correct me if I am wrong.


text:
Q: Transforming subquery to INNER JOIN Transforming the following query (with subquery)
SELECT *
FROM t1
WHERE t1.a IN (SELECT t2.b FROM t2 where t2.c = 1)

.. to this query with INNER JOIN
SELECT *
FROM t1
INNER JOIN t2
ON t1.a = t2.b AND t2.c = 1

I can get a nice performance boost (learned at http://spin.atomicobject.com/2011/03/25/mysql-in-query-performance)
But how about a query like this:
SELECT *
FROM t1
WHERE t1.a NOT IN (SELECT t2.b FROM t2 where t2.c <> 1)

Note for the "NOT IN" and "<>". Can I achieve something similar?

A: Try this:
SELECT *
FROM t1
LEFT OUTER JOIN t2
ON t1.a = t2.b
WHERE t2.b IS NULL OR t2.c = 1

EDIT: I accidentally wrote INNER join. Sorry; it should be LEFT OUTER join.


text:
Q: How Do I Make A Django (Python) Project Use Only A Specific Interpreter? I am trying to set up a Django project. Initially I had Python 3.5 installed for a data analysis project I worked on. So while Python 3.5 works in tandem with matplot, pandas, scipy etc, the Django tutorial recommended I use 2.7 for the Django project as MySQL support for Python 3.5 is only third-party. I am also required to download Microsoft Visual C++ 14.0 anytime I try pip install mysqlclient for 3.5. Unfortunately my internet connection/data is quite limited.
The thing is, I have installed 2.7 and it resides in C:\Python27. Python 3.5 is installed in C:\Users\XXXX\AppData\Local\Programs\Python\Python35-32
I have created a project directory - django-admin startproject myproject. I have installed the MySQLDb package to C:\Python27. But each time I attempt from command promptC:\Users\XXXX\Documents\WebDev\seedstars> python manage.py runserver, I get this error message:
Traceback (most recent call last):
   File "C:\Users\XXXX\AppData\Local\Programs\Python\Python35-32\lib\site-    packages\django\db\backends\mysql\base.py", line 25, in <module>
   import MySQLdb as Database
   ImportError: No module named 'MySQLdb'

I tried setting my Python interpreter in PyCharm to Python 2.7. Each time I do this - python manage.py runserver, it reverts back to the error above.
Please, how do I set this Django project to only "listen" to the Python2.7 interpreter, at cmd?
Thanks.

A: simillar question is already answered here. You can use virtualenv to isolate your project, here you can have independent python environment for dependencies & also set python version.
Check extenal site here for more detailed tutorial.Using virtualenv you can create this setup using the below command.
virtualenv <virtualenv name> -p <path to version specific python>


text:
Q: NiFi ExecuteSQL Processor Timestamp When extracting a table from MariaDb through the NiFi ExecuteSQL processor it is giving me the following error:

org.apache.nifi.processor.exception.ProcessException: Value '0000-00-00 00:00:00' can not be represented as a java.sql.Timestamp;
I am running NiFi version 1.1.1 and the datatype of the columns in question is a regular datetime type. I assume this is happening because of null values being present but is there a way to avoid having to escape all null values and have nifi handle this automatically.
Found the answer already.
'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error


text:
Q: Error: Cannot find module 'express' I'm using webpack to compile my Express app (written in TypeScript). But I have some trouble running the compiled file.
webpack.config.json
const root = require('app-root-path').path;
module.exports = {
    entry: `${root}/server/server.ts`,
    target: 'node',
    externals: [
        /^[a-z\-0-9]+$/
    ],
    output: {
        filename: 'compiled.js',
        path: `${root}`,
        libraryTarget: "commonjs"
    },
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
    },
    module: {
        loaders: [{
            test: /\.tsx?$/,
            exclude: `/node_modules/`,
            loader: 'ts-loader'
        }]
    }
}

When I try to run the compiled file I get this:
Error: Cannot find module 'express'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/compiled.js:717:18)
    at __webpack_require__ (/compiled.js:20:30)
    at Object.<anonymous> (/compiled.js:644:17)
    at Object.<anonymous> (/compiled.js:705:30)
    at __webpack_require__ (/compiled.js:20:30)
    at /compiled.js:63:18


text:
Q: O que é herança diferencial? Eu estava lendo este artigo no SO em inglês e me deparei com o termo differential inheritance.
O que, exatamente, é herança diferencial?
É possível termos um exemplo mínimo, preferencialmente em JavaScript?

A: Tradução livre de artigo da Wikipedia (tão magro que a gente até desconfia):

Herança diferencial é um modelo comum de herança utilizado em linguagens de programação baseadas em protótipos, como JavaScript, Io e NewtonScript. Opera segundo o princípio que muitos objetos derivam de outros objetos mais genéricos, e só diferem deles em poucos detalhes; geralmente o objeto derivado mantém internamente uma lista de ponteiros para os mais genéricos.

Nesta pergunta do SO, dizem que herança diferencial é um sinônimo de herança prototípica, mas que seu uso em relação a JavaScript é para enfatizar o padrão "puro" em que se usa Object.create para herdar diretamente de outro objeto, em vez do new, que é um artifício que o JavaScript possui para ficar mais parecido com as linguagens baseadas em classes (aliás, no ES6 teremos até a keyword class, mas internamente tudo continuará funcionando da mesma maneira, a herança continuará prototípica).

A: Complementando a resposta do bfavaretto.
Em linguagens como Java e .NET, as instâncias são todas bastardas**, pois somente os tipos têm direito a herança.
Já em Javascript, todo mundo pode "herdar" de todo mundo. Todo objeto em Javascript possui um protótipo. O protótipo diz a um objeto que propriedades ele possui via herança. E a linguagem permite que você faça atrocidades bem legais como essa:
var foo = {}; // esse objeto herda de Object.
foo.prototype = Array.prototype; // E agora ele tem um protótipo comum com o Array :D

Você pode levar isso um passo adiante.
var bar = {nome: "John Doe", idade: 21};
foo.prototype = bar; //sim, isso é permitido.

Dá pra levar mais adiante...
var bar = {nome: "John Doe", idade: 21};
var foo = function () {};
foo.prototype = bar;
var ni = new foo(); // sério, veja as propriedades de ni.

Temos um processo de adoção aqui, pois agora o "pai" de foo passa a ser bar. O pai do objeto passa a ser outro objeto, e não um tipo.
Sim, essas relações familiares modernas, com laços tão tênues, são realmente bem complexas...
Falando sério agora: essa história de herdar de um objeto e não de um tipo é que se chama herança diferencial. Isso dá muito poder ao programador - você pode definir as heranças dinamicamente e em tempo de execução, e com mais flexibilidade do que no modelo OO "tradicional". Mas esses poderes trazem grandes responsabilidades, especialmente em um mundo onde a única tipagem segura é a tipagem de pato.
** Isso NÃO é um termo técnico ;)


text:
Q: ComboBox TextWrap Binding I have the following ComboBox
<ComboBox x:Name="TaskText" Text="{Binding TaskNameBinding}" ItemsSource="{Binding
    taskList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name"
    Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="90"/>

I wish to apply Text Wrapping to this combobox and followed to code snippet from the answer here
<ComboBox x:Name="TaskText" ItemsSource="{Binding taskList, ElementName=MainWin}"
    SelectedValuePath="_id" DisplayMemberPath="_name" Background="Yellow" Padding="0"
    Margin="0" BorderThickness="0" Width="90">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TaskNameBinding}"
                TextTrimming="CharacterEllipsis" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

But this template is breaking the binding and the combobox displays no values. Any help would be appreciated

A: Figured it out
<ComboBox x:Name="TaskText" Text="{Binding TaskNameBinding}" ItemsSource="{Binding taskList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="90">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock
                                Text="{Binding _name}"
                                TextWrapping="Wrap" />
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>


text:
Q: Microsoft Botframework channel messenger not working in development mode I need enable channel messenger for botframework.
i make follow this guide: https://learn.microsoft.com/en-us/azure/bot-service/bot-service-channel-connect-facebook#enable-messenger
exclude "submit for review". i want test before submit review.
Until an app is published, it is in Development Mode. Plugin and API functionality will only work for admins, developers, and testers.

i am administrator for app & that page.
i try chat but bot not working.
Env info:
Facebook API version: 2.12
Bot framework ver: 3.14
And i has migrated to azure bot service.
My bot screenshots:
Facebook app & web hook setting
Bot setting
Channel status
Skype channel status is ok
In messenger bot not working
Any one can help me ?
Thank in advance!

A: Problem solved!
My problem is: i detected a problem about my account "Your free credit has expired after i create new bot service.
then i fix above issue, and bot worked.
Hope Azure service will show alert when create new channel for trial program.

A: If you just channel messenger for botframework about yesterday, so I think that your issues relate to my issues:
403 forbidden with POST request on https://facebook.botframework.com
My facebook channels bot framework worked well about 6 months till 2018, 19 April. All request suddendly response 403 forbidden.
And I am trying to find any document which mentioned to  any change or update API from microsoft bot server at 2018, 19 April.

A: The following is some steps for facebook set up which help me on the succcess:
step1 - Get app_id and app_secret
https://i.stack.imgur.com/WCdKH.jpg
step2 - Webhooks for page
https://i.stack.imgur.com/1Ve8u.jpg
step3 - Webhooks for page - enter microsoft bot service callback and verify token
https://i.stack.imgur.com/HX2qR.png
step 4- Messenger setting - subscribe page and get page access_token
https://i.stack.imgur.com/wwwj4.jpg
step 5 - Get page_id at facebook page
https://i.stack.imgur.com/JL78m.jpg


text:
Q: Angular 4 error with angular core change detection differs after upgrade from 2 I have a ng2 website I upgraded to ng4. On building, I get an error
ERROR in /home/docker/urlmgr-client/node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts

(15,48): error TS2304: Cannot find name 'Iterable'.
It is the only error and I never got this error in ng2.
I'm not sure where to begin debugging this. Any help would be appreciated.

A: I had the same issue, it is due to having a file left over from Angular 2. You will need to delete the node_modules folder and reinstall Angular.
Adding "export declare type NgIterable = Array | Iterable" is completely unnecessary.


text:
Q: How do I get identically written html? I want to take innerHTML from style and show it in a div demo. But it should be written identically, example
I get:
#one {width: 50px; height: 50px; background-color: red; }

and I need to get;
#one{
  width: 50px;
  height: 50px;
  background-color: blue;
}

So be one below the other, with spaces, as written in notepad ++

function myFunction() {
  var x = document.getElementById("style").innerHTML
  document.getElementById("demo").innerHTML = x;
}

<button onclick="myFunction()">click</button>

A: If you style the output element (demo) with the CSS white-space:pre-wrap, its content will wrap the way you need.
From MDN:

pre-wrap
Sequences of white space are preserved. Lines are broken at newline characters, at
, and as necessary to fill line boxes.

function myFunction(){
var x = document.getElementById("style").innerHTML;
document.getElementById("demo").innerHTML = x;
}
#demo {white-space:pre-wrap;} /* does the trick */

<button onclick="myFunction()" >click</button>