text:
Q: Saving SwatchLegend when Saving A Graph to a File I have created a labeled digraph and a legend using SwatchLegend.
 transitiontransversion = Labeled[Graph[{
T \[DirectedEdge] T, T \[DirectedEdge] C, T \[DirectedEdge] G,
T \[DirectedEdge] A,
C \[DirectedEdge] C, C \[DirectedEdge] A, C \[DirectedEdge] T,
C \[DirectedEdge] G,
G \[DirectedEdge] G, G \[DirectedEdge] A, G \[DirectedEdge] C,
G \[DirectedEdge] T,
A \[DirectedEdge] A, A \[DirectedEdge] C, A \[DirectedEdge] T,
A \[DirectedEdge] G
}, EdgeStyle -> {A \[DirectedEdge] A -> {Green,
   AbsoluteThickness[6], Arrowheads[.05]},
 C \[DirectedEdge] C -> {Green, AbsoluteThickness[6],
   Arrowheads[.05]},
 G \[DirectedEdge] G -> {Green, AbsoluteThickness[6],
   Arrowheads[.05]},
 T \[DirectedEdge] T -> {Green, AbsoluteThickness[6],
   Arrowheads[.05]},
 T \[DirectedEdge] C -> {Blue, AbsoluteThickness[6],
   Arrowheads[.05]},
 C \[DirectedEdge] T -> {Blue, AbsoluteThickness[6],
   Arrowheads[.05]},
 T \[DirectedEdge] G -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 T \[DirectedEdge] A -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 A \[DirectedEdge] G -> {Blue, AbsoluteThickness[6],
   Arrowheads[.05]},
 G \[DirectedEdge] A -> {Blue, AbsoluteThickness[6],
   Arrowheads[.05]},
 A \[DirectedEdge] T -> {Red , AbsoluteThickness[6],
   Arrowheads[.05]},
 A \[DirectedEdge] C -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 C \[DirectedEdge] A -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 C \[DirectedEdge] G -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 G \[DirectedEdge] C -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]},
 G \[DirectedEdge] T -> {Red, AbsoluteThickness[6],
   Arrowheads[.05]}}, VertexSize -> { Large},
 VertexStyle -> {A -> Yellow, G -> Yellow, C -> Orange,
 T -> Orange}, VertexLabels -> {
 A ->
  Placed[{Text[Style["Adenine", Bold, 20]],
    adenine}, {Center, {-1, 2}}],
  C ->
  Placed[{Text[Style["Cytosine", Bold, 20]],
    cytosine}, {Center, {-1, -1.5}}],
  G ->
  Placed[{Text[Style["Guanine", Bold, 20]],
    guanine}, {Center, {2, 2}}],
  T ->
  Placed[{Text[Style["Thymine", Bold, 20]],
    thymine}, {Center, {2, -1.5}}]
 }, ImageSize -> 800,
 PlotLabel ->
 Text[Style["Molecular Character State Changes", Bold, 30]]],
 SwatchLegend[{Green, Blue, Red, Yellow,
 Orange}, {Text[Style["Identity Transformations", Bold, 15]],
 Text[Style["Transitions", Bold, 15]],
 Text[Style["Transversions", Bold, 15]],
 Text[Style["Purine", Bold, 15]],
 Text[Style["Pyrimidine", Bold, 15]]},  LegendLayout -> "Row"]]

All works as expected.  However, when I select the graph object using a mouse right click to save it as a *.png fie, the legend is not included, although the graph itself is nicely rendered as a *.png file.
How does one structure the graph output so that the SwatchLegend also appears in the final saved graphic?
Right-clicking on the Legend, which appears in this case below the bounding box of the graph does not provide the option to save the legend as a graphic.
If an answer to this is present in the documentation, it is well hidden.


text:
Q: Extending search in backend orders list for product items by id or by sku Im trying to use the following code from Search by order item SKU or ID in Woocommerce Orders Admin page to enable searching woocommerce orders by sky and id, sku being the important part for me.
   add_filter( 'woocommerce_shop_order_search_fields', function ($search_fields ) {
    $posts = get_posts(array('post_type' => 'shop_order'));

    foreach ($posts as $post) {
        $order_id = $post->ID;
        $order = new WC_Order($order_id);
        $items = $order->get_items();

        foreach($items as $item) {
            $product_id = $item['product_id'];
            $search_sku = get_post_meta($product_id, "_sku", true);
            add_post_meta($order_id, "_product_sku", $sku);
            add_post_meta($order_id, "_product_id", $product_id);
        }
    }

    return array_merge($search_fields, array('_product_sku', '_product_id'));
});

When I add this to my functions.php I get the following errors:
Array() expects parameter 1 to be a valid callback, function 'woocommerce_shop_order_search_order_total' not found or invalid function name in /var/sites/s/silverfx.co.uk/public_html/wp-includes/plugin.php on line 235

Warning: array_merge(): Argument #1 is not an array in /var/sites/s/silverfx.co.uk/public_html/wp-content/themes/SilverFx-Theme/functions.php on line 156

Warning: array_map(): Argument #2 should be an array in /var/sites/s/silverfx.co.uk/public_html/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php on line 1533

Warning: array_map(): Argument #2 should be an array in /var/sites/s/silverfx.co.uk/public_html/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php on line 1557

Warning: implode(): Invalid arguments passed in /var/sites/s/silverfx.co.uk/public_html/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php on line 1557

Im making the assumption that since this is about 1 year old and woocommerce have gone through some big changes in that time, this code is needs updating in someway however i am not experienced enough with woocommerce to recognise what is wrong.
If anyonce out there is able to just confirm I am on the correct path or offer guidence / suggestions as to what I might need to do that would be great.
Thanks

A:
Updated: compatibility with WooCommerce 3+

While woocommerce_shop_order_search_fields filter hook extend search in backend orders list, you need to add some post_meta fields for order item(s) search based on id or sku.
The author have made a mistake in product sku add_post_meta(). You need to replace undefined $sku variable by $search_sku instead, I think.
Update: after some thinking and some search around wordpress functions used in this code snippet, I think i have got the solution.
Here is the updated code related to add_post_meta() function issue:
add_filter( 'woocommerce_shop_order_search_fields', function ($search_fields ) {
    $orders = get_posts( array( 'post_type' => 'shop_order' ) );

    foreach ($orders as $order_post) {
        $order_id = $order_post->ID;
        $order = new WC_Order($order_id);
        $items = $order->get_items();

        foreach( $order->get_items() as $item_id => $item_values ) {
            if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
                $product_id = $item_values['product_id'];
            } else {
                $product_id = $item_values->get_product_id();
            }
            $search_sku = get_post_meta($product_id, "_sku", true);
            add_post_meta($order_id, "_product_id", $product_id, true); //  <= ## Here ##
            add_post_meta($order_id, "_product_sku", $search_sku, true); // <= ## Here ##
        }
    }
    return array_merge($search_fields, array('_product_id', '_product_sku'));
} );

There is a missing optional argument, that specify that the value is not an array, when set to true.
This should work now.
Reference:

*

*Search by order item SKU or ID in Woocommerce Orders Admin page

*https: WP codex add_post_meta()

A: You can do an additinal query in the search result filter. This code will also search the product meta like attributes etc.
function woocommerce_shop_order_search_results_with_product_info( $order_ids, $term, $search_fields ) {
global $wpdb;

if ( ! empty( $search_fields ) ) {
    $order_ids = array_unique(
        array_merge(
            $order_ids,
            $wpdb->get_col(
                $wpdb->prepare(
                    "SELECT DISTINCT order_id
                            FROM kn_woocommerce_order_items
                            RIGHT JOIN (
                                SELECT kn_woocommerce_order_itemmeta.order_item_id, kn_postmeta.meta_value
                                FROM kn_woocommerce_order_itemmeta
                                LEFT JOIN kn_postmeta ON kn_woocommerce_order_itemmeta.meta_value = kn_postmeta.post_id
                                WHERE kn_woocommerce_order_itemmeta.meta_key = '_product_id' AND kn_postmeta.meta_value LIKE %s
                            ) AS order_items ON order_items.order_item_id = kn_woocommerce_order_items.order_item_id",
                    '%' . $wpdb->esc_like( wc_clean( $term ) ) . '%'
                )
            )
        )
    );
}

    return $order_ids;
}

add_filter( 'woocommerce_shop_order_search_results', 'woocommerce_shop_order_search_results_with_product_info', 999, 3 );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is String type a class or a struct? Or something else? class MyString: String {}

gives an error:

Inheritance from non-protocol, non-class type 'String'`.

So looks like String is not a class. But why it can be used in context where AnyObject is expected? I though AnyObject is for class type only, while Any could be a class or non-class type.

A: If you command+click String in Xcode
struct String {
    init()
}

So String is a struct.
You can't subclass from struct as the error message said:

error: Inheritance from non-protocol, non-class type 'String'

However, you can implicitly convert it to NSString (which is subtype of AnyObject) only if you have imported Foundation directly or indirectly.
From REPL
  1> var str = "This is Swift String"
str: String = "This is Swift String"
  2> var anyObj : AnyObject = str
.../expr.oXbYls.swift:2:26: error: type 'String' does not conform to protocol 'AnyObject'
var anyObj : AnyObject = str
                         ^

  1> import Foundation // <---- always imported in any useful application
  2> var str = "This is Swift String"
str: String = "This is Swift String"
  3> var anyObj : AnyObject = str
anyObj: _NSContiguousString = "This is Swift String" // it is not Swift string anymore
  4>

But try to avoid to subclass String or NSString unless you absolute have to. You can read more at NSString Subclassing Notes.
Use extension to add new method to String
extension String {
    func print() {
        println(self);
    }
}

"test".print()

Use delegation pattern if you want to have more control over it
struct MyString {
    let str : String = ""

    func print() {
        println(str)
    }
}


text:
Q: Angular ng-disabled If someone have this problem please answer me.
Something like this works fine (element will be disabled when its true):
            <input type="text" class="no-phone-input" name="phone" ng-model="currentOrder.Customer.Phone" ng-pattern="/^[0-9-]+$/" ng-disabled="{{currentOrder.Status == 7 || currentOrder.Status == 9}}"/>

And this works too:
<input type="text" id="orderNumberInput" class="no-num-input" name="OrderNumber" ng-model ="currentOrder.OrderNumber" ng-disabled="{{currentOrder.Status == 2 || currentOrder.Status == 3  || currentOrder.Status == 4 || currentOrder.Status == 6 || currentOrder.Status == 7 || currentOrder.Status == 8 || currentOrder.Status == 9}}" required/>

But this doesn`t work at the same angular view (same scope):
<input id="customer" name="customer" type="text" ng-model="currentOrder.Customer.Name" ng-disabled="{{currentOrder.Status == 7 || currentOrder.Status == 9}}" required/>

Element doesn`t disabled...

A: Or just do in controller:
$scope.disabler = function(){
    if($scope.currentOrder.Status ==7 || $scope.currentOrder.Status ==9 ){
        return true;
    }
}

and in your template :
<input id="customer" name="customer" type="text" ng-model="currentOrder.Customer.Name" ng-disabled="disabler()" required/>

A: this works in my build ..
<input id="customer" name="customer" type="text" ng-model="currentOrder.Customer.Name" ng-disabled="(currentOrder.Status == 7 || currentOrder.Status == 9)" required/>

change {{}} into ()


text:
Q: Brownian Moment Generating Function and Hitting Times Here is my question. I've done the first part, but I'm stuck on the second. If I can work out (/be advised) how to do the second, then I hope to be able to do the third similarly.
Please note: While I'd really appreciate help on this question, please don't just tell me the answer! I want to learn from the question, so I'd love it if someone would advise me of the next step to take.

I'm really unsure how to proceed at all. Let me write
$$S_a^{-b} = \sup_{0 \le s \le t} (W_s - bs) \;\ \text{and} \;\ \{ T_{a,b} > t \} = \{ S_a^{-b} \le a \}.$$
So we have a nice (well, explicit) expression for $1(T_{a,b} < t)$. However, I can't work out how to combine this with the rest of the expectation. We can say
$$ E(e^{\theta W_t} 1(T_{a,b} < t)) = E(e^{\theta W_t} \mid S_a^{-b} \le a)P(S_a^{-b} \le a),$$
and we have an explicit expression for the latter, but then this first expectation is equally difficult.
We know that $Z_t = \mathcal{E}(\theta W)_t = e^{\theta W_t - \theta^2 t/2}$ defines a UI martingale, and so I hoped to maybe use OST to convert the $e^{\theta W_t}$ into $e^{\theta t/2}$, but I can't see how to do that (or even if that would be a thing). Certainly deriving the third part from the second it looks like it would (/could) use this.
Any advise would be most appreciated. :)


text:
Q: Fourth degree Maclaurin $f(x) = \dfrac{\sin x}{1-x}$ $$f(x) = \frac{\sin x}{1-x}$$
I tried to differentiate it but it is very difficult, what is the trick?

A: I agree with David. Find the series for $\sin(x)$ and $\dfrac1{1-x}$ (a much simpler task), then find the first several terms of the product.


text:
Q: How to call a Usercontrol from another in same window in WPF ? I have two UserControls in my project's MainWindow. In MainWindow I call the first  UserControl whose content is a Button and put this FirstControl in a Grid. How can I call the second UserControl when I click on the button in FirstUserControl in MainWindow?
First UserControl :
<UserControl x:Class="BenashManage.UserControl.ButtonUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             Height="auto" Width="auto" RenderTransformOrigin="0,0">
    <Grid>
        <Border x:Name="BorderAddEdit"  BorderBrush="{DynamicResource BorderBrush}" BorderThickness="5,5,5,5" CornerRadius="9,9,9,9" Background="{x:Null}">
            <Grid Margin="0.2,0.2,5.4,4.2">
                <Grid.RowDefinitions>
                    <RowDefinition Height="3*"/>
                </Grid.RowDefinitions>
                <Button Content="one"  TextBlock.Foreground="White"  Grid.Row="1"  Margin="9,9,9,9"                  Height="28" TextBlock.FontSize="15" Name="btn_MartyMang" Click="click_Marty"/>
            </Grid>
        </Border>
    </Grid>
</UserControl>

Second UserControl:
<UserControl x:Class="BenashManage.UserControl.InjuredUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             Height="auto" Width="auto"
             mc:Ignorable="d" RenderTransformOrigin="0,0" FontFamily="Arial" FontSize="14"   TextBlock.Foreground="White">

    <Grid VerticalAlignment="Top" Height="auto" Width="360"  HorizontalAlignment="Right">
        <Border x:Name="BorderAddEdit"  Margin="6,2,6,6"  BorderThickness="5,5,5,5" CornerRadius="9,9,9,9" Background="{x:Null}">
            <Grid VerticalAlignment="Center" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto" MinHeight="20.8"/>
                </Grid.ColumnDefinitions>
                <TextBlock TextWrapping="Wrap" Text=":jjj" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,4,-0.4,3"/>
                <TextBox  Grid.Row="6" TextAlignment="Right" VerticalAlignment="Center" Margin="3,2.8,2.2,2.2" />

            </Grid>
        </Border>

    </Grid>

</UserControl>

MainWindow:
<Window x:Class="BenashManage.MartyrManage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:BenashManage.UserControl"
        Title="MartyrManage" Height="550" Width="550"  Style="{DynamicResource ModalWindowStyle}" Loaded="Window_Loaded_1">
    <Window.CommandBindings>
        <CommandBinding Command="Close"
        Executed="CloseCommand_Executed"/>
    </Window.CommandBindings>
    <Grid >
        <Grid Margin="179,10,10.4,10" HorizontalAlignment="Center" VerticalAlignment="Center"
*******
Height="456" Width="357" Name="MoveToUserControl" ></Grid>
        <Grid Margin="10,71,372.4,67" HorizontalAlignment="Center" VerticalAlignment="Center" Height="338" Width="auto" Name="ButtonManage" >
            <controls:FirstUserControl Margin="0,0,0,92">

            </controls:FirstUserControl>
        </Grid>
    </Grid>
</Window>

A: There are a couple of ways you can do this:
1) Get the parent of the UserControl and then get its children.
(((control1).Parent as Panel).Children[1] as UserControl)

2) Raise an event in the one UserControl which is handled by MainWindow to call the function in the other UserControl.


text:
Q: DDD – How to implement validation against database I'm struggling with a basic issue. The project is in C#, but the issue is general.
I'm following the always valid object principle. As one example I have a product entity that has a mandatory property "ProductCategory". The allowed product categories are user defined and therefore persisted (in a database).
For type safety and better reading I defined Value Objects for various properties to encapsulate the business rules for those types. So there is a ProductCategory class. When creating a ProductCategory instance a factory method checks for example the max length of the string that is passed to the factory before creating the instance. This ensures that each instance of ProdcutCategory is valid.
Simple parameter checks like length are easy and straight forward. My question is where to implement the validation check against the possible values that are persisted. A repository for the allowed values hides the persistence technology and has a method Exists or IsValid.
Option 1) calling the repository from the application layer before calling the factory.
Here the domain layer has no dependency on the repository/infrastructure layer as many advocate. But the factory can't ensure a valid object anymore. It depends on the application layer that the business rule is implemented. Also each command that needs a ProductCategory has to check the repository, which violates DRY.
Option 2) calling the repository from the value object factory
Since factories are part of the domain layer the layer must have access to the repository, which introduces extra coupling. The benefit is that the business validity of ProductCategory is ensured by the object itself and can't be circumvented.
Is there another solution to this dilemma or are there any specific criteria that encourage one or the other option?
Would it be OK, if the factory is programmed against an interface of the repository that is saved in the domain layer and only implemented by the repository in the infrastructure layer?
I have tried to understand the different approaches, but in this case I feel lost.

A: If I understand correctly, your ProductCategory value object takes care of its own invariants, but whether a particular ProductCategory can be assigned to a particular Product is user defined and stored in the database.
You could use DomainEvents:

*

*You assign the Category to the Product in the Domain model.

*The Product adds a DomainEvent "ProductCategoryAssigned".

*Before committing your unit of work a DomainEvent handler performs the check with the databse that the particular Category can be assigned to the Product, and throws if not.

This will prevent the transaction completing with an invalid state.
You could use ValidatorAggregate:
If you really want your Product to be "always valid", even before the unit of work is committed, then you could go for:

*

*Create a ValidCategoriesAggregate and Repository that loads the valid Categories based on Product properties.

*Your Product's "SetCategory" method (or factory method) declares a ValidCategoriesAggregate as a required parameter, forcing your application layer to get one before calling the factory method.

*In your factory method, you can call "ValidCategoriesAggregate.HasCategory(category)" and throw before creating the Product if not present.

Try to avoid injecting repositories into your domain model.

A: Option 2 seems the better one.
Coupling is not an issue in this case, you are coupling your factory to the query needed to check validation, making this dependency explicit.
Watch out that the only way to not have this checks eventual consistent is having all the data inside a single aggregate. Otherwise there's no way to prevent the fact that the same category is created just after you did the check and before you commit your transaction (this is the real reason of aggregates).
Mind about eventual consistency only if there's a real issue in having it, how often a category is created? how often a product is created? how much is the possibility of a conflict to happen? is there some real issue if that happen?
Most of the times being full consistent is much more expensive than accept eventual consistency.


text:
Q: Run command in the environment of a specific systemd service Quite commonly I stumble over issues where a command yields different results, depending wether being run in my user shell or as part of a Systemd service, e.g. via ExecStart.
Is there any way to run a command in a shell that mimics that of a specific Systemd service, e.g. dhcpcd.service as close as possible? Having the same capabilities, env variables and resources available would be a start.
In my current issue I have a hard time replicating the behaviour of ip link in ExectStart of my dhcpcd.service. But this would be super useful in general for debugging systemd services.

A: You can use systemd-run:
# systemd-run ip link
Running as unit: run-r2723175b10a543f38faddda99baa8ca3.service
# journalctl -u run-r2723175b10a543f38faddda99baa8ca3.service
-- Logs begin at Fri 2020-09-11 23:45:32 CEST, end at Fri 2020-09-18 15:33:51 CEST. --
Sep 18 15:33:51 w systemd[1]: Started /usr/bin/ip link.
Sep 18 15:33:51 w ip[3904]: 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
...

Use -E and other flags to 'mimic' the environment of your service.


text:
Q: Why does this Windows Terminal batch file open an extra tab? I'm attempting to run all four sites at the same time within a single tab of Windows Terminal using split panes only. I have the following abp tiered MVC/efcore startup batch file:
wt -M -d "./src/MyProject.Web" cmd /k "title Website & dotnet watch run"; ^
split-pane -V -d "./src/MyProject.IdentityServer" cmd /k "title IdentityServer & dotnet watch run"; ^
move-focus left; ^
split-pane -H -d "./src/MyProject.HttpApi.Host" cmd /k "title ApiHost & dotnet watch run"; ^
move-focus right; ^
split-pane -H -d "./src/MyProject.Web.Public" cmd /k "title Public & dotnet watch run";

When it starts, there are two tabs. One tab correctly has all four sites started and the other is just the startup directory and/or profile. How can I modify the batch file to eliminate the extra useless tab?
This is what I want (only):

A: Ah - the answer was the last semi-colon was causing a new tab. I was reading the documentation and noticed that the (;) was being used to open tabs which makes sense in the middle of the command but the one at the end was extraneous.
This is the correct batch for this task:
wt -M -d "./src/MyProject.Web" cmd /k "title Website & dotnet watch run"; ^
split-pane -V -d "./src/MyProject.IdentityServer" cmd /k "title IdentityServer & dotnet watch run"; ^
move-focus left; ^
split-pane -H -d "./src/MyProject.HttpApi.Host" cmd /k "title ApiHost & dotnet watch run"; ^
move-focus right; ^
split-pane -H -d "./src/MyProject.Web.Public" cmd /k "title Public & dotnet watch run"


text:
Q: Installing gulp with npm i am trying to install gulp via npm on DigitalOcean droplet with following command (with and without sudo):
npm install -g gulp

and im getting errors i cant figure out:
> v8flags@1.0.5 install /root/local/lib/node_modules/gulp/node_modules/v8flags
> node fetch.js

sh: 1: node: Permission denied
npm ERR! Linux 3.13.0-24-generic
npm ERR! argv "node" "/root/local/bin/npm" "install" "-g" "gulp"
npm ERR! node v0.10.33
npm ERR! npm  v2.1.11
npm ERR! code ELIFECYCLE

npm ERR! v8flags@1.0.5 install: `node fetch.js`
npm ERR! Exit status 127
npm ERR!
npm ERR! Failed at the v8flags@1.0.5 install script 'node fetch.js'.
npm ERR! This is most likely a problem with the v8flags package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node fetch.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls v8flags
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /root/local/bin/npm-debug.log

The node install is made according to this guide.

A: I had the same issue, installing an earlier version of gulp worked for me:
sudo npm install -g gulp@3.8.8

Found this here: http://forum.ionicframework.com/t/osx-error-v8flags-after-npm-update-ionic/13905/5
Also tried a bunch of other solutions involving solutions as mentioned here:
NPM cannot install dependencies - Attempt to unlock something which hasn't been locked
None of that worked for me.
The error I was getting was this:
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
/
node.js:815
    var cwd = process.cwd();
                      ^
Error: EACCES, permission denied
    at Function.startup.resolveArgv0 (node.js:815:23)
    at startup (node.js:58:13)
    at node.js:906:3


text:
Q: How to install new QStyle for PyQt? I'm writing a GUI in PyQt4 (and migrating to PyQt5). This is how I start my GUI:
if __name__== '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion')) # <- Choose the style
    myGUI = MyMainWindow("First GUI")
    app.exec_()

Default Styles in PyQt4 :
Apparently, PyQt4 has the following styles:

*

*'Windows'

*'WindowsXP'

*'WindowsVista'

*'Motif'

*'CDE'

*'Plastique'

*'Cleanlooks'
Default Styles in PyQt5 :
PyQt5 has the following styles:

*

*'Windows'

*'WindowsXP'

*'WindowsVista'

*'Fusion'
Custom styles?
None of these styles has proper support for HiDpi displays (4k and the like). For example, scrollbars are too small( see this post: How to resize the scrollbar from a QTextEdit in PyQt?). And I didn't even mention the problems for those people with unsharp eyesight..
Do you know a style (preferably open-source) that provides good support for 4k displays or for people with eyesight problems?
If so, how can one download this style, and install it?
Thank you so much.

A: I got the answer (or let's say a workaround) through another question:
How to make Icon in QMenu larger (PyQt)?
The most straightforward way to create a new QStyle is deriving it from an existing one. PyQt provides the QProxyStyle class for that purpose. Below is the example that I've also given in the How to make Icon in QMenu larger (PyQt)? question. In this example, a custom QStyle is created (derived from "Fusion" style), and the custom style provides very big icons for the QMenu.
import sys
import os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

# Create a custom "QProxyStyle" to enlarge the QMenu icons
#-----------------------------------------------------------
class MyProxyStyle(QProxyStyle):
    pass
    def pixelMetric(self, QStyle_PixelMetric, option=None, widget=None):

        if QStyle_PixelMetric == QStyle.PM_SmallIconSize:
            return 40
        else:
            return QProxyStyle.pixelMetric(self, QStyle_PixelMetric, option, widget)

# This is the main window class (with a simple QMenu implemented)
# ------------------------------------------------------------------
class TestWindow(QMainWindow):
    def __init__(self):
        super(TestWindow, self).__init__()

        # 1. Set basic geometry and color.
        self.setGeometry(100, 100, 400, 400)
        self.setWindowTitle('Hello World')
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(200, 200, 200))
        self.setPalette(palette)

        # 2. Create the central frame.
        self.centralFrame = QFrame()
        self.centralFrame.setFrameShape(QFrame.NoFrame)
        self.setCentralWidget(self.centralFrame)

        # 3. Create a menu bar.
        myMenuBar = self.menuBar()
        fileMenu = myMenuBar.addMenu("&File")

        testMenuItem = QAction(QIcon("C:\\my\\path\\myFig.png"), "&Test", self)
        testMenuItem.setStatusTip("Test for icon size")
        testMenuItem.triggered.connect(lambda: print("Menu item has been clicked!"))

        fileMenu.addAction(testMenuItem)

        # 4. Show the window.
        self.show()

# Start your Qt application based on the new style
#---------------------------------------------------
if __name__== '__main__':
    app = QApplication(sys.argv)
    myStyle = MyProxyStyle('Fusion')    # The proxy style should be based on an existing style,
                                        # like 'Windows', 'Motif', 'Plastique', 'Fusion', ...
    app.setStyle(myStyle)

    myGUI = TestWindow()

    sys.exit(app.exec_())

Just copy-paste the code snippet, and paste it in a *.py file. Of course, you should replace the path to the icon with a valid path on your local computer. Just provide a complete path ("C:..") to be 100% sure that Qt finds the icon drawing.
Try it out, and you should get the following window:


text:
Q: How to implement search and filter in lektor Im trying to implement blog in lektor same like my wordpress site but i want search feature on my blog. What are ways to search and filter the content in lektor.

A: There are several options, but of course none of them directly supported by Lektor:

*

*On swingrock.be I have implemented search functionality with tipue, a Javascript libary.

*On improblog.be I have implemented search functionality with a Google Programmable Search Engine https://developers.google.com/custom-search/
Both work well, but Tipue requires some more fiddling to get right and also makes your build process heavier. With a Google Programmable Search Engine, a possible problem is that you won't have much control over it.


text:
Q: Software to record a Khan Academy style video? Firstly, this question is not a duplicate of anything like https://softwarerecs.stackexchange.com/questions/18650/software-to-make-khan-academy-style-video-tutorials-on-ubuntu , as some may think
Secondly, I tried to record some videos using xournal. I want to have no menus, no UI in the video, canvas only. I also want my video to have 1280x720 dimensions (I have a 1366x768 laptop display and I'd like not to use a second hardware display).
The problem is that I can't use menus without showing them in the screen recording area. What can I do?
I thought that there should be a program which allows user to record working area only.
P.S. I've tried using simplescreenrecorder and it has a video upscale option. And I don't really understand what it does. Is it better to upscale it in the program (record in 854x480 and upscale to 1280x720) or is it better to send the 854x480 to YouTube?


text:
Q: How do we know that our definitions/axioms are not contradictory? Let us assume that we have declared some axioms. Now, we wish to declare a new axiom too. How do we establish that the new axiom is not a consequence of, nor a contradiction to the original set of axioms?
Ditto for definitions. How do we know that the criteria are not contradictory?
For instance,
when creating the set of real numbers axiomatically, our definition says that 1 is not equal to 0, where 1 is the multiplicative identity and 0 is the additive identity.
But, how do we know/prove that 1 not equal to 0 is not a consequence of the field axioms, nor is contradictory to the field axioms?

A: Let's take an example: the axioms of a group. Now we wish to declare a new axiom: all elements commute.
How do we establish that this new axiom is not a consequence of the old ones? By constructing a noncommutative group.
How do we establish that it is not in contradiction to the original ones? By constructing a commutative group.
Here are a couple of other examples, using exactly the same proof scheme.
The parallel postulate is neither a consequence of nor a contradiction to the other axioms of Euclidean geometry: construct the Cartesian coordinate plane with distances and angles etc., to show that it is not in contradiction; and construct the hyperbolic plane to show that it is not a consequence.
The axiom of choice AC is neither a consequence of nor a contradiction to the other axioms ZF of set theory: construct the set theoretic model of constructible numbers to show that AC is not in contradiction to ZF; use forcing to construct models which show that AC is not a consequence of ZF.

A: In a logical approach:
Assume we have a theory $T$ and its set of axioms $\Gamma$, such that $T=\{\varphi|\Gamma \vdash \varphi\}$ (a theory is closed under logical consequence). Now, for some reason, we want to postulate a new axiom to $T$, call it $\psi$. Clearly, we have a new axiom set $\Gamma'=\Gamma \cup \{\psi\}$ and so a new theory $T'=\{\varphi|\Gamma' \vdash \varphi\}$.
Your question is how to proof that:

*

*$T \neq T'$

*$T \cup \{\psi\} \nvdash \bot$

is the case, assuming that $T$ is consistent.
Then:

*

*We need to establish an independence proof of $\psi$ in $T$, that is, we need to show that $T \nvdash \psi$. Mathematicians usually do this using models (see the completeness theorem), and the matter turns out to find an interpretation $\mathcal{M}$ of $T$ where $\psi$ is false. This shows that $T \nvdash \psi$ and that $T \subset T'$, since $T' \vdash \psi$.

*The matter is how to give a consistency proof of $T \cup \{\psi\}$. In other words, this means that adding $\psi$ is consistent with the axiom set of $T$. Since $T$ is consistent, it suffices to show that $T \nvdash \neg\psi$. In this case, we need to show that there is a model $\mathcal{M}$ of $T$ where $\psi$ is true.


text:
Q: MAUI Blazor page transition (via MAUI routing not Blazor routing) - Always load whole app with "Loading..." I want to have MAUI page transition so it feels more native. When I create CounterPage.xaml for "Counter" page and I register it as singleton and then try to navigate with await App.Current.MainPage.Navigation.PushModalAsync(new CounterPage()); it always load whole app with quick flash "Loading..." (like WASM). What am I doing wrong? Is it because of "new CounterPage()"?
Index.razor
@page "/"

Index

<button class="btn btn-secondary" @onclick="NavigateToCounterPage">MAUI navigation Counter</button>

@code {
    async void NavigateToCounterPage()
    {
        await App.Current.MainPage.Navigation.PushModalAsync(new CounterPage());
    }
}

CounterPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:MAUIBlazorMAUIPageTransition.Pages"
             x:Class="MAUIBlazorMAUIPageTransition.CounterPage"
             Title="CounterPage">
    <BlazorWebView HostPage="wwwroot/index.html">
        <BlazorWebView.RootComponents>
            <RootComponent Selector="#app" ComponentType="{x:Type pages:Counter}" />
        </BlazorWebView.RootComponents>
    </BlazorWebView>
</ContentPage>

CounterPage.xaml.cs
namespace MAUIBlazorMAUIPageTransition;

public partial class CounterPage : ContentPage
{
    public CounterPage()
    {
        InitializeComponent();
    }
}

MauiProgram.cs
builder.Services.AddSingleton<CounterPage>();

I tried everything I could think of. Thank you.

A: First, any call with Modal in the name is used to show something that later you will return from. You want to go forward, then be able to go forward again later.
Don't use that call; probably use GoToAsync.

Second, as you suspect, new CounterPage isn't what you want; it constructs a new page, which means it constructs a new BlazorWebView, which (I assume) results in what you see.
You've done half of what is needed to re-use CounterPage:

builder.Services.AddSingleton<CounterPage>();

The other half is to ask for that again.
I'm not finding doc that explains how to get at Maui's ServiceProvider; with help from Gerald Versluis, here is a way to remember ServiceProvider when app starts:
// In app.xaml.cs (the cross-platform App class, where MainPage is set\):
    public static IServiceProvider Services;

    public App(IServiceProvider provider)
    {
        InitializeComponent();

        Services = provider;

        MainPage = ...
    }

Now can access a service as needed:
var page = App.Services.GetRequiredService<CounterPage>();
await App.Current.MainPage.Navigation.GoToAsync(page);


text:
Q: How to display Perl cgi results in on a HTML page instead of .cgi Ok, I confess I'm a designer and know little about backend coding. I have a site with a frontend form created with HTML in WordPress. On submission the form action="/cgi-bin/test.cgi" method="POST"
Test.cgi receives form text and radio option inputs, calculates the values of the user-selected radio options, and displays the results in a table with plain text paragraphs above and below the table.
The browser loads //domain/test.cgi and the minimally formatted content is spread across the entire width of the browser.
Ideally, I would like to display the test.cgi result within a WordPress page so it is consistent with the rest of the site, but I can't figure out how to do this.
Goals:
1 - Create an HTML form with radio answer options for several questions, and have those sent to cgi script - Succes
2 - Create cgi script to calculate values of selected options and display results in a table explaing text content above and below the table (for the user to read), so the user can see them in their browser - Success
3 - Display the script results on a WP page in an iframe (or some other way) for a better visual experience - Fail
Is there a way to do this?
I tried a couple of things:
I thought I might be able to display the results in an iframe so I created a WP page with an iframe
<iframe src="/cgi-bin/test.cgi" width="300" height="450"></iframe>

I tried sending the form (when submitted by the user) to this iframe WP page after submission. I thought that when it loads it might run test.cgi. Didn't work. It may have run the script, but I don't think the form inputs were passed on to test.cgi because it came back with the error used when users don't fill in their email. But, it was in the iframe.
Then I tried to change the test.cgi script so it would send to the WP page in the browser. Basically this:
#!/usr/bin/perl
use strict;
print "Location: /iframe-page-name\n\n";
script stuff here
#end of script

That resulted in server errors.


text:
Q: Create indicator variable for NA values in a dataframe using index values for larger dataset I have a dataframe with around 300 features and 1million observations. I have created a list variable with has the index values that contain 80% of data  as NA values.
My index list has -> 2,4
I want to create an indicator variable for the columns with index 2 ,3 of dataframe to replace NA values with "0" and other values in the column with "1"
I tried to loop through each row but as data is huge its taking long time to loop it.
Input dataframe -> df
row        col1     col2      col3
a          NA      1        3
a        NA      1       NA
a        2     2     NA
Expected output:
row        col1     col2      col3
a          0      1        1
a        0      1       0
a        1     2     0
Can anyone point me to the right direction to achieve this faster.
Thanks,
Renuka

A: You can use dplyr::mutate_at to select the columns you want to change then apply a case_when function to recode NAs as 0 and anything else as 1 which should be a lot quicker than a for loop.
library(dplyr)

df %>%
  mutate_at(vars(col1, col3), funs(
    case_when(
      is.na(.) ~ 0,
      TRUE ~ 1
  )))


text:
Q: What are headphones with 6mm adapters called? I'm looking for a headphone with a 6mm adapter. I have a lenovo thinkpad and it doesn't recognize regular headphones with 3.5mm adapters. I've called the tech support and they told me to get a 6mm one. They said Apple and Sony make such headphones. But couldn't give me exactly one name. So I want to buy one, but don't know it's name (they don't know too). Anybody knows?

A: They're called headphones. :)
You're specifically refering to the larger audio connector that used to be common and now is generally only found on pro-audio systems such as sound boards and the like.
Go to Walmart and get an adapter. It just looks like a larger audio connector with a smaller hole in the back. This will allow you to use your own current headphones with their 3.5mm connector in the 6mm hole.
UPDATE: They are specifically called 6mm Audio Connectors ("Connectors" can also be replaced with "Jacks", though some would argue the Jack is what the Connector plugs in to). As opposed to what you currently have, which is a 3.5mm Audio Connector. It's pretty much the same thing as a USB, mini USB, and micro USB. It's the same connector just in a different size.
6MM isn't very common, and I'm kinda wondering what sort of laptop design you have that incorporates a 6mm jack. Once Walkmen and portable CD players came into common usage, the 3.5mm Audio Connector fits much more easily in the smaller designs.
UPDATE: Wikipedia calls them TRS connectors: http://en.wikipedia.org/wiki/TRS_connector and now I know why I didn't recognize "6mm" right off the bat. I'm used to calling them "quarter inch audio connectors" because they're technically 6.38mm, or 1/4in, in diameter.

A: i can't think of any computer that would use a 1/4 inch TRS plug - certainly not thinkpads. You can get an adaptor at almost any electronics part store.  Quite a few medium-high end headphones come with them as well.
I do believe the newer thinkpads support a 3.5 mm TRRS plug for headphone and mic however.
EDIT: and.. while its not exactly the answer - apparently on windows 7 thinkpads with the combo trrs jacks, you can use a normal headphone by setting your headphones as the default device - plug in your headphones rightclick on the mixer icon, select playback devices, and set your headphones as the default device. It will switch back to the speakers as default when you unplug. HOWEVER, if you want to deactivate the headset again, you have to do it with headphones plugged in.

A: Those would be headphones with a "1/4 inch" plug -- the same plug that plugs into your electric guitar or the headphone jack on your dad's old stereo set.  Converters between the 3.5mm and this size are readily available at a Radio Shack, et al, though they would likely be called "1/8 inch to 1/4 inch" converters.
Keep in mind that "3.5mm" used to be 1/8 inch -- both 3.5mm and 6mm are approximations to the real "nominal" sizes.  (6.5mm would be a closer approximation to 1/4 inch, but it matters not given that there must be some "slop" in the measurement anyway to allow for ease of insertion/removal, and there are no other standard sizes in the same range that might create confusion.)
There is also a (relatively rare) 3/16 inch standard that would amount to about 5mm, and a 3/32 inch standard which is the same as the 2.5mm connector used on some phones.


text:
Q: cakephp tcpd error: Some data has already been output to browser, can't send PDF file on remote server I'm getting the following warning when try to view list_of_holidays.pdf from the remote server:
 Warning (2): Cannot modify header information - headers already sent by (output started
 at /home/aquinto1/app/views/helpers/flash.php:155) [APP/vendors/tcpdf/tcpdf.php, line 8541]
 TCPDF ERROR: Some data has already been output to browser, can't send PDF file

line 155 is the last line in flash.php ie the closing tag for php (?>). Before that it is the code to embedSWF. I don't see anything wrong with that.
However, it is displaying fine on the local server.
I've checked for whitespaces and yet the error is still there.
i'm already using ob_clean before the output.
can someone tell me on what i'm doing wrong. FYI i'm using cakephp with tcpdf.
The following is flash.php
class FlashHelper extends AppHelper {
var $helpers = array('Javascript');
/**
 * Used for remembering options from init() to each renderSwf
 *
 * @var array
 */
var $options = array(
    'width' => 100,
    'height' => 100
);

/**
 * Used by renderSwf to set a flash version requirement
 *
 * @var string
 */
var $defaultVersionRequirement = '9.0.0';

/**
 * Used by renderSwf to only call init if it hasnt been done, either
 * manually or automatically by a former renderSwf()
 *
 * @var boolean
 */
var $initialized = false;

/**
 * Optional initializing for setting default parameters and also includes the
 * swf library. Should be called once, but if using several groups of flashes,
 * MAY be called several times, once before each group.
 *
 * @example echo $flash->init();
 * @example $flash->init(array('width'=>200,'height'=>100);
 * @return mixed String if it was not able to add the script to the view, true if it was
 */
function init($options = array()) {
    if (!empty($options)) {
        $this->options = am($this->options, $options);
    }
    $this->initialized = true;
    $view =& ClassRegistry::getObject('view');
    if (is_object($view)) {
        $view->addScript($this->Javascript->link('swfobject'));
        return true;
    } else {
        return $this->Javascript->link('swfobject');
    }
}

/**
 * Wrapper for the SwfObject::embedSWF method in the vendor. This method will write a javascript code
 * block that calls that javascript method. If given a dom id as fourth parameter the flash will
 * replace that dom object. If false is given, a div will be placed at the point in the
 * page that this method is echo'ed. The last parameter is mainly used for sending in extra settings to
 * the embedding code, like parameters and attributes. It may also send in flashvars to the flash.
 *
 * For doucumentation on what options can be sent, look here:
 * http://code.google.com/p/swfobject/wiki/documentation
 *
 * @example echo $flash->renderSwf('counter.swf'); // size set with init();
 * @example echo $flash->renderSwf('flash/ad.swf',100,20);
 * @example echo $flash->renderSwf('swf/banner.swf',800,200,'banner_ad',array('params'=>array('wmode'=>'opaque')));
 * @param string $swfFile Filename (with paths relative to webroot)
 * @param int $width if null, will use width set by FlashHelper::init()
 * @param int $height if null, will use height set by FlashHelper::init()
 * @param mixed $divDomId false or string : dom id
 * @param array $options array('flashvars'=>array(),'params'=>array('wmode'=>'opaque'),'attributes'=>array());
 *         See SwfObject documentation for valid options
 * @return string
 */
function renderSwf($swfFile, $width = null, $height = null, $divDomId = false, $options = array()) {
    $options = am ($this->options, $options);
    if (is_null($width)) {
        $width = $options['width'];
    }
    if (is_null($height)) {
        $height = $options['height'];
    }
    $ret = '';
    if (!$this->initialized) {
        $init = $this->init($options);
        if (is_string($init)) {
            $ret = $init;
        }
        $this->initialized = TRUE;
    }
    $flashvars = '{}';
    $params =  '{wmode : "opaque"}';
    $attributes = '{}';
    if (isset($options['flashvars'])) {
        $flashvars = $this->Javascript->object($options['flashvars']);
    }
    if (isset($options['params'])) {
        $params = $this->Javascript->object($options['params']);
    }
    if (isset($options['attributes'])) {
        $attributes = $this->Javascript->object($options['attributes']);
    }

    if ($divDomId === false) {
        $divDomId = uniqid('c_');
        $ret .= '

';
    }
    if (isset($options['version'])) {
        $version = $options['version'];
    } else {
        $version = $this->defaultVersionRequirement;
    }
    if (isset($options['install'])) {
        $install = $options['install'];
    } else {
        $install =  '';
    }

    $swfLocation = $this->webroot.$swfFile;
    $ret .= $this->Javascript->codeBlock(
        'swfobject.embedSWF
("'.$swfLocation.'", "'.$divDomId.'", "'.$width.'", "'.$height.'", "'.$version.'",
            "'.$install.'", '.$flashvars.', '.$params.', '.$attributes.');');
        return $ret;
    }

 }
?>

A: Simply do what the error tells you: Check app/views/helpers/flash.php line 155 and see what it is outputting there and fix it. There must be some code that outputs something.

A: Could it be one of the return statements?
if (is_object($view)) {
        $view->addScript($this->Javascript->link('swfobject'));
        return true;
    } else {
        return $this->Javascript->link('swfobject');
    }

$ret .= $this->Javascript->codeBlock(
        'swfobject.embedSWF
("'.$swfLocation.'", "'.$divDomId.'", "'.$width.'", "'.$height.'", "'.$version.'",
            "'.$install.'", '.$flashvars.', '.$params.', '.$attributes.');');
        return $ret;
    }

What other code is on the page calling flash?


text:
Q: SocketIO network/power failure issue How does the server know when the client suddenly dies/disconnects due to network/power failure in SocketIO. Since the client wont have any chance to emit a disconnect event to the server... is there any way to solve this issue?

A: Socket.io has an internal keep alive mechanism. If a client disconnects abruptly, the server doesn't know about it immediately. Instead, when the next keep alive mechanism event will fire and no response will arrive within the time limit, the server will fire disconnect event for that client. The time it takes for the server to detect a client disconnected is affected from the keep alive polling intervals and the timeout limit.
You can change those values using 'pingInterval' and 'pingTimeout', which will change the way engine.io is configured.


text:
Q: How do you filter a layer on a joined table in QGIS? I am attempting to do a join in QGIS between a SQL Server Spatial table and a non-spatial table (on a single integer field).  I was able to add both successfully and make the join, but the query builder dialog only shows the fields from the spatial table.
I also tried setting a feature filter on the non-spatial table before joining to the spatial table, but that filter was not honored (no error, but no affect on the layer).
QGIS version: 2.12.1-Lyon    QGIS code revision: 16760fd
Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
    Feb 10 2012 19:39:15
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)

A: I found these 2 feature requests which seem to confirm that you can't filter the layer on the joined table.  The workaround is to export the layer to shapefile as @wiltomap suggested (provided the data is static).
Not possible to define subset of layer using field from joined table
query / filter on attribute tables with external tables joined


text:
Q: c# BackgroundWorker streamreader repeat every few seconds So I am trying to build an SSH company for my own use that simplifies things for my project ( I am working on an ecommerce website and I have to reindex manually due to cron errors ) so this SSH tool is supposed to make things easier.

I want my program to give me a live result when I execute a command. I currently think that a timer could be the solution, sadly I haven't been successful. not only that but I've tried several things but for some reason the "ProgressChanged"seems to do nothing, atleast not when I'm trying something.
I've read a few threads This one for example,
which explains what and how, but I am not able to do it for myself, so my question was if someone could help me achieve this.
 private void btnUitvoeren_Click(object sender, EventArgs e)
    {
        backgroundWorker.RunWorkerAsync();

        lblStatus.Text = "Process is bezig... een moment geduld aub";
        lblStatus.ForeColor = Color.Orange;
    }

    public void ReindexCommand()
    {
        var cmd = client.CreateCommand(txtBoxInput.Text);
        var result = cmd.Execute();
        this.Invoke(new Action(() =>
        {
            rTxtBoxOutput.Text += result;

            var reader = new StreamReader(cmd.ExtendedOutputStream);
            rTxtBoxOutput.Text += "\n" + reader.ReadToEnd();
        }
         ));
    }

    public void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        ReindexCommand();
    }

    private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    {
                    // Gonna work on this
    }

    private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {

        lblStatus.Text = "Process Compleet";
        lblStatus.ForeColor = Color.Green;
    }

A: I've made a small example for you how to use the background-worker correctly. Remark that all objets that are needed to do the background-stuff should be passed as an argument to the RunWorkerAsync-Method. You can not access your UI-Control in the DoWork-Method:
 private void InitializeBackgroundWorker()
    {
        backgroundWorker = new BackgroundWorker
        {
            WorkerReportsProgress = true
        };
        backgroundWorker.DoWork += backgroundWorker_DoWork;
        backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
        backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
    }
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // get your result-object and cast it to the desired type
    string myStringResult = (string)e.Result;

    // and here we are back in the UI-Thread
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Now we are in the UI-Thread
    // get the passed progress-object and cast it to your desired type
    string myStringObject = (string)e.UserState;

    // do some UI-Stuff...
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // get your argument
    string input = (string)e.Argument;

    // do your async stuff
    // to call the progress-changed handler call
    ((BackgroundWorker)sender).ReportProgress(0, null /*Object to pass to the progress-changed method*/);

    // to pass an object to the completed-handler call
    e.Result = null; // null = your object

}

private void btnUitvoeren_Click(object sender, EventArgs e)
{
    backgroundWorker.RunWorkerAsync(txtBoxInput.Text);  // pass the input-string to the do-work method

    lblStatus.Text = "Process is bezig... een moment geduld aub";
}

If you use .net 4.5 or higher than you should take a look at async-await. If you want I can also make a small example for you how to use this


text:
Q: Remove file from dependency jar using maven I am trying to remove a file from a dependency jar that I am including in my war file in maven. I am deploying the war to JBoss 5.1 and the jar in question contains a persistence.xml file that I don't want.
Here's what is going on:
my-webapp.war
|
`-- WEB-INF
    |
    `-- lib
        |
        `-- dependency.jar
            |
            `-- META-INF
                |
                `-- persistence.xml

When I am building my war, I want to remove persistence.xml Any one have any idea if this can be done easily?

A: Not available out of the box AFAIK, you'll have to use the Maven AntRun plugin after package to do a few dirty things:

*

*unzip the war in a temp directory

*unzip the dependency in another temp directory

*delete the file from the dependency

*zip the temp directory of the dependency back into a jar

*move the dependency back in the temp directory of the war

*zip the temp directory of the webapp back into a war

*delete the temp directory of the dependency

*delete the temp directory of the webapp

The following resources might help

*

*ant task to remove files from a jar

*RE: Removing a file from .jar file

Now, if the problem is that JBoss is deploying the persistence unit defined in the persistence.xml (and you don't want that), there might be a better solution.  It seems that you can declare files to ignore in a jboss-ignore.txt file, for example:
WEB-INF/lib/dependency.jar/META-INF/persistence.xml

The feature is there, but I've never used it.
See

*

*Excluding persistence.xml from deployment

*JBoss5 custom metadata files

A: You can achieve this with the TrueZIP Maven Plugin.
This should work for your use case:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>truezip-maven-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <id>remove-a-file-in-sub-archive</id>
            <goals>
                <goal>remove</goal>
            </goals>
            <phase>package</phase>
            <configuration>
                <fileset>
                    <directory>target/my-webapp.war/WEB-INF/lib/dependency.jar/META-INF</directory>
                    <includes>
                        <include>persistence.xml</include>
                    </includes>
                </fileset>
            </configuration>
        </execution>
    </executions>
</plugin>

Also see the examples.

A: I guess you would have to use the maven shade plugin (see link below)
Either build an Über-jar that includes your dependency minus the persistence-xml or just transform the dependency into something new that does not have the persistence.xml.
This should be the way to go:
http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html
Sean


text:
Q: Enumitem - How to get custom label in line with the margin I have the following very basic question concerning the behavior of enumitem:

How do we make a custom (potentially long) label be in line with the margin?

Take the following MWE.
\documentclass{article}

\usepackage{enumitem}
\usepackage{blindtext}

\begin{document}

\blindtext

\begin{enumerate}[label=Counter \arabic*]
\item \blindtext
\item \blindtext
\end{enumerate}

\end{document}

How do we make the label Counter \arabic* be in line with the margins provided by the file?
[Of course the answer should be robust to the usage of additional packages such as geometry and it should not consist of some trial-and-error with leftmarginin the options.]
Also, a counter that gets at most one digit (from 1 to 9) is fine, just to avoid aligning with potential multiple digits.
Thanks a lot for any feedback.

A: You can have one of these, for instance, depending on where you want to have the list left margin:
\documentclass{article}
\usepackage{geometry}
\usepackage{enumitem}
\usepackage{blindtext}

\begin{document}

\blindtext

\begin{enumerate}[label=Counter \arabic*. , wide=0pt, font=\itshape]
\item \blindtext
\item \blindtext
\end{enumerate}

\begin{enumerate}[label=Counter \arabic*., wide=0pt, leftmargin=*]
\item \blindtext
\item \blindtext
\end{enumerate}

\end{document}


text:
Q: Sending Scheduled Messages through PHP I have a database of scheduled messages. I want to create a service that continuously runs on the web server (see Windows server) and selects the rows that need to be executed by checking the scheduled time. I want this to happen without any human intervention. Can you please help me in regard to this?
I have done a bit of research and the results that turned up were to use cron jobs. But my hosting is not on Linux, and I need to implement it in PHP.

A: 1) Use Windows scheduler.
2) You are able to run php-files with:
C:\Path\to\php.exe -f "C:\Path\to\file.php"

A: I would start with a question: do you absolutely have to have such a job run on the web server? I mean, it might be better to isolate the webserver from the cron-like jobs. All you need there is a way to access the scheduled messages databases from somewhere where you can run scheduled tasks.
If you have to do it from within a windows server, I believe you'll have to use a scheduled task (Although, you have to check it with your hosting provider, most don't allow such services).


text:
Q: Find probability of 3 heads, given there is at least one head The question stated:

Find the probability that, in three tosses of a fair coin, there are three heads, given that there is at least one head.

And provided an answer of:

$\displaystyle\frac {\Pr (HHH)}{1-\Pr (TTT)}=\displaystyle\frac {\displaystyle\frac {1}{8}}{\displaystyle\frac {7}{8}}=\displaystyle\frac {1}{7}$

Which I'm having trouble understanding.

I understand that $\Pr (HHH) = \frac{1}{8}$ and $\Pr (TTT) = \frac{1}{8}$, but I don't see why they divided the top by the complementary?
Could someone please explain this in words?
Please understand that I'm working at an year 12 level, and probably won't understand higher level math jargon.

A: Sample space of three tosses with atleast one head is = {HHH,HHT,HTH,THH,HTT,THT,TTH}=7
Probability of three Head is = $\frac{1}{7}$


text:
Q: How to disable a submit button in javascript after clicking on it? I'm using a button tag to create the button. I want to disable the button when I click on it. But I'm not able to do it. I hope someone here can help me...

A: You need to change the .disabled property of the button.
var btn = document.querySelector("#submit-btn");
btn.disabled = true;

Live example:

var btn = document.querySelector("#submit-btn");
btn.addEventListener('click', function() {
  submit();
});
function submit() {
  btn.disabled = true;
}
#submit-btn {
  width: 100%;
  height: 30px;
  border: solid black .5px;
}
#submit-btn:disabled {
  background-color: gray;
}
<input type="submit" id="submit-btn" value="Submit">

Resourced from this question.

A: HTML <input type="button" id="btn1" onClick="clicked()" value="text">
JS
function clicked(){
    var btn1 = document.getElementById("btn1");
    btn1.disabled = true;
}


text:
Q: Setting data-attributes with loop? (more below) I 'd like to set a data attribute to divs created by looping though an array.
let myLibrary = [ ] //the array

for (const book of myLibrary){
    let cover = document.createElement('div')
    cover.textContent =`title: ${book.title}`
        cover.classList.add('bookStyle')     //adding class for css
        books.appendChild(cover)             //appending to class='books'
    }

adding delete buttons to books:
const addedBooks = document.querySelectorAll('.bookStyle')
    addedBooks.forEach(book => {
        book.addEventListener('click', removeBook)

    let del = document.createElement('BUTTON');
    del.classList.add('delBtn')
    del.textContent = 'x'
    book.appendChild(del)
})

I want to do something like this:
(looping through childs, adding data-attribute)
for (let i = 0; i < myLibrary.length; i++){
        book.setAttribute('data-index', i)
    }

in the end, a list of "books" would look like something like this:

 Title of book

 Title of book

 Title of book

 Title of book

Any help appreciated!

A:

const books = document.querySelectorAll('.bookStyle')
books.forEach((book, i) => book.setAttribute('data-index', i))

 Title of book

 Title of book

 Title of book

 Title of book

A: Thanks for all the replies, this worked for me:
const books = document.querySelectorAll('.bookStyle')
books.forEach((book, i) => book.setAttribute('data-index', i))


text:
Q: Mathematica implementation of Zeilberger's algorithm (previously done in Maple) I have this Mathematica code:
G = (4^(-3 - 2 α) Gamma[5/2 + 3 α] Gamma[2 + 5
            α] ((-54 + α (39 + 5 α (628 + 25 α (161 +
              2 α (-581 + 740 α)))))
                    HypergeometricPFQ[{
                          1, 2/5 + α, 3/5 + α, 4/
                                5 + α, 5/6 + α, 7/6 + α,
                                       6/5 + α}, {13/10 + α,
                                        3/2 + α, 17/10 + α, 19/10 + α, 2 + α, \
21/10 + α}, 27/64] + (347274 + 5 α (-312019 + 25 α (22255 + 8
                    α (-2431 + 925 α)))) HypergeometricPFQ[{2, 2/5 + α, 3/
                    5 + α, 4/5 + α, 5/6 +
                  α, 7/6 + α, 6/5 + α}, {13/10 + α, 3/2 + α,
                    17/10 + α, 19/10 + α, 2 + α, 21/10 + α}, 27/
                    64] + 10 ((-769797 + 25 α (66227 + 4 α (-12843 + 3700
              α))) HypergeometricPFQ[{3, 2/5 + α, 3/5 + α, 4/5 +
                          α, 5/6 + α, 7/6 + α, 6/5 +
                                α}, {13/10 + α, 3/2 + α, 17/
                                      10 + α, 19/10 + α, 2 + α, 21/10 + α}, \
27/64] + 75 ((44133 + 8 α (-6131 + 1850 α)) HypergeometricPFQ[{4, 2/5 + α, 3/
                    5 + α, 4/5 + α, 5/6 + α, 7/6 + α, 6/5 + α}, {13/10 + α, 3/
                  2 + α, 17/10 + α, 19/10 + α, 2 + α, 21/10 + α}, 27/64] +
                      8 ((-7981 + 3700 α) HypergeometricPFQ[{5, 2/
                    5 + α, 3/5 + α, 4/5 + α, 5/6 + α, 7/6 + α,
               6/5 + α}, {13/10 + α, 3/2 +
                          α, 17/10 + α, 19/10 + α, 2 +
                                α, 21/10 + α}, 27/64] +
                                      3700 HypergeometricPFQ[{6, 2/5 + α, 3/5 \
+ α, 4/5 + α, 5/6 + α, 7/6 + α, 6/5 + α}, {13/10 + α, 3/2 + α, 17/
                                      10 + α, 19/10 + α, 2 + α, 21/10 +
                                      α}, 27/64])))))/(3
                                    Gamma[1 + α] Gamma[3 + 2 α]
                                       Gamma[13/2 + 5 α]);

In my J. Phys. A paper, in Figs. 5 and 6 I include two Maple worksheets of Qing-Hu Hou applying the famous Zeilberger ("creative telescoping") algorithm to this expression, with the resultant very interesting set of relations shown in eqs. (1)-(3) of the paper.
Now, I'd like to perform the same analysis and related ones in Mathematica ("my native language"). There is an available Mathematica package to do this, it would seem. However, I haven't gotten it to succeed. Don't know if the output is too large or not, or if I'm doing things exactly right. So, what I want is an implementation in Mathematica of what Qing-Hu Hou accomplished with Maple. (I do have Maple 14--not very recent I think--and did try implementing his package on my machine, but have not really succeeded.)

A: There is also a newer package, HolonomicFunctions, that has an implementation of Chyzak's generalization of Zeilberger's algorithm. To perform the desired task, use the following commands:
smnd = Simplify[
 G /. HoldPattern[HypergeometricPFQ[pl_List, ql_List, x_]] :>
  (Times @@ (Pochhammer[#, k] & /@ pl)) /
  (Times @@ (Pochhammer[#, k] & /@ ql)) * x^k / k!];

CreativeTelescoping[smnd, S[k] - 1, S[α]]

As answer, you get exactly the same output as Hou's Maple package.


text:
Q: How to include other configuration files in web.xml I need to define many servlets, but I don't want to write the configuration all in the web.xml.
Can I define some servlet configuration files, and include them in web.xml? Or is there any other way to split a web.xml to multi files?

A: The Servlet 3.0 specification provides a new annotation, @WebServlet, that may be used to declare servlets in the code without the need for the web.xml. See Section 8.1.1 of the Servlet 3.0 specification and review the javadoc for more details.
@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
    //...
}

Additionally, Servlet 3.0 introduced the concept of web fragments, which addresses your second question about splitting the web.xml into multiple files. These fragments can contain a portion (or all) of the web deployment descriptor by including a META-INF/web-fragment.xml file and/or servlet annotations in jar files within your web module's WEB-INF/lib directory. See Section 8.2 of the Servlet 3.0 specification for more details.

A: The Servlet 3.0 specification allows for declaring servlets through Java annotations - so no entries required within the web.xml file.  Other than that, I'm not aware of any "include" functionality.


text:
Q: Duplicated button doesnt change its text i am implementing a tic tac toe game but with special specification that when i press a button it open a new DIV of the game and disable the old one and the button pressed must be changed in both DIV and so on but when i click button it change the original div not the one i want it to be updated so any help ?
Thanks in adance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

        <input type="submit" class="btn" name="1" id="1" value="Submit" />
        <input type="submit" class="btn" name="2" id="2" value="Submit" />
        <input type="submit" name="3" class="btn" id="3" value="Submit" />

        <input type="submit" name="3" class="btn" id="4" value="Submit" />
        <input type="submit" name="3" class="btn" id="5" value="Submit" />
        <input type="submit" name="3" class="btn" id="6" value="Submit" />

        <input type="submit" name="3" class="btn" id="7" value="Submit" />
        <input type="submit" name="3" class="btn" id="8" value="Submit" />
        <input type="submit" name="3" class="btn" id="9" value="Submit" />

A: The problem is duplicate IDs. ID's must be unique use classes instead.
jQuery
    var id = this.id;
    if (c % 2 === 0) {
        $("." + id).val("X");
        $("." + id).prop("disabled", true);
    } else if (c % 2 !== 0) {
        $("." + id).val("O");
        $("." + id).prop("disabled", true);
    }

HTML
    <input type="submit" class="btn 1" name="1" id="1" value="Submit" />
    <input type="submit" class="btn 2" name="2" id="2" value="Submit" />
    <input type="submit" name="3" class="btn 3" id="3" value="Submit" />

    <input type="submit" name="3" class="btn 4" id="4" value="Submit" />
    <input type="submit" name="3" class="btn 5" id="5" value="Submit" />
    <input type="submit" name="3" class="btn 6" id="6" value="Submit" />

    <input type="submit" name="3" class="btn 7" id="7" value="Submit" />
    <input type="submit" name="3" class="btn 8" id="8" value="Submit" />
    <input type="submit" name="3" class="btn 9" id="9" value="Submit" />

DEMO


text:
Q: Django template extension; django.template.exceptions.TemplateSyntaxError: Invalid block tag when trying to load i18n from a base template I have a base.html template file for Django (4.1.2) as:
<!DOCTYPE html>

    {% load static %}
    {% load i18n %}

    <meta charset="utf-8">
      {% block title %}
        <title>My Title</title>
      {% endblock %}

    {% block content %}

    {% endblock content %}

and an index.html page, at the same level in the /templates folder of my app, extending the base one, as:
{% extends "base.html" %}

{% block content %}

My Django project

{% trans "Admin" %}

{% trans "Foo" %}

{% endblock %}

But when I browse the latter page, the server returns the following error:
django.template.exceptions.TemplateSyntaxError:
  Invalid block tag on line 6:
    'trans', expected 'endblock'.
    Did you forget to register or load this tag?

But if I simply add {% load i18n %} at the second line of the index.html, the page loads fine.
What is wrong with the loading of the base template in the index.html page?
This doesn't help as it doesn't differentiate the behaviour encountered here with the fact that loading, e.g. {% load django_bootstrap5 %} in base.html is working very well through all child pages without having to ever specify it again in those pages.

A: you must always load any tag library in each page if you want to use it.Even if the you have already load it in parent page.

A: I found a way to globally enable i18n in settings.py:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
        'builtins': ['django.templatetags.i18n'], # <---- add this line
    },
]

Then, apparently, you no more need to load this template tag in every html template. It is not even necessary in base.html anymore.
More on templates built-in backends: https://docs.djangoproject.com/en/4.1/topics/templates/#module-django.template.backends.django
And on writing {% load i18n %} only once: https://code.djangoproject.com/ticket/1193
Inspired by: Load a Django template tag library for all views by default


text:
Q: Dynamic database table creation in ASP.Net Core 2 with Entity Framework I have problem on dynamic table or user will create table in the web application and will insert record after.How i can create a model on runtime without knowing number of columns inputted by user. Is EF can support this problem ?
Example
I have 1 textbox for tablename and then textbox2 for number columns
after inputting number of columns it will dynamically create textbox for column names and then user will save it.

A: Not sure, but I am afraid you cannot do that. But you can simulate it:
Classes for CodeFirst:
public class Table
{
    public int Id{get;set;}
    public string Name {get;set;}
    public ICollection<Column> Columns {get;set;}
    public ICollection<Row> Rows {get;set;}
}

public class Row
{
    public int Id{get;set;}
    public ICollection<ColumnValueBase> Values {get;set;}
}

public abstract class Column
{
    public int Id {get;set;}
    public Column Column {get;set;}
}

public abstract class ColumnValue
{
    public int Id {get;set;}
}

public class IntColumn : Column
{
    public IntColumnValue IntValue {get;set;}
}

// other types of columns and values

public class TablesContext : DbContext
{
    public DbSet<Table> Tables {get;set;}
}

I used similar approach in my project and it works pretty well. Adding new types of columns is easy through migrations. Only problem may be performance - this is my question about it, but EF Core is supposed to be faster.


text:
Q: How to make C++ logging more concise I am using log4cxx for logging in C++ projects. Currently, my log calls look like
LOG4CXX_INFO(log4cxx::Logger::getRootLogger(), "parsed " << lc << " lines");

This is still too verbose and hard to remember. Ideally, a logging statement would look similar to
log.debug("parsed %d lines", lc)

a) What can I do to get more concise logging statements?
b) Is it possible to use a printf-like syntax?

A: You can use the Boost.Format library http://www.boost.org/doc/libs/1_52_0/libs/format/doc/format.html
PS. C++11 convenience functions example:
#include <boost/format.hpp>
#include <iostream>

void
log (const boost::format &fmt)
{
  std::cout << fmt;
}

template<typename T, typename... Args>
void
log (boost::format &fmt, const T &v, Args... args)
{
  log (boost::format (fmt) % v, args ...);
}

template<typename... Args>
void
log (const char *fmt, Args... args)
{
  boost::format f (fmt);
  log (f, args ...);
}

int
main ()
{
  log ("some number %1% and some other %2%", 1, 3.5f);
}


text:
Q: How to calculate number of Orders for given date range Need some help in writing sql query to capture number of active Orders between date range on month wise grouping. i.e if the user selected 2018-01-01 to 2019-12-31, I have to show number of active orders on a month basis i.e total 12 records.
I'm querying against Order Table whose schema looks like below
OrderID    CustomerFirstName   PurchaseDate   OrderEndDate
1           XYZ                2018-01-01     9999-12-31
2           ABC                2018-02-02     2018-06-30
3           PQR                2018-06-01     2018-06-30
4           GHI                2018-01-01     2018-02-28

Order EndDate 9999-12-31 is never ending order.All considers has existing order in all date ranges.
From My UX, if I select Jan to Dec... Results should
JAN   ==> 2 orders
Feb   ==> 3 Orders => Order ID are 1,2,4.
Reason for Month FEB Order ID : 1,2,4 are consider as Active orders because
their end dates are falling in FEB.
For example : ORDER ID : 1 having End date has 9999-12-31 which is never ending. Always Active orders in all the date range
Order ID : 2 having End Date has 2018-06-30 so till June he should be considered has Active order for every Month
Order ID : 4 having end date has 2018-02-28 for Feb month OrderID is active Orders
Expected Output
Month     NoOfOrders
Jan         2
Feb         3
Month  NoOfOrder
Jan      2
Feb      3

A: Create a year-month table (inspired from this answer) and join the Order table against it
DECLARE @DateFrom datetime, @DateTo Datetime
SET @DateFrom = ' 2018-01-01'
SET @DateTo = '2018-12-31'

SELECT YearMonth, COUNT(*)
FROM (SELECT CONVERT(CHAR(4),DATEADD(MONTH, x.number, @DateFrom),120) + '-' + CONVERT(CHAR(2),DATEADD(MONTH, x.number, @DateFrom),110) As YearMonth,
             CONVERT(DATE, CONVERT(CHAR(4),DATEADD(MONTH, x.number, @DateFrom),120) + '-' + Convert(CHAR(2),DATEADD(MONTH, x.number, @DateFrom),110) + '-01', 23) fulldate
      FROM master.dbo.spt_values x
      WHERE x.type = 'P'
        AND x.number <= DATEDIFF(MONTH, @DateFrom, @DateTo)) YearMonthTbl
LEFT JOIN  Orders o ON YEAR(fulldate) >= YEAR(purchaseDate) AND  MONTH(fulldate) >= MONTH(purchaseDate) and fulldate < = enddate
GROUP BY YearMonth

I decided to include also year in output if the input range crosses into a new year
Here is the output for completeness
2018-01 2
2018-02 3
2018-03 2
2018-04 2
2018-05 2
2018-06 3
2018-07 1
2018-08 1
2018-09 1
2018-10 1
2018-11 1
2018-12 1

A: First Part - Handling records with orderenddate= '9999-12-31'
You can try like following. By putting a OR condition for orderenddate = '9999-12-31' will make sure that never ending records will eppear in all the searchs if the strat date is within the boundary.
SELECT *
FROM   [order]
WHERE  purchasedate >= @startdate
       AND ( orderenddate <= @enddate
              OR orderenddate = '9999-12-31' )

Second Part :

sql query to capture number of active Orders between date range on
  month wise grouping.

For month wise grouping you can try like following.
  ;WITH numbersequence( number )
     AS (SELECT 1 AS Number
         UNION ALL
         SELECT number + 1
         FROM   numbersequence
         WHERE  number < 12)

SELECT Sum(ct) ActiveOrderCount,
       number  AS [month]
FROM   (SELECT number,
               CASE
                 WHEN c.number >= Month(purchasedate)
                      AND c.number <= Month(orderenddate) THEN 1
                 ELSE 0
               END ct
        FROM   @order
               CROSS JOIN numbersequence c
        WHERE  purchasedate >= @startdate
               AND ( orderenddate <= @enddate
                      OR orderenddate = '9999-12-31' )) t
GROUP  BY number

Online Demo
Output
+------------------+-------+
| ActiveOrderCount | Month |
+------------------+-------+
| 2                | 1     |
+------------------+-------+
| 3                | 2     |
+------------------+-------+
| 2                | 3     |
+------------------+-------+
| 2                | 4     |
+------------------+-------+
| 2                | 5     |
+------------------+-------+
| 3                | 6     |
+------------------+-------+
| 1                | 7     |
+------------------+-------+
| 1                | 8     |
+------------------+-------+
| 1                | 9     |
+------------------+-------+
| 1                | 10    |
+------------------+-------+
| 1                | 11    |
+------------------+-------+
| 1                | 12    |
+------------------+-------+

Assumption : Start Date and End Date falls under same year. Otherwise you need to put year condition also.


text:
Q: How to hide Material-Ui Mini variant Drawer on mobile view How can I hide Mini variant drawer on mobile view. I don't want the side bar on mobile view. It should be hidden in mobile view.
I am following the official doc Original Code

Remove in mobile View

A: change styles to do it:
drawerPaperClose: {
        overflowX: 'hidden',
        transition: theme.transitions.create('width', {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),
    width: theme.spacing.unit * 7,
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing.unit * 9,
    },
    [theme.breakpoints.down('sm')]: {
      width: 0,
      display:'none',
    },
  },
  nested: {
    paddingLeft: theme.spacing.unit * 4,
  },

A: const drawerWidth = 240;

const styles = theme => ({
  root: {
    display: 'flex',
  },
  toolbar: {
    paddingRight: 24, // keep right padding when drawer closed
  },
  toolbarIcon: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: '0 8px',
    ...theme.mixins.toolbar,
  },
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginLeft: 12,
    marginRight: 36,
  },
  menuButtonHidden: {
    display: 'none',
  },
  title: {
    flexGrow: 1,
  },
  drawerPaper: {
    position: 'relative',
    whiteSpace: 'nowrap',
    width: drawerWidth,
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
    [theme.breakpoints.up('md')]: {
      position: 'relative',
    },
  },
  drawerPaperClose: {
    overflowX: 'hidden',
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    width: theme.spacing.unit * 7,
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing.unit * 9,
    },
  },
  appBarSpacer: theme.mixins.toolbar,
  content: {
    flexGrow: 1,
    padding: theme.spacing.unit * 3,
    height: '100vh',
    overflow: 'auto',
  },
  chartContainer: {
    marginLeft: -22,
  },
  tableContainer: {
    height: 320,
  },
});

class Dashboard extends React.Component {
  state = {
    open: false,
    auth: true,
    anchorEl: null,
  };

  handleDrawerOpen = () => {
    this.setState({ open: true });
  };

  handleDrawerClose = () => {
    this.setState({ open: false });
  };

  handleChange = event => {
    this.setState({ auth: event.target.checked });
  };

  handleMenu = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  handleClose = () => {
    this.setState({ anchorEl: null });
  };

  render() {
    const { classes, siteTitle, children,theme } = this.props;
    const { auth, anchorEl } = this.state;
    const open = Boolean(anchorEl);
    return (
      <React.Fragment>
        <CssBaseline />

          <AppBar
            position="absolute"
            className={classNames(classes.appBar, this.state.open && classes.appBarShift)}
            style={{ background: '#051745', boxShadow: 'none' }}
          >
            <Toolbar disableGutters={!this.state.open} className={classes.toolbar}>
              <IconButton
                color="inherit"
                aria-label="Open drawer"
                onClick={this.handleDrawerOpen}
                className={classNames(
                  classes.menuButton,
                  this.state.open && classes.menuButtonHidden,
                )}
              >
                <MenuIcon />
              </IconButton>
              <Typography variant="title" color="inherit" noWrap className={classes.title}>
                {siteTitle}
              </Typography>
              <IconButton color="inherit">
                <Badge badgeContent={4} color="secondary">
                  <NotificationsIcon />
                </Badge>
              </IconButton>

                <IconButton
                  aria-owns={open ? 'menu-appbar' : null}
                  aria-haspopup="true"
                  onClick={this.handleMenu}
                  color="inherit"
                >
                  <AccountCircle />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={anchorEl}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={open}
                  onClose={this.handleClose}
                >
                  <MenuItem onClick={this.handleClose}>Profile</MenuItem>
                  <MenuItem onClick={this.handleClose}>My account</MenuItem>
                </Menu>

            </Toolbar>
          </AppBar>

          <Hidden mdUp>
          <Drawer
            variant="temporary"
            onClose={this.handleDrawerClose}
            classes={{
              paper: classNames(classes.drawerPaper, !this.state.open && classes.drawerPaperClose),
            }}
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
            open={this.state.open}
          >

              {siteTitle}
              <IconButton onClick={this.handleDrawerClose}>
                <ChevronLeftIcon />
              </IconButton>

            <Divider />
            <List >{mainListItems}</List>
            <Divider />
            <List>{secondaryListItems}</List>
          </Drawer>
        </Hidden>
        <Hidden smDown implementation="css">
          <Drawer
            variant="permanent"
            classes={{
              paper: classNames(classes.drawerPaper, !this.state.open && classes.drawerPaperClose),
            }}
            open={this.state.open}
          >

              {siteTitle}
              <IconButton onClick={this.handleDrawerClose}>
                <ChevronLeftIcon />
              </IconButton>

            <Divider />
            <List >{mainListItems}</List>
            <Divider />
            <List>{secondaryListItems}</List>
          </Drawer>
          </Hidden>

            {children}

      </React.Fragment>
    );
  }
}

Dashboard.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
};

export default withStyles(styles)(Dashboard);

A: All you need to do is change the styles of th drawerClose object.
THE CODE IN THE DOCUMENTATION
  drawerClose: {
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: 'hidden',
    width: theme.spacing(7) + 1,
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing(9) + 1,
    },
    [theme.breakpoints.down('sm')]: {
      width: theme.spacing(0) + 1,
    },
  },

The below is the new code, where you update the breakpoints by adding the .down('sm') method. Which modifies the styles for all screens below the specified 'sm' breakpoints.
[theme.breakpoints.down('sm')]: {
      width: theme.spacing(0) + 1,
    },

THE NEW UPDATED CODE:
  drawerClose: {
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: 'hidden',
    width: theme.spacing(7) + 1,
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing(9) + 1,
    },
    // New Code.
    [theme.breakpoints.down('sm')]: {
      width: theme.spacing(0) + 1,
    },
  },


text:
Q: Google Charts Showing Blank White Page I am building a google line chart. I have inserted my data via php and this is what the html source looks like. I can't for the life of me find why this is just showing a white page. I put the word test in there to make sure it is loading and "test" shows up but nothing else. Apache logs show no errors. I appreciate any help or suggestions!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="refresh" content="180" >

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>

test

A: Bad syntax. Ln
        var data = new google.visualization.DataTable(
should be
        var data = new google.visualization.DataTable();
and then remove
        );
after the data


text:
Q: VueJS+Spring change sub-path I need start my jar file on sub-path "/new"
If i change  publicPath: '/new/', in my vue.config.js
After build java in index in java i have src="/new/static/js/app.c5c5f2e6.js"
and this path dont work, because i dont have path "/NEW/"
And in console i get error
Refused to apply style from 'http://localhost:8098/new/static/css/app.61cdbd8f.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

because app.61cdbd8f.css in to http://localhost:8098/static/css/app.61cdbd8f.css (without new)
How i can change path with / to /new/


text:
Q: How to understand this "I not only" structure I read this sentence from a book.
"I not only lost all my money - I also lost my passport".
Why it's not "I am not only.." or "I don't only..".
I don't know how to describe this kind of grammar, couldn't get much help from google.
Could you please explain this to me?
Thanks a lot.

A: That's a good question.
The answer, I think, is that not only acts as a unit. I can't think of another adverb which can take not in this way.*
The regular form I didn't only lose all my money is also possible.
*Constructions with not + adverb are common when there is no verb, as in "Do you always go that way?" "Not always"; or "He finished the job, but not quickly". But when there is a verb, the negative normally goes to the verb in the usually way "I don't always go that way"; "He didn't finish quickly".
Edit: I have thought of one more example: not infrequently. But neither often nor frequently works this way.

A: The fullest version of this coordinate pair is not only . . . but also. A slightly more economical version of the sentence would be "I lost not only all my money but also my passport"—since subject and verb remain the same, one can economize here by zeugma.

A: It's a logical negation. Removing not, we get I only lost all my money - I also lost my passport, which is not correct; Adding the also invalidates the only. So, adding the not makes the sentence acceptable.
In common usage, this structure is used to reinforce the positive or negative aspect of the situation, as in not only did one bad thing happen, but another did, so it's even worse as opposed to two bad things happened.


text:
Q: Any way of detect mouse coordinate in Excel without using Win API I want to find out if it is possible to track the coordinates of the mouse cursor in Excel Worksheet or in User Form WITHOUT using the Win Api?
Ideally, without connecting Avaliable References.

A: Userform controls have the MouseMove event (as well as MouseDown/Up) which can track the X & Y coordinates of the mouse. The issue is you need to apply this to all controls that are on the form you wish it to work within. Doing this though, the coordinates given are relative to the control the mouse is over. In order to remedy that, you would need to add calculations for each controls position and add/subtract from the coordinates to get the real position of the mouse on the form.
Here's a little example of it:

Edit:
I actually just realised you just need to use the .Left or .Top values of the control and add it to the X or Y value to get the real position relative to the form/frame top left.


text:
Q: Safely Use Explicit Address Assignment Is there a best practice of any type in regards to using an explicit number for a pointer address safely? By that I mean the following example:
#define BASE_ADDRESS  0x10000

typedef struct my_var_list
{
   int var1;
   int var2;
} my_function_list;

my_var_list *MyVars;
MyVars = BASE_ADDRESS;    // Set the address of MyVars to be 0x10000

This may demonstrate some ignorance on my part, but how can you guarantee that 0x10000 is not being used by something else at that time and you aren't causing memory corruption? If you can't assume that, is there any safe way of hard defining an address to use?

A: the assumption is that if you KNOW its 0x10000 then you also know when that is true. Typically this is for hardware stuff (I know io port 5 is at 0x10000) or low level OS kernel (boot image is loaded at 0x10000 by another part of kernel). If you arent writing either of those things then you shouldnt be doing hard coded addresses

A: If you're running under Windows, the VirtualAlloc function allows you to specified a recommended base address. If the requested region is free, VirtualAlloc will use that. If, however, the region is in use, VirtualAlloc will select a different base address.
For linux (and maybe unix), you can use the mmap function the same way - it'll try your given address first before picking a different one.


text:
Q: SVG transformation not working in Web Version of a React-Native-SVG app, but working in mobile? IM a having a very WEIRD bug here.
Im doing an application where the user can zoom in and out and draw some stuff inside a SVG screen using react-native-svg.
In my mobile application running on a simulator the transformation works perfectlly.
In the same app, running as a webapp (expo start --web) no transformation its never applied. Even If I hard code it on the matrix.
This is part of my code that matters:
export default class DrawView extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      currentMax: 0,
      currentPoints: [],
      reaction: new Reaction(),
      zoom: 1,
      left: 0,
      top: 0,
      transformerMatrix: { a: 1, e: 1, c: 0, f: 0 },
      startDrawing: false,
      seconds: 0,
      email: '',
      userSentData: false,
      showPopUp: false
    };

This is a simple transformer Matrix. On my render method I have:
 <View style={{ flex: 1 }}>
    <View
      //onLayout={this._onLayoutContainer}
      style={[
        styles.drawContainer,
        this.props.containerStyle,

        { width: this.props.width, height: this.props.height }
      ]}
    >
      <View {...this._panResponder.panHandlers}>
        <Svg
          style={styles.drawSurface}
          width={this.props.width}
          height={this.props.height}
        >
          <G
            transform={{
              translateX: this.state.transformerMatrix.c,
              translateY: this.state.transformerMatrix.f,
              scale: this.state.transformerMatrix.a
            }}
          >
            {/* <Grid /> */}
            <Image
              width={'100%'}
              height={'100%'}
              preserveAspectRatio="xMidYMid slice"
              opacity="1"
              href={require('../assets/images/FinalEarthGifPaletaWeb-8192x8192.gif')}
              clipPath="url(#clip)"
            />

If I change my transformerMatrix.a to 1.3 for instance. The image its zoomed by 30%. On Simulator it makes the transformation. But in the webApp nothing happens.

As you can see. Nothing its zoomed in on the webapp application, instead of the iOS one.
Does anyone know something related with react-native-svg not being transformed when in webApp?

A: The answer for that, after trying A LOT of stuff is that, theres a bug on the library on the transform property here:
<G
  transform={{
    translateX: this.state.transformerMatrix.c,
    translateY: this.state.transformerMatrix.f,
    scale: this.state.transformerMatrix.a
  }}
>

This transform property, on iOS works well, but in web NEED to be a string:
If we change the method for a String interpolation and pass to the property, it works:
<G
  transform=`
    translateX: ${this.state.transformerMatrix.c},
    translateY: ${this.state.transformerMatrix.f},
    scale: ${this.state.transformerMatrix.a}
  `
>

Its a very tricky solution. I sent a PR to fix it on the native-svg library.


text:
Q: ASP.NET MVC 2 HiddenField is empty? Hi,
I have a ViewClass that contains a CI property (Guid), to keep track of this CI property I have added a hidden value for it like this :
<%: Html.HiddenFor(model => model.CI)%>

This does however render an empty hidden field, i have also tried :
<%: Html.Hidden("CI", Model.CI)%>

But with the same result.
When just typing :
<%: Model.CI %>

The Guid is printed for example like this : 5f7a1f53-9f90-4b77-aad4-64e835662efc
So why is this not working?
Edit1 :
This workes fine, but I do not see why HiddenFor is not working?
<input type="hidden" name="CI" value="<%: Model.CI %>" />


text:
Q: Creating reusable UI components In jQuery, you can create reusable UI components. In AngularJS, I understand that using Directives is the equivalent way of doing this. The Directive syntax includes a Link property where you can manipulate the DOM. But this is where I get confused. AngularJS is meant to avoid manipulating the DOM because AngularJS manipulates the DOM internally, so why would you do this? Is there a better way of doing this without actually having to manipulate the DOM?

A: Where did you get the idea that all DOM manipulation is a bad thing? How would anything ever get rendered if the DOM wasn't being manipulated? It's a bad idea to mess with the DOM in controllers or outside of Angular's context but in directives you're plugging into Angular and can safely make DOM changes without breaking anything.
You're basically asking how to manipulate the DOM without manipulating the DOM which makes no sense.
Go ahead and do your stuff in the link-function, it's perfectly fine.

A: At some point you will have to engage in manipulating the DOM in some way or another, but for 95% of all cases you can stick to angular's built in directives, such as ng-if, ng-hide/show, ng-switch, ng-repeat etc...
But these are all directives, so angular isn't manipulating the DOM "internally", it does it through directives, just as it's meant to do...
And keep in mind that in your directive templates, you can use those other directives, so your directive can focus on it's own task.

A: Use the $new(isolate) method from the $rootScope to create reuseable UI components. Set isolate to true. Don't manipulate anything outside of your UI component:

If true, then the scope does not prototypically inherit from the
  parent scope. The scope is isolated, as it can not see parent scope
  properties. When creating widgets, it is useful for the widget to not
  accidentally read parent state.

https://docs.angularjs.org/api/ng/type/$rootScope.Scope