text:
Q: Qt5 VideoOverview example won't work I am stucked for a month with video example given in Qt Video Overview.
I tried that code, but only I get is blank square (QWidget). I am using GStreamer0.10 for media playback over Qt5. I also played video with gst-launch-0.10 command and it works okay, but I cannot determine what's happening in Qt and why it won't work?
I looked in error log of X Server, located in /etc/X11/Xorg.0.log, and when I use fbdev as a display driver configured in /etc/X11/xorg.conf it shows me the error:

"FBDEV(0): FBIOPUTCMAP: Invalid argument"

when I use modesetting driver everything acts the same but no errors. I figured out that when I delete xorg.conf file and start X server again, video works but with lack of colors and with flickering also example works well on my Ubuntu VM and via vnc client. Every advice and help will be appreciated.

*

*Target machine: BeagleBone Black

*Distribution: Debian Jessie 8.2

*Kernel Version: 4.1.15-ti-rt-r43
List of available drivers in /usr/lib/xorg/modules/drivers: ati_drv.so, mach64_drv.so, nouveau_drv.so, r128_drv.so, vesa_drv.so, fbdev_drv.so, modesetting_drv.so, omap_drv.so, radeon_drv.so
Here is a full error log from Xorg when I try to launch my Qt application on BeagleBone Black under Debian Jessie 8.2 -> http://pastebin.com/4x8KztBk
xorg.conf file from /etc/X11 -> http://pastebin.com/4WhX8pJc

A: It's an incompatibility between the versions of Qt5 and libGStreamer0.10.
You need libgstreamer1.0-0 (1.22.0-2), and gstreamer1.0-qt5 (1.22.0-5) plugin, and also you may need gtk+3.
gst-plugins built from gst-plugins-good1.0 (1.22.0-5). See: https://packages.debian.org/sid/gstreamer1.0-qt5


text:
Q: How do I locate certain words on a webpage I am doing a small project that requires me to locate a certain word and highlight that word inside a web browser.
To put it simply, I have the following questions:

*

*I was wondering if there is a location(x,y) tagged to each word on a webpage.

*Could anybody point me into the direction of some useful tutorials about working within a webpage.
I would like to implement the following code and have it interact with any webpage on google chrome. It is a simple find and highlight function.
function doSearch(text) {
if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.getElementById("button").blur();
        document.execCommand("HiliteColor", false, "lavender");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "lavender");
        textRange.collapse(false);
    }
}

}
Thank you for your time and effort.

A: I think this covers what you want. Also caters to considering the search term as a phrase or individual words.
Pure Javascript Search and Text Highlighting

redpajama_set_name: RedPajamaStackExchange


text:
Q: Achieve irregular rectangular shape image masking in html css Is it possible to achieve such an effect in HTML5 and CSS3 , Please find the attached image
Here I have two divs with overflow:hidden, inside each is an image. And when I hover each image, the image zoom in or moves up or down inside this same div container. So basically the div works like a mask for the big image.
What I fail to achieve here is the shape of the div to mask the image. Is there a way to achieve that and can work in the latest versions of almost all browsers?
Thanks for you help !

A: For something like that, I would suggest two different possibilities:

*

*Using CSS transformations (in particular skewY); or

*Using SVG (with just some polygons)

Each of them has some good/bad things and will work in all the modern browsers and in mobile, as you can see in the caniuse.com website for transform and SVG.
Using CSS 2D Transformations
You would have a container div that would be skewed vertically, and then inside of it other divs with the skew (over)corrected. Then hiding the overflow so the excess of the contained divs is not shown.
You can see a demo here (or on this JSFiddle):

#skewed {
    position:relative;
    margin-top:20px;
 width: 500px;
 height: 300px;
    transform: skewY(-2deg);
 -webkit-transform: skewY(-2deg);
 -moz-transform: skewY(-2deg);
 -o-transform: skewY(-2deg);
    overflow:hidden;
    background:black;
    -webkit-backface-visibility: hidden;
}

#skewed div {
    position:absolute;
    height:200px;
    width:500px;
    transform: skewY(4deg);
    -webkit-transform: skewY(4deg);
 -moz-transform: skewY(4deg);
 -o-transform: skewY(4deg);
    overflow:hidden;
    opacity:0.4;
    transition:all 0.5s;
    z-index:1;
    background-size:100% 100%;
    -webkit-backface-visibility: hidden;
}

#skewed div:hover {
    opacity:1;
    z-index:2;
    background-size:110% 110%;
}

#top {
    top:-50px;
    left:0;
    background:url(http://lorempixel.com/1000/400/animals) no-repeat center center;
}

#bottom {
    top:150px;
    left:0;
    background:url(http://lorempixel.com/1000/400/people) no-repeat center center;
}

About this solution:

*

*Supported by all major browsers (except Opera Mini), although you'll need to use prefixes.

*Easy to implement and extend with further content (text, links, etc.)

*In Chrome, the edges look too sharp. Although this can be fixed using -webkit-backface-visibility: hidden as suggested by Neven in this answer.

Using SVG
Use polygons to define the basic shapes that you want to create.
I am not a SVG-expert, so I can't do anything fancy, but this is to get a general idea. Here is a simple demo (you can also see it on this JSFiddle):

polygon {
    opacity:0.4;
    transition:all 0.5s;
}

polygon:hover {
    opacity:1;
}
<svg width="500" height="300" viewBox="0 0 500 300">
    <defs>
        <pattern id="img1" patternUnits="userSpaceOnUse" width="600" height="300">
            <image xlink:href="http://lorempixel.com/600/300/animals" x="0" y="0" width="600" height="300" />
        </pattern>
        <pattern id="img2" patternUnits="userSpaceOnUse" width="600" height="300">
            <image xlink:href="http://lorempixel.com/600/300/people" x="0" y="0" width="600" height="300" />
        </pattern>
    </defs>
    <polygon id="top" points="0,20 500,0 500,170 0,130" fill="url(#img1)" />
    <polygon id="bottom" points="0,130 500,170 500,280 0,300" fill="url(#img2)" />
</svg>

About this solution:

*

*Supported by all the major browsers (no need for prefixes or anything)

*Highly customizable: I used polygons, but you could use paths and curves to give a more personal solution.

*SVG is not as easy as the other solution (Ok, something as simple as this is easy, but something more complex will require some learning).


text:
Q: VB.net Serial.write slow on Windows 7 I have the following problem on a Windows 7 using VB.net with .NET Framework 4.0.
I have to send via a serial port a buffer of byte. The PC act like master and a device connected as slave receive the buffer. Each byte must be spaced from its next by a certain amount of time expressed in microseconds.
This is my code snippet
                        Dim t1 As New Stopwatch
                        Dim WatchTotal As New Stopwatch

                        WatchTotal.Reset()
                        WatchTotal.Start()

                        t1.Stop()
                        For i As Integer = 0 To _buffer.Length - 1

                            SerialPort1.Write(_buffer, i, 1)

                            t1.Reset()
                            t1.Start()

                            While ((1000000000 * t1.ElapsedTicks / Stopwatch.Frequency) < 50000) ' wait 50us
                            End While
                            t1.Stop()
                        Next

                        WatchTotal.Stop()

                        Debug.Print(WatchTotal.ElapsedMilliseconds)

Everything loop inside a thread.
Everything works correctly but on a machine with Windows 7 the Serial.write of 1 byte takes 1ms so if we have to send 1024 bytes it takes 1024ms.
This is confirmed by printing the elapsed time
Debug.Print(WatchTotal.ElapsedMilliseconds)

The problem seems to be in SerialPort.Write method.
The same code on a machine with Windows 10 takes less than 1ms.
The problem is more visible when we have to send many buffers of byte, in this case we send 16 buffers of 1027 bytes. On Win 7 it takes less than 20 seconds, in Win10 it takes the half or less (to send 1 buffers of 1027 bytes it takes approximately 120-150ms and less than 5 seconds to send 16 buffers of data).
Does anyone have any idea what that might depend on?
Thanks

EDIT 22/05/2020
If i remove the debug printing and the little delay to pause the communication i always have about 1027ms for sending 1027 bytes so i think that the problem belong only to SerialPort method and not to the timing or stopwatch object. This happen on a Windows 7 machine. The same executable on a Windows 10 machine go fast as expected.
                        For i As Integer = 0 To _buffer.Length - 1
                            SerialPort1.Write(_buffer, i, 1)
                        Next

A: One thing, your wait code seems cumbersome, try this.
        'one tick is 100ns, 10 ticks is as microsecond
        Const wait As Long = 50L * 10L ' wait 50us as ticks
        While t1.ElapsedTicks < wait
        End While

Busy loops are problematic and vary from machines.  As I recall serial port handling was not very good on Win7, but I could be mistaken.
It is hard to believe that the receiver is that time sensitive.

A: If the Win7 workstation doesn't have or isn't using a high resolution timer, then that could account for the described difference.
From the Remarks section of the StopWatch class:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

Check the IsHighResolution field to determine if this is what is occurring.


text:
Q: Python - setuptools - working on two dependent packages (in a single repo?) I am working on a python project which contains two modules. The modules are very closely related and hence I want them to be in the same git repo, and to be able to develop them together in my IDE:

*

*module1 depends on module2

*module1 has lots of other heavy dependencies, module2 does not

*module1 and module2 will be used in different runtime environments

*module2 should be installable separately so it can run in e.g. an AWS Lambda

Consequently I have tried to set up a project structure which contains the two modules in two folders within one repo, each folder having a setup.py so it can packaged. Is this a reasonable approach?
\module1
  setup.py
  \module1
    __init__.py
    [scripts].py
\module2
  setup.py
  \module2
    __init__.py
    [scripts].py

The above structure should allow me to work on the project locally treating module2 as a regular module, but the setup.py file means that it can be distributed as it's own package, right?
The problem is that I can't include the module2 dependency in module1's setup.py:
from setuptools import setup

setup(
    name="module1",
    version="0.1",
    packages=['module1'], # I really need to include module2 scripts here, right?...
    install_requires=['pandas', 'numpy', ...]
)

Does anyone have any advice on how to approach this problem? The two solutions I can guess are:

*

*Packaging and publishing module2 on it's own before depending on it from module1. This makes development much more infleixble

*Nesting module2 within module1 so I can include it in the packages argument to the setup(...) function. This breaks the clarity that module1 should be treating module2 as if it were essentially an external dependency...

A: Your main reason to keep them in the same repository is to enable parallel work on both the modules in your IDE. I would suggest to keep the modules in separate repositories and use the editable mode for pip or develop mode for setuptools to achieve the "parallel" development.
Essentially, you would be installing module2 in a develop/editable mode when you use it in module1. Thereafter, you will see all the changes made to module2 immediately while developing module1
Doing the same will also make sure that things like pip install git+<git_directory> do not break and you can install directly from git


text:
Q: Help Troubleshoot Exception XCode I am trying to run the following code:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";
    GradeToolAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate = [UIApplication sharedApplication].delegate;
    // Dequeue or create a cell of the appropriate type.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    NSLog(@"Array Count: %d", [appDelegate.modules count]);
    // Configure the cell.
    //cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];
    //Module * aModule = [appDelegate.modules objectAtIndex:indexPath.row];
    //cell.textLabel.text = aModule.moduleTitle;
    return cell;
}

But it just crashes the app with:
2011-05-20 15:38:09.256 GradeTool[3994:207] -[GradeToolAppDelegate modules]: unrecognized selector sent to instance 0x5523f80
2011-05-20 15:38:09.258 GradeTool[3994:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GradeToolAppDelegate modules]: unrecognized selector sent to instance 0x5523f80'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00eebbe9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x00ce05c2 objc_exception_throw + 47
    2   CoreFoundation                      0x00eed6fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x00e5d366 ___forwarding___ + 966
    4   CoreFoundation                      0x00e5cf22 _CF_forwarding_prep_0 + 50
    5   GradeTool                           0x000037ff -[RootViewController tableView:cellForRowAtIndexPath:] + 322
    6   UIKit                               0x003367fa -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
    7   UIKit                               0x0032c77f -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
    8   UIKit                               0x00341450 -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
    9   UIKit                               0x00339538 -[UITableView layoutSubviews] + 242
    10  QuartzCore                          0x01ff8451 -[CALayer layoutSublayers] + 181
    11  QuartzCore                          0x01ff817c CALayerLayoutIfNeeded + 220
    12  QuartzCore                          0x01ff137c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
    13  QuartzCore                          0x01ff10d0 _ZN2CA11Transaction6commitEv + 292
    14  UIKit                               0x002c519f -[UIApplication _reportAppLaunchFinished] + 39
    15  UIKit                               0x002c5659 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690
    16  UIKit                               0x002cfdb2 -[UIApplication handleEvent:withNewEvent:] + 1533
    17  UIKit                               0x002c8202 -[UIApplication sendEvent:] + 71
    18  UIKit                               0x002cd732 _UIApplicationHandleEvent + 7576
    19  GraphicsServices                    0x01a70a36 PurpleEventCallback + 1550
    20  CoreFoundation                      0x00ecd064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    21  CoreFoundation                      0x00e2d6f7 __CFRunLoopDoSource1 + 215
    22  CoreFoundation                      0x00e2a983 __CFRunLoopRun + 979
    23  CoreFoundation                      0x00e2a240 CFRunLoopRunSpecific + 208
    24  CoreFoundation                      0x00e2a161 CFRunLoopRunInMode + 97
    25  UIKit                               0x002c4fa8 -[UIApplication _run] + 636
    26  UIKit                               0x002d142e UIApplicationMain + 1160
    27  GradeTool                           0x00002960 main + 102
    28  GradeTool                           0x000028f1 start + 53
)
terminate called after throwing an instance of 'NSException'

The GradeToolAppDelegate * appDelegate = [UIApplication sharedApplication].delegate; seems to be one of the major problems, and when running NSLog(@"Array Count: %d", [appDelegate.modules count]); causes the exception
Can anyone help me out here on what I am doing wrong.
Thanks.

A: Your GradeToolAppDelegate does not have a modules method defined. Seeing that you are referencing via dot-notation, I'd assume you forgot to either: define the property and/or synthesize the property.


text:
Q: System of recurrence relations with unknown delay I was wondering if there is any way to solve this system of recurrences (initial conditions $X_0$, $Y_0$ and $Z_0$ are known):
\begin{align*}
X_t &= a_1 X_{t-1}+a_2 X_{t-a} + a_3 Y_{t-a} + a_4 Y_t \\
Y_t &= b_1 Y_{t-1} + b_2 X_t \\
Z_t &= c_1 Z_{t-1} + c_2 Y_t
\end{align*}
Here we have $a\in\mathbb{N}$, $a_i, b_j, c_k \in\mathbb{R}$.
The problem is, I've tried using the second equation and plugging it into the first one, trying to get the first recurrence to be only in $X$, but the problem is that $a$ is unknown and the recurrence becomes very complicated.
I couldn't find any helpful literature on the subject of systems of recurrences except hints that I should first try to express one recurrence in terms of just one variable so that I get a linear recurrence.


text:
Q: mouse coordinates offset on JPanel inside JScrollPane I have a JPanel inside a JScrollPane. The JPanel has a MouseListener attached to react to mouse events. When I add the JPanel directly to the parent JComponent (without the JScrollPane in between) it all works correctly. Once I add the JScrollPane to the mix, the mouse coordinates sent to the event handlers on the JPanel all have a positive offset along both the x and y axis.
Example (mouse listener on JPanel):
public void mousePressed(MouseEvent ev) {
    System.out.println(ev.getPoint());
    System.out.println(this.getMousePosition());
}

When I click on the upper left corner of the JPanel instead of (0,0) I get something like (5,60) from both functions while the lower right corner (for a JPanel sized 600x400) returns (605,460). Any idea where this linear offset comes from?
Edit: Nevermind, I reduced it to a simple testcase and it works as expected. So it must be something in my surrounding code that is causing this behavior.
public class JScrollPaneTest {
public static void main(String[] args) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout());
    MyPanel panel = new MyPanel();
    window.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);

    window.setSize(new Dimension(600, 400));
    window.setVisible(true);

}

}

public class MyPanel extends JPanel implements MouseListener, Scrollable {
public MyPanel() {
    setLayout(null);
    addMouseListener(this);
    this.setAutoscrolls(true);
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(2000, 2000);
}

@Override
public void mousePressed(MouseEvent ev) {
    System.out.println("Event mouse position: " + ev.getPoint());
    System.out.println("Panel mouse position: " + this.getMousePosition());
}
}

A: please could you reproduce your problem based on this example?
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class MainViewPort {

    public static void main(String[] args) {
        JPanel viewportPanelTop = new JPanel();
        JPanel viewportPanelBottom = new JPanel();
        JPanel viewportPanel = new JPanel();
        viewportPanel.setBackground(Color.BLACK);
        viewportPanel.setPreferredSize(new Dimension(1000, 1000));
        JPanel viewportPanel1 = new JPanel();
        viewportPanel1.setBackground(Color.red);
        JPanel viewportPanel2 = new JPanel();
        viewportPanel2.setBackground(Color.blue);
        JPanel viewportPanel3 = new JPanel();
        viewportPanel3.setBackground(Color.cyan);
        JPanel viewportPanel4 = new JPanel();
        viewportPanel4.setBackground(Color.yellow);
        JPanel viewportPanel5 = new JPanel();
        viewportPanel5.setBackground(Color.LIGHT_GRAY);
        JPanel viewportPanel6 = new JPanel();
        viewportPanel6.setBackground(Color.magenta);
        viewportPanel.setLayout(new GridLayout(3, 2));
        viewportPanel.add(viewportPanel1);
        viewportPanel.add(viewportPanel2);
        viewportPanel.add(viewportPanel3);
        viewportPanel.add(viewportPanel4);
        viewportPanel.add(viewportPanel5);
        viewportPanel.add(viewportPanel6);

        viewportPanel.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println(e.getPoint());
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setPreferredSize(new Dimension(800, 600));
        scrollPane.setBackground(Color.BLUE);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.getViewport().add(viewportPanel);
        scrollPane.getViewport().setViewPosition(new Point(0, 0));
        scrollPane.getViewport().setBackground(Color.red);
        scrollPane.setBorder(new LineBorder(Color.black, 2));

        JFrame frame = new JFrame();
        frame.setTitle("Viewport JFrame");
        frame.setLocation(150, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(viewportPanelTop, BorderLayout.NORTH);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(viewportPanelBottom, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private MainViewPort() {
    }
}


text:
Q: advanced custom field (ACF) + Contact Form 7 I use ACF (Advanced Custom Fields plugin) for Categories, Contact Form 7 and/or Contact Form 7 - Dynamic Text Extension / Contact Form 7 Modules: Hidden Fields.
I will try to explain with example what I want to achieve...
I create categories where i fill some additional data using ACF. In my case, every category is Company Name. I use ACF, to fill Copmany Phone, Company E-mail, Company Address, etc.
After than, I create posts, where every post is associated with some category.
In this posts, I use Contact form with shortcode directly in single.php (echo do_shortcode( '[contact-form-7 id="206" title="Contact form EN"]' );)
Here coming my dilemma and BIG question:
I want in this Contact form, to load pre populated data from category where is this post. (eg. If post is in category Company A, I want this post to preload Contact form with hidden fields from their category).

A: you could insert the fields you need to populate the contact form in your url as query parameters and then get them with contact form

www.yourwebsite.com/?your-name=foo

[text* your-name default:get]

see https://contactform7.com/getting-default-values-from-the-context/


text:
Q: Parsing "clusters" of lines in a text file based on number of lines below a word in python So I have a uniformly formatted text file that I am trying to parse based on the number of lines below the word 'cluster'. Here is my code so far:
f = open('file.txt', 'r')
main_output = open('mainoutput.txt', 'w')
minor_output = open('minoroutput.txt', 'w')
f_lines = f.readlines()
main_list = []
minor_list = []
for n, line in enumerate(open('file.txt')):
    if 'cluster' in line:
        if 'cluster' in f_lines[n+1] or f_lines[n+2] or f_lines[n+3]:
            minor_list.append(line)
            minor_list.append(f_lines[n+1])
            minor_list.append(f_lines[n+2])
            minor_list.append(f_lines[n+3])
        if 'cluster' not in f_lines[n+1] or f_lines[n+2] or f_lines[n+3]:
            main_list.append(line)
            main_list.append(f_lines[n+1])
            main_list.append(f_lines[n+2])
            main_list.append(f_lines[n+3])
minor_output.write(''.join(minor_list))
main_output.write(''.join(main_list))
f.close()
main_output.close()
minor_output.close()

The format of the text file is as follows:
>Cluster 1
line 1
line 2
line 3
...

>Cluster 2
line 1
line 2
...

and so on for many clusters.

Each cluster has a variable number of lines below it, from 1 to 100+. I am interested in sorting these clusters by the number of lines(items) in each cluster. This code is working but the two output files are identical. Any help with my code or my strategy would be awesome!

A: If I understand the code you've posted correctly, you want to sort your data into two different files depending on how many items are in a cluster. If there are three or fewer, the cluster goes into minoroutput.txt, while if there are more than that, it goes into mainoutput.txt.
There are a couple of significant logic errors that I suspect are causing your code to not sort the data properly.
Firstly, your test to see if an line contains the word "cluster" won't match capitalized "Cluster" like you have in your example data. This may only be an issue with the example data you've shown, and it's would be easy to fix by calling lower() on the line before checking it.
Second, your check of later lines is incorrect. The code if 'cluster' in f_lines[n+1] or f_lines[n+2] or f_lines[n+3] doesn't check for "cluster" in each of the three strings, but rather only in the first. The second and third strings are being evaluated all by themselves, in boolean context. If they're not empty lines, they'll be True, making the whole expression almost always true as well. For this to work, you'd need to check 'cluster' in f_lines[n+1] or 'cluster' in f_lines[n+2] or 'cluster' in f_lines[n+3] (but I'll show a better alternative later). The same problem happens with the other if statement, where you will also almost always get a True result from your condition, since f_lines[n+2] and f_lines[n+3] are probably not both empty.
Lastly, your logic for writing out the clusters is probably incorrect. It currently writes out exactly four lines always, even though many clusters will have more or fewer items than that. For every cluster written to mainoutput.txt, some lines will be discarded (this might be deliberate). For some cluster's written to minoroutupt.txt, however, there's going to be a clear bug where it will write out the start of the next cluster after a cluster with only one or two items.
Here's some code that I think will work for you. I've changed around the loop so that it just reads the file once, rather than reading the lines once into a list and a second time in enumerate. Rather than explicitly looking at the next three lines, I simply put each line into a list, resetting each time there's a line with cluster in it (with any capitalization).
with open('file.txt', 'r') as f, \
     open('mainoutput.txt', 'w') as main_out, \
     open('minoroutput.txt', 'w') as minor_out:
    cluster = [] # this variable will hold all the lines of the current cluster
    for line in f:
        if 'cluster' in line.lower(): # if we're at the start of a cluster
            if len(cluster) > 4: # long clusters go in the "main" file
                main_out.writelines(cluster) # write out the lines
                # main_out.writelines(cluster[:4])
            else:
                minor_out.writelines(cluster) # or to the other file

            cluster = [] # reset the cluster variable to a new, empty list

        cluster.append(line) # always add the current line to cluster

    if len(cluster) > 4: # repeat the writing logic for the last cluster
        main_out.writelines(cluster)
        # main_out.writelines(cluster[:4])
    else:
        minor_out.writelines(cluster)

Use the two commented writelines lines in place of the uncommented ones just before them if you only want the first three items in a cluster to be output into mainout.txt (with the rest being discarded). I don't think there's a reasonable alternative to printing all the lines in minorout.txt.
Given file.txt with these contents:
>Cluster 1
line 1
line 2
line 3
>Cluster 2
line 1
line 2
line 3
line 4
>Cluster 3
line 1
>Cluster 4
line 1
line 2
line 3
line 4
line 5

The code above will output two files:
mainoutput.txt:
>Cluster 2
line 1
line 2
line 3
line 4
>Cluster 4
line 1
line 2
line 3
line 4
line 5

minoroutput.txt:
>Cluster 1
line 1
line 2
line 3
>Cluster 3
line 1


text:
Q: Is overriding of constraints() and removeConstraints() necessary when creating a custom control? I'm creating a custom control that uses auto-layout to arrange its subviews.
Naturally, I don't want users of my custom control to inadvertently mess with these internal constraints when programmatically manipulating the control's constraints so I thought I should override constraints() to hide those internal ones the user should never need to know about and also removeConstraints() to prevent the user from removing them.
But then it occurred to me that UIKit itself probably invokes constraints() and/or removeConstraints() and expects to be able to see all of them.
So, should I or should I not, override constraints() and removeConstraints() ?


text:
Q: How can I copy a single file to Multiple Destinations if they exist I have a script for Adobe AE that has to be installed in the installation folder ex. "C:\Program Files\Adobe\Adobe After Effects CC 2017\Support Files\Scripts\"
We have users with multiple  installed versions of AE and will require the script in each. Ideally what I would like for is a script that would copy "script.jsx" to the destination folders if they exist.
I tried using the below but it fails to check if the destination exists.
"C:\Program Files\Adobe\Adobe After Effects CC 2018\Support Files\Scripts\","C:\Program Files\Adobe\Adobe After Effects CC 2017\Support Files\Scripts\","C:\Program Files\Adobe\Adobe After Effects CC 2016\Support Files\Scripts\" |
ForEach-Object {Copy-Item $dirFiles\rd_RenderLayers.jsx -Recurse -Destination $_}

I have also tried this
if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2014\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2014\Support Files\Scripts\
 }
 if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2015\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2015\Support Files\Scripts\
 }
 if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2016\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2016\Support Files\Scripts\
 }
 if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2017\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2017\Support Files\Scripts\
 }
 if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2018\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2018\Support Files\Scripts\
 }
 if ( $(Try { Test-Path "C:\Program Files\Adobe\Adobe After Effects CC 2019\Support Files\Scripts\".trim() } Catch { $false }) ) {
   Copy-Item -Path C:\Users\Desktop\rd_renderlayers_v3.1\rd_RenderLayers.jsx -Destination C:\Program Files\Adobe\Adobe After Effects CC 2019\Support Files\Scripts\
 }

A: foreach ($dest in 'there2','there3') { cp there $dest }

A: You need to create a conditional with Test-Path -LiteralPath $_ inside your ForEach-Object to limit copying to those input directories that exist:
$dirs |
  ForEach-Object {
    if (Test-Path -LiteralPath $_) {
      Copy-Item $dirFiles\rd_RenderLayers.jsx -Destination $_
    }
  }

Note that I've removed -Recurse, because it doesn't apply when you're copying a single file.


text:
Q: Windows Mobile - Disable USB (Compact Framework - C#) I need to disable USB on Windows Mobile. How to disable USB on Windows Mobile using Compact Framework 2.0 (C#)? I am using OpenNETCF too. If it has some class to disable USB, I can use it too.

A: A bit of advice, you have to implement both operations to lock / unlock the usb device. Because if you can't unlock it you must perform a clean boot.
You should provision the device with this specific policies
<!-- DenyRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="0"/>
    </characteristic>
</wap-provisioningdoc>

<!-- AllowRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="2"/>
    </characteristic>
</wap-provisioningdoc>

I provide a link to the original post in which is suggested that you create the cabs.
Original Post
I have used another approach to read the XML configuration and then using the following method I execute the provisioning
Microsoft.WindowsMobile.Configuration.ConfigurationManager.ProcessConfiguration(XmlDocument,boolean);

Another option is to use builds the cabs and install them by using wceload.exe

A: If your application is code-signed and running in full trust, then you have access to protected registry keys. You could then try to edit or remove the various USB device driver configuration registry values. Then you might have disabled USB.
Edit: Possibly involved registry keys:

HKEY_LOCAL_MACHINE\Drivers\USB\FunctionDrivers


text:
Q: -fshort-wchar and std::wstring - segmentation fault I use Ubuntu 18.04 and gcc 7.5.0. I have a library which is compiled with -fshort-wchar. I have noticed that using std::wstring in the library  may leads to the segmentation fault. I have found a similar topic. There is an explanation:

-fshort-wchar is not usable if you want to interact with any part of the standard library or third-party library code using the correct (32-bit) definition of wchar_t.

I understand that I can't use std::wstring when a library is compiled with -fshort-wchar but what with the other standard library content ? Why I can't interact with any part of the standard library, for example std::vector ?

A: -fshort-wchar          sets the size of wchar_t to 2 bytes

Now think about what will happen if you use a part of the standard library that is not header only. A big part of the standard library is compiled into a library that you link with (libstdc++ / libc++). When that was compiled -fshort-wchar was not used and the size of the wchar_t is therefore 4 bytes in the library.


text:
Q: Why can't my Redis Lua script atomically update keys on different Redis Cluster nodes? I have a Redis Cluster consisting of multiple nodes. I want to update 3 different keys in a single atomic operation. My Lua script is like:
local u1 = redis.call('incrby', KEYS[1], ARGV[1])
local u2 = redis.call('incrby', KEYS[2], ARGV[1])
local u3 = redis.call('incrby', KEYS[3], ARGV[1])

And I fired it with:
EVAL script 3 key1 key2 key3 arg

But I got the error message:
WARN Resp(AppErr CROSSSLOT Keys in request don't hash to the same slot)

The above operations cannot be done, and the updates will fail.  It seems I cannot modify the keys in different nodes with a single Lua script.  But according to the doc:

All Redis commands must be analyzed before execution to determine
which keys the command will operate on. In order for this to be true
for EVAL, keys must be passed explicitly. This is useful in many ways,
but especially to make sure Redis Cluster can forward your request to
the appropriate cluster node.
Note this rule is not enforced in order
to provide the user with opportunities to abuse the Redis single
instance configuration, at the cost of writing scripts not compatible
with Redis Cluster.

So I think as long as I follow the key passing rule, the script should be compatible with Redis Cluster. I wonder what's the problem here and what should I do to update all keys in a single script.

A: I'm afraid you've misunderstood the documentation. (And I agree that it's not very clear.)
Redis operations, whether commands or Lua scripts, can only work when all the keys are on the same server. The purpose of the key passing rule is to allow Cluster servers to figure out where to send the script and to fail fast if all the keys don't come from the same server (which is what happened in your case).
So it's your responsibility to make sure that all the keys you want to operate on are located on the same server. The way to do that is to use hash tags to force keys to hash to the same slot. See the documentation for more details on that.


text:
Q: Structs and interface types Could someone please explain (or if it's a long thing to explain at least point me to some documentation) why this code is behaving like it does. It's a bit lengthy but I couldn't figure out a good way of shortening it without losing too much info.
What confuses me is that I need to have the method "Find" on each type of struct for it to be recognized as the type it is. With Find on only the baseTypeImp is it printing that each is baseTypeImp, if I have it on baseTypeImp and advancedBaseTypeImp are those two identified correctly, but not the last type.
PlaygroundLink
My Code
package main

import (
    "fmt"
    "reflect"
)

type BaseType interface {
    Name() string
    Find(string) BaseType
    Children() []BaseType
    Options()
}

type baseTypeImp struct {
    name     string
    children []BaseType
}

func (b baseTypeImp) Options() {
    fmt.Println("Not implemented")
}

func (b baseTypeImp) Find(name string) BaseType {
    if b.name == name {
        return b
    }

    for _, c := range b.children {
        if m := c.Find(name); m != nil {
            return m
        }
    }
    return nil
}

func (b baseTypeImp) Name() string {
    return b.name
}
func (b baseTypeImp) Children() []BaseType {
    return b.children
}

type AdvancedBaseType interface {
    Value()
}

type advancedBaseTypeImp struct {
    baseTypeImp
}

func (a advancedBaseTypeImp) Options() {
    fmt.Println("Is implemented")
}

func (a advancedBaseTypeImp) Value() {
    fmt.Println("Value called")
}

func (a advancedBaseTypeImp) Find(name string) BaseType {
    if a.name == name {
        return a
    }

    for _, c := range a.children {
        if m := c.Find(name); m != nil {
            return m
        }
    }
    return nil
}

type reallyAdvancedBaseTypeImp advancedBaseTypeImp

func newThingy(name, variant string, children []BaseType) BaseType {
    base := baseTypeImp{name: name, children: children}
    switch variant {
    case "advanced":
        return advancedBaseTypeImp{baseTypeImp: base}
    case "reallyAdvanced":
        return reallyAdvancedBaseTypeImp{baseTypeImp: base}
    }
    return base
}

func whatType(b BaseType) {
    if b == nil {
        return
    }
    fooType := reflect.TypeOf(b)
    fmt.Println(b.Name(), " is type ", fooType.Name())
    b.Options()
}

func main() {
    advanced := make([]BaseType, 0, 5)
    for i := 0; i < 5; i++ {
        advanced = append(advanced, newThingy(fmt.Sprintf("Advanced %d", i), "advanced", nil))
    }
    reallyAdvanced := make([]BaseType, 0, 2)
    for i := 0; i < 2; i++ {
        reallyAdvanced = append(reallyAdvanced, newThingy(fmt.Sprintf("ReallyAdvanced %d", i), "reallyAdvanced", advanced[i:i+3]))
    }
    basic := newThingy("Basic parent", "basic", reallyAdvanced)
    whatType(basic.Find("Basic parent"))
    for i := 0; i < 2; i++ {
        whatType(basic.Find(fmt.Sprintf("Advanced %d", i)))
        whatType(basic.Find(fmt.Sprintf("ReallyAdvanced %d", i)))
    }
}

The output now is:
Basic parent  is type  baseTypeImp
Not implemented
Advanced 0  is type  advancedBaseTypeImp
Is implemented
ReallyAdvanced 0  is type  baseTypeImp
Not implemented
Advanced 1  is type  advancedBaseTypeImp
Is implemented
ReallyAdvanced 1  is type  baseTypeImp
Not implemented

What I'd like to have is:
Basic parent  is type  baseTypeImp
Not implemented
Advanced 0  is type  advancedBaseTypeImp
Is implemented
ReallyAdvanced 0  is type  reallyAdvancedBaseTypeImp
Is implemented
Advanced 1  is type  advancedBaseTypeImp
Is implemented
ReallyAdvanced 1  is type  reallyAdvancedBaseTypeImp
Is implemented

Is there a way to get this working without having to implement Find on each level? It kind of defeats the purpose of having the common methods in the top layer struct. And of course, if possible explain why it's behaving the way it does.

A: When you embed a struct into another one, the outer struct gets the methods of the embedded one.
type inner struct {
}

func (i inner) f() {}

type outer struct {
  inner
}
...

x:=outer{}
x.f()

You can think of this as syntactic sugar for:
type outer2 struct {
  i inner
}

y.i.f()

When you embed inner without a field name, you simply drop the i in the call. You can still call x.inner.f() in the first example.
When you redefine a type, it does not get the methods defined for its base type.
type newtype inner

newtype does not have f() defined. However, if inner also embeds other structs (like you do), then those are still embedded in the new type, so those function are defined:
type deepest struct {}
func (deepest) deep() {}

type inner struct{}
func (inner) in() {}

type outer inner

Above, the type outer does not have the function in, but it has deep.
So when you call reallyAdvancedBaseTypeImp.Find(), what you're really doing is reallyAdvancedBaseTypeImp.baseTypeImp.Find(), which works on that portion of the struct. That's why you're getting the types you get.
You're trying to emulate method overriding. You can't really do that. Formulate your problem in a different way.


text:
Q: insert text to file - bash I am exploring sed function(I am aware that I had asked a similar question like this before, but given the fact that I am terribly bad at regex , I need lots of help, but that doesn't mean I didn't try out myself)
what I have here is a simple text file shown below
Id,fruit name and quantity.
this time I want to add the price of the fruit behind the quantity of each fruit respectively BY FINDING THE FRUIT NAME.
fruit.txt
1,apple,50
2,banana,40

I tried this command
sed -i -r "s/(apple.*)([,0-9]*)/\1,5/" "fruit.txt"

so on the first input
 sed -i -r "s/(apple.*)([,0-9]*)/\1,5/" "fruit.txt"

my textfile(clothes.txt) will become like this
1,apple,50,5
2,banana,40

on the second input
 sed -i -r "s/(apple.*)([,0-9]*)/\1,30/" "fruit.txt"

my textfile(clothes.txt) will become like this
1,apple,50,5,30
2,banana,40

how do I make it to become like this.
expected output
first input of sed command
my textfile(fruit.txt) will become like this
1,apple,50,5
2,banana,40

on the second input of sed command
my textfile(fruit.txt) will become like this
1,apple,50,30
2,banana,40

A: Use this:
sed -i -r "s/(apple,[0-9]*).*/\1,30/" "fruit.txt"

Here, \1 is a backreferences. It matches the first capture group.
Before, your first capture group was matching too much.

A: Instead of saying [,0-9]*, ensure that you match only one ,.  You can say:
sed -i -r 's/(apple,[^,]*).*/\1,15/' filename

Here saying (apple,[^,]*) would put apple followed by a , followed by anything that is not a , into a group.  The .* would match everything remaining.
This would change
1,apple,50,5
2,banana,40

to
1,apple,50,15
2,banana,40


text:
Q: Regular expression to parse option string I'm using the Java matcher to try and match the following:
@tag TYPE_WITH_POSSIBLE_SUBTYPE -PARNAME1=PARVALUE1 -PARNAME2=PARVALUE2: MESSAGE

The TYPE_WITH_POSSIBLE_SUBTYPE consists of letters with periods.
Every parameter has to consist of letters, and every value has to consist of numerics/letters. There can be 0 or more parameters.
Immediately after the last parameter value comes the semicolon, a space, and the remainder is considered message.
Everything needs to be grouped.
My current regexp (as a Java literal) is:
(@tag)[\\s]+?([\\w\\.]*?)[\\s]*?(-.*=.*)*?[\\s]*?[:](.*)

However, I keep getting all the parameters as one group. How do I get each as a separate group, if it is even possible?
I don't work that much with regexps, so I always mess something up.

A: If you want to capture each parameter separately, you have to have a capture group for each one.  Of course, you can't do that because you don't know how many parameters there will be.  I recommend a different approach:
Pattern p = Pattern.compile("@tag\\s+([^:]++):\\s*(.*)");
Matcher m = p.matcher(s);
if (m.find())
{
  String[] parts = m.group(1).split("\\s+");
  for (String part : parts)
  {
    System.out.println(part);
  }
}
System.out.printf("message: %s%n", m.group(2));

The first element in the array is your TYPE name and the rest (if there are any more) are the parameters.

A: Try this out (you may need to add extra '\' to make it work within a string.
(@tag)\s*(\w*)\s*(-[\w\d]*=[\w\d]*\s*)*:(.*)

By the way, I highly recommend this site to help you build regular expressions: RegexPal.  Or even better is RegexBuddy; its well worth the $40 if you plan on doing a lot of regular expressions in the future.


text:
Q: Convergence of a sequence of partial sums of partial sums Let $(x_n)$ be a real-valued sequence with partial sums $s_n = x_1 + x_2 + ... +x_n$. We define $\sigma_n = \frac{1}{n}(s_1 + s_2 + ... + s_n)$. Now, supposing $\Sigma\,x_n$ is convergent, I need to show that the sequence $(\sigma_n)$ is convergent and that $lim\,\sigma_n = \Sigma\,x_n$.
My intuition is to simply say that since $\Sigma\,x_n$ converges, then $lim\,sup\,s_n = lim\,s_n = L$, some real number, and then try to find a way to use a convergence test.
But I don't have any information about the $x$-values, so I can't say they're non-negative, which means I can't use comparison, and the ratio and root test both come out inconclusive since $lim\,\frac{\sigma_{n+1}}{\sigma_n}=1$.
Should I be finding a way to use the Cauchy criterion here? Or am I missing a different technique altogether?
EDIT: This isn't actually a duplicate of the arithmetic mean problem, because there is only one series of partial sums in the arithmetic mean. This problem takes the sum of each of those sums from 1 to n and presents a new problem with that.
EDIT 2: Upon further review, although not identical, the problem turns out to essentially be a re-skin of the arithmetic mean. See answer below.

A: Following Convergence of the arithmetic mean
Let $a_n:=s_n=x_1+\cdots+x_n$.
$(a_n)_n$ is convergent, because $\sum x_n$ is convergent.
Hence, (by the previous post) $\frac{1}{n}(a_1+\cdots+a_n)$ is convergent to $L:=\lim a_n$.
But $\frac{1}{n}(a_1+\cdots+a_n)=\sigma_n$ , so $(\sigma_n)_n$ is convergent to $L=\lim a_n=\sum x_n$.

A: By Stolz–Cesàro theorem
$$\lim_{n\to \infty }\frac{(s_1 + s_2 + ... + s_n+s_{n+1})-(s_1 + s_2 + ... + s_n)}{n+1-n}=\lim_{n\to \infty } s_{n+1}=\sum x_n$$
then
$$\lim_{n\to \infty }\sigma(n)=\lim_{n\to \infty }\frac{s_1 + s_2 + ... + s_n}{n}=\sum x_n$$


text:
Q: Bind multiple queries into one result Can anybody help me to get a result form multiple SQL requests:
SELECT *
(COUNT(*) AS Records FROM wp_posts WHERE post_type='news' AND post_status='publish') as News,
(COUNT(*) AS Records FROM wp_posts WHERE post_type='promotion' AND post_status='publish') as Promos,
(COUNT(*) AS Records FROM wp_posts WHERE post_type='contact' AND post_status='publish') as Contacts
FROM wp_posts

I just want to find out how many custom posts in my WP MySQL by sending one SQL requests.

A: There is no need for subqueries at all:
SELECT
  SUM(CASE WHEN post_type='news' THEN 1 ELSE 0 END) AS News,
  SUM(CASE WHEN post_type='promotion' THEN 1 ELSE 0 END) AS Promos,
  SUM(CASE WHEN post_type='contact' THEN 1 ELSE 0 END) AS Contacts
FROM wp_posts
WHERE post_status='publish';

or even shorter:
SELECT
  SUM(IF(post_type='news', 1, 0)) AS News,
  SUM(IF(post_type='promotion', 1, 0)) AS Promos,
  SUM(IF(post_type='contact', 1, 0)) AS Contacts
FROM wp_posts
WHERE post_status='publish';

A: Use UNION ALL to combine the queries (they need to have the same number of columns)
SELECT * FROM (
SELECT 1
UNION ALL
SELECT 2
)

A: You can issue one select with three nested select queries and get the results as columns:
SELECT
(SELECT COUNT(*) FROM wp_posts WHERE post_type='news' AND post_status='publish') as News,
(SELECT COUNT(*) FROM wp_posts WHERE post_type='promotion' AND post_status='publish') as Promos,
(SELECT COUNT(*) FROM wp_posts WHERE post_type='contact' AND post_status='publish') as Contacts


text:
Q: NOT LESS THAN IN MYSQL Following is my sql query in which i am trying to pull only those records whose dt_dischargedt can be null or they should NOT LESS THAN the current date so it'll show only those patient's records who doesnot get discharged. Kindly let me know how can i modify the following query to accomplish what i have been trying to do.
       SELECT *
       FROM z_census
       where
       DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 MONTH),'%m-%Y') NOT LESS THAN DATE_FORMAT(dt_dischargedt,'%m-%Y') OR dt_dischargedt IS NULL

A: Why not try greater than or equal to? >= ?


text:
Q: Hooking Direct X Endscene in Direct X 11 game I have to do some memory reading in a game and some injection. However, to avoid race conditions, I need to inject my ASM code into the endscene.
Previously I have used this code:
uint D3D9_Device;
D3D9_Device = Memory.Read<uint>(Memory.BaseAddress + Direct3D9__Device);
D3D9_Device = Memory.Read<uint>(D3D9_Device + Direct3D9__Device__OffsetA);
D3D9_Device = Memory.Read<uint>(D3D9_Device);
D3D9_Device = Memory.Read<uint>(D3D9_Device + Direct3D9__Device__OffsetB);

To access the Dx9 device, and find the endscene using reversed offsets.
However, in windows 7, directx 11 is forced, which means that this read fails and gives a null object.
Any idea how I might perform a hook into the endscene of a game when DirectX 11 is in use?

A: You should be IAT hooking GetProcAddress and calls to D3DCreate, capturing the device pointer and hooking the VFTable from there. dunno how you 'reversed' the COM vftable offsets (these are predefined by how COM dlls are build, you need only count up the virtual methods defined in the DX SDK headers, start at 0, then multiply by sizeof(INT_PTR) to get the offset), but the way your reading them looks wrong too (you've got one too many indirections).
Try having a look at something like MSDetours, it has an example on COM object hooking. you can also give this question a read through too


text:
Q: mouse down and take a screenshot of an element I am trying to simulate a mousedown action on an element then take a snapshot but this doesn't seem to work as the screenshot isn't what I expect.
according to the api docs, this is what it does
mouse.down([options])
options <Object>
button <"left"|"right"|"middle"> Defaults to left.
clickCount <number> defaults to 1. See UIEvent.detail.
returns: <Promise>
Dispatches a mousedown event.

I have tried the following:
  it('primary button visually looks correct on mouse down', async () => {
    await page.goto('my_url_page');
    await page.waitForSelector(testData.button, 20000);
    const elementHandle = await page.$(testData.button);
    await page.mouse.move(0, 0);
    await page.mouse.down();
    const image = await elementHandle.screenshot();

    expect(image).toMatchImageSnapshot();
  });

the button has some animation when the mouse is pressed down and this is what I want to take a screenshot of.
Appreciate the support with this


text:
Q: How to return two value from a function in dart? here is my code
import 'dart:io';
import 'dart:math';

void main() {
  bool flag = false;
  for (int i = 0; i < 100; i++) {
    gameCode();
    if (userNumber == computerNumber) {
      flag = true;
      break;
    }

  }
}

int randomNumber(number) {
  Random randNumber = Random();
  int random = randNumber.nextInt(number);
  return random;
}

gameCode() {
  int computerNumber = randomNumber(9);
  print("start guessing the number : ");
  int userNumber = int.parse(stdin.readLineSync()!);
  if (userNumber == computerNumber) {
    print("You got it");
  }
}

in this code you can see gameCode function. in that function there is two value that i need to use in main function.so how do i return those two keyword from that function ?
//userNumber // computerNumber

this is the variable that i want to return from that code

A: Dart not support return multiple values in function, you can return it with array, map, or you can use third lib tuple

A: Dart does not support returning multiple values in the current latest version. I would in your case recommend creating a class for the specific purpose of define the result from gameCode(). So something like this:
class GameCodeResult {
  int userNumber;
  int computerNumber;

  GameCodeResult({
    required this.userNumber,
    required this.computerNumber,
  });
}

Which we can then use like this in your program:
import 'dart:io';
import 'dart:math';

void main() {
  bool flag = false;
  for (int i = 0; i < 100; i++) {
    GameCodeResult result = gameCode();
    if (result.userNumber == result.computerNumber) {
      flag = true;
      break;
    }
  }
}

final _random = Random();
int randomNumber(int maxNumber) => _random.nextInt(maxNumber);

GameCodeResult gameCode() {
  int computerNumber = randomNumber(9);
  print("start guessing the number : ");
  int userNumber = int.parse(stdin.readLineSync()!);

  if (userNumber == computerNumber) {
    print("You got it");
  }

  return GameCodeResult(userNumber: userNumber, computerNumber: computerNumber);
}

Note, I also fixed your randomNumber() method since it is not recommended to generate a new Random() object for each new random number you want. We should instead reuse an instance of Random in our program.

A: Please refer to below code
import 'dart:io';
import 'dart:math';

void main() {
  bool flag = false;
  for (int i = 0; i < 100; i++) {
   Map<String, dynamic> res = gameCode();
    print(res);
    if (res['user_number'] == res['computer_number']) {
      flag = true;
      break;
    }

  }
}

int randomNumber(number) {
  Random randNumber = Random();
  int random = randNumber.nextInt(number);
  return random;
}

Map<String, dynamic> gameCode() {
  int computerNumber = randomNumber(9);
  print("start guessing the number : ");
  int userNumber =
    int.parse(stdin.readLineSync()!);
  if (userNumber == computerNumber) {
    print("You got it");
  }
  return {
    "computer_number": computerNumber,
    "user_number": userNumber,
  };
}


text:
Q: Accelerometers as external interrupt If I am using an accelerometer to externally wake up my microcontroller, will my accelerometer consume power all the time? or only during a event detection?

A: it depends on accelerometer but in the common case YES, the accelerometer will work!
Almost all accelerometers allow setup threshold to generate an interrupt, in this case, you can reduce consumptions by the set minimal sampling frequency.
And some accelerometers have the internal mechanism to detect primitive motions, consumption in this also can be various.
And don't forget to provide independent power supply to accelerometer


text:
Q: Need to move this Object in one direction I am trying to move this seatBelt object just on the horizontal plane. I have posted what I did so far. it's not really working out because it seems like once I press the button the seat belt is only able to move towards the right side and MOUSE_UP doesn't work. can somebody guide me on how to go about doing this?
 seatBelt.addEventListener (MouseEvent.MOUSE_DOWN, prsing);
    seatBelt.addEventListener (MouseEvent.MOUSE_UP, lfting);
    seatBelt.addEventListener (MouseEvent.MOUSE_MOVE, mving);

    function prsing (e:MouseEvent){
    posX= seatBelt.x ;
        posY = seatBelt.y ;
        mouseclick = 1;

    }
    function mving (e:MouseEvent) {
        if (mouseclick == 1) {
        seatBelt.x = mouseX ;
        }
    }

    function lfting (e:MouseEvent){
        seatBelt.x = posX;
        seatBelt.y = posY;
        mouseclick =0;

    }

A: So your intended functionality is to be able to drag the seatBelt along the x-axis and on release for it to go back to its original position?
You need to change the MOUSE_UP and MOUSE_MOVE to listen to the stage rather than the seatBelt. This is because it is possible for you to release the button when it is no longer over the seatBelt and so the function never gets called. The stage however will receive the event.
stage.addEventListener(MouseEvent.MOUSE_UP, lifting);
stage.addEventListener(MouseEvent.MOUSE_MOVE, moving);

I am not sure where you are declaring the mouseX variable but if you are after dragging functionality alter the listener to:
   function moving (e:MouseEvent) {
        if (mouseclick == 1) {
        seatBelt.x = e.stageX;
        }
    }

A: What you have mostly looks okay code-wise, except what I think is happening is that you are "mousing up" on the stage/somewhere off the seatBelt object. I'm guessing this as to make the object move you have it reacting to mouse moving...to which I am guessing you are moving the mouse all over the stage and off the seatbelt object at which point you are then releasing the mouse.
To check if this is the case, try releasing the mouse over your seatBelt object to see if your MOUSE_UP event does get triggered.
I'm guessing the behaviour you want is that you want to have the object stop moving at any point regardless of where the mouse is released. To do this, try adding the MOUSE_UP event listener to the stage:
this.stage.addEventListener (MouseEvent.MOUSE_UP, lfting);

Though, since you may not always want this listener to be active, perhaps only add it when the mouse is pressed down over the object by adding and removing the listener only as needed.
I've edited your code a bit to show what I mean and taken out the "mouseclick" boolean as it wouldn't really be needed to keep track of the mouse down/up event anymore:
seatBelt.addEventListener(MouseEvent.MOUSE_DOWN, prsing);

function prsing(e:MouseEvent){
    posX= seatBelt.x ;
    posY = seatBelt.y ;
    this.stage.addEventListener(MouseEvent.MOUSE_MOVE, mving);
    this.stage.addEventListener(MouseEvent.MOUSE_UP, lfting);
}

function mving(e:MouseEvent) {
    seatBelt.x = mouseX;
}

function lfting(e:MouseEvent){
    seatBelt.x = posX;
    seatBelt.y = posY;
    this.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mving);
    this.stage.removeEventListener(MouseEvent.MOUSE_UP, lfting);
}

A: You can use the Sprite.startDrag method to do what you need. No MOUSE_MOVE listener is needed. Lookup the params if you need to: Sprite.  I like to only have only one of the MOUSE_DOWN or MOUSE_UP listeners active at a time.
seatBelt.addEventListener (MouseEvent.MOUSE_DOWN, prsing);

function prsing (e:MouseEvent){
    seatBelt.startDrag(false, new Rectangle(0,seatBelt.y,stage.width,seatBelt.y));
    seatBelt.removeEventListener (MouseEvent.MOUSE_DOWN, prsing);
    seatBelt.addEventListener (MouseEvent.MOUSE_UP, lfting);
}

function lfting (e:MouseEvent){
    seatBelt.stopDrag();
    seatBelt.addEventListener (MouseEvent.MOUSE_DOWN, prsing);
    seatBelt.removeEventListener (MouseEvent.MOUSE_UP, lfting);
}


text:
Q: CSS3 Overhead border-top transition looking like border-bottom Trying to get a CSS3 transition to grow a border-top line above my links.  For some reason it just keeps growing as if its border-bottom.   Here is the code below, using SASS mixing.  Its currently working but growing from the bottom and not the top.
#linkReport {
    padding-left: 20px;
    border-top: 0px solid transparent;
    display: inline-block;
    text-decoration: none;
    color: $defaultText;
    padding: 3px;

    &:after {
        @include outsideLinks;
    }

    &:hover:after {
      @include outsideHover;
    }
}

 @mixin outsideLinks() {
    border-top: 2px solid grey;
    content: '';
    display: block;
    width: 0;
    -webkit-transition: 0.5s ease;
    transition: 0.5s ease;
}

@mixin outsideHover() {
    width: 100%;
}

Below is a demo created with the compiled CSS produced by the above code.

#linkReport {
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  display: block;
  width: 0;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}
Some Text

A: Why is the top border appearing at the bottom?
The pseudo-element was set to display: block and so by default it will be displayed in the next line below the main element's content. This is the reason why the border-top of the pseudo-element was looking as though it was border-bottom.
Demo with problem: (Added a height and background color so that you can see what I mean)

#linkReport {
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  display: block;
  width: 0;
  height: 10px;
  background: cyan;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}
Some text

What is the solution?
Instead of setting display: block, position the pseudo-element absolutely with respect to the parent element like in the below snippet.

#linkReport {
  position: relative; /* add this */
  padding-left: 20px;
  border-top: 0px solid transparent;
  display: inline-block;
  text-decoration: none;
  color: black;
  padding: 3px;
}
#linkReport:after {
  border-top: 2px solid grey;
  content: '';
  /* display: block; remove this */
  position: absolute; /* add this */
  top: 0px; /* add this */
  left: 0px; /* add this */
  width: 0;
  -webkit-transition: 0.5s ease;
  transition: 0.5s ease;
}
#linkReport:hover:after {
  width: 100%;
}
Some text


text:
Q: Netsuite Oauth Through consumer key and Secret Referring to Stack solution
Oauth implementation in netsuite using php
What we have to send in $details?

A: Your data object. It should be a JSON formatted object.


text:
Q: How to save and load a RoomPlan scan to use as a "test" scan I'm working on a RoomPlan app. I've successfully managed to capture, save and load scans using NSKeyedArchiver. However, for apps run on the simulator or on devices without a LiDAR Scanner, I do not have any scans saved on that device so I cannot test the functionality. I want to "fill" my app with a test scan or two to be able to test my app on those devices.
The core problem here is that I can't figure out how to "capture" objects in Swift and save them hardcoded in the app instead of in NSKeyedArchiver, which is local to every device.

A: You are doing this:

*

*RoomScan --(via NSKeyedArchiver/Encodable)--> Data --(save)--> UserDefaults

*UserDefaults --(read)--> Data --(via NSUnarchiver/Decodable)--> RoomScan
So, what I suggest:
Scan a room, then convert it as Data, save it if needed.
Intercept that Data either by forcing a reading, or before saving into UserDefaults.
Choose the solution you find easier/quicker for you for the "intercept":
Convert the Data into HexString (see How to convert Data to hex string in swift), print it into Console, copy the output or save maybe that content into a Data file, and send it via AirDrop/Mail.
Create a new file into your project, and read it when needed (simulator, etc). Depending on the solution chosen since the writing might differ, the reading also might differ.


text:
Q: Electron Package - asar unpack pattern not working I need to exclude only the "package.json" from the root folder
but at the moment all "package.json" files are unpacked (from node_modules ...)
Electron v18
Electron Package v15.4.0
Windows
script in package.json
"scripts": {
    "package": "electron-packager . TestApp --out=dist/win --asar.unpack=\"{*/jar/**/*,**/jre/**/*,package.json}\"
}

and with this pattern, no file will be unpacked
/package.json => NOK

/{,!(node_modules)/**/}package.json => NOK

any ideas??
Greetings
Klaus


text:
Q: Virtual function behavior in derived classes Can I have a virtual function in the base class and some of my derived classes do have that function and some don't have.
class A{
   virtual void  Dosomething();
};

class B : public A{
   void  Dosomething();
};

class C : public A{
  //Does not have Dosomething() function.
};

A: Derived classes do not have to implement all the virtual functions, unless it is a pure virtual function. Even in this case, it will cause an error only when you try to instantiate the derived class( without implementing the pure virtual function ).
#include <iostream>

class A{
    public :
   virtual void  foo() = 0;
};

class B: public A{
    public :
   void  foo(){ std::cout << "foo" << std::endl;}
};

class C: public A{
    void bar();
};

int main() {
    //C temp; The compiler will complain only if this is initialized without
    // implementing foo in the derived class C
    return 0;
}

A: I think the closest you might get, is to change the access modifier in the derived class, as depicted below.
But, I would consider it bad practice, as it violates Liskov's substitution principle.
If you have a situation like this, you might need to reconsider your class design.
#include <iostream>

class A {
public:
    virtual void doSomething() { std::cout << "A" << std::endl; }
};

class B : public A {
public:
    void doSomething() override { std::cout << "B" << std::endl; };
};

class C : public A {
private:
    void doSomething() override { std::cout << "C" << std::endl; };
};

int main(int argc, char **args) {
    A a;
    a.doSomething();
    B b;
    b.doSomething();
    C c;
    //c.doSomething(); // Not part of the public interface. Violates Liskov's substitution principle.
    A* c2 = &c;
    c2->doSomething(); // Still possible, even though it is private! But, C::doSomething() is called!
    return 0;
}

A: From one of my c++ textbook:

Once a function is declared virtual, it remains virtual all the way down the inheritance, even if the function is not explicitly declared virtual when the derived class overrides it.
  When the derived class chooses not to override it, it simply inherits its base class's virtual function.

Therefore to your question the answer is No. Class c will use Class A's virtual function.


text:
Q: storing data into a file rather than returning to the terminal i have this function: write_reversed_file(input_filename, output_filename) that writes to the given output file the contents of the given input file with the lines in reversed order. i just need the output to be written to the file (output_filename) rather than to the terminal (python shell).
the only part im missing is to store the output into the file.
i successfully managed to complete the reversing lines part.
def write_reversed_file(input_filename, output_filename):
    for line in reversed(list(open(filename))):
        print(line.rstrip())

A: def write_reversed_file(input_filename, output_filename):
    s = ""
    f = open(input_filename,"r")
    lines = f.read().split("\n")
    f.close()
    for line in reversed(lines):
        s+=line.rstrip()+"\n"
    f = open(outPutFile.txt,"w")
    f.write(s)
    f.close()

A: It is good practice to use 'with open as' format when working with files since it is automatically closing the file for us. (as recommended in docs.python.org)
def write_reversed_file(input_filename, output_filename):
    with open(output_filename, 'w') as f:
        with open(input_filename, 'r') as r:
            for line in reversed(list(r.read())):
                f.write(line)

write_reversed_file("inputfile.txt", "outputfile.txt")


text:
Q: MVC6 new minification and bundling with Bower/NPM I started getting up to date with the ASP.NET 5 and MVC 6, and I see a lot of internet posts about Bower VS NPM.

*

*The default started MVC template however uses both, is this required for the taskrunner (gulp) to work or is there another reason?

*Second question is about the resource path, in MVC < 6 you could declare a relative path to research the minified/bundled js/css. This way each MVC View would have its own path to its own specific js/css. How can I do this with gulp?

*In MVC < 6 the js/css would NOT minify when debug enabled (as default setting), so it remains readable. I see the option to use an if-like statement on the environment variable like
environment names="Development">script path
and another one for production in the view. This seems very cumbersome, is there a simple solution for not minifying in debug instead of having to list all paths twice (one minified and one not)?

A: Have one version of watch minify your js files and one that doesn't. Either way all of your project paths can just point to the built js file to prevent having to switch back and forth for dev or prod. You would need to break the minify stuff out of the 'scripts' task below and create a task that just does that.
//Concatenate & Minify JS
gulp.task('minscripts', function () {
    return gulp.src(config.alljs, { base: 'public/' })
        .pipe($.concat('all.js'))
        .pipe(gulp.dest('_build'))
        .pipe($.rename('all.min.js'))
        .pipe($.uglify())
        .pipe(gulp.dest(config.build));
});

gulp.task('scripts', function () {
    return gulp.src(config.alljs, { base: 'public/' })
        .pipe($.concat('all.js'))
        .pipe(gulp.dest('_build'))
        .pipe($.rename('all.min.js'))
        .pipe(gulp.dest(config.build));
});

gulp.task('watchWith', function () {
    gulp.watch('public/app/views/*.js', ['lint', 'minscripts']); //<- runs 'scripts' here
    gulp.watch('public/css/*.less', ['less']);
});

gulp.task('watchWithout', function () {
    gulp.watch('public/app/views/*.js', ['lint', 'scripts']);
    gulp.watch('public/css/*.less', ['less']);
});


text:
Q: No Graphics Output from RTX 3080; X Server Not Configured Beginner user here.
I've got a server box loaded with an Intel S2600ST, an Intel Xeon Silver 4216, and an RTX 3080, and either Ubuntu 20.04.03 or 21.04.
When I've had the LTS loaded, it would recognize my nVidia as a generic device, however 21.04 directly identifies it as a 3080.
I currently have this system connected with a VGA from the baseboard, which outputs fine. During the OS Boot, my main monitor (Or at least, what I'd like to use) over DisplayPort will activate with the Ubuntu loading animation, and then once that's completed, turn right back off.
I've been working on this for probably 10 hours, not understanding exactly what I'm missing.
I've installed the latest nVidia driver 470 a variety of ways, from the general Update menu for Tested and Propietary, to CLI, to the actual .run file from nVidia.
I've confirmed that the driver is installed right or at least contacting the hardware with
nvidia-smi

And I'll get what seems like a correct readout
If I run
prime-select query

I'll get an output of "nvidia", and not intel.
However, whenever I run
sudo nvidia-settings

I get the following output
(nvidia-settings:2458): GLib-GObject-CRITICAL **: 11:57:02.390: g_object_unref: assertion 'G_IS_OBJECT (object)' failed

** (nvidia-settings:2458): CRITICAL **: 11:57:02.392: ctk_powermode_new: assertion '(ctrl_target != NULL) && (ctrl_target->h != NULL)' failed

ERROR: nvidia-settings could not find the registry key file or the X server is
       not accessible. This file should have been installed along with this
       driver at
       /usr/share/nvidia/nvidia-application-profiles-key-documentation. The
       application profiles will continue to work, but values cannot be
       prepopulated or validated, and will not be listed in the help text.
       Please see the README for possible values and descriptions.

** Message: 11:57:02.434: PRIME: No offloading required. Abort
** Message: 11:57:02.434: PRIME: is it supported? no

nVidia X Server Settings app will actually launch, but looks very similar to this https://i.stack.imgur.com/PB1EG.png
I think that means I'm mostly in the right-ish ballpark, however it looks to be an error with nVidia Settings not having the right configuration even when automatically or manually installed.
I currently have it set for the 470 version under Additional Drivers for Software & Updates.
Edit #1: I've seen other users with issues having a close-ish issue to mine with Secure Boot enabled, however for my issue, I have Secure Boot disabled, confirmed in the BIOS and CLI.
If you can help point me in the right direction for this one, that'd be very much rather appreciated.


text:
Q: wanted to transfer data from child to parent in react I am getting that "props.myfunction is not a function"
This is my parent file to which I want to get data from its childjs file. As you can see I did pass the function inside the component to receive data but I receive the error on the console and I can't see the output.
PARENT:->
 const newExpense=()=>
    {
        const saveExpenseHandler=(enteredExpenseData)=>{
            console.log(enteredExpenseData);
        };
        return (

            <div className="newExpense">
                <ExpenseForm onSaveExpenseData={saveExpenseHandler}/>
            </div>
        )
        //onSaveExpenseData is used to pass function (saveExpenseHandler) as a property for props and then to recieve dta from child and bring it back to parent.
    };

CHILD:->
const ExpenseForm = (props) => {
      const expenseData = {
            title: enteredTitle,
            amount: enteredAmount,
            date: new Date(enteredDate)
             };
    props.onSaveExpenseData(expenseData);
}

;
and i am getting this error on console-

Uncaught TypeError: props.onSaveExpenseData is not a function

A: Check this
const ExpenseForm = (props) => {
  const expenseData = {
    title: "ABC",
    amount: "OK",
  };

  return (
    <>
      <button onClick={() => props.onSaveExpenseData(expenseData)}>ok</button>
    </>
  );
};


text:
Q: Defining Random Variable, Expected Value for Number of Fixed Points given a permutation Let $n \in \mathbb N$, and $\mathcal{K}$ be the set of permutations possible for a set $\{1,...,n\}$. Let $\sigma \in \mathcal{K}, $ such that $\sigma: [n] \to [n]$ is a randomly selected permutation.
Define/Find: the appropriate probability space and define the random variable $X$ as the number of fixed points (note: $i$ is a fixed point under $\sigma$ if $\sigma(i) = i$ for $i \in [n]$). Moreover, find $\mathbb E[X]$.
My ideas:
$\Omega:=\{(1,\sigma(1))\times...\times(n,\sigma(n))\in (\{1,...,n\},\{1,...,n\})^{n}:\sigma \in \mathcal{K}\}$ (not sure in this case; any alternatives?).
I am having difficulties to define random variable $X$ as one "function": As multiple functions I would take $\sum_{i=1}^{n}X_{i}=X$, where
$X_{i}(\omega)=\begin{cases}
       \text{1,} &\quad\text{if } \text{$i=\sigma(i)$}\\
       \text{0,} &\quad\text{otherwise.} \\
     \end{cases}$
Is there anyway of defining $X$ as simply one "Function"?
Now onto my greatest worry, the expected value $\mathbb{E}[X]$:
Initially I thought to myself, the probability measure $\mathbb{P}$ needs to be a binomial distribution, given that we're looking at a given number of "successes" within $n$ particular instances. Then I thought about the parameter $p$ and knew it would not be constant, which changed my thinking (Does this mean $Binom(n) \to X$ is only valid if $(X_{i})_{i =1,...,n}$ are I.I.D?).
With this in mind, we know $\mathbb{E}[X]=\sum_{i=1}^{n}\mathbb{E}{[X_{i}]}$. Individually, this means $\mathbb{E}[X_{1}]=0\times \frac{n-1}{n}+1\times\frac{1}{n}$. But then for $X_{2},...,X_{n}$ surely it would differ greatly on the basis of what "happened" in the previous random variable? How can I calculate this expected value?

A: You can take $\Omega=\mathcal K$ equipped with $\sigma$-algebra $\wp(\mathcal K)$ and where all outcomes are equiprobable, so that $P(\{\sigma\})=\frac1{n!}$ for every $\sigma\in\mathcal K$.
Then $X:\Omega=\mathcal K\to\mathbb R$ is prescribed by $\sigma\mapsto|\{i\in[n]\mid i=\sigma(i)\}|$.
$X$ has no binomial distribution (e.g. note that $P(X=n-1)=0$).
To find $\mathbb EX$ you can use linearity of expectation, and your setup for this (introducing $X_i$) is okay. The $X_i$ are not independent, but that does not matter. Independence is not needed for linearity of expectation. The $X_i$ all have the same distribution, allowing us to make use of symmetry as well.
Then we find:$$\mathbb EX=\sum_{i=1}^n\mathbb EX_i=n\mathbb EX_1=nP(\sigma(1)=1)=n\frac1n=1$$


text:
Q: How to use Microsoft Graph API chatMessage to send a message with clickable hyperlink in it According the offical guidebook I'm able to send Microsoft Teams message using Microsoft graph API, the message contains a link, and the receiver received the message as plain text, the link is not clickble,    how to send a message that enable the receiver to click on it if it's text content with links in it?
POST https://graph.microsoft.com/v1.0/teams/fbe2bf47-16c8-47cf-b4a5-4b9b187c508b/channels/19:4a95f7d8db4c4e7fae857bcebe0623e6@thread.tacv2/messages
Content-type: application/json

{
  "body": {
    "content": "Hello Dan, please go to www.microsoft.com"
  }
}

A: Teams message support a subset of markdown syntax, so you can encode your link appropriately. More info here: https://support.microsoft.com/en-us/office/use-markdown-formatting-in-teams-4d10bd65-55e2-4b2d-a1f3-2bebdcd2c772
In principle, your example would look like this:
POST https://graph.microsoft.com/v1.0/teams/fbe2bf47-16c8-47cf-b4a5-4b9b187c508b/channels/19:4a95f7d8db4c4e7fae857bcebe0623e6@thread.tacv2/messages

Content-type: application/json
{
"body": {
"content": "Hello Dan, please go to [www.microsoft.com] (https://www.microsoft.com)"
}
}
(I've put a space between ']' and '(' just so it renders here in Stack Overflow properly - remove it before testing. I needed to do that because Stack Overflow itself support is trying to render my markdown)


text:
Q: Passing Values Between Views in Django Simple scenario - firstview has a form (firstform) which has a field 'reference'.  In secondview, there is a separate form (secondform) which also has a field 'reference'.  I would like to initialize the value of 'reference' in secondview to be = the value of 'reference' in firstview.
Am I able to do this without passing that parameter through the URL?
I am using python 2.7 for reference.
This is what I've tried.  It doesn't seem to work this way and I am getting a "does not exist" error which I know just mean that I'm not actually getting that value.
views.py
def firstview(request):

    if request.method == "POST":
        form = FirstForm(request.POST) #this form contains 'reference'
        if form.is_valid():
            form.save()
            return redirect('secondview')

def secondview(request):
    form = SecondForm(request.POST)

    if request.method == "POST":
        if form.is_valid():

            form.save()

            ...

    reference_id =  request.POST.get('reference') #this is how Im trying to get reference from the firstview

    form = SecondForm(initial={

         'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist" error

         })
   ....

    return render(request, 'manifest_readonly.html', context)

A: Activate django.contrib.sessions.middleware.SessionMiddleware and then you can pass data between views using request.session dictionary as follows:
def firstview(request):
    ...
    form = FirstForm(request.POST) #this form contains 'reference'
    ...
    request.session['selected_form'] = form
    ...

def secondview(request):
    ...
    form = request.session.get('selected_form')
    # now use the form data here
    ...

A: I don't know why you don't want to pass it in the URL, but if not you can use the session.
def firstview(request):
    ...
    if form.is_valid():
        form.save()
        request.session["reference"] = form.cleaned_data["reference"]
        return redirect('secondview')

def secondview(request):
    ...
    reference_id =  request.session.pop('reference')


text:
Q: How can I use an oracle keyword as an alias? I would like use the following sql statement in my code:
SELECT ..., DATA.EXT_ID AS NUMBER, ... FROM DATA;

But I can't since "NUMBER" is a keyword.
Is there any way around this?
Thanks!

A: Use double quotes around the keyword:
SELECT DATA.EXT_ID AS "NUMBER" FROM DATA;


text:
Q: Show/Hide bottom tab navigator when scrolling I have a bottom tab bar, and I want when scrolling in the home screen to hide it exactly like LinkedIn.
How can this be done with smooth animation ?
Like when I scroll up and down I want to hide it (with animation) and when stop scrolling to show it again.
Also, I have a Custom Bottom Tab.
Here is my implementation:
<Tab.Navigator
    tabBar={(props) => <CustomBottomNavbar {...props} />}
    initialRouteName="Home"
  >
    <Tab.Screen name="Home" component={Home} />
    <Tab.Screen name="Explore" component={Explorer} />
    ...
</Tab.Navigator>


text:
Q: Generalizing the Leibniz rule Given the Leibniz rule:
$$\frac{d}{dy}\int^a_b f(x,y) dx = \int_b^a \frac{\partial f}{\partial y} (x,y) dx$$
How do I prove a more general case using the chain rule and the above:
$$\frac{d}{dy} \int_{g_1(y)}^{g_2(y)} f(x,y) dx =?$$
From the fundamental theorem of calculus we have that: $$\frac{d}{dt} \int_{f_2(t)}^{f_1(t)} g(s) ds = g(f_1(t))f'_1(t) - g(f_2(t))f'_2(t)$$
But when I just apply the fundamental theorem of calculus I get an incorrect answer (because I also need to use Leibniz rule itself...).

A: Do the linear change of variables $$x = g_1(y)+(g_2(y)-g_1(y))u.$$
The integral becomes $$\int_{g_1(y)}^{g_2(y)} f(x,y) dx =(g_2(y)-g_1(y)) \int_0^1 f(g_1(y)+(g_2(y)-g_1(y))u,y) du$$ and now you can apply the traditionnal Leibniz Rule.

A: You're very, very close. The last term is the Leibnitz rule as you are familiar with it itself. That is,
$$\dfrac{d}{dt}\int_a^bf(x,t)dx=f(b,t)b'-f(a,t)a'+\int_a^b\dfrac{\partial f(x,t)}{\partial t}dx.$$ This is because our integral
$$=F(b,t)-F(a,t)$$ which when differentiated gives
$$\dfrac{\partial F(b,t)}{\partial b}b'+\dfrac{\partial F(b,t)}{\partial t}-\dfrac{\partial F(a,t)}{\partial b}a'-\dfrac{\partial F(a,t)}{\partial t}$$ which afterwards it becomes obvious that
$$\dfrac{\partial F(b,t)}{\partial b}b'-\dfrac{\partial F(a,t)}{\partial a}a'=f(b,t)b'-f(a,t)a'$$ and that because we took the partial derivatives of F as if $b$ and $a$ were independent of $t$, we obtain that the last term is
$$\dfrac{\partial F(b,t)}{\partial t}-\dfrac{\partial F(a,t)}{\partial t}=\dfrac{\partial F(x,t)}{\partial t}\Bigg|_{x=a}^{x=b}=\dfrac{\partial}{\partial t}\int_a^b f(x,t)dx=\int_a^b \dfrac{\partial}{\partial t}f(x,t)dx$$ Done!


text:
Q: SQL Server: compare datetime day with GETDATE() I have a stored procedure that should fetch all records with a date equal to the current date or in the future.
The dates are saved in column targetDate and formatted as datetime.
My corresponding WHERE clause is the following:
WHERE A.targetDate >= GETDATE()

In general my stored procedure works fine, my only problem is if the targetDate equals the current date as all dates are saved as follows, i.e. with the time set to zeros:
2014-02-22 00:00:00.000

How do I have to change my WHERE clause so that it only considers the date but ignores the time saved with it so that I get any records with the current date even if the time is already passed ?
Many thanks for any help with this, Tim.

A: Change to:
WHERE A.targetDate >= cast(GETDATE() as date)

Edit - because targetdate also contains time, yes, format both like this:
WHERE cast(A.targetDate as date) >= cast(GETDATE() as date)

Edit - given comments re: performance, may want to try:
WHERE a.targetdate >= cast(cast(getdate() as date) as datetime)

Last edit should give you the same result and take advantage of any indexes on targetdate

A: The following should give you the current date with no time:
SELECT DATEADD(dd,0,DATEDIFF(dd,0,GETDATE()))

This should be your final line:
WHERE A.targetDate >= DATEADD(dd,0, ATEDIFF(dd,0,GETDATE()))


text:
Q: Splitting a char array by delimeter, then saving the result? I need to be able to parse the following two strings in my program:
cat myfile || sort
more myfile || grep DeKalb

The string is being saved in char buffer[1024]. What I need to end up with is a pointer to a char array for the left side, and a pointer to a char array for the right side so that I can use these to call the following for each side:
int execvp(const char *file, char *const argv[]);

Anyone have any ideas as to how I can get the right arguments for the execvp command if the two strings above are saved in a character buffer char buffer[1024]; ?
I need char *left to hold the first word of the left side, then char *const leftArgv[] to hold both words on the left side.  Then I need the same thing for the right.  I have been messing around with strtok for like two hours now and I am hitting a wall.  Anyone have any ideas?

A: I recommend you to learn more about regular expressions. And in order to solve your problem painlessly, you could utilize the Boost.Regex library which provides a powerful regular expression engine. The solution would be just several lines of code, but I encourage you to do it yourself - that would be a good exercise. If you still have problems, come back with some results and clearly state where you were stuck.

A: You could use std::getline(stream, stringToReadInto, delimeter).
I personally use my own function, which has some addition features baked into it, that looks like this:
StringList Seperate(const std::string &str, char divider, SeperationFlags seperationFlags, CharValidatorFunc whitespaceFunc)
{
    return Seperate(str, CV_IS(divider), seperationFlags, whitespaceFunc);
}

StringList Seperate(const std::string &str, CharValidatorFunc isDividerFunc, SeperationFlags seperationFlags, CharValidatorFunc whitespaceFunc)
{
    bool keepEmptySegments     = (seperationFlags & String::KeepEmptySegments);
    bool keepWhitespacePadding = (seperationFlags & String::KeepWhitespacePadding);

    StringList stringList;

    size_t startOfSegment = 0;
    for(size_t pos = 0; pos < str.size(); pos++)
    {
        if(isDividerFunc(str[pos]))
        {
            //Grab the past segment.
            std::string segment = str.substr(startOfSegment, (pos - startOfSegment));
            if(!keepWhitespacePadding)
            {
                segment = String::RemovePadding(segment);
            }

            if(keepEmptySegments || !segment.empty())
            {
                stringList.push_back(segment);
            }

            //If we aren't keeping empty segments, speedily check for multiple seperators in a row.
            if(!keepEmptySegments)
            {
                //Keep looping until we don't find a divider.
                do
                {
                    //Increment and mark this as the (potential) beginning of a new segment.
                    startOfSegment = ++pos;

                    //Check if we've reached the end of the string.
                    if(pos >= str.size())
                    {
                        break;
                    }
                }
                while(isDividerFunc(str[pos]));
            }
            else
            {
                //Mark the beginning of a new segment.
                startOfSegment = (pos + 1);
            }
        }
    }

    //The final segment.
    std::string lastSegment = str.substr(startOfSegment, (str.size() - startOfSegment));
    if(keepEmptySegments || !lastSegment.empty())
    {
        stringList.push_back(lastSegment);
    }

    return stringList;
}

Where 'StringList' is a typedef of std::vector, and CharValidatorFunc is a function pointer (actually, std::function to allow functor and lambda support) for a function taking one char, and returning a bool. it can be used like so:
StringList results = String::Seperate(" Meow meow , Green, \t\t\nblue\n   \n, Kitties!", ',' /* delimeter */, DefaultFlags, is_whitespace);

And would return the results:
{"Meow meow", "Green", "blue", "Kitties!"}
Preserving the internal whitespace of 'Meow meow', but removing the spaces and tabs and newlines surrounding the variables, and splitting upon commas.
(CV_IS is a functor object for matching a specific char or a specific collection of chars taken as a string-literal. I also have CV_AND and CV_OR for combining char validator functions)
For a string literal, I'd just toss it into a std::string() and then pass it to the function, unless extreme performance is required. Breaking on delimeters is fairly easy to roll your own - the above function is just customized to my projects' typical usage and requirements, but feel free to modify it and claim it for yourself.

A: In case this gives anyone else grief, this is how I solved the problem:
//variables for the input and arguments
char *command[2];
char *ptr;
char *LeftArg[3];
char *RightArg[3];

char buf[1024]; //input buffer

//parse left and right of the ||
number = 0;
command[0] = strtok(buf, "||");

//split left and right
while((ptr=strtok(NULL, "||")) != NULL)
{
    number++;
    command[number]=ptr;
}

//parse the spaces out of the left side
number = 0;
LeftArg[0] = strtok(command[0], " ");

//split the arguments
while((ptr=strtok(NULL, " ")) != NULL)
{
    number++;
    LeftArg[number]=ptr;
}

//put null at the end of the array
number++;
LeftArg[number] = NULL;

//parse the spaces out of the right side
number = 0;
RightArg[0] = strtok(command[1], " ");

//split the arguments
while((ptr=strtok(NULL, " ")) != NULL)
{
        number++;
        RightArg[number]=ptr;
}

//put null at the end of the array
number++;
RightArg[number] = NULL;

Now you can use LeftArg and RightArg in the command, after you get the piping right
execvp(LeftArg[0], LeftArg);//execute left side of the command

Then pipe to the right side of the command and do
execvp(RightArg[0], RightArg);//execute right side of command


text:
Q: Pinescript minutes and seconds plotting incorrectly In pinescript, I have a code to plot CPR lines for the entire day wherein the lines from start to end of day are plotted per the normal Intraday session.
How can I have this for say 16 minutes and 30 seconds?
One_Day = 24 * 60 * 60 * 1000
Half_Day = ((1 * 16 * 60 * 1000) + (1 * 30 * 60 * 1000))
The below plots the first 16 minutes and 30 seconds perfectly but fails to do from the second 16 minutes and 30 seconds trading session. So basically the need is to break a trading session to half and thereafter making further cuts to the session. Meaning a 450 minute session can be minimum of 15 minute each to a maximum of 225 minute which will be termed as the half of that scripts trading session in a day.
//@version=5
indicator(title="Test", shorttitle="Test", overlay= true, max_labels_count=500, max_lines_count=500,  max_boxes_count=500)
T0 = "Small font size recommended for mobile app or multiple layout"
Transparency = input(defval=75)
i_s_font    = input.string("normal",       "Font size", tooltip = T0, options = ["tiny", "small",  "normal", "large", "huge"])
tointeger    = input.int(defval = 1, title = "To Integer")

i_timeZone = input('GMT+05:30')
f_print(_txt) =>
    var _lbl = label.new(bar_index, ta.highest(10)[1], _txt, xloc.bar_index, yloc.price, #00000000, label.style_none, color.black, size.tiny, text.align_left)
    label.set_xy(_lbl, bar_index, ta.highest(10)[1])
    label.set_text(_lbl, _txt)

// f_print(tostring(hour(timenow), "00:") + tostring(minute(timenow), "00:") + tostring(second(timenow), "00") + " (Exchange)\n")
// f_print(tostring(hour(timenow, i_timeZone), "00:") + tostring(minute(timenow, i_timeZone), "00:") + tostring(second(timenow, i_timeZone), "00") + " (Input: " + i_timeZone + ")")
f_print(str.tostring(dayofmonth(timenow, i_timeZone), '00-') + str.tostring(month(timenow, i_timeZone), '00-') + str.tostring(year(timenow, i_timeZone), '00'))

// ============================ Time Function { ================

is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := ta.change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := ta.change(t) != 0 ? 1 : 0
    ch

// ============================ Time Function } ================

Label_Color         = input.color(defval=color.new(color.white,100),    title='Label_Color' )

Want_Daily          = input.bool(defval=true,                           title='Daily',      inline='Daily'      )
Want_Daily_Lines    = input.bool(defval=true,                           title='Lines',      inline='Daily'      )
Daily_Color         = input.color(defval=color.new(color.blue, 85),     title='Color',      inline='Daily'      )
Daily_Width         = input.int(  defval=1,                             title='Width',      inline='Daily'      )
Daily_HL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )
Daily_LL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )

Want_W188         = input.bool(defval=false,                          title='W188',     inline='W188'     )
Want_W188_Lines   = input.bool(defval=false,                          title='Lines',      inline='W188'     )
W188_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_Width        = input.int(  defval=1,                             title='Width',      inline='W188'     )
W188_HL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_LL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )

Next_CPR(TF, BG_Color, HL_Color, LL_Color, Width, Lines)=>

    // *********  Making Pivot  { ********
    PDH     = request.security(syminfo.ticker, TF, high[1]  , barmerge.gaps_off, barmerge.lookahead_on)
    PDL     = request.security(syminfo.ticker, TF, low[1]   , barmerge.gaps_off, barmerge.lookahead_on)
    PDC     = request.security(syminfo.ticker, TF, close[1] , barmerge.gaps_off, barmerge.lookahead_on)
    PDR     = (PDH - PDL)
    Pivot   = (PDH + PDL + PDC)/3

    // *********  Drawing Pivot  { ********
    var Bars      = 0, Bars  += 1
    var Line_Size = 0

    var label Label_Pivot = na
    Half_Day       = (12 * 60 * 60 * 1000)
    ONE_DAY       = 24 * 60 * 60 * 1000

    END_POINT     =    TF=="188"  ? Half_Day
                     : TF=="D"  ? ONE_DAY

    // if dayofmonth!=dayofmonth[1]
    if is_newbar(TF)
        Bars       := 1
        Line_Size  := math.min( Bars[1], 450 )

        if Lines
            line.new(time, Pivot , time+END_POINT, Pivot , color=color.fuchsia, xloc=xloc.bar_time, width=Width ),
            Label_Pivot := label.new(bar_index+1, Pivot , color=Label_Color, textcolor=color.fuchsia, style=label.style_label_left, text=str.tostring(TF + '_' + 'PIV' + str.tostring(Pivot, format.mintick)) + ' ', size=i_s_font)
            label.set_x(Label_Pivot, bar_index+1)

// *********  Drawing Pivot  } ********

if Want_Daily
    Next_CPR('75',  Daily_Color,   Daily_HL_Color, Daily_LL_Color, Daily_Width,       Want_Daily_Lines    )
if Want_W188
    Next_CPR('188',  W188_Color,   W188_HL_Color, W188_LL_Color, W188_Width,      Want_W188_Lines   )