text:
Q: Cómo detectar un movimiento horizontal sobre una superficie plana con accelerometer en Javascript es posible con Javascript, en una superficie plana moviendo un movil, saber en qué dirección se está moviendo?
quiero hacer una secuencia de imágenes que cambia cuando voy a mover el
móvil a la derecha o a la izquierda (sobre una tabla plana).
Muchas gracias!
Codigo Script:
(function($) {
    jQuery.shake = function(options) {

        var opts = jQuery.extend({},
        jQuery.shake.defaults, options);

        if (opts.debug !== "") {
            var debug = $(opts.debug);
            debug.append('x: 0
');
            debug.append('y: 0
');
            debug.append('z: 0

');

            debug.append('shake: 0
');
            debug.append('shakeaccum:
');
            debug.append('debug:
');
        }

        // initialize acceleration variables
        var ax = 0;
        var ay = 0;
        var az = 0;
        var axa = 0;
        var aya = 0;
        var aza = 0;

        // initialize misc internal variables
        var shakecount = 0;
        var shakeaccum = 0;
        var curtime = new Date();
        var prevtime = new Date();
        var timeout = false;

        // detect whether acceleration is supported
        if (window.DeviceMotionEvent === undefined) {
            if (opts.supported !== "") {
                $(opts.supported).html("Your browser does not support Device Orientation and Motion API. Try it on an iPhone, iPod or iPad with iOS 4.2+.");
            }
        } else {
            window.ondevicemotion = function(event) {
                // get acceleration values
                var acc = event.accelerationIncludingGravity;
                ax = acc.x;
                ay = acc.y;
                az = acc.y;

                // high pass-filter to remove gravity

                axa = ax - ((ax * opts.hf) + (axa * (1.0 - opts.hf)));
                aya = ay - ((ay * opts.hf) + (aya * (1.0 - opts.hf)));
                aza = az - ((az * opts.hf) + (aza * (1.0 - opts.hf)));

            **texto en negrita**
                var beenhere = false;
                var shake = false;
                if (beenhere) {
                    return;
                }
                beenhere = true;
                if (Math.abs(ax - 2 * axa) > opts.violence * 1.5 || Math.abs(ay - 2 * aya) > opts.violence * 2 || Math.abs(az - 2 * aza) > opts.violence * 3 && timeout === false) {
                    shakeaccum += 1;
                }

                // detect shake event (several shakes)
                curtime = new Date();
                var timedelta = curtime.getTime() - prevtime.getTime();
                $('#console').html(timedelta);

                if (timeout) {
                    if (timedelta >= opts.debounce) {
                        timeout = false;
                    } else {
                        timeout = true;
                    }
                    shakeaccum = 0;
                }

                if (shakeaccum >= opts.shakethreshold && timeout === false) {
                    shakecount += 1;
                    $("#shake").html(shakecount);
                    prevtime = curtime;
                    timeout = true;
                    opts.callback.call();
                }
                beenhere = true;
            };
        }
        if (opts.debug !== "") {
            setInterval(function() {
                // output debug data
                $('#x').html(Math.abs(ax - 2 * axa).toFixed(1));
                $('#y').html(Math.abs(ay - 2 * aya).toFixed(1));
                $('#z').html(Math.abs(az - 2 * aza).toFixed(1));
                $('#shakeaccum').html(shakeaccum);
            },
            10);
        }
    };
})(jQuery);

// plugin default options
jQuery.shake.defaults = {
    // debug div id
    debug: "debug",

    // not supported message div
    supported: "",

    // single shake sensitivity
    violence: 1.0,

    // high-pass filter constant
    hf: 0.2,

    // number of single shakes required to fire a shake event
    shakethreshold: 1,

    // delay between shake events (in ms)
    debounce: 1000,

    // anonymous callback function
    callback: function() {}
};

A: Te recomiendo que veas este post: Javascript Accelerometer Demo and Source.
En el mismo se muestra un ejemplo que hace uso de DeviceMotionEvent:
window.ondevicemotion = function(event) {
    var accelerationX = event.accelerationIncludingGravity.x;
    var accelerationY = event.accelerationIncludingGravity.y;
    var accelerationZ = event.accelerationIncludingGravity.z;
}


text:
Q: Loading global event listener JBPM I have jbpm system (wildfly+kie-server+workbench) and I want to use one global ProcessEventListener within the system. I've created simple process event lestener:
public class SimpleProcessEventListener implements ProcessEventListener {

    public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
        System.out.println("Before Node triggered: " + event.getNodeInstance().getNodeName());
    }

    ...

    public void afterVariableChanged(ProcessVariableChangedEvent event) {
        System.out.println("After Variable changed: " + event.getVariableId());
    }

My pom.xml:
<modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>simple-process-event-listener</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.jbpm</groupId>
            <artifactId>jbpm-flow</artifactId>
            <version>6.5.0.Final</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

When I add it as deployment dependency and declare it as event listener in my jbpm project via workbench everything works fine.
But now I have a lot of projects and It's uncomfortable to attach the event listener to every project. So I've created new module in wildfly:
<module xmlns="urn:jboss:module:1.1" name="com.listener">

    <resources>
        <resource-root path="simple-process-event-listener-1.0.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="org.slf4j"/>
    </dependencies>
</module>

Created deployment-descriptor.xml server level:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<deployment-descriptor xsi:schemaLocation="http://www.jboss.org/jbpm/deployment-descriptor.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <persistence-unit>org.jbpm.domain</persistence-unit>
    <audit-persistence-unit>org.jbpm.domain</audit-persistence-unit>
    <audit-mode>JPA</audit-mode>
    <persistence-mode>JPA</persistence-mode>
    <runtime-strategy>SINGLETON</runtime-strategy>
    <marshalling-strategies/>
    <event-listeners>
        <event-listener>
            <resolver>reflection</resolver>
            <identifier>org.example.SimpleProcessEventListener</identifier>
            <parameters/>
        </event-listener>
    </event-listeners>
    <task-event-listeners/>
    <globals/>
    <work-item-handlers/>
    <environment-entries/>
    <configurations/>
    <required-roles/>
    <remoteable-classes/>
    <limit-serialization-classes>true</limit-serialization-classes>
</deployment-descriptor>

So when I create a new jbpm process and deploy it on kie-server via workbench I've got:

Caused by: java.lang.NoClassDefFoundError: Failed to link
  org/example/SimpleProcessEventListener (Module "com.listener" from
  local module loader @3c19aaa5 (finder: local module finder @3349e9bb
  (roots:
  /opt/jboss/wildfly/modules,/opt/jboss/wildfly/modules/system/layers/base))):
  org/kie/api/event/process/ProcessEventListener

So It's obviously It is tried to use my listener but can't find org.kie.api.event.process.ProcessEventListener which is implemented by my listener.
So what should I do? Why is it not loaded? It belongs to kie-internal-api. And I have jbpm-flow in maven dependency with 'provided' scope.
 Is it the right way to use one listener in all my jbpm processes?

A: add simple-process-event-listener-1.0.jar in WEB-INF/lib and dont add war file dependency on 'com.listener' module

A: add process-event-listener.jar file under the path wildfly-\modules\system\layers\base ,in order to reflect

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby Class Module Uninitialized Constant I'm trying to create a namespace for my classes in a console application.
My structure is something like the following:
lib/somemodule/class1.rb
lib/somemodule/class2.rb
Now for example I would have the following:
 module SomeModule
      class Class1
          def self.method1
             SomeModule::Class2.new()
          end
      end
 end

 module SomeModule
      class Class2

      end
 end

This would result in an error like the following: uninitialized constant SomeModule::Class2
Please advise on how to solve this problem.

A: I think the following should work: simply add :: to the name of the module:
 module SomeModule
      class Class1
          def self.method1
             ::SomeModule::Class2.new()
          end
      end
 end

A: I am not getting any error? ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin11.4.2]


text:
Q: WPF DataGrid - how to suspend UI updates from databind and do a bulk update later Having to do a lot of cell-by-cell changes in code on my source DataTable, I need a way to temporarily halt it sending data-binding updates to its bound DataGrid:
I have a DataGrid bound to a DataTable in code behind.
DataGrid has defined columns in XAML along with binding properties:
<DataGrid.Columns>
            <DataGridTextColumn Header="{StaticResource str_Line}" Binding="{Binding Path=Pkey}" />

In code behind at load time I assign the data source (DataTable) to my grid:
myGrid.ItemsSource = myTable.DefaultView;

Now due to having to run a bunch of custom data formatting on the display data (mostly having to blank out some columns based on values of other columns, also some image switching) I am updating this source table manually - it's relatively small, always less than 20 rows. I am going row by row, cell by cell and determining whether or not this particular cell needs it's value hidden or displayed.
I don't want my UI thread getting a separate update event for each cell but I haven't found any way to switch binding.
Found the Binding.UpdateSourceTrigger property - but that still means a separate update for each column.

A: Set your UpdateSourceTrigger to Explicit. You can get the binding expression you want to refresh and call UpdateTarget when you are ready.  See BindingExpression.


text:
Q: How to change date value to Unicode with Javascript? How can I convert a month and year value into Unicode using Javascript? For instance, "6, 2013" would become "\u1046, \u1042\u1040\u1041\u1043" (Myanmar text).
Patrick pointed me to Codepen where I got this:

Zero (0; u1040, #4160) was ignored by this script until I moved the radix number to the same line as "parseInt". (mmrtext.ttf or similar Unicode font is needed to see characters displayed.)
  So, this now works well for my purpose. And I think will be be the basis for future transcoding of character pages since Myanmar-related languages use many different sets.
  Thanks a million until you are better paid.
  R. Holland

A: Check out http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
You will have to add some checking if you only want to encode numbers (run each element through parseInt most likely), since it would encode the command and the spaces as well.


text:
Q: How to write a file to a device paired via the WebUSB API Is it possible to write a file to a USBDevice object after it has been paired in browser? Specifically when the device is mass storage such as a USB Flash Drive or SD card, and a compatible browser (such as Chrome >=61)?
After running the following lines of JS:
const usbDevice = await navigator.usb.requestDevice();

// After selecting the device, and
// assuming that both of these Promises don't throw errors

await usbDevice.open();

Can a transfer (whether isochronous or otherwise) be instantiated to write a new text file to the connected mass storage?
If so, what protocol/s would need to be used in order to do so if the data must be sent raw?


text:
Q: I get error in the log for Cloning into '/tmp/buildpacks/db2heroku-buildpack-php' when i use cf push myapp -b https://github.com/ibmdb/db2heroku-buildpack-php in the log, it says
2016-03-04T11:35:16.893-0500
[STG/0]
err
Cloning into '/tmp/buildpacks/db2heroku-buildpack-php'...

A: The right command to use is:
cf push myapp -b https://github.com/ibmdb/db2heroku-buildpack-php.git


text:
Q: Android: Change color of line below ActionBar I want to change the color of the orange line below the ActionBar.

I've tried a few things but nothing has helped so far.
The current theme on my Galaxy S2 is an orange theme.
So changing the theme, also changes the line.
But I don´t know how to get access to that line, in order to change the color.

A: There is A simpler way than this (Creating Bunch of Styles).
Refering to this . Just set
getActionBar().setBackgroundDrawable(null);

This will Remove the line from Your Action Bar

A: You can use This code for achieving your purpose.
background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ff0000" />
        </shape>
    </item>
    <item android:bottom="5dp">
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
        </shape>
    </item>
</layer-list>

styles.xml
<resources>
    <style name="AppTheme" parent="android:Theme.Holo">
        <item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
        <item name="android:background">#ffffff</item>
        <item name="android:colorBackground">#ffffff</item>
    </style>
    <style name="AppTheme.ActionBar" parent="android:Widget.ActionBar">
        <item name="android:background">@drawable/background</item>
    </style>
</resources>

These codes are suitable when you have not any options menu like image shows in question, if you have options menu you must customize your option menu items background.
If you have Option menu below code is suitable:
<resources>
    <style name="AppTheme" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
        <item name="android:popupMenuStyle">@style/AppTheme.PopUpMenu</item>
    </style>
    <style name="AppTheme.ActionBar" parent="android:Widget.ActionBar">
        <item name="android:background">@drawable/background</item>
    </style>
    <style name="AppTheme.PopUpMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/background</item>
    </style>
</resources>

A: I used this ^_^ and it is 100% working:
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Drawable res = getResources().getDrawable(R.drawable.ab_transparent_example);
    getActionBar().setBackgroundDrawable(res);

and JUST USE THIS

A: In my case, in my application, I used the Holo theme.
<style name="AppTheme" parent="android:Theme.Holo">
       ...
 </style>

Background toolbar is set through the property.
<style name="AppTheme" parent="android:Theme.Holo">
    <item name="android:actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:background">@drawable/action_bar_background</item>
</style>

Standard Holo action bar background is nine-patch drawable like this:

nine patch drawable
So, if you want to change the color of the bottom line, you need to create a new nine-patch drawable.
Create Resizable Bitmaps (9-Patch files)
Put the file in the folder drawable (example drawable-xxhdpi) and specify the path to the file in the theme.


text:
Q: Необходимо вычислить разность между суммой ряда и константой с заданной точностью delta
Мне не понятно, почему сложение не происходит циклично, а заканчивается на втором члене ряда. Подскажите пожалуйста, где ошибка.
#include <stdio.h>
#include <math.h>
#include <conio.h>
double f(int n)//вычисление n-ого члена
{
    return pow(-1,n+1)/pow(n,4);
}

int main()
{
    double pi;pi=3.141592;
    double delta;
    printf("delta =");
    scanf("%lf", &delta);
    double a_1, a_n;//переменные предыдущего и текущего членов ряда
    double sum = 0;//сумма ряда
    int n = 0;
    n++;
    a_n = f(n);
    sum += a_n;
    printf("sum-c(input) = %lf\n",fabs(sum-(7*pow(pi,4)/720)));
    while (fabs(sum -(7*pow(pi,4)/720) > delta))
    {
        a_1 = a_n;
        n++;
        a_n = f(n);
        sum +=a_n;
    printf("sum=%lf\n",sum);
    printf("sum-c(in cycle) = %lf\n",fabs(sum-(7*pow(pi,4)/720)));
    }
        getch();
    return 0;
}

A: Ну-ка, посмотрим
while (fabs(sum -(7*pow(pi,4)/720) > delta))

Условие -
fabs(sum -(7*pow(pi,4)/720) > delta)

Так от чего же вы берете fabs? От
sum -(7*pow(pi,4)/720) > delta

Дальше рассказывать или не нужно?
А вообще-то я бы делал так:
#include <stdio.h>
#include <math.h>
#include <conio.h>

int main()
{
    const double pi = 3.1415926;
    const double theor_sum = 7.0*pi*pi*pi*pi/720.0;
    double delta;
    printf("delta = ");
    scanf("%lf", &delta);
    double sum = 0;
    for(int n = 1; fabs(sum-theor_sum) > delta; ++n)
    {
        sum += (2*(n%2)-1)/((double)n*n*n*n);
        printf("sum = %lf\n",sum);
        printf("sum-c(in cycle) = %lf\n",fabs(sum-theor_sum));
    }

    getch();
}


text:
Q: Converting openCV Mat to Dlib's image I am trying to integrate dlib with the zed 3D camera in their webcam_face_pose_ex by retrieving the input through the Zed camera rather than the normal webcam.
The problem occurs when trying to match the captured image matrices to be used by the dlib. In dlib I have to convert the cv::Mat of the image that I retrieved from the Zed camera to be in dlib's special format that is used within the example as in below:
cv::Mat temp = sl::zed::slMat2cvMat(left); // converts the zed Mat to openCV mat
cv_image<bgr_pixel> cimg(temp); // converts the opencv matrix to dlib matrix`

I receive the following error when doing the second step is as follows:
Error detected at line 36.
Error detected in file /home/yomna/Resources/apps/dlib/dlib-master/dlib/../dlib/opencv/cv_image.h.
Error detected in function dlib::cv_image<pixel_type>::cv_image(cv::Mat) [with pixel_type = dlib::bgr_pixel].

Failing expression was img.depth() == cv::DataType<typename pixel_traits<pixel_type>::basic_pixel_type>::depth && img.channels() == pixel_traits<pixel_type>::num.
The pixel type you gave doesn't match pixel used by the open cv Mat object.
     img.depth():    0
     img.cv::DataType<typename pixel_traits<pixel_type>::basic_pixel_type>::depth: 0
     img.channels(): 1
     img.pixel_traits<pixel_type>::num: 3

Do you know what's wrong with the conversion between the openCV image matrix to the dlib format that might cause this?

A: The error you pasted says

The pixel type you gave doesn't match pixel used by the open cv Mat object.

It also tells you your image is single channel.  So it's not a BGR image.  It looks like 8bit grayscale, so you need to use something like unsigned char as the pixel since that's the type of image you have.


text:
Q: Unable to uninstall typescript globally through npm I've installed typescript 2.4.1 on my system globally (tsc -v gives me version 2.4.1). I want to uninstall it as I want to go to version 2.3.4 for some of my e2e tests to work. But right now I'm unable to uninstall it. I tried to uninstall through npm
npm uninstall -g tsc

but after running the command when I run
tsc -v

it again shows me
version  2.4.1.

I've search this problem and found some solutions
uninstalling typescript without node
and
npm installing old versions of (typescript compiler) package
but I've tried all i.e. try to find if in installed programs but could not find it.
Then going into
C:\Program Files (x86)\Microsoft SDKs\TypeScript

to delete the folder manually but there was version 2.3, not 2.4.1 which its showing in command prompt.
Any help how can I get rid of typescript 2.4.1. ?

A: FOR WINDOWS
You might have an old TypeScript installation on your computer because of a Microsoft SDK:
cmd>tsc --version
Version 1.0.3.0

If you check the PATH environment variable, you may find an entry like this:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\

In my case, the uninstallation of "TypeScript Tools for Microsoft Visual Studio 2015" did not remove tsc.exe etc. from this path, probably because it was installed as part of the Windows 10 SDK or something else.
You can remove the entry from the PATH environment variable or at least move it below the entry for Node.js (probably C:\Program Files\nodejs) or nvm (like C:\Users\<username>\AppData\Roaming\nvm) in case you use Node Version Manager. This will prevent that calls to tsc run the ancient TypeScript compiler:
cmd>tsc --version
Version 3.1.3

Don't forget to restart your command line after changes to environment variables for them to take effect!
If you are unsure what binary the tsc command will actually run then use the where command to find out:
cmd>where tsc
C:\Program Files\nodejs\tsc
C:\Program Files\nodejs\tsc.cmd
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\tsc.exe
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\tsc.js

The priority is top to bottom. The first entry in my case is a (Linux) shell script and usually not executable on Windows. The second entry is a Windows Batch script and this is the one that will be executed. It basically invokes Node.js (simplified):
node.exe node_modules\typescript\bin\tsc

OR
You can now uninstall "TypeScript Tools for Microsoft Visual Studio 2015" from the Control Panel in Programs and Features. It was automatically installed with Visual Studio 2015 in my case.

FOR Ubuntu Linux
Uninstall node-typescript
To uninstall only node-typescript from Ubuntu 16.04 (Xenial Xerus) run in terminal:
sudo apt-get remove node-typescript

Uninstall node-typescript and dependent packages
To uninstall the node-typescript package and any other dependent packages that are no longer needed by Ubuntu Xenial.
sudo apt-get remove --auto-remove node-typescript

Expunge node-typescript
If you also want to clear the node-typescript settings and / or data from Ubuntu Xenial then use this command:
sudo apt-get purge node-typescript

To clear the node-typescript settings and / or data files and their Ubuntu Xenial dependent packages, run:
sudo apt-get purge --auto-remove node-typescript

More information about apt-get remove
Advanced Package Tool, or APT, is a free software user interface that works with core libraries to handle the installation and removal of software on Debian, Ubuntu and other Linux distributions. APT simplifies the process of managing software on Unix-like computer systems by automating the retrieval, configuration and installation of software packages, either from precompiled files or by compiling source code.
apt-get is the command-line tool for handling packages, and may be considered the back end user to other tools using the APT library.
apt-get remove is identical to install except that packages are removed instead of installed. Note that removing a package leaves its configuration files on the system. If a plus sign is appended to the package name (with no intervening space), the identified package will be installed instead of removed.

A: Please type:
npm uninstall -g typescript

instead of
npm uninstall -g tsc

That should solve your problem! :)

A: FOR LINUX:
if npm uninstall doens't work - try this command with sudo. This is the way out for me
sudo npm uninstall -g typescript

sudo npm uninstall -g tsc

A: On Linux Fedora 36 I had to do:
sudo dnf remove nodejs-typescript

Command output:
Dependencies resolved.ejs-typescript
=============================================================================
 Package              Architecture   Version           Repository  Size
=============================================================================
Removing:
 nodejs-typescript    noarch         4.1.3-4.fc36      @fedora     53 M

Transaction Summary
=============================================================================
Remove  1 Package

Then to get the latest version I did:
sudo npm install -g typescript

A: You probably are missing
sudo

Do something like this below:
npm uninstall -g typescript


text:
Q: Get div's margin value? I'm trying to figure out if it's possible to read a div's margins with JavaScript if those margins are set in external css file.
So far I am able to read div's margin data when it is written as an inline style (not in CSS file but inside HTML):
(function() {
  var banner = document.getElementById('banner');
  var move = document.getElementById('box');

  banner.onclick = function() {

    alert(move.style.marginLeft);

  };
})();

Here is JSFiddle:
https://jsfiddle.net/b0kaLk1f/
It works well but just remove  style="margin-left: 500px" and it will stop working.  I'd like to read CSS data from style.css file rather than from inline styles.

A: The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

(function() {
  var banner = document.getElementById('banner');
  var move = document.getElementById('box');
  banner.onclick = function() {
    var style = window.getComputedStyle(move, null);
    alert(style.marginLeft);
  };
})();
#box {
  margin-left: 500px;
  -webkit-transition: 0.5s;
  transition: 0.5s;
  background: #af0000;
  width: 500px;
  height: 300px;
}
#banner {
  border: solid 1px #000;
  overflow: hidden;
  width: 500px;
  height: 300px;
}

A: Essentially you are trying to maintain state in the form of style properties, which is not a good idea. You will have to retrieve them and set them. Instead, use a class to move the extended banner back and forth. The code is shorter and simpler:
banner.onclick = function () {
  ext.classList.toggle('hide_extended_banner');
};

See https://jsfiddle.net/b0kaLk1f/2/.


text:
Q: Passing a property to a slot I'm trying to find the "cleanest" way of passing a property to a child component.
I have a custom component (lets call it parent in this example) that can take any child component via a slot. Imagine the parent component wants to update some property x of a child.
The solution that I've come up with uses scoped slots, like so:
// parent.vue

<template>
    … some template stuff
    <slot :x="parentX"></slot>
</template>

<script>
    ...component setup

    computed: {
        parentX: function() {
            return ...some number
        }
    },

    ...more component stuff
</script>

--
// child.vue

<template>
    ...some html that uses property x
</template>

<script>
    ...component setup

    props: { x: Number },

    ...more component stuff
</script>

--
// app.vue

<template>
    <parent>
        <template scope="A">
            <child :x="A.x" />
        </template>
    </parent>
</template>

This works, but it's not very nice for a couple of reasons:

*

*The extra markup needed to wire then components together.

*The fact that the user of these components needs to know about properties that they shouldn't need to know about. The parent component is sending an internal bit of state to it's child. The fact that I have to manually wire up this is a little annoying, especially because it's just boiler plate.

Is there a better way of doing this so I can say:
<template>
    <parent>
        <child />
    </parent>
</template>

Then all I need to know is that the child has a property x.
UPDATE (28-10-18)
It's possible to remove some of the boiler-plate by using slot-scope directly on the child element. e.g.
<template>
    <parent>
        <child slot-scope="child" :x="child.x" />
    </parent>
</template>

but the real problem still persists. I need to manually wire up the components in the app.vue even though this has already been fully defined in the parent and child components.

A: A slot is for uncoupled content. Your requirement is that the content be a component that takes a prop. It seems to me that what you want to do is pass the child component to the parent as a prop, and have the parent template do something like
<div :is="childComponent" :x="child.x"></div>


text:
Q: custom sort list in magento grid I am having magento grid sort option like bellow

*

*Best Value

*Price

*Name

I want to modify it like bellow

*

*My whislist

*Price: High to Low

*Price:Low to High

*Designer:A-z

*Designer:Z-A

Designer,Price are attributes so can add it list but how to make it ascending and descending sorting.
How can i sort product by "My Wishlist" ?
I tried this
$this->getOrderUrl('mywishlist', 'asc')

But not working.
     $tbl_wishlist_item = Mage::getSingleton('core/resource')->getTableName('wishlist_item');
     $tbl_wishlist = Mage::getSingleton('core/resource')->getTableName('wishlist');
     $tbl_catindex = Mage::getSingleton('core/resource')->getTableName('catalog_category_product_index');
     $tbl_price_index = Mage::getSingleton('core/resource')->getTableName('catalog_product_index_price');

 $collection = Mage::getResourceModel('catalog/product_collection');
  $collection->getSelect()
             ->join(array('t2' => $tbl_wishlist_item),'e.entity_id = t2.product_id','*')
             ->join(array('t3' => $tbl_wishlist),'t2.wishlist_id = t3.wishlist_id','*')
             ->join(array('t4' => $tbl_catindex),'e.entity_id = t4.product_id','*')
             ->where('t4.category_id = 3 AND t3.customer_id='.$customer_id);

I tried this collection it sorts the correct number of product.But does n't show any products objects like name,image,price and etc. What is the problem.


text:
Q: C# ¿como obtener la palabra que sigue a una palabra especifica? quisiera saber como obtener la palabra que sigue a una palabra especifica en un string, (sin saber cual es ni cuantas palabras tiene el string).Ej:
string:"Las aguilas vuelan y los delfines nadan", deseo obtener la palabra inmediatamente posterior a "los", en  este caso "delfines".Gracias

A: primero debes separarlas con un split(' '), luego recorrer el array hasta encontrar la palabra específica, haces un next.
string palabras = "Las aguilas vuelan y los delfines nadan";
var arr = palabras.split(' ');
bool encontrada = false;
foreach(var palabra in arr){
     if (encontrada)
       {
           return palabra;
       }
      if (palabra = "los") encontrada = true;
}


text:
Q: Javascript: How can I lint for promise chains that do not have a `fail` block at the end? How can I lint my Javascript code to identify promise chains (promise.then().then().then()...) that do not have a fail block at the end? Do any of the existing tools (JSHint, JSLint, the Flow static type checker, Typescript, ...?) allow this?
The motivation for this, candidly, is that sometimes I just forget to put one in code that I write. Then, if an error occurs in that code, it will fail silently and it can be a beast to debug. Instead, it would be better software engineering to be able to catch those errors at lint-time in the same way that I can use linting to identify typos in variable names
For example:
q(this_function_returns_a_promise())
.then(function(data) {
  console.log('The promise returned some data: ' + JSON.stringify(data));
})
// .. more thens, spreads, alls
.then(function(modified_data) {
  this_function_will_throw_an_error(modified_data);
})
// .. more thens, spreads, alls
.then(function(modified_modified_data) {
  console.log('I will not be printed, logging and execution will just stop in ' +
    'the middle then()');
});
// if only there was a .fail(function(err) { ... }) here that printed the error!

A: This is not something you can lint for or otherwise identify via static analysis. There are many (most?) cases where a promise chain does not provide a catch and doesn't need to or want to, because the catch will happen somewhere downstream.
What you need to do is use your promise library's facilities for reporting on "zombie" promises, or uncaught rejected promises. This will happen at run-time, not "compile" time. The specifics of how to do that will differ from library to library. Some browsers are already beginning to implement things along this line. In Chrome, try typing the following into the console:
> Promise.resolve().then(function() {throw "throw";})
< Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
< Uncaught (in promise) throw
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^


text:
Q: What is the practical difference between read_csv and read.csv? When should one be used over another? I often work with comma separated values, and was curious to the differences between read_csv() and read.csv().
Are there any practical differences that could shine light on the situational usage of both?

A: Quoted from the introduction page.
11.2.1 Compared to base R
If you've used R before, you might wonder why we're not using read.csv(). There are a few good reasons to favour readr functions over the base equivalents:
They are typically much faster (~10x) than their base equivalents. Long running jobs have a progress bar, so you can see what's happening. If you're looking for raw speed, try data.table::fread(). It doesn't fit quite so well into the tidyverse, but it can be quite a bit faster.
They produce tibbles, they don't convert character vectors to factors*, use row names, or munge the column names. These are common sources of frustration with the base R functions.
They are more reproducible. Base R functions inherit some behaviour from your operating system and environment variables, so import code that works on your computer might not work on someone else's.

*Note that from R 4.0.0

R [...] uses a stringsAsFactors = FALSE default, and hence by default no longer converts strings to factors in calls to data.frame() and read.table().

A: read_csv() reads comma delimited numbers. It reads 1,000 as 1000.
original numbers
read by read_csv
read by read.csv


text:
Q: Find max/minima of $x\sqrt{16-x^{2}}$ This function has a closed interval of (-4, 0), (4, 0), while passing through the origin.
I'm struggling to find the maxima and minima of the function, since this finction doesn't have a standalone constant.  According to my book, f has a relative minimum if f'(x) changes from negative to positive at (c, f(c)), and a relative maximum from positive to negative at (c, f(c)).
I calculated the first derivative as $\sqrt{16-x^{2}} -\frac{x^{2}}{\sqrt{16-x^{2}}}$ and the critical points are at $x= -4, 0, 4$.  I've been taught that to find the relative max/min by plugging in the critical number(s) into f(x), but in this case, zero is the only output.
One other difficulty I have is these calculations require a number from a given interval.  Other than picking a number at random or testing each possiblilty, how do you find the min/max when there is no constant number in the function?

A: I believe you have found the incorrect critical points. To find them, you set $f'(x)=0$, in this case,
$$
\begin{align*}
\sqrt{16-x^{2}} -\frac{x^{2}}{\sqrt{16-x^{2}}}=0 &\implies \sqrt{16-x^2}=\frac{x^{2}}{\sqrt{16-x^{2}}} \\
&\implies 16-x^2=x^2 \\
&\implies x^2=8 \\
&\implies x=\pm 2\sqrt{2}
\end{align*}
$$
So your critical points are $x=-4,\pm 2\sqrt{2},4$, when you include the endpoints of your interval. Plugging back in, you find $f(4)=f(-4)=0$, and $f(2\sqrt{2})=8$ and $f(-2\sqrt{2})=-8$. From this you can conclude what the relative extrema are on your interval.

A: Hint: $\sqrt{16 - x^2}$ is just $y$ in a circle with radius 4, so you're really maximizing the area of a rectangle inscribed in a circle.  What shape would that be?
As far as the calculus goes, I think you took the derivative correctly and messed up with the algebra in finding critical points.

A: Where did you find a critical point of 0? You'd like $f'(x)$ to be 0 or undefined.


text:
Q: Multiple SelectMany in Rx I have an interface like this:
interface IProcessor{
    IObservable<Item> Process(Item item);
}

I have an array of workers:
IProcessor[] _workers = ....

I want to pass an item through all the workers:
var ret = Observable.Return(item);
for (var i = 0; i < _workers.Length; i++)
{
    int index = i;
    ret = ret
        .SelectMany(r => _workers[index].Process(r))
    ;
}
return ret;

I'm not too happy with how this looks -- is there a cleaner way?

A: This works for me:
IObservable<Item> ret = _workers.Aggregate(
    Observable.Return(item),
    (rs, w) =>
        from r in rs
        from p in w.Process(r)
        select p);

Please keep in mind that this kind of aggregation of observables - both in your question and in my answer - can cause memory issues (i.e. stack overflow) quickly. In my tests I could get 400 workers working, but 500 caused a crash.
You're better off changing your IProcessor to not use observables and implement your observable like this:
interface IProcessor{
    Item Process(Item item);
}

var f =
    _workers.Aggregate<IProcessor, Func<Item, Item>>(
            i => i,
            (fs, p) => i => p.Process(fs(i)));

var ret = Observable.Start(() => f(item), Scheduler.ThreadPool);

With this approach I can get over 20,000 nested workers before a stack overflow and the results are almost instantaneous up to that level.

A: Maybe something like this:?
var item = new Item();
_workers
  .ToObservable()
  .SelectMany(worker => worker.Process(item))
  .Subscribe(item => ...);

I made an assumption that the workers can process the item in parallel.
P.S. If you'd like sequential processing, it would be
var item = new Item();
_workers
  .ToObservable()
  .Select(worker => worker.Process(item))
  .Concat()
  .Subscribe(item => ...);


text:
Q: Repeat two words n number of times in a single formula in Excel I want to repeat two words n number of times specified from a reference using a single formula with the result being a dynamic array.
For example, if the two words are Hello and Adam and I need the two words to repeat 3 times, I would like the result to show in a row as shown in the table below:

column A
column B
column C
column D
column E
column F

Hello
Adam
Hello
Adam
Hello
Adam
Adam

How can I do that?

A: use CHOOSE and SEQUENCE
=CHOOSE(MOD(SEQUENCE(,A3*2,0),2)+1,"Hello","Adam")

Where A3 holds the number of repeats:


text:
Q: Cannot maintain internet connection on Linux Mint 18 I am running Mint 18 (I had the same problem on Ubuntu 14.04 - so I assume this is a general Ubuntu problem) where my internet connection goes out intermittently.
It stays connected to the wifi, but suddenly it cannot resolve any addresses. I have to turn wifi off and on again to reconnect (which is a pain since this is my media server)
I tried tailing the system log and saw something about resolver waking up- but wasn't sure if that was something to do with it or what it meant- couldn't find anything.
Any suggestions would be greatly appreciated.
Not sure why this was put on hold, I felt it was pretty clear what I am asking. How to keep my connection from going out and not resolving dns issues.

A: In a similar case with realtek wifi i had to disable all power saving features of rtlwifi.
If you also have a RealTek Wifi card, you can follow these steps:
lsmod |grep rtl #to identify the wifi module. In my case was rtl8192se.
#alternatively search dmesg with grep wifi or grep rtl
modinfo rtl8192se  #to see available options for the module.

You should see something like this in the end:
parm:           swenc:Set to 1 for software crypto (default 0)
 (bool)
parm:           ips:Set to 0 to not use link power save (default 1)
 (bool)
parm:           swlps:Set to 1 to use SW control power save (default 1)
 (bool)
parm:           fwlps:Set to 1 to use FW control power save (default 0)
 (bool)
parm:           debug:Set debug level (0-5) (default 0) (int)

If you have similar output, the parameter swlps , fwlps and ips are related to automatic power saving features.
You can unload the module and reload it with all power saving features disabled:
modprobe -r rtl8192se (that was the module in my case)
modprobe rtl8192 ips=0 fwlps=0 swlps=0

If everything is ok, you can make the changes permanent by going to /etc/modprob.d directory, open file modesetting.conf and add to the end:
options rtl8192se modeset=1
options rtl8192se fwlps=0 ips=0 swlps=0


text:
Q: Modify the `Head`of a function I created a function HIntthat gives me a traditional output for integrates.
HInt/:MakeBoxes[HInt[f_,{x_,x1_}],StandardForm]:=RowBox[{SubscriptBox["\[Integral]",ToBoxes[x1]],ToBoxes[f],"\[DoubleStruckD]",ToBoxes[x]}]

Example:
HInt[f, {v, V}]

Now I created a function HIntTogether that unifies two integrates with the same domain.
HIntTogether/:MakeBoxes[HIntTogether[HInt[f_,{v_,V_}]+HInt[g_,{s_,S_}]]/;(v==s&&V==S),StandardForm]:=RowBox[{MakeBoxes[HInt[f+g,{v,V}]]}]

Example:
HIntTogether[HInt[f, {v, V}] + HInt[g, {v, V}]]

The problem is: When I look at the FullFormof the result I have:

But the Head of the result that I want is some like a new integrate:
HInt[Plus[f,g],{v,V}]

Some like this. How to change the Headof the result applying the function HIntTogether?

A: result = HIntTogether[...]

result will contain the result of evaluation of HIntTogether[...]. Out[]/% also refer to the result of evaluation.
And during evaluation nothing really happend because your code defines typesetting of your expressions. Only for display purposes. Here's the sequence, roughly:

input -> parsing -> evaluation -> formatting -> typesetting -> rendering

Please read:

*

*tutorial/TheMainLoop

*tutorial/WolframSystemSessions

And related tutorials.


text:
Q: yumvar.update not working in CentOS 7 I wrote a custom yum plugin in CentOS 5 that worked fine in 6, but is broken in 7.  I've tracked it down to the following code:
repos = conduit.getRepos()
for repo in repos.findRepos('*'):
        repo.yumvar.update(conf.yumvar)

I added a few prints before and after that code and found that it's not actually doing substitutions, as it does in 6 (and presumably 5, but I don't have a 5 box to check it on anymore).
Anyone else seen this or have any ideas?


text:
Q: Como hacer select con tablas relacionadas tengo dos tablas (cliente) y (factura), para registrar una factura lo estoy haciendo de esta manera:
SqlCommand query = new SqlCommand("insert into factura (identificacion, nombrecp, " + "fecha, iva, tipo, vtotal, descripcion, subtotal) " +
                                              "values ('" + idCliente.Text + "', '" + nombreCliente.Text +
                                              "', '" + fecha.Text + "', '" + IVA.Text + "', '" + tipoFactura.Text +
                                              "', '" + totalPagar.Text + "', '" + descripcion.Text +
                                              "', '" + Subtotal.Text + "')", conexion);

No he encontrado la forma de hacer una consulta que por el numero de factura me diga que cliente esta asociado, el valor y el producto que compro.
He buscado por internet y lo que encuentro todo lo que encuentro cada vez me enreda más. La tabla esta relacionada 1:M, ojala puedan ayudarme lo mas pronto posible!! :(

el codigo que estoy usando para la consulta es este:
select identificacionc, nombre
from cliente cli inner join factura fac
on fac.identificacion = fac.identificacion
where numero = 32;

lo mire en una pagina he intente usarlo pero no entiendo bien toda la query y no me muestra todos los datos que necesito.

A: Para obtener lo que me mencionas en los comentarios; dado un número de factura obtener los datos del cliente
Usamos un INNER JOIN
El uso de Inner Join nos permite hacer un match de lo que existe en la tabla de la izquierda con la tabla de la derecha y entonces mostrarme todos los registros
Código
SELECT cliente.nombre, factura.identificacion, factura.nombrecp, factura.fecha
       factura.iva, factura.tipo, factura.vtotal, factura.descripcion, factura.subtotal
       factura.estado
FROM cliente
INNER JOIN factura ON cliente.identifcacionc = factura.identificacion
WHERE factura.numero = 32;

EXPLICACIÓN

*

*Al hacer un SELECT idealmente yo hago esto tabla.columna

*Hago un FROM de la tabla cliente

*El INNER JOIN lo hago con la tabla facturas

*Uso el ON para indicar que el JOIN se lleve a cabo en cliente.identificacionc = facturas.identificacion por que una es la llave primaria y la otra la llave foránea que estan uniendo ambas tablas

*Al final para que de toda la consulta anterior solo me muestre las coincidencias de un registro en específico hago uso del WHERE y añado que muestre todo donde factura.numero = 32
Pruebalo primero desde tu gestor de bases de datos y cualquier cosa comentamelo


text:
Q: Draw line with oblique border How to draw line with oblique border like this:

I drew only a normal line:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 30.f);
CGContextSetStrokeColorWithColor(context, [UIColor personalBlue].CGColor);
CGContextMoveToPoint(context, 0.f, 0.f);
CGContextAddLineToPoint(context,self.bounds.size.width, 0.f);
CGContextStrokePath(context);

A: I use CAShapeLayer:
class TriangleView: UIView {

    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentMode = UIViewContentMode.redraw
    }

    override func draw(_ rect: CGRect) {
        let mask = CAShapeLayer()
        mask.frame = self.layer.bounds

        let width = self.layer.frame.size.width
        let height = self.layer.frame.size.height

        let path = CGMutablePath.init()

        path.move(to: CGPoint(x: width, y: 0))
        path.addLine(to: CGPoint(x: width, y: height))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.addLine(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 0, y: 50))

        mask.path = path

        self.layer.mask = mask

        let shape = CAShapeLayer()
        shape.frame = self.bounds
        shape.path = path
        shape.lineWidth = 3.0
        shape.strokeColor = UIColor.white.cgColor
        shape.fillColor = UIColor.white.cgColor

        self.layer.insertSublayer(shape, at: 0)
    }

}

The result is this:


text:
Q: Plotting points and multipolygon objects in R with sf I've been trying to plot both points and multipolygon sf objects with no success. Following is a reproducible example of my problem.
library(sf)
library(magrittr)
library(RColorBrewer)

nc <- st_read(system.file("shape/nc.shp", package = "sf")) %>%
    st_transform(crs = 4326)
points <- data.frame(p = seq(15, 75, 15),
                     long = c(-85, -80, -78, -75, -82),
                     lat = c(34, 36, 37, 38, 35)) %>%
        st_as_sf(coords = c('long', 'lat'), crs = 4326)
points$p_cut <- cut(points$p, seq(0, 100, 20))

#plot1
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
     pal = brewer.pal(5, 'Paired'))
plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)

The multipolygon doesn't appear but if I inverse the order:
#plot2
plot(st_geometry(nc), axes = TRUE, graticule = TRUE)
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
     pal = brewer.pal(5, 'Paired'), add = TRUE)

Two points and the key are missing from the final plot.
How can I overcome these issues? I thought of changing the bbox of the multipolygon object in order to make the missing points appear in the second plot but I couldn't find a way for this.
Any help is appreciated.
EDIT.
Modified the epsg of the multipolygon in order to match the points epsg. The issues remains though.
EDIT2.
It's weird but running the code randomly seems to produce the "correct plot". I used this particular order (copied from the console):
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
+      pal = brewer.pal(5, 'Paired'))
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
+      pal = brewer.pal(5, 'Paired'), add = TRUE)
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
> #plot2
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE)
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
+      pal = brewer.pal(5, 'Paired'), add = TRUE)
> # plot1
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
+      pal = brewer.pal(5, 'Paired'))
> plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
> plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16,
+      pal = brewer.pal(5, 'Paired'), add = TRUE)

and got this:

One of the missing points appears (-85,34) but there are repeated points. Also the key is not shown properly. It seems too that the location of the repeated points and the size of the multipolygon depend on the size of the plot viewer.

A: I used a blank plot with the extent of the bigger plot (in this case the bigger extent belongs to the points object) and added both the points and the multipolygon objects to it:
# sf object with the extent of the points object
bb_sol <- data.frame(long = c(-85, -75, -75, -85),
                     lat = c(34, 34, 38, 38)) %>%
        st_as_sf(coords = c('long', 'lat'), crs = 4326)
# plot extent
plot(st_geometry(bb_sol), axes = TRUE, graticule = TRUE, pch = '.')
# plot the multipolygon
plot(st_geometry(nc), axes = TRUE, graticule = TRUE, add = TRUE)
# plot the points
plot(points['p_cut'], axes = TRUE, graticule = TRUE, pch = 16, key.pos = NULL,
pal = brewer.pal(5, 'Paired'), add = TRUE)

Which produces:

The missing points appear but there is no key. In order to add a key I tried to use the .image_scale_factor() function but with no good results.


text:
Q: Cassandra 1.1 composite keys / columns and hierarchical queries So far, this is what I understand of the current Cassandra architecture:

*

*Super columns are not desirable any more due to performance issues.

*Composite columns (actually keys) are a good choice for indexing hierarchical keys.

*Composite columns store nested components in sorted order. There is no actual index.

I have some questions:

*

*Is everything I stated correct?

*Can composite columns efficiently process range queries per component (assuming logical usage)?

*Are composite columns suited to extremely large numbers of rows while still yielding rapid query results (considering they are not an index per se)?

*Can secondary indexes be created against composite columns. If yes, can range queries be efficiently performed?

Thanks in advance.

A: *

*Yes

*Yes

*Yes, because they are sorted on write just like any other column

*Yes, secondaries can be created against composites as of 1.2. See this JIRA ticket


text:
Q: Map printing using OpenLayers Following OpenLayers map printing demo here, I'm able to get my map in image format. But I'm facing two issues with the export:

*

*Google Street base map is not included in the image output;

*Whenever I activate any WMS layer, the export fails with the error TypeMismatchError: The type of an object is incompatible with the expected type of the parameter associated to the object
To get an image output of the map, I'm using Canvas.toDataURL(), which opens another window with the image of my WFS layers. According to the demo, when using Canvas.toDataURL(), images should be requested through a proxy, a point I don't understand as far as Google base layer is concerned. Any clarification will be appreciated.
I'm not sure what I may be doing wrong. Below shows how I retrieve Google base map and WMS layers:
Google base map:
var gStreet = new OpenLayers.Layer.Google(
            'Google Street',
            {numZoomLevels: 19},
            {visibility: true},
            {isBaseLayer: true},
            {useCanvas: OpenLayers.Layer.Grid.ONECANVASPERLAYER}
    );

WMS Layer:
var wmsLayer = new OpenLayers.Layer.WMS("My WMS Layer",
        GEOSERVER_HOST + "/wms",
        {layers: "wms_layer", format: 'image/png'},
        {
            useCanvas: OpenLayers.Layer.Grid.ONECANVASPERLAYER,
            isBaseLayer: false
        }
    );

GEOSERVER_HOST is proxied via Apache web server. I've configured Apache to channel all GeoServer requests as necessary. As such, I'm not making direct request to GeoServer in my client.
Any idea on what I may be doing wrong will be appreciated.


text:
Q: Django form is not submitting I am trying to save a modelform which has following fields
class DiaryText(models.Model):
   DiaryUser=models.CharField(max_length=30,unique=False)
   DateCreated=models.DateTimeField(default=timezone.now)
   DiaryBody=models.TextField(max_length=10000)
   DiaryHeading=models.CharField(max_length=50,unique=False,null=True)

the corresponding modelform is :-
 class MakeADiaryForm(forms.ModelForm):
     class Meta:
        model=DiaryText
        fields={'DiaryHeading','DiaryBody'}
        widgets={
            'DiaryHeading':forms.TextInput(attrs={'placeholder':'Enter Title','class':'Headline'}),
            'DiaryBody':forms.Textarea(attrs={'placeholder':'Start Writing','class':'BodyDiary'}),
        }

Corresponding View function is as follows:-
 def NewEntryView(request,slug):
    UserPresent=get_object_or_404(DiaryUser,Username=slug)
    if request.method=='POST':
        form=MakeADiaryForm(request.POST)
        if form.is_valid():
            BlogEntry=form.save(commit=False)
            BlogEntry.DiaryUser=slug
            BlogEntry.save()
            return redirect('Display',**{'slug':BlogEntry.DiaryUer})
    else:
        form=MakeADiaryForm()
        return render(request,'Mobile/AddNewEntry.html',{'form':form,'slug':slug})

But the form is not saving the entered value and keeps on redirecting to same page. Display here is the name of another view while slug is the username.
can i also use a better keyword in place of slug like username. if yes, please specify how to

A: This is pretty common to see when you are new to Django forms. Here are some of the things that developers might often do which may result in this issue:
(1) Not mentioning CSRF token: Django uses CSRF tokens as a way to encrypt all the information you provide while sending it to the server. If you do not define it in your HTML template, depending on how you managed the submission, your page may either throw an error or simply reload.
(2) Not declaring method of form: This seems to be the issue in your case. Developers, when they are new with HTML, often forget to declare the HTTP method call that they shall be making with their form. Be sure to declare that you are making a POST method call inside the form tag, and it should work. Here's an example:
<form method = "POST" action = "">

Let me know if this solves the problem.

A: First of all, the return is located in the wrong place (maybe just SO code pattern has done it) and you have to define instance in the form otherwise it will create the new one. For sure, this was your issue.:
def NewEntryView(request,slug):
    UserPresent=get_object_or_404(DiaryUser,Username=slug)
    if request.method=='POST':
        form=MakeADiaryForm(request.POST, instance=UserPresent) # You have to define the instance you want to edit othervise it tries to create a new one. Most probobly this was your issue
        if form.is_valid():
            BlogEntry=form.save(commit=False)
            BlogEntry.DiaryUser=slug
            BlogEntry.save()
            return redirect('Display',**{'slug':BlogEntry.DiaryUer})
    else:
        form=MakeADiaryForm()

    return render(request,'Mobile/AddNewEntry.html',{'form':form,'slug':slug}) # here

Be sure your method name is POST in the form and you are not using any action since you are redirecting forms with urls.py. And another cause can be that the form is not passing is_valid() filter. Make sure you are inserting valid data.
Tip: in template use {{ form.as_p }} if this successfully loads that means your issue is with is_valid() filter. Alternatively, you can locate print('valid') right after if is_valid(): to check it.


text:
Q: How to update a row depending on a condition I try to update a row in my database. i receive no error but the update does not happend
$sql = "UPDATE calendar_events
        SET event_title='".$_POST["naam"]."'
        WHERE id ='($event_id)'";

problem is by variable $event_id. If i place a nummber in place of $event_id ( WHERE id =6)
then it is ok and i have my update but any  he do not accept any variable
I did change a lot of things. The type of variabls id and  $event_id  are the same. De value of the id and $event_id are de same . i did try with $event_id, and '".$event_id."'. every thing is ok
and no erroror from database bat the update do not happen.
can someone help me
thanks

A: Try with
$sql = "UPDATE calendar_events
        SET event_title='".$_POST["naam"]."'
         WHERE id ='$event_id'";

Otherwise, you are comparing it with (1), (2) or whatever number it has, but with parenthesis.
UPDATE: and, of course, SANITIZE your $_POST variables!!!


text:
Q: Neo4j - How to use createRelationshipIndex / createNodeIndex in full-text search So I understand that Neo4j 3.5 and above implements full-text search in cypher query via createNodeIndex(), e.g.:
CALL db.index.fulltext.createNodeIndex("myIndex", ["PersonNode"], ["name"])

where myIndex is an arbitrary variable I make up to store the index, PersonNode is the name of my Node label, and name is one of the attributes of PersonNode where I want the full-text search performed.
And to actually perform the search by name, I can do something like the following:
CALL db.index.fulltext.queryNodes("myIndex", "Charlie")

But now assume that PersonNode has a relationship of type PURCHASED_ITEM, which is connected to another node label ProductNode as follows:
PersonNode-[:PURCHASED_ITEM]->ProductNode

And assume further that ProductNode has an attribute called productTitle indicating the display title name for each product.
My question is, I would like to set up an index for this relationship (using, presumably, createRelationshipIndex()), and perform a full-text search by productTitle and return a list of all PersonNode that purchased the given product. How can I do this?
Addendum: I understand that the above could be done by first getting a list of all ProductNode instances matching the given title, then performing a normal cypher query to extract all related PersonNode instances. I also understand that for the above example, a normal cypher query would be all that I need. But the reason I'm asking this question is that I eventually need to implement a single search bar that would allow the user to input any text, including possible misspellings and all, and have it perform a search through multiple attributes and/or relationships of PersonNode, and the results need to be sorted by some kind of relevance score. And in order to do this, I feel I need to first grasp exactly how the relationship queries work in neo4j.

A: Here is an example of how to create a full-text index for the productTitle property of PURCHASED_ITEM relationships:
CALL db.index.fulltext.createRelationshipIndex("myRelIndex", ["PURCHASED_ITEM"], ["productTitle"])

And here is a snippet showing the use of that index:
CALL db.index.fulltext.queryRelationships("myRelIndex", "Hula Hoop") YIELD relationship, score
...

A: product title is the property of product node not the purchased item


text:
Q: Optimize sysem utilization Java Application Short about the program:
It's my first program and is therefore not best and most effectively programmed path but it works and does the job. The program diehnt as Design Management. It manages about 3000 designs. It can be sorted by each group for each group are then generated in a scrollPane container. There each design is specific number displayed a small preview with 20-30 kb and even a style name. These designs dan can still be filtered in more detail and dan be printed or sent via e-mail.
In the appendix a few screenshots of the application so you do including about anything imaginable.
The program has been programmed using XDEV.
Problem # 1:
It will appear in the scrollPane only about 200 designs to more must be seen to be turned over. Say the scrollPane once emptied and refilled with the dan designs. The problem is that it takes to load the images for too long. The sql query and generation of container in which the designs are displayed takes about 500ms. But until the images are loaded, it takes about 5 seconds. The pictures are on an external server and downloaded over the network, there is a dedicated line and on the Internet speed it can not lie.
What's the fastest way to load images into the program and therefore the show is fully charged in about 1-2 seconds?
Problem # 2:
The program takes too much system performance. If I press the button of the SQL query, which starts generation of container and loading the images increases system utilization briefly to 90-100%. For a normal PC is not necessarily a problem but the program is running on a terminal server and there is a big problem when the system increases capacity utilization. As I mentioned have only started with the program and do not know myself why I still look good even everything up out in a single thread, ie the main thread in the the window itself is generated.
How can I eliminate the system performance in a search only slightly increases ie below 10%? Would it help if I gave the loading of the images and the SQL query in a separate thread? Or how can I solve this best?


text:
Q: Android upload JSON to server error I am trying to upload a JSON file to my server which is using PHP. But the response is always false and I don't know why. I have tried to switch the order of information but it didn't help.
Here is the code of my method:
public void uploadJSON(){
    try {
        JSONObject toSend = new JSONObject();
        toSend.put("user", "guri1");
        toSend.put("ts", System.currentTimeMillis() / 1000L);
        toSend.put("lat", 35.45);
        toSend.put("lon", 48.4);
        toSend.put("text", "Toto som poslal");
        toSend.put("tags", "");
        toSend.put("img", "");
        JSONTransmitter transmitter = new JSONTransmitter();
        transmitter.execute(new JSONObject[] {toSend});

    } catch (JSONException e) {
        e.printStackTrace();
    }

JSONTransmitter is basically an asynctask. Here is the code for it:
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {

String url = "MYURLISHERE";

@Override
protected JSONObject doInBackground(JSONObject... data) {
    JSONObject json = data[0];
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

    JSONObject jsonResponse = null;
    HttpPost post = new HttpPost(url);
    try {
        StringEntity se = new StringEntity("json="+json.toString());
        post.addHeader("content-type", "application/x-www-form-urlencoded");
        post.setEntity(se);

        HttpResponse response;
        response = client.execute(post);
        String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

        Log.i("Response from server", resFromServer);
    } catch (Exception e) { e.printStackTrace();}

    return jsonResponse;
}

And here is the php:
function postevent(){
$data=json_decode(file_get_contents('php://input'), true);
$ts=$data["ts"]*1;
$lat=$data["lat"]*1;
$lon=$data["lon"]*1;
$user=mysql_real_escape_string($data["user"]);
$text=mysql_real_escape_string($data["text"]);
$tags=mysql_real_escape_string($data["tags"]);
$img=mysql_real_escape_string($data["img"]);
if ($user!=""){
$result=db_query("INSERT INTO events SET ts='$ts',lat='$lat',lon='$lon',user='$user',text='$text',tags='$tags',img='$img'");
} else { $result=FALSE; }
if($result==FALSE){
echo "false";
} else {
echo "true";
}
}

A: You can directly access server(php script file url ) and set parems in request and make different debug checks it may help you.

A: Basically, there was a simple error that was causing this whole problem. I have used StringEntity and ther I put the "json=" thing. And that's what the server didn't like. Here is the working code snippet:
@Override
protected JSONObject doInBackground(JSONObject... data) {
    JSONObject json = data[0];
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

    JSONObject jsonResponse = null;
    HttpPost post = new HttpPost(url);
    try {
        StringEntity se = new StringEntity(json.toString());
        post.addHeader("Content-Type", "application/json");
        post.setEntity(se);

        HttpResponse response;
        response = client.execute(post);
        String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

        Log.i("Response from server", resFromServer);
    } catch (Exception e) { e.printStackTrace();}

    return jsonResponse;
}


text:
Q: Is there a more effective way to loop a prepared statements execute and get_result functions? I was trying to gather an unknown amount of data from my MySQL database to up load it on my webpage using PHP. But for some reason I kept getting ERR_CONNECTION_RESET in the browser whenever I tried to get more than 1 row of data.
//Connect to database
$Conn = Connect();

//Prepare statement
$SQL = $Conn->prepare("CALL GetProductByID (?)");
$SQL->bind_param("i", $ProductID);

//Loop to get data
foreach ($_SESSION['Cart'] as $ProductID) {
        $SQL->execute();
        $Result = $SQL->get_result();
        while ($Product = $Result->fetch_array(MYSQLI_ASSOC)) {
                //Show all items in cart
                echo '

Namn: ' . $Product["Name"] . '

Pris: ' . $Product["Price"] . ' kr
Antal: <input type="number" name="' . $Product["ProductID"] . '" placeholder="Antal" min="0" max="150" value="1" required>
';
        }
}
//Close all connections
$SQL->close();
$Conn->close();

The code above would work so long as it only ran the loop once, but as soon as it tried running it a second time the ERR_CONNECTION_RESET issue would appear. Every time I would try to enter the page and the error occurred the following would be logged in Apaches error log:
[Thu Feb 03 21:56:08.649559 2022] [mpm_winnt:notice] [pid 20304:tid 568] AH00428: Parent: child process 36668 exited with status 3221225477 -- Restarting.
[Thu Feb 03 21:56:08.743608 2022] [ssl:warn] [pid 20304:tid 568] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Thu Feb 03 21:56:08.754618 2022] [mpm_winnt:notice] [pid 20304:tid 568] AH00455: Apache/2.4.51 (Win64) OpenSSL/1.1.1l PHP/8.0.12 configured -- resuming normal operations
[Thu Feb 03 21:56:08.754618 2022] [mpm_winnt:notice] [pid 20304:tid 568] AH00456: Apache Lounge VS16 Server built: Oct  7 2021 16:27:02
[Thu Feb 03 21:56:08.754618 2022] [core:notice] [pid 20304:tid 568] AH00094: Command line: 'f:\\program\\xampp\\apache\\bin\\httpd.exe -d F:/Program/XAMPP/apache'
[Thu Feb 03 21:56:08.756620 2022] [mpm_winnt:notice] [pid 20304:tid 568] AH00418: Parent: Created child process 25108
[Thu Feb 03 21:56:09.069307 2022] [ssl:warn] [pid 25108:tid 564] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Thu Feb 03 21:56:09.108307 2022] [ssl:warn] [pid 25108:tid 564] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Thu Feb 03 21:56:09.121319 2022] [mpm_winnt:notice] [pid 25108:tid 564] AH00354: Child: Starting 150 worker threads.

However, the code below would work without any issues.
//For some reason the connect and close needs to be inside the foreach loop

foreach ($_SESSION['Cart'] as $ProductID) {
        //Connect to database
        $Conn = Connect();

        //Prepare statement
        $SQL = $Conn->prepare("CALL GetProductByID (?)");
        $SQL->bind_param("i", $ProductID);
        $SQL->execute();
        $Result = $SQL->get_result();
        while ($Product = $Result->fetch_array(MYSQLI_ASSOC)) {
                //Show all items in cart
                echo '

Namn: ' . $Product["Name"] . '

Pris: ' . $Product["Price"] . ' kr
Antal: <input type="number" name="' . $Product["ProductID"] . '" placeholder="Antal" min="0" max="150" value="1" required>
';
        }
        //Close all connections
        $SQL->close();
        $Conn->close();
}

My question is if there is a way to make my first solution work. It seems an awful waste to me to open and close the entire connection every loop and very much defeats the purpose of a prepared statement.


text:
Q: Is it better to define all routes in the Global.asax than to define separately in the areas?  I am working on a MVC 4 project that will serve as an API layer of a larger application.
The developers that came before me set up separate Areas to separate different API requests (i.e Search, Customers, Products, and so forth).
I am noticing that each Area has separate Area registration classes that define routes for that area.  However, the routes defined are not area-specific (i.e. {controller}/{action}/{id} might be defined redundantly in a couple of areas).
My instinct would be to move all of these route definitions to a common place like the Global.asax to avoid redundancy and collisions, but I am not sure if I am correct about that.

A: Short Answer: Moving area route registrations to common place is not necessary, better to keep them under specific Areas that they belong to. You may use      AreaRegistration.RegisterAllAreas(); statement in Global.asax that does the registration.
I have listed and example code (for Clients area) that you may need to declare for each area in your project.
    public class ClientsAreaRegistration : AreaRegistration
        {
            public override string AreaName
            {
                get
                {
                    return "Clients";
                }
            }

     public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Clients_default",
                "Clients/{controller}/{action}/{*id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
}

A: Your route organization will depend entirely on what your goals are.
Some routes are organized in such a way that the resulting URLs increase search engine optimization.  Others are designed for readability, or to be as short as possible.  Still others are arranged hierarchically, based on the folder structure of the application.
In short, there is no "one, true way."  This is why routing exists in the first place.  Were there only a single right way to arrange your URLs, you wouldn't need the "patch-bay" mechanism that routing provides.

If your question is where to put the routes, you should put them where it makes most sense to you.  If the areas function independently and have different routing rules, it probably makes sense for each area to have its own routes.  If, on the other hand, all the areas use the same routing scheme, it probably makes sense to keep a set of global rules.
It is my understanding that ASP.NET MVC checks the area routing rules first, so if you have some rules that are specific to a certain area, you can put those rules in the area, and if none of them match, the routing engine will fall back to the global routes.


text:
Q: Why this is not decrypt? I'm writing a program to encrypt the text in C++ with a specific key and a half reduce algorithm. It works perfectly but when I want to decrypt the same text and I want return the cipher text to plain it gives me wrong chars. This is an encrypt function:
int encryption()
{
    cout << "please enter the plain text" << endl;
    char LUT[] = "opqrstuvwxyzabcdefghijklmn";
    char message[100];
    char ch;
    int i;

    cin.getline(message, 100);
    for (i = 0; message[i] != '\0'; ++i) {
        ch = message[i];
        if (isupper(ch))
            message[i] = toupper(LUT[ch - 'A']);
        else
            message[i] = LUT[ch - 'a'];
    }

    cout << "the cipher text is equal to"  << message << endl;
    return 0;
}

It's normal that when I press

a

I'll get

o

also for

b is p

But when I want write the reverse function for the same thing it doesn't work. I mean when I want add the pressed char to 'a' index it gives me the wrong char. Actually it should return

a

when I press

o

and this is my function:
int decryption()
{
    cout << "please enter the cipher text" << endl;
    char LUT[] = "opqrstuvwxyzabcdefghijklmn";
    char message[100];
    char ch;
    int i;

    cin.getline(message , 100);
    for (i = 0; message[i] != '\0'; ++i) {
        ch = message[i];
        if (isupper(ch))
            message[i] = toupper(LUT[ch + 'A']);
        else
            message[i] = LUT[ch + 'a'];
    }

    cout << "the plain text is equal to" << message << endl;
    return 0;
}

thanks to any suggestion or tell me where I have an semantic error

A: Your code assumes ASCII encoding.
With ASCII the value of 'o' is 111 and the value of 'a' is 97. So when you do ch + 'a' what you're really doing is 111 + 97 which is equal to 208. Not a valid index of your LUT array.
You should continue to use ch - 'a', and modify your LUT array to be the opposite translation instead, so 'o' maps to 'a' instead of the opposite.

A: Well you said half reduce algorithm. Basically your encoding string should have been
char LUT  [] = "nopqrstuvwxyzabcdefghijklm";
In which case, applying the same encoding algorithm would have brought you back the original string. It has to be the first 13 characters at the end and the last 13 characters at the beginning (rotating the alphabet 13 times)
But if you want to keep your encoding string(12 rotions to the left), then the decoding string should be
mnopqrstuvwxyzabcdefghijkl
(12 rotations to the right). Except that you must use the exact same algorithm.
(ch-'a'  and ch-'A')


text:
Q: Creating daily % change in Google Sheets I am maintaining a tracker of sorts for enterprise wide. Recently my manager came to me with a request that he wants to see daily change against each of the respective business unit. The challenge is information is updated in real time and I don't have a time stamp to calculate the instance to be taken for calculation. Is there any way in Google Sheets to do that ?
Pasting the image below for better understanding
enter image description here

A: Make a short script that copy as values 'Cases (Live)' to 'Previous day Instance' column. And then put a trigger on that function to be activated each day at 23:59. Put a link to your project to go further. Example :
function histo(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('my Sheet');
  var range = sheet.getRange('B5:B9');
  range.copyTo(sheet.getRange('D5'), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}

to define a trigger based on time
function createTimeDrivenTriggers() {
  // Trigger every day at 06:00AM CT.
  ScriptApp.newTrigger('histo')
      .timeBased()
      .everyDays(1)
      .atHour(6)
      .create();
}

Reference:

*

*Installable Triggers


text:
Q: Command Prompt Multiple Commands on Startup I have a command prompt shortcut in my start menu. What I have done is add /k prompt Commands$g.
I want a way to make it so I can do multiple commands after the /K. When I try, it just adds it to the end of the previous command.

A: I think you are on windows PC (because I have not faced the same problem from linux pc), one thing you can do is that press "Windows Key" of your keyboard and type cmd and then repeat.


text:
Q: How to make callback function in Coffeescript I can't find out how to make a function that calls another function at the end.
I want to be able to do something like this:
book.save (err) ->
  MyFunc param1, param2, (callbackParam) ->
    # some code using callbackParam

MyFunc = (param1, param2) ->
  # some other code that defines callbackParam
  ?.call(callbackParam)

What has to be called and how does it receive the data?

A: If you want to call MyFunc as:
MyFunc param1, param2, some_function

Then it should look like this:
MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback callbackParam

And if you want to make the callback optional:
MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback? callbackParam

And if you want to supply a specific @ (AKA this), then you'd use call or apply just like in JavaScript:
MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback?.call your_this_object, callbackParam

The (callbackParam) -> ... stuff is just a function literal that acts like any other parameter, there's no special block handling like in Ruby (your tags suggest that Ruby blocks are the source of your confusion).


text:
Q: I need to count the number of dates selected in a multidatepicker and pass that count to a pdf report ?how to do that $(document).ready(function(){
  var date_input=$('input[name="rosterdate"]'); //our date input has the name "myrosterdate"
  var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
  var options={
  multidate:true,
  format: 'yyyy-mm-dd',
    container: container,
    todayHighlight: true,
    autoclose: false,
  };
  date_input.datepicker(options);
})

A: From the Bootstrap Datepicker Events documentation, you can hook to the changeDate event of the control. From there you can interrogate the dates property of the event to get an array of the selected dates, using length to determine how many selections have been made.
Alternatively you can use the getDates metod to retrieve the dates under any other event, outside of the control.

jQuery($ => {
  let $date_input = $('input[name="rosterdate"]'); //our date input has the name "myrosterdate"
  let $container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";

  $date_input.datepicker({
    multidate: true,
    format: 'yyyy-mm-dd',
    container: $container,
    todayHighlight: true,
    autoclose: false,
  }).on('changeDate', e => {
    // get count of dates when a selection is made
    console.log(e.dates.length);
  });

  $('form').on('submit', e => {
    e.preventDefault();

    // get count of dates when submitting your form
    let dates = $date_input.datepicker('getDates');
    console.log(dates.length);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" integrity="sha512-T/tUfKSV1bihCnd+MxKD0Hm1uBBroVYBOYSk1knyvQ9VyZJpc/ALb4P0r6ubwVPSGB2GvjeoMAJJImBG12TiaQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" integrity="sha512-mSYUmp1HYZDFaVKK//63EcZq4iFWFjxSL+Z3T/aCt4IO9Cejm03q3NKKYN6pFQzY0SBOr8h+eCIAZHPXcpZaNw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="bootstrap-iso">
  <form>
    <input type="text" name="rosterdate" />
    <button>Submit</button>
  </form>
</div>


text:
Q: Prime radical that is nil but not nilpotent Please help me to show that the prime radical of the ring $R=\prod\limits_{n = 1}^\infty  { \mathbb{Z} /2^n\mathbb{Z} } $ is nil but not nilpotent.

A: If $\sqrt{0}^n=0$, then in particular $(2 e_n)^{n-1}=0$, i.e. $2^{n-1} = 0 \bmod 2^n$, a contradiction.


text:
Q: More Than One OG URL Specified and only Yoast graph is open not Jetpack I'm having some problem with the od: tags which is the most common issue.

Only Yoast is active for open graphs not Jackpack publicize and then how the og: tags are showing in the header of the page as shown above in the image.
would be grateful if anyone can help

A: There can be two possibilities:

*

*The other og tag is printed in theme's header.php. If it's there then comment that code and you're good to go.

*The OG tag is being generated by some function hooked to wp_head hook. Now it can be anywhere, in any file in plugin or theme. The best approach would be to check all the hooked functions for wp_head hook. You can do so by this code:
add_action("wp", function(){ print_r($GLOBALS['wp_filter']); echo '';exit; } );
Write this code in functions.php of your theme and look for all the functions which are hooked with wp_head hook. You can then comment the code in that particular function.

A: It is possible that your template adds the additional og:url header (from your page source it appears so). You need to disable the additional headers using either a switch in template settings or by manual edit.


text:
Q: Invoking a click on a class which is only used once I'm trying to use a loop and I'm getting freezing but no full crash.
Dim theElementCollection As HtmlElementCollection
theElementCollection = WebBrowser1.Document.GetElementsByTagName("DIV")

For Each curElement As HtmlElement In theElementCollection
 Dim controlName As String = curElement.GetAttribute("name").ToString
 curElement.InvokeMember("click")
Next

In my case there should only be one div class name and I just want to invoke a click on it.
edit-improved formatting

A: I found a workaround like so
For Each h As HtmlElement In WebBrowser1.Document.GetElementsByTagName("input")
        If Not Object.ReferenceEquals(h.GetAttribute("className"), Nothing) AndAlso h.GetAttribute("className").Equals("numeroCustomer") Then
            h.InnerText = loginid
            Exit For
        End If
    Next

Hope this helps anybody with a similar problem.


text:
Q: What is Pods-App.framework and it is a umbrella framework? I have a question about whether Pod-App.framework in /Build/Product directory, is it an umbrella framework?
I just found Pods_App.the framework has a header Pods-App-umbrella.h and searched around did not get more info.
As I know Umbrella framework may have a sub-framework in the directory.


text:
Q: I cannot update my app after "google manage my key" we create a project in android consoles Google manage your app signing key
Then I upload my apk , first release if ok
but when we update the apk , it says different sh1
You uploaded an APK that is not signed with the upload certificate. You must use the same certificate. The upload certificate has fingerprint:
SHA1: C5:B7:05:86:FB:C9:72:5D:CC:0C:F6:27:A0:26:E7:8B:59:E6:7E:D9
and the certificate used to sign the APK that you uploaded has fingerprint:
SHA1: BA:87:48:72:2A:3F:F1:2C:03:9B:5C:F1:4E:93:20:91:43:EE:47:73
"C5:B7:05:86:FB:C9:72:5D:CC:0C:F6:27:A0:26:E7:8B:59:E6:7E:D9" we did not generate this

A: Before uploading the updated application, be sure that you have incremented the android:versionCode and android:versionName attributes in the element of the manifest file. Also, the package name must be the same and the .apk must be signed with the same private key. If the package name and signing certificate do not match those of the existing version, Market will consider it a new application and will not offer it to users as an update.


text:
Q: Mean Squared Error random variable I'm reading Elements of Statistical Learning (2nd edition, 12th printing) and there are two things that are bothering me.
Regarding Equation 2.25, one is the training set Τ. I'm assuming that it is a function of two random variables X and Y, so when calculating the expected value, would the underlying probability density function be the joint distribution of X and Y?
Another thing is whether I should be interpreting y0-hat as a constant or a random variable? I know that it is an estimate of the test input point. If y0-hat is a random variable, what would be the underlying probability distribution?
I understand the derivation of decomposition of mean squared error into variance and bias, but when I look at Var(y0-hat), I can't help thinking that y0-hat is a constant and hence Var(y0-hat) = 0. What's wrong with my thinking?
Similar confusion arises for expected prediction error (equation 2.27), where the expected value is calculated with respect to y0|x0, which seems to me that y0 is a random variable and x0 is an event.
Sorry, I don't know how to format. Apologize if this was already posted. Any help would be greatly appreciated!

A: Yes, $X$ and $Y$ are random variables. Let me fill in some of the technical details.
For convenience, let $Z_i = (X_i,Y_i)$ be i.i.d. and define $\mathbf{Z} = \{Z_1,\ldots,Z_N\}$.
The estimator $\hat{y}$ is a function of all the observations in the training data (which is random) and $x$ (which is deterministic). In other words,
$$\hat{y}= g(\mathbf{Z},x)$$
For example, the linear prediction fits this form
$$ \hat{y} \equiv \hat{y}(x) = x \hat{\theta}_{OLS}$$
where $\hat{\theta}_{OLS}$ is the ordinary least squares estimate using all the observations in the training sample. In this case, $x$ is just a user-input whereas $\hat{\theta}$ needs to be estimated (with uncertainty). The true prediction is $f(x) = x \theta$.
This basic notation allows us to answer your question

*

*The expectation is taken over $\boldsymbol{Z}$, which includes all the $(X,Y)$ values in the training sample.

*The estimator $\hat{y}$ depends on the realizations of all the $Z_i$. You would get a different result if you randomly selected another training sample. Therefore, $Var(\hat{y}) > 0$.

*Yes, the MSE is a function of a deterministic input, $x$. However, remember that $\hat{y}$ is a function of both $\mathbf{Z}$ and $x$. The expectation integrates over $\mathbf{Z}$. There is no need to compute a conditional expectation.


text:
Q: Kubuntu installer crashes I'm trying to install Kubuntu 16.04.1 on my acer laptop (256 gb ssd, 1 tb hdd, 16 gb ram). All of the guided partition builds only use one of the disks so I attempted to do the manual. This is my first hdd/ssd pc so I don't expect that I did this well. I just put this together after reading the other similar posts about the install here.
 sda
 - /         20 gb
 - /usr       7 gb
 - /usr/local 7 gb
 - /opt       5 gb

and on the hdd
sdb
 - /boot    350 mb
 - /home    10  gb
 - /var      5  gb
 - /tmp     500 mb

But the installer crashed over and over again. I left the partitions as they were but didn't name them and it loaded, but once it restarted I removed the usb and reset the bios to factory settings and now it is saying there is no bootable device.
Any thoughts to what I could be doing wrong? thanks.

A: I've experienced a similar situation when installing to an single hard disk, I reset the BIOS after installing. I figured out a solution by looking at the settings and remembered that I had the legacy option on during the install, but was off after. After switching it on again, I rebooted and ouila! It worked. I changed the setting back and reinstalled it in UEFI mode, and that also worked after reboot. But in this case, I think you have to set the boot disk properly, among puting /boot (or have no /boot partition) on the ssd you don't need so many partitions, and should really have only 2, / on  the ssd and /home on the HDD.


text:
Q: logical equivalence of ¬((q∨¬p)∧¬r) I have just started the course of logic and still not familiar with applying different formula to obtain logically equivalent statement.
¬((q∨¬p)∧¬r)should be (¬q∧p)∨ r, and it asks me to find a equivalent statement without using and/or/negation. I want to know who to get there.
Then in second part, the question is to find equivalent formula for (p∨ ¬q)∨ (p∧(q∧ ¬r)).
I can list the truth table for these but I don't know the tech of finding logical equivalent formula.

A: Starting from the formula : $¬((q \lor ¬p) \land ¬r)$, we have to use the tautological equivalence : $\lnot (\alpha \land \beta) \equiv (\alpha \to \lnot \beta)$ to get : $(q \lor ¬p) \to r$, and then use Material Implication :

$(p \to q) \to r$.

Same approach for the second one :  $(p \lor ¬q) \lor (p \land (q \land ¬r))$.
We have to replace $(p \lor ¬q)$ with $q \to p$.
Regarding $p \land (q \land ¬r)$ we have : $p \land \lnot (q \to r) \equiv \lnot [p \to (q \to r)]$.
In conclusion, the complete formula will be equivalent to :

$(q \to p) \lor \lnot [p \to (q \to r)] \equiv (p \to (q \to r)) \to (q \to p)$.

A: Are you familiar with the NAND operator? Let's denote it by $\uparrow$. You can express any logical operator with NAND. Indeed, negation is given by
$$\neg p \equiv p\mathbin{\uparrow}p,$$
conjunction is given by
$$p\land q \equiv (p\mathbin{\uparrow} q) \mathbin{\uparrow} (p\mathbin{\uparrow} q),$$
and disjunction is given by
$$p\lor q \equiv (p\mathbin{\uparrow} p) \mathbin{\uparrow} (q\mathbin{\uparrow} q).$$
I don't know how you could express a logical formula without any of and/or/not unless you use something like this.


text:
Q: What programming language should I study to know WordPress very well? I want to know WordPress structure and functions very well.
So what programming language should I study to know WordPress very well? PHP?

A: WordPress functions are PHP. you should start here: https://developer.wordpress.org/
As the first steps I recommend to study:
Theme development: https://codex.wordpress.org/Theme_Development
The Loop: https://codex.wordpress.org/The_Loop
And The WP theme hierarchy: https://developer.wordpress.org/themes/basics/template-hierarchy/

A: I would suggest you can learn below in order to reach wordpress theme and plugin development.

*

*HTML

*CSS

*Javascript

*PHP with Database (MySQL)

Once you have some basic knowledge of all the above things. Then you can do coding and development into WordPress. I would suggest first you can make a simple core php project so you will get some ideas how websites are working.


text:
Q: Unable to figure out permissions with docker mounted volume I have a docker container with a mounted volume running on an Ubuntu 20 host. I'm having trouble figuring out permissions to write to the directory.
I don't know what group to set the directory to. I set the directory to 775 on my host, but I get errors that I can't write in from the docker container. When I change the directory to 777, I see uploaded files are written as 82:82, which I assume is the uid:guid from docker.
I know I can set the user for the mounted directory, but I'm having trouble understanding if that means the user on the host or the container. I read somewhere I should create a host user with the same uid and then add that user to the group on the directory, but this feels like a really poor method; what if the id in the container already exists on the host?
If my google-fu has failed me, can someone help me understand better permissions control on docker volumes, or if there are any patterns I should be learning/following on this?


text: Q: To find 256 point FFT in matlab I am implementing FFT in Libero using an 'FFT IPcore'. I have got an output,but I want to verify its correctness. I have the input values with me and I want to find the FFT coefficients of these values using MAT LAB .


text:
Q: SGE Cluster qsub email notifications not working I'm working on an SGE cluster and having some problems with the qsub email notification system.  All of my jobs work perfectly, but I seem unable to modify the default behaviour to only notify at an aborted job.  The -M flag works correctly, and I do receive an email when the job is aborted, however I would like to get an email when a job begins, ends, is aborted, or suspended.  I am using the following flags (and more) in my scripts, is there something stupid that I am missing?
#!/bin/bash
#$ -S /bin/bash
#$ -M email@server
#$ -m beas

program

It also does not work when I try the following:
qsub -M email@server -m baes script.sh

Is this an issue that I should take up with my cluster sys admins, or have I done something incorrectly?
Thanks for your help.

A: The important thing to understand in solving this problem is that your job status email will be sent by the node where the job runs.  For example, I have a test job with the following output:
#!/bin/bash
#
#$ -N MAIL
#$ -j y
#$ -m easb
#$ -M pkenyon

hostname

Now, run the job, and see where it ran.
[pkenyon@head ~]$ qsub mail.sh
Your job 346 ("MAIL") has been submitted
[pkenyon@head ~]$ cat MAIL.o346
node03.cluster

If you look at the mail logs on the system, you'll see the delivery attempts made.  You'll have to diagnose from there.  Here are a few examples for failures (or even successes that aren't successful in the way you want them to be):

*

*Sent to the compute node address, using -M pkenyon
...
Jun  5 13:56:00 node04 postfix/local[13141]: 14A3E143320: to=<pkenyon@node04.cluster>, orig_to=<pkenyon>, relay=local, delay=0.05, delays=0.03/0/0/0.01, dsn=2.0.0, status=sent (delivered to mailbox)
...

*Head node MX not set up right, using -M pkenyon@head.cluster
...
Jun  5 14:00:30 node04 postfix/smtp[13283]: 35CC4143320: to=<pkenyon@head.cluster>, relay=none, delay=0.36, delays=0.17/0/0.19/0, dsn=5.4.4, status=bounced (Host or domain name not found. Name service error for name=head.cluster type=AAAA: Host not found)
...

*You need to set up your system to use a local mail relay if using -M someone@gmail.com
...
Jun  5 12:20:47 node04 postfix/smtp[12798]: 1EEA5143320: to=<someone@gmail.com>, relay=ASPMX.L.GOOGLE.com[64.233.168.27]:25, delay=0.64, delays=0.04/0/0.59/0.02, dsn=5.0.0, status=bounced (host ASPMX.L.GOOGLE.com[64.233.168.27] said: 550 Relay not permitted (in reply to RCPT TO command))
...

So yes, you need to talk to your cluster sysadmins, but these are the first steps to figuring out where your SGE emails are hanging up.  With a little more information, your admins will be able to fix the configuration issue and help you get more out of your cluster environment.


text:
Q: Field manipulation I have some text files and I need to remove the first character from the fourth column only if the column has four characters
file1 as follows
ATOM   5181  N  AMET K 406      12.440   6.552  25.691  0.50  7.37           N
ATOM   5182  CA AMET K 406      13.685   5.798  25.578  0.50  5.87           C
ATOM   5183  C  AMET K 406      14.045   5.179  26.909  0.50  5.07           C
ATOM   5184  O   MET K 406      14.595   4.083  27.003  0.50  7.07           O
ATOM   5185  CB  MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5185  CB  MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5202  N  AARG K 408      12.186   3.982  29.147  0.50  6.55           N

file2 as follows
ATOM     41  CA ATRP A   6     -18.975 -29.894  -7.425  0.50 19.50           C
ATOM     42  CA BTRP A   6     -18.979 -29.890  -7.428  0.50 19.16           C
ATOM     43  C   HIS A   6     -18.091 -29.845  -8.669  1.00 19.84           C
ATOM     44  O   HIS A   6     -17.015 -30.452  -8.696  1.00 20.10           O
ATOM     45  CB ASER A   9     -18.499 -28.879  -6.370  0.50 19.73           C
ATOM     46  CB BSER A   9     -18.565 -28.837  -6.367  0.50 19.13           C
ATOM     47  CG CHIS A   12    -19.421 -27.711  -6.216  0.50 21.30           C

Desired output
file1
ATOM   5181  N   MET K 406      12.440   6.552  25.691  0.50  7.37           N
ATOM   5182  CA  MET K 406      13.685   5.798  25.578  0.50  5.87           C
ATOM   5183  C   MET K 406      14.045   5.179  26.909  0.50  5.07           C
ATOM   5184  O   MET K 406      14.595   4.083  27.003  0.50  7.07           O
ATOM   5185  CB  MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5185  CB  MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5202  N   ARG K 408      12.186   3.982  29.147  0.50  6.55           N

file2
ATOM     41  CA  TRP A   6     -18.975 -29.894  -7.425  0.50 19.50           C
ATOM     42  CA  TRP A   6     -18.979 -29.890  -7.428  0.50 19.16           C
ATOM     43  C   HIS A   6     -18.091 -29.845  -8.669  1.00 19.84           C
ATOM     44  O   HIS A   6     -17.015 -30.452  -8.696  1.00 20.10           O
ATOM     45  CB  SER A   9     -18.499 -28.879  -6.370  0.50 19.73           C
ATOM     46  CB  SER A   9     -18.565 -28.837  -6.367  0.50 19.13           C
ATOM     47  CG  HIS A   12    -19.421 -27.711  -6.216  0.50 21.30           C

A: This might work for you (GNU sed):
sed -r 's/^((\S+\s+){3})\S(\S{3}\s)/\1 \3/' file

This replaces the first character of the fourth column with a space if that column has four non-space characters.

A: Use the length() function to find the length of the column and the substr() function to print the substring you need:
$ awk 'length($4)==4{$4=substr($4,2)}1' file | column -t
ATOM  5181  N   MET  K  406  12.440  6.552  25.691  0.50  7.37  N
ATOM  5182  CA  MET  K  406  13.685  5.798  25.578  0.50  5.87  C
ATOM  5183  C   MET  K  406  14.045  5.179  26.909  0.50  5.07  C
ATOM  5184  O   MET  K  406  14.595  4.083  27.003  0.50  7.07  O
ATOM  5185  CB  MET  K  406  14.812  6.674  25.044  0.50  6.80  C
ATOM  5185  CB  MET  K  406  14.812  6.674  25.044  0.50  6.80  C
ATOM  5202  N   ARG  K  408  12.186  3.982  29.147  0.50  6.55  N

Piping to column -t rebuilds a nice table format. To store the changes back to a file uses the redirection operator:
$ awk 'length($4)==4{$4=substr($4,2)}1' file | column -t > new_file

With sed you could do:
$ sed -r 's/^((\S+\s+){3})\S(\S{3}\s)/\1\3/' file
ATOM   5181  N  MET K 406      12.440   6.552  25.691  0.50  7.37           N
ATOM   5182  CA MET K 406      13.685   5.798  25.578  0.50  5.87           C
ATOM   5183  C  MET K 406      14.045   5.179  26.909  0.50  5.07           C
ATOM   5184  O  MET K 406      14.595   4.083  27.003  0.50  7.07           O
ATOM   5185  CB MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5185  CB MET K 406      14.812   6.674  25.044  0.50  6.80           C
ATOM   5202  N  ARG K 408      12.186   3.982  29.147  0.50  6.55           N

To store the changes back to the original file you can use the -i option:
$ sed -ri 's/^((\S+\s+){3})\S(\S{3}\s)/\1\3/' file


text:
Q: Como instalar y visualizar correctamente un archivo pdf con mpdf en laravel? Actualmente tengo en vista un boton que me lleva hacia una ruta y lo que pretendo es hacer una prueba de visualizacion para un pdf de esta manera mostrare mi codigo. utilizo laravel 5.5
Detalle

Controlador
public function dada(){

return view('Unidad_medida.pdf');

}

mi ruta
Route::get('Unidad_medida/pdf','UnidadmedidaController@dada')->name('pdf');

muestro el codigo de mi vista pdf
<?php

$mpdf = new \Mpdf\Mpdf([]);
$mpdf->WriteHTML('
Hello world!
');
$mpdf->Output();

ahora muestro la instalacion desde mi terminal, utilizo vscode

estoy teniendo este Problema al visualizar

lo que quiero es saber como instalar y visualizar correctamente esta libreria en laravel 5.5, y si tengo algo malo en mi codigo se lo agradeceria mucho.....