text:
Q: Java executor service: Waiting for all tasks to finish I am trying to introduce concurrency in my program. Structure of program is something like this:
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
    List<String> initialData = dao.fetchFromDB("input");
    Queue queue = new MyQueue();
    queue.add(initialData);

    while(queue.length() > 0) {
        int startingLength = queue.length();
        for (int i = 0; i < startingLength; i++) {
            String input = queue.remove();
            if(input.equals("some value")) {
              missionAccomplished = true;
              break;
            } else {
                  MyRunnable task = new MyRunnable(input, queue, dao);
                  executor.execute(task);
            }

        }
        if(missionAccomplished) {
           break;
        }
        executor.shutdown();
    }

So queue contains the data needed to be processed one by one. Inside while loop I run a for loop which picks data from queue one by one sequentially and performs some check on it, and if check fails I create a runnable task with this data and hands it over to executor(as DB operation is time consuming, I want to use parallelism for it). for loop picks data only upto certain length in given iteration of while.
What I want to achieve is that 'while' loop goes to next iteration only when all tasks submitted to executor in current iteration are finished.
How can this be achieved?

A: try-with-resources in Project Loom
You asked:

What I want to achieve is that 'while' loop goes to next iteration only when all tasks submitted to executor in current iteration are finished.

Project Loom promises to make this simpler.
One of the changes brought by Project Loom is that the ExecutorService interface is a sub-interface of AutoCloseable. This means we can use try-with-resources syntax. The try-with-resources automatically blocks until all submitted tasks are done/failed/canceled — just what you asked for.
Also, the executor service is automatically shut down when exiting the try. These changes mean your code becomes simpler and clearer.
Also, for code that blocks often, such as database access, you will see dramatically faster performance using virtual threads (a.k.a. fibers). Virtual threads is another new feature of Project Loom. To get this feature, call Executors.newVirtualThreadExecutor.
Experimental builds of Project Loom are available now, based on early-access Java 17. The Loom team is asking for feedback. For more info, see recent presentations and interviews by Ron Pressler of Oracle.
System.out.println( "INFO - executor service about to start. " + Instant.now() );
try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    for ( int i = 0 ; i < 7 ; i++ )
    {
        executorService.submit( ( ) -> System.out.println( Instant.now() ) );
    }
}
// Notice that when reaching this point we block until all submitted tasks still running are fin
// because that is the new behavior of `ExecutorService` being `AutoCloseable`.
System.out.println( "INFO - executor service shut down at this point. " + Instant.now() );

When run.
INFO - executor service about to start. 2021-02-08T06:27:03.500093Z
2021-02-08T06:27:03.554440Z
2021-02-08T06:27:03.554517Z
2021-02-08T06:27:03.554682Z
2021-02-08T06:27:03.554837Z
2021-02-08T06:27:03.555015Z
2021-02-08T06:27:03.555073Z
2021-02-08T06:27:03.556675Z
INFO - executor service shut down at this point. 2021-02-08T06:27:03.560723Z


text:
Q: ASP.NET Validation i have one page to design. in this it includes an , password text box,
My requirment is that when an user hit the submit button without entering any data, then it  shows a message in red color at side of both the text box as "Cannot be empty"
How it can be done without using Javascript?

A: In this instance you would use a RequiredFieldValidator control, drop that in your page. It will by default use javascript and server side. You can turn the javascript off by setting the EnableClientScript property to false. You'd associate this validator with your text box using the ControlToValidate property. Set the Text property to the message you want to display.
On the server side event generated by your button simply call the Page's IsValid property and only if it is valid continue processing.

A: See Validating Form Input Controls.
I found this tutorial at http://social.msdn.microsoft.com/Search/en-US/?query=asp.net%20validation&ac=8.

A: You can use validation controls. They support client side and server side validation.
You don't need to know javascript if you mean that.

A: In ASP.Net you can have Validators.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=121&AspxAutoDetectCookieSupport=1
Short but true =)

redpajama_set_name: RedPajamaStackExchange


text:
Q: char variable has not been declared I have ran into a problem yesterday when trying to split my code into several files.
Yesterday morning my whole code was in one file and to keep track of everything more easily I wanted to split the code into more files.
This went well until I got to a function where I need to declare a variable although I already have (but maybe in the wrong place).
Because the code is too long, I have put all files to pastebin.
I have declared "field" in main.cpp:
char field[20][41];

Whole file here: https://pastebin.com/Jy1XvdpL
And I want to use this in my field.cpp:
void loadLevel(int levelnumber) {

// concatenate leven base with level number
std::string level = "level" + std::to_string(levelnumber) + ".txt";

// print field
// load the text file
std::ifstream file;
file.open(level);
char c;

// read line by line, character by character and store it in field
for (int i = 0; i < 20; i++) {
    for (int j = 0; j < 41; j++) {
        file.get(c);
        field[i][j] = c;
    }
}
file.close();

}

The field.h looks like this:
#ifndef field
#define field

#include <iostream>
#include <string>
#include <fstream>

void loadLevel(int levelnumber);
void drawField();

#endif // !field

The problem is that I do not know, where to define char field because I get an error if done in either of these files. So what do I need to do to get char field workin in field.cpp and therefore work in my main?
P.S. This is my first program in c++ and I am learning new things everyday. I appreciate any hints on how to do certain things better ^^
Kind Regards,
Benjamin

A: When you declare a variable in your main file, you are not able to use it in another file. (or at least easily)
if you wish to use your field variable in the field.cpp, then you can define it in field.h.
Code for this could be as followed.
#ifndef field
#define field

#include <iostream>
#include <string>
#include <fstream>

void loadLevel(int levelnumber);
void drawField();

char field[20][41];

#endif // !field

Though this will not allow you to use the information you assign to field[i][j] will not be available in your main file.
To do this I would make a function in field.h and field.cpp that returns the value of field[i][j].

A: You can use field array in your function by passing it as an argument to your loadlevel function, check this question too if you want to use pointers.
So your function will look like:
void loadLevel(int levelnumber,char field[][41]);


text:
Q: Adding two numbers in two string variables in SCSS I have two numbers in variables, i need to add those two variable and the result needs to go into another variable. But all three variable need to be strings in the end because im using them for the value of content:
You can see my CodePen here.
There you can see that $minority and $majority works, as i already have them set as strings, but when i try to add them together for the variable $btctotal, it just concatenation them. What would be the easiest way to do this?

A: I figured it out. I just made my original two numbers as integers, and then when it was time to display next to content: i just used interpolation #{ }
http://codepen.io/marcchoover/pen/BKQezE


text:
Q: Image perspective correction I need to rotate my BufferedImage on 3 axis (x, y and z), by the angles given in 3 integers. Is there any native methods in java? If not, how would I achieve that?
Update #1: I've done some of it with OpenCV... Will update when finished!
Update #2: Since this was just a part of my project, I realized that solving just a part of the problem wouldn't be good, so I used OpenCV getPerspectiveTransform() and then warpPerspective() methods from Imgproc class to transform image. I have basically just ported this code to java and it works fine :)
Also I have changed the thread name due the changes to make it fit the actual question/solution.
Code (I used OpenCV 3.1, since it's the latest version):
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;

public class Main extends JFrame {
    private static final long serialVersionUID = 1L;

    BufferedImage transformed = null;

    //These locations are just the corners of the 4 reference points. I am writing the auto recognition part right now :)
    Point p4 = new Point(260, 215);
    Point p1 = new Point(412, 221);
    Point p2 = new Point(464, 444);
    Point p3 = new Point(312, 435);

    public Main() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        File f = new File("FILEPATH ");

        MatOfPoint2f corners = new MatOfPoint2f();

        Mat src = Imgcodecs.imread(f.getAbsolutePath());

        corners.push_back(new MatOfPoint2f(p1));
        corners.push_back(new MatOfPoint2f(p2));
        corners.push_back(new MatOfPoint2f(p3));
        corners.push_back(new MatOfPoint2f(p4));

        Point center = new Point(0, 0);
        for (int i = 0; i < corners.toArray().length; i++) {
            center.x += corners.toArray()[i].x;
            center.y += corners.toArray()[i].y;
        }

        center.x /= corners.toArray().length;
        center.y /= corners.toArray().length;
        sortCorners(corners, center);

        Mat quad = Mat.zeros(1000, 1900, CvType.CV_8U);

        MatOfPoint2f quad_pts = new MatOfPoint2f();

        quad_pts.push_back(new MatOfPoint2f(new Point(0, 0)));
        quad_pts.push_back(new MatOfPoint2f(new Point(quad.width(), 0)));
        quad_pts.push_back(new MatOfPoint2f(new Point(quad.width(), quad.height())));
        quad_pts.push_back(new MatOfPoint2f(new Point(0, quad.height())));

        Mat transmtx = Imgproc.getPerspectiveTransform(corners, quad_pts);

        Imgproc.warpPerspective(src, quad, transmtx, quad.size());

        transformed = matToBufferedImage(quad);

        setSize(500, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void paint(Graphics g) {
        g.clearRect(0, 0, this.getWidth(), this.getHeight());
        g.drawImage(transformed, 0, 22, null);
    }

    public MatOfPoint2f sortCorners(MatOfPoint2f corners, Point center) {
        MatOfPoint2f top = new MatOfPoint2f();
        MatOfPoint2f bot = new MatOfPoint2f();

        for (int i = 0; i < corners.toArray().length; i++) {
            if (corners.toArray()[i].y < center.y){
                top.push_back(new MatOfPoint2f(corners.toArray()[i]));
            }
            else
                bot.push_back(new MatOfPoint2f(corners.toArray()[i]));
        }

        Point tl = p4;
        Point tr = p1;
        Point bl = p2;
        Point br = p3;

        tl = top.toArray()[0].x > top.toArray()[1].x ? top.toArray()[1] : top.toArray()[0];
        tr = top.toArray()[0].x > top.toArray()[1].x ? top.toArray()[0] : top.toArray()[1];
        bl = bot.toArray()[0].x > bot.toArray()[1].x ? bot.toArray()[1] : bot.toArray()[0];
        br = bot.toArray()[0].x > bot.toArray()[1].x ? bot.toArray()[0] : bot.toArray()[1];

        corners.release();
        corners.push_back(new MatOfPoint2f(tl));
        corners.push_back(new MatOfPoint2f(tr));
        corners.push_back(new MatOfPoint2f(br));
        corners.push_back(new MatOfPoint2f(bl));
        System.out.println(corners.toArray()[0] + ", " + corners.toArray()[1] + ", " + corners.toArray()[2] + ", " + corners.toArray()[3] + ", ");
        return corners;

    }

    public BufferedImage matToBufferedImage(Mat image) {
        Mat image_tmp = image;
        MatOfByte matOfByte = new MatOfByte();

        Imgcodecs.imencode(".jpg", image_tmp, matOfByte);

        byte[] byteArray = matOfByte.toArray();
        BufferedImage bufImage = null;

        try {

            InputStream in = new ByteArrayInputStream(byteArray);
            bufImage = ImageIO.read(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufImage;
    }
}

A: I think that the TransformJ package does what you want, but I don't think it contains native code.


text:
Q: What is the dominant cause for ocean waves at a beach? What is the dominant cause for ocean waves at a beach? Are they the result of wind/pressure difference? If so, the waves do seem to exist in similar intensity even during relative quiet times of the day.
Is there a simple mathematical model that we can quickly explain the intensity/frequency of waves with? Does the strength of the waves (say the variance and mean of the amplitude of waves) relate to a simple physical quantity (temperature, off shore wind, pressure difference)?

A: Yes, primarily wind.  It's called the Kelvin-Helmholtz instability.  Strong winds in an area will excite a range of wavelengths, the longer wavelengths will go faster according to the deep water dispersion relation ( speed proportional to square root of wavelength).  So if you see a train of waves with decreasing wavelength over time, you could in principle infer a common point of origin (this is a common textbook or qualifying exam type problem).

A: The normal dominant cause of most waves you see (i.e., not a Tsunami) is frictional force between the wind and water over very large distances.
Even though the wind may not be blowing at your particular beach, it is ALWAYS blowing somewhere out in the ocean.  The waves produced by this effect can (and do) travel thousands of miles away from the source.


text:
Q: Alert long message Is there a way to set the height of alert to display really long messages with enabling scrolling option for messages that extends screen height ?
Help would be appreciated , all plugins are not recommended.

A: You can't control a JavaScript alert box in anyway.
Modern web development uses a modal dialog box to show this type of information.
jQuery UI dialog() is one such popular option.  See here: http://jqueryui.com/dialog/

A: alert() only takes a message and cannot be configured in any way.
I know of no browsers that implement scrolling in the resulting dialog box. Firefox and IE just pop up a modal Windows MessageBox in the OS theme's default dialog font, where Chrome has a little piece of toast that pops up towards the top of the browser window.
You would have to use a floating div to make a sort of fake "dialog box" with the features you want. For example, jQuery dialog, or the excellent alertify.

A: Not possible.
Jquery will be best for your criteria
Jquery Dialog Link


text:
Q: ffmpeg 4.2.2 gives segmentation fault after a while I have compiled ffmpeg 4.2.2 and it gives me a segmatation fault after a while and i don't knw why, i put it the request and a part of the debug log file.
My ffmpeg request:
/usr/local/bin/ffmpeg -loglevel debug -use_wallclock_as_timestamps 1 -rtsp_transport tcp -i "rtsp://root:My_PW@My_IP_Address:5541/live.sdp" -f image2 -loop 1 -i ./overlay_score_160.png -i ./partenaire.png -filter_complex 'overlay=x=2:y=1,overlay=(main_w-overlay_w)/2:y=1' -framerate 25 -crf 18 -preset veryfast -g 50 -vcodec libx264 -acodec copy -f flv rtmp://localhost/hls/stream1 -async 1 -vsync 1 2> debug.txt
ffmpeg version 4.2.2-eric-01022020-FF422 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
  configuration: --prefix=/usr/local --enable-gpl --enable-version3 --enable-nonfree --disable-static --enable-shared --disable-debug --enable-avresample --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-pthreads --enable-libfreetype --enable-filters --enable-openssl --enable-runtime-cpudetect --enable-libxvid --enable-libfontconfig --enable-libspeex --extra-version=eric-01022020-FF422 --docdir=/usr/share/doc/ffmpeg-4.2.2
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
Splitting the commandline.
Reading option '-loglevel' ... matched as option 'loglevel' (set logging level) with argument 'debug'.
Reading option '-use_wallclock_as_timestamps' ... matched as AVOption 'use_wallclock_as_timestamps' with argument '1'.
Reading option '-rtsp_transport' ... matched as AVOption 'rtsp_transport' with argument 'tcp'.
Reading option '-i' ... matched as input url with argument 'rtsp://root:MyPW@My_IP_Address:5541/live.sdp'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'image2'.
Reading option '-loop' ... matched as AVOption 'loop' with argument '1'.
Reading option '-i' ... matched as input url with argument './overlay_score_160.png'.
Reading option '-i' ... matched as input url with argument './partenaire.png'.
Reading option '-filter_complex' ... matched as option 'filter_complex' (create a complex filtergraph) with argument 'overlay=x=2:y=1,overlay=(main_w-overlay_w)/2:y=1'.
Reading option '-framerate' ... matched as AVOption 'framerate' with argument '25'.
Reading option '-crf' ... matched as AVOption 'crf' with argument '18'.
Reading option '-preset' ... matched as AVOption 'preset' with argument 'veryfast'.
Reading option '-g' ... matched as AVOption 'g' with argument '50'.
Reading option '-vcodec' ... matched as option 'vcodec' (force video codec ('copy' to copy stream)) with argument 'libx264'.
Reading option '-acodec' ... matched as option 'acodec' (force audio codec ('copy' to copy stream)) with argument 'copy'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'flv'.
Reading option 'rtmp://localhost/hls/stream1' ... matched as output url.
Reading option '-async' ... matched as option 'async' (audio sync method) with argument '1'.
Reading option '-vsync' ... matched as option 'vsync' (video sync method) with argument '1'.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option loglevel (set logging level) with argument debug.
Applying option filter_complex (create a complex filtergraph) with argument overlay=x=2:y=1,overlay=(main_w-overlay_w)/2:y=1.
Applying option async (audio sync method) with argument 1.
Applying option vsync (video sync method) with argument 1.
Successfully parsed a group of options.
Parsing a group of options: input url rtsp://root:MyPW@My_IP_Address:5541/live.sdp.
Successfully parsed a group of options.

........

[libx264 @ 0x55819256fc00] frame=24887 QP=17.51 NAL=2 Slice:P Poc:80  I:53   P:783  SKIP:38   size=8835 bytes
[libx264 @ 0x55819256fc00] frame=24888 QP=21.08 NAL=2 Slice:B Poc:76  I:0    P:219  SKIP:655  size=254 bytes
[h264 @ 0x5581925ca200] nal_unit_type: 1(Coded slice of a non-IDR picture), nal_ref_idc: 1
[image2 @ 0x558192485380] Opening './overlay_score_160.png' for reading
[file @ 0x7f32640080c0] Setting default whitelist 'file,crypto'
[AVIOContext @ 0x7f3264008140] Statistics: 1988 bytes read, 0 seeks
[Parsed_overlay_0 @ 0x5581927cbf00] n:20781.000000 t:831.281311 pos:nan x:2.000000 xi:2 y:1.000000 yi:0
[Parsed_overlay_1 @ 0x5581927cdf00] n:20781.000000 t:831.281311 pos:nan x:258.000000 xi:258 y:1.000000 yi:0
Clipping frame in rate conversion by 0.474174
[libx264 @ 0x55819256fc00] frame=24889 QP=22.84 NAL=0 Slice:B Poc:74  I:0    P:7    SKIP:867  size=36 bytes
[h264 @ 0x5581925e68c0] nal_unit_type: 1(Coded slice of a non-IDR picture), nal_ref_idc: 1
[Parsed_overlay_0 @ 0x5581927cbf00] n:20782.000000 t:831.311122 pos:nan x:2.000000 xi:2 y:1.000000 yi:0
[Parsed_overlay_1 @ 0x5581927cdf00] n:20782.000000 t:831.311122 pos:nan x:258.000000 xi:258 y:1.000000 yi:0
Clipping frame in rate conversion by 0.580742
[libx264 @ 0x55819256fc00] frame=24890 QP=22.80 NAL=0 Slice:B Poc:78  I:0    P:190  SKIP:684  size=167 bytes
[h264 @ 0x558192603080] nal_unit_type: 1(Coded slice of a non-IDR picture), nal_ref_idc: 1
[image2 @ 0x558192485380] Opening './overlay_score_160.png' for reading
[file @ 0x7f3264007f80] Setting default whitelist 'file,crypto'
[AVIOContext @ 0x7f3264008300] Statistics: 1988 bytes read, 0 seeks
[Parsed_overlay_0 @ 0x5581927cbf00] n:20783.000000 t:831.351278 pos:nan x:2.000000 xi:2 y:1.000000 yi:0
[Parsed_overlay_1 @ 0x5581927cdf00] n:20783.000000 t:831.351278 pos:nan x:258.000000 xi:258 y:1.000000 yi:0
Clipping frame in rate conversion by 0.377281
[libx264 @ 0x55819256fc00] frame=24891 QP=17.17 NAL=2 Slice:P Poc:88  I:1    P:230  SKIP:643  size=806 bytes
frame=24917 fps= 30 q=24.0 size=   25410kB time=00:13:51.90 bitrate= 250.2kbits/s dup=6033 drop=1899 speed=   1x    ^M[h264 @ 0x55819261f840] nal_unit_type: 1(Coded slice of a non-IDR picture), nal_ref_idc: 1
[image2 @ 0x558192485380] Opening './overlay_score_160.png' for reading
[file @ 0x7f3264006d80] Setting default whitelist 'file,crypto'
[AVIOContext @ 0x7f32640080c0] Statistics: 1988 bytes read, 0 seeks
[Parsed_overlay_0 @ 0x5581927cbf00] n:20784.000000 t:831.372222 pos:nan x:2.000000 xi:2 y:1.000000 yi:0
[Parsed_overlay_1 @ 0x5581927cdf00] n:20784.000000 t:831.372222 pos:nan x:258.000000 xi:258 y:1.000000 yi:0
Past duration 0.749565 too large
[libx264 @ 0x55819256fc00] frame=24892 QP=18.73 NAL=2 Slice:B Poc:84  I:0    P:29   SKIP:845  size=80 bytes
[h264 @ 0x55819263c000] nal_unit_type: 1(Coded slice of a non-IDR picture), nal_ref_idc: 1
[image2 @ 0x558192485380] Opening './overlay_score_160.png' for reading
[file @ 0x7f3264007f80] Setting default whitelist 'file,crypto'
[AVIOContext @ 0x7f32640080c0] Statistics: 1988 bytes read, 0 seeks
[image2 @ 0x558192485380] Opening './overlay_score_160.png' for reading
[file @ 0x7f3264006d80] Setting default whitelist 'file,crypto'
[AVIOContext @ 0x7f32640080c0] Statistics: 1988 bytes read, 0 seeks

Then i get "Segmentation fault" and ffmpeg exits


text:
Q: ASP.NET Core MVC filtering: How can I send multiple value to action? I want to filter products in my e-commerce project, but I have a problem: I want my filtering to change dynamically, I choose a brand from the selected list and the necessary filtering is done. When the second filter is done, my first filter is reset and the last filtering becomes valid.

I need such a URL structure:
/?SelectedVendor=Asus&SelectedMemory=4+GB
FilterViewModel.cs
public class FilterViewModel
    {
        public List<string> Vendors { get; set; }
        public List<string> Memories { get; set; }
        public string SelectedVendor { get; set; }
        public string SelectedMemory { get; set; }
    }

CategoryController.cs
    [HttpGet]
    public ViewResult Gaming(int productPage = 1, FilterViewModel model=null)
    {

        ProductListViewModel productList = new ProductListViewModel()
        {
            Products =
                _productService.GetProductsByCategoryId(1).OrderBy(p => p.Id).Skip((productPage - 1) * pageSize).Take(pageSize),
            FilterTypes = new FilterViewModel()
            {
                Vendors = _productService.Products.Select(I => I.Vendor).Distinct().OrderBy(I => I).ToList(),
                Memories = _productService.Products.Select(I => I.MemoryCapacity).Distinct().OrderBy(I => I).ToList(),
            }
        };

        if (!string.IsNullOrEmpty(model.SelectedVendor))
        {
            productList.Products = productList.Products.Where(I => I.Vendor.Contains(model.SelectedVendor));
            productList.FilterTypes.Memories = productList.Products.Select(I => I.MemoryCapacity).Distinct()
                .OrderBy(I => I).ToList();
        }

        if (!string.IsNullOrEmpty(model.SelectedMemory))
        {
            productList.Products = productList.Products.Where(I => I.MemoryCapacity == model.SelectedMemory);
        }

        return View(productList);
    }

FilterPartial.cshtml

Brand

            <form method="get" asp-controller="@controllerName" asp-action="@actionName">

                @foreach (var vendor in Model.Vendors)
                {

                        <input type="submit" value="@vendor" asp-for="SelectedVendor"/>

                }

Memory

                @foreach (var memory in Model.Memories)
                {

                        <input type="submit" asp-for="SelectedMemory" value="@memory"/>

                }
            </form>

A: Here is a demo to pass both SelectedVendor and SelectedMemory to action:
TestFilter.cshtml:
@await Html.PartialAsync("Partial", Model.FilterTypes)

Partial.cshtml:
<form id="form1" method="get" asp-controller="Test" asp-action="TestFilter">

    @foreach (var vendor in Model.Vendors)
    {

            <input type="button" value="@vendor" onclick="addSelectedVendor(this)" />

    }

Memory

    @foreach (var memory in Model.Memories)
    {

            <input type="button" value="@memory" onclick="addSelectedMemory(this)" />

    }
    <input hidden asp-for="SelectedVendor"/>
    <input hidden asp-for="SelectedMemory"/>
</form>

TestController(I use fake data to test):
 [HttpGet]
            public IActionResult TestFilter(FilterViewModel model)
            {
                ProductListViewModel productList = new ProductListViewModel {  FilterTypes=new FilterViewModel()};
                productList.FilterTypes.Vendors = new List<string> { "Apple", "Asus", "Dell", "Lenovo", "MSI" };
                productList.FilterTypes.Memories = new List<string> { "16GB", "4GB", "8GB"};

                return View(productList);
            }

result:

A: You can filter by list in your get method.
you should change get method like that
   public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = DbSet;

        if (filter != null) query = query.Where(filter);

        if (includeProperties != null)
            foreach (var includeProperty in includeProperties.Split
                (new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                query = query.Include(includeProperty);

        if (orderBy != null)
            return orderBy(query).ToList();
        return query.ToList();
    }


text:
Q: correct way to run a unittest for reading a (yaml) file with pytest I created a function to read a config file in yaml-format. Now I want to add simple unittests with pytest.
My approach would be to create both a test_config.yml (containing some data) and a test_config_reader.py (containing the actual tests, which are performed based on the data in test_config.yml).
Is this approach correct? Or do I need to create my "data" (i.e. the data in test_config.yml) as a fixture in test_config_reader.py?
To sum up: Is it okay to have non test_*.py files ("data"-files, like .yml, .csv, .pkl, ...) in the tests/ folder of my project to use them in tests?

A: As far as I know, and I think I understand your approach. You could run Pytest from your YAML file, so it looks like this.
- id: run-pytest
  name: 'python'
  entrypoint: '/usr/local/bin/python'
  args: ["-m", "pytest"]


text:
Q: Bigcommerce Repeating url So this is a two-parter.

*

*I'm doing SEO for a client using Bigcommerce and Screaming Frog is returning some crazy URLs. Here is an example:

~/shop/product_images/product_images/product_images/uploaded_images/img-email.jpg

There are thousands of these. with /product_images being repeated ranging from only once, to up to dozens and dozens of times. This is duplicated over the product categories as well ie

~/shop/kitchen/countertops/product_images/...

*The weirdest part about it is that they all (including ~/shop/product_images/img-email.jpg) resolve to the home page, with a 200 response no less. Not a 404 or a 301/302 redirect or anything.

Feel like I'm missing something obvious, but I can't find anything in the dashboard that seems to make sense.
Anyone seen anything like this before?

A: Check all your links. May be you have errors. Something like product_images instead of /product_images i.e. missing slash. You can find this info as Inlinks and Outlinks in Screaming Frog.


text:
Q: Why in Flutter, PlatformView cannot shrink to its own size? For example:
child: Row(
  children: [
    const Expanded(child: AndroidNativeView()),
    ElevatedButton(
        child: const Text("PLUS"))
  ],
)

In layouts without parent constraints like Flex(Row/Column), The AndroidNativeView (a PlatformViewLink) cannot determine its size thus an exception will be thrown. So the instant solutions are wrapping it inside an Expanded/Flexible, or a Container-like widget with width/height hardcoded. Both solutions are not flexible for the layout.
From the current Dart-side implementations' perspective, I know the sizedByParent function of PlatformViewRenderBox is overridden to true. So it takes the constraint from parent, without measuring itself, and fill up whatever space it gets.
What I don't understand is, since there is "WRAP_CONTENT" on Android side, what's the reason that they didn't make it possible to shrink a PlatformView to its own size in Flutter? What are the technical difficulties/tradeups?

A: If you use a Flex(Row/Column) in a constraints independent width like if you don't provide width/height to your container then it's child has right to decide that how much space it want to cover in Row/Column we've a property named mainAxisSize by default it is set to MainAxisSize.max but you can set it to min as well then Row/Column will also cover space whatever is needed by their children.
But if you provide constraints to the parent widget then as you know already that in Flutter constraints goes parent to child so it will cover all the available space.


text:
Q: Insert inside of a case statement I have a table of data in which I have decided I want to change the way I save and extract data. It was a poor design on my part and now I need to fix it without going through every row manually. I want to change the primary keys from ItemID and VendorID to ItemID and Function. I want a separate record for each function+id rather than a combined record if the vendor id is the same for both functions. I will be eliminating the use of the other_functions column.
Basically my table looks something like this:
ItemID(PK)| VendorID(PK) |   Function   |   other_functions
_______________________________________________________
    1     |    23        |    cooking   |
    1     |    36        |    cleaning  |
    2     |    45        |    cooking   |   cleaning

After I update the PK's, How do I go through the table, and for each record where other_functions = 'cleaning', insert a new row to make it look more like this:
ItemID(PK)| VendorID     | Function(PK)
______________________________________
    1     |    23        |    cooking
    1     |    36        |    cleaning
    2     |    45        |    cooking
    2     |    45        |    cleaning

I am using PostgreSQL. It seems like it should be a simple solution but haven't been able to find the answer I am looking for. Can this be done with just an insert + case statement?

A:
Can this be done with just an insert + case statement?

CASE would make the value conditional - in your case you want to make the insert itself conditional.  A better method would just be to insert records that have a other_functions value:
INSERT INTO {table}
(ItemID, VendorId, Function)
(
SELECT ItemID, VendorId, other_functions
FROM {table}
WHERE other_functions IS NOT NULL
)


text: Q: elementFromPoint relative to parent not document I got two layers (divs) - both positioned absolutely at 0,0 on relative background. One has lower z-index than other. On both there are some other divs. Would like to be able to act on top layer (so pointer-events:none; does not apply), but to show tooltips to elements on bottom layer (with lower z-index). As far as I know, there is a elementFromPoint() function that can get element from coordinates. But this only applies to document. Is there any function that would do the same but with children of selected node? In other words. Would like to know what object do I have on given coordinates of given layer, that is not top-most without losing events bind to top-most one.


text:
Q: Empty Unsat Cores when using Tactics in z3 Solver returns empty unsat core when using tactics.
Case 1:
s = Solver()
x = Real('x')
B = Bool('b')
C = Bool('c')
s.add(B == (x > 1))
s.add(C == (x == -1))
s.check(B, C)

Case 2:
s = Then('simplify', 'solve-eqs', 'smt').solver()
x = Real('x')
B = Bool('b')
C = Bool('c')
s.add(B == (x > 1))
s.add(C == (x == -1))
s.check(B, C)

In both the cases, the check returns unsat (as it should), but I get an empty unsat core in the second case where I use tactics. Is there any way to get unsat core when using solvers with tactics?
PS: These are really simple examples for demonstration. I am working on a bigger problem where I have a number of LRA constraints (where tactics might be helpful) and I need to extract the unsat cores.

A: You need to explicitly enable unsat cores if you're using tactics. The following works:
from z3 import *
s = Then('simplify', 'solve-eqs', 'smt').solver()
s.set(unsat_core=True)
x = Real('x')
B = Bool('b')
C = Bool('c')
s.add(B == (x > 1))
s.add(C == (x == -1))
s.check(B, C)

print s.unsat_core()

Note the call to s.set on the third line. Output:
$ python b.py
[b, c]


text:
Q: Diferences between photoelectric effect and the Compton effect Could anyone explain the differences between the photoelectric effect and the Compton effect in a complete but perceptible form?

A: You might want to check out this answer Compton scattering vs. photoelectric effect
But the gist of it is that the Photoelectric effect occurs at low energies for bounded electrons, resulting in the ionization of the electrons. The key thing in the Photoelectric effect is that it does not depend the intensity of light but rather the energy of the photons.
Where as Compton Scattering occurs at high energies on free electrons, where the photon scatters off of an electron imparting some of it's momentum on to an electron, and since $c = f\lambda$  and $E = hf = \frac{hc}{\lambda}$ so after imparting its momentum the photon loses some of its energy since $h$ is a constant its frequency $f$ will decrease thus its wave length $\lambda$ will increase as it is inversely proportional to the frequency.
Also see
https://en.wikipedia.org/wiki/Photoelectric_effect
https://en.wikipedia.org/wiki/Compton_scattering
https://en.wikipedia.org/wiki/Photon_energy


text:
Q: Image and Face detection libraries/image mining I am looking for open source Face/ Image Detection, Recognition, Video Face Mining libraries similar to the ones that were at one time available from Pittsburg Pattern Recognition. I am also interested in libraries that detect various states of facial expressions that would work on captured still images.libra   I looked at OpenCV but I was not able to find a cohesive library.  Also, I would be interested in getting in touch with any group that would do contract development or license available libraries. Much thanks in advance.

A: OpenCV has support for Face Detection and even gesture recognition, such as smile recognition, like this: auto-smiley.
openFrameworks is a good library which wraps OpenCV and makes life considerably easier, very sophisticated image processing can be done with the two.


text:
Q: Check value of fields before running function in jquery I basically want to have a script on the page which shows a map when it finds two fields on the page named "lng" and "lat" which have a value.
This means that if there are the fields on the page with values, then it will try and display a map, but if not, then it will not.
This is the code I have so far:
http://jsfiddle.net/spadez/xJhmk/3/
function mapDisplay() {

    var latval = $('input[id=lat]').val();
    var lngval = $('input[id=lng]').val();

    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(latval, lngval),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false
    };
    var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}

$(function () {
    mapDisplay();
});

I am not very good at jquery at the moment but this is what I tried which didn't work:
if (latval !=NULL && lngval != NULL)){
...my code
}

Can someone with a little more knowledge help me understand why this approach doesn't work please?

A: Try this
if ( !isNaN(latval) && !isNaN(lngval)) {

So basically it checks if the 2 inputs are numbers, and only if true will step into the if condition.
Also
var latval = $('input[id=lat]').val();
var lngval = $('input[id=lng]').val();

can be safely written as
var latval = $('#lat').val(),
    lngval = $('#lng').val();

You can hook up the change event for the inputs that will display the maps
Code
function mapDisplay() {

    var latval = $('#lat').val(),
        lngval = $('#lng').val();
      if (!isNaN(parseFloat(latval)) && !isNaN(parseFloat(lngval))) {
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(latval, lngval),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            scrollwheel: false,
            draggable: false
        };
        var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        $('#map_canvas').removeClass('hidden');
    } else {
        $('#map_canvas').addClass('hidden');
    }
}

$(function () {
    $('input').on('change', mapDisplay).trigger('change');
});

Check Fiddle

A: You can do this:
var latval = $('#lat').val();
var lngval = $('#lng').val();

if ($.trim(latval) != '' && $.trim(lngval) != '') {
    // You code

*

*No need to do this input[id=lat], you can directly call it like $('#lat')

*Use $.trim() to remove the whitespace from the beginning and end of a string.

A: your code is correct : you just have to add a line in you css in order to view the map:
add
display:block; in #map_canvas

like this :
#map_canvas {
    display:block;
    height: 150px;
    width: 300px;
}

moreover you can change its display setting by setting this display property using jquery(depending upon whether variables have values or not.).
by default textbox returns string value. so for empty textbox you can check :
if(latval=='' && lngval==''){alert('blank');}
else{your code;}

A: the value returned from text box is not a NULL it is just an empty string so you should check whether the value is empty or not
if(latval !="" && lngval !=""){
Your code
}

and if you want to specific for only numbers , try adding
$.isNumeric()

 if($.isNumeric(latval) && $.isNumeric(lngval )){
    Your code
    }

A: As you are prob checking latitude/longtitude, I would also check if they are numeric.
function checkValues() {
    var valueOK = false;
    if($.isNumeric($('#lat').val())) {
         if($.isNumeric($('#lng').val())) valueOK = true;
    }

    return valueOK;
}

$(function () {
    if(checkValues) {
         mapDisplay();
    }
}

A: You can access variables like
var lat = jQuery.trim($('#lat').val());
var lng = jQuery.trim($('#lng).val());

And check if the fields were empty
if(lat == '' && lng == '') {
    //do code
} else {
   //show the map
   $("#mapId").show();
}


text:
Q: Radiation by an electric monopole I was reading about the power radiated by an oscillating electric dipole. It then said that monopoles don't radiate.
But a monopole is just a charge, right? And an accelerated charge radiates EM waves. Can someone please explain.

A: Dipoles can radiate because a time changing electric dipole moment does not violate the conservation of charge (you can think of the two opposite charges rapidly changing places with time). However, for the value of an electric monopole (a single charge) to change with time without there being any other charge in the region, conservation of charge would have to be violated; Which is impossible.
Edit:
I don't think that the author of what you're reading means an accelerating charge; just like us not considering accelerating dipoles when we are talking about dipole radiation.


text:
Q: Required WebLogic 12.2.1 jar files for running jwsc ant task We have WebLogic Server 12.2.1 on a server, and I have my development done on my notebook. I am not able to install WebLogic on my notebook due to company policy. If I want to use the jwsc ant task on my notebook, what are the required JAR files that I need to copy from the server?
I have read about weblogic.jar, but this file contains only a single MANIFEST.MF file that includes class paths to other JAR files. I am sure that just copying weblogic.jar to my notebook is not enough to get jwsc task to work.
Thanks.

A: At minimum you need these jar files:

wlHome/wlserver/modules/clients/com.oracle.webservices.wls.jaxws-wlswss-client.jar
  wlHome/wlserver/modules/com.bea.core.repackaged.apache.xerces.jar
  wlHome/wlserver/modules/com.bea.core.annogen.jar
  wlHome/wlserver/modules/com.bea.core.xml.xmlbeans.jar
  wlHome/wlserver/modules/com.bea.core.descriptor.j2ee.jar
  wlHome/wlserver/modules/com.bea.core.xml.staxb.runtime.jar
  wlHome/wlserver/modules/com.oracle.weblogic.application.jar
  wlHome/wlserver/modules/com.bea.core.descriptor.application.jar
  wlHome/wlserver/modules/com.bea.core.descriptor.application.binding.jar
  wlHome/wlserver/modules/com.bea.core.beangen.jar
  wlHome/wlserver/modules/com.bea.core.descriptor.settable.binding.jar
  wlHome/wlserver/modules/com.bea.core.appdescriptor.jar
  wlHome/wlserver/modules/com.oracle.weblogic.management.base.jar
  wlHome/wlserver/modules/com.oracle.weblogic.management.upgrade.jar

You may need additional jars from wlHome/wlserver/modules depending on what WS features you want.


text:
Q: Go from child navigation to parent navigation I have two NavigationContainer. What I want is when I am on the SignIn screen go to the MainPage. And the problem goes when I am in MainPage > Profile. The Button Logout does not go to the SignIn Screen.
App.js

import React from "react";
import {SignIn} from './src/screen/authentication/signIn'
import {SignUp} from "./src/screen/authentication/signUp";
import {MainPage} from "./src/screen/drawer";
import {createStackNavigator} from "@react-navigation/stack";
import {NavigationContainer} from "@react-navigation/native";

const Stack = createStackNavigator();

class App extends React.Component {
    render() {
        return (
            <NavigationContainer>
                <Stack.Navigator initialRouteName="SignIn" headerMode={null}>
                    <Stack.Screen name="SignIn" component={SignIn} />
                    <Stack.Screen name="SignUp" component={SignUp} />
                    <Stack.Screen name="Home" component={MainPage} />
                </Stack.Navigator>
            </NavigationContainer>
        );
    }
}

drawer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {Dashboard} from "./dashboard/dashboard";
import {AddWidget} from "./addWidget/addWidget";
import {Profile} from "./profile/profile";

const Drawer = createDrawerNavigator();

export function MainPage({navigation}) {
    return(
    <NavigationContainer independent={true}>
            <Drawer.Navigator>
                <Drawer.Screen name="Dashboard" component={Dashboard} />
                <Drawer.Screen name="Add widget" component={AddWidget} />
                <Drawer.Screen name="Profile" component={Profile} initialParams={{navigation: () => navigation.navigate('SignIn')}} />
            </Drawer.Navigator>
    </NavigationContainer>
    );
}

Profile.js

import * as React from 'react';
import {Button, Text, View} from "react-native";
import {useHistory} from "react-router-dom";
import {styles} from "./styles"

export function Profile({navigation}) {
    const history = useHistory();
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={styles.title}>Username</Text>
            <Button title="Logout" onPress={() => navigation.navigation} />
        </View>
    );
}

A: you should be able to just do this:
        <Button title="Logout" onPress={() => navigation.navigate("SignIn")} />

if the above doesn't work, you can try this:
import * as React from 'react';
import {Button, Text, View} from "react-native";
import {useHistory} from "react-router-dom";
import { useNavigation } from '@react-navigation/native';
import {styles} from "./styles"

export function Profile() {
    const history = useHistory();
    const navigation = useNavigation();
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={styles.title}>Username</Text>
            <Button title="Logout" onPress={() => navigation.navigate("SignIn")} />
        </View>
    );
}

A: A trick that I found is printing props with console.log and finding the function inside the object.
So what I did is changing the name of initialparams from Profile, navigation to parentNaivgation. And also removing ({navigation}) to (props) in the Profile component.
At the end, the route to finding the function navigation was props.route.params.parentNavigation.navigate("SignIn")


text:
Q: React Native white-space: nowrap width for absolutely positioned Text node In HTML/CSS if you want an absolutely positioned element to expand wider than its parent to fit all its text in one line, you can use white-space: no-wrap
.parent {
  position: relative;
  width: 100px;
}
// text content of this node is wider than 100px
.child {
  position: absolute;
  white-space: nowrap;
}

The child element will grow just wide enough to fit all the text in one line. There doesn't be a way to do this with Text components in React Native. You have to specify a fixed number width or the Text component will max out at the parent width. Is there a way?

A: Figured out that the answer is quite simple.
Text wrap can be specified with the <Text> component's built-in interface called numberOfLines, instead of CSS.
<Text numberOfLines={1}>Foobar</Text>

The documentation for this can be found here.


text:
Q: How can I do mansory style or something like this image area I'm using Bootstrap4. If I do responsive for mansory style gallery with img-fluid tag. For example, the second image is so long(as height) and there is a so much space with other images. How can I do this gallery like these for example tumblr or pexels.com ?

I did like the answer but I need lazy load on this. I've tried so much but I could do this together please help!

@media only screen and (min-width: 1100px) {
  .masonry {
    -moz-column-count: 4;
    -webkit-column-count: 4;
    column-count: 4;
  }
}

@media only screen and (min-width: 900px) {
  .masonry {
    -moz-column-count: 3;
    -webkit-column-count: 3;
    column-count: 3;
  }
}

@media only screen and (min-width: 700px) {
  .masonry {
    -moz-column-count: 2;
    -webkit-column-count: 2;
    column-count: 2;
  }
}

.masonry {
  margin: 1.5em 0;
  padding: 0;
  -moz-column-gap: 1.5em;
  -webkit-column-gap: 1.5em;
  column-gap: 1.5em;
  font-size: .85em;
}

.item {
  background-color: #eee;
  display: inline-block;
  margin: 0 0 1em;
  width: 100%;
}

.item img {
  max-width: 100%;
  height: auto;
  display: block;
}

A: Just add masonry to the page and configure it with itemSelector: '.col-md-4'

$('.row').masonry(function() {
  itemSelector: '.col-md-4'
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">

And if you want to get rid of the horizontal padding in the cells that creates a gutter between the images, you could always just not use bootstrap .col classes there, or you can add .nowrap to the parent .row and remove the padding with CSS like .nopad > div { padding: 0; }

$('.row').masonry(function() {
  itemSelector: '.col-md-4'
});
.nopad > div {
  padding: 0;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

A: Pure CSS version of responsive masonry, no plugin or script used.

@media only screen and (min-width: 1100px) {
  .masonry {
    -moz-column-count: 4;
    -webkit-column-count: 4;
    column-count: 4;
  }
}

@media only screen and (min-width: 900px) {
  .masonry {
    -moz-column-count: 3;
    -webkit-column-count: 3;
    column-count: 3;
  }
}

@media only screen and (min-width: 700px) {
  .masonry {
    -moz-column-count: 2;
    -webkit-column-count: 2;
    column-count: 2;
  }
}

.masonry {
  margin: 1.5em 0;
  padding: 0;
  -moz-column-gap: 1.5em;
  -webkit-column-gap: 1.5em;
  column-gap: 1.5em;
  font-size: .85em;
}

.item {
  background-color: #eee;
  display: inline-block;
  margin: 0 0 1em;
  width: 100%;
}

.item img {
  max-width: 100%;
  height: auto;
  display: block;
}


text:
Q: Remove required field validation of configurable attribute in product view page magento I am using Magento ver. 1.9.0.1. I just want to remove the validation of configurable attribute as it is not necessary to select. If the user will not select the configurable attribute then default product will add to cart.
 I checked all stuffs but didn't get the fruitful result.
Thanks!
Your help would be appreciated.

A: GO to the folder /catalog/product/view/type/option/configurable.phtml and there you have to do hard coding by your self


text:
Q: При выборе input type radio менять стиль блока Стоит такая задача. На HTML странице есть блок с классом right_box в котором выводятся блоки с номерами вопросов. Мне необходимо сделать так, чтобы когда я выбираю ответ например в 3 вопросе, то к классу у объекта down_mini добавляется used_mini.
<?php
    include "../script/func/function.php"; //Файл с фунциями
    session_start();
    check_coock(); //Проверка куки
    check_coock_testing();
    //------------ Задаем параметры для панели навигации -----------\\
    $exit = 'Выход';
    $admin = 'Админ';
    $main_page = 'Главная';
    $admin_hr = '
';
?>
<!DOCTYPE HTML>

    <link rel="icon" href="https://amt.rosminzdrav.ru/theme/image.php/adaptable/theme/1605257379/favicon">
    <link rel="stylesheet" href="../css/style-main.css">
    <link rel="stylesheet" href="../css/style-testing.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Тестирование</title>

         <text class="goto_exit"></text>

          <?php //Выпадающий список навигации по сайту
            if (isset($_COOKIE["admin"])) {
             echo $exit;
             echo $admin_hr;
             echo $admin;
             echo $admin_hr;
             echo $main_page;
            } else {
              echo $exit;
            }
          ?>

         <text class="up_text">
             <?php //Данные пользователя (Имя и фамилия)
                 echo $_COOKIE["name"];
                 echo " ";
                 echo $_COOKIE["surname"];
             ?>
         </text>

            <text>Тестирование - 1 -й этап</text>

 Навигация по тесту

                     <?php
                        get_mass_session_testing();
                        for ($i = 1; $i < 61; $i++){
                            echo '

                                      '.$i.'

';
                        }
                     ?>

                             1

Закончить попытку...

            <?php
                get_mass_session_testing();
                for ($i = 1; $i < 61; $i++) {
                    $num = get_num(4);
                    $id_qs = $_SESSION["mas_test"][$i];
                    echo'

                        Вопрос '.$i.'

                            Пока нет ответа

                            Балл: 1,00

                             Отметить вопрос

';
                    echo withdraw_quest($num, get_quest($_SESSION["mas_test"][$i]), $id_qs);
                    echo '
';
                }
           ?>

    <form action="" class="endform">
        <input type="button" value="Завершить">
    </form>

A: Смотри можеш сделать так. Что при клике добавлять класс.
HTML:

JavaScript c jQuery:
$(function() {
$('.down_mini').click(function() {
    $('.down_mini').addClass('used_mini');
});

});
И потом этому классу добавлять стили.


text:
Q: How can I save an edited Word document with Python? I am attempting to create a script which can extract the XML from a Word document, modify it, and finally save the new Word document, all using Python. Here's the code I used, which was effectively stolen from here:
import zipfile
import os
import tempfile
import shutil

def getXml(docxFilename):
    zip = zipfile.ZipFile(open(docxFilename,"rb"))
    xmlString = str(zip.read("word/document.xml"))
    return xmlString

def createNewDocx(originalDocx,xmlContent,newFilename):
    tmpDir = tempfile.mkdtemp()
    zip = zipfile.ZipFile(open(originalDocx,"rb"))
    zip.extractall(tmpDir)
    with open(os.path.join(tmpDir,"word/document.xml"),"w") as f:
        f.write(xmlContent)
    filenames = zip.namelist()
    zipCopyFilename = newFilename
    with zipfile.ZipFile(zipCopyFilename,"w") as docx:
        for filename in filenames:
            docx.write(os.path.join(tmpDir,filename),filename)
    shutil.rmtree(tmpDir)

One important difference between my code and Virantha's is that he expressed createNewDocx as a class. Unfortunately I don't know what classes are or how they work, so I figured it would be easier to write a function instead.
getXML extracts the XML from a Word document. I tried it out on a test document (named test.docx) and it worked well. In theory, createNewDocx is supposed to take the original docx file (in this case, test.docs) and the modified XML as a string to create a new Word document, entitled newFileName.
As a test, I ran createNewDocx with the original XML to see if I would get a copied version of text.docx. That is, I ran
originalXml = getXml("test.docx")
createNewDocx("test.docx",originalXml,"test2.docx")

This did indeed create a Word document entitled "test2.docx", but when I tried to open the file it just wouldn't open; Word would just crash.
Does anyone know how I can modify my code to make it work?
EDIT: I decided to include originalXml in case there's some problem with how it's formatted.
b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"><w:body><w:p w:rsidR="00000000" w:rsidRDefault="00971B91"><w:r><w:t>You owe me ${debt}. Pay back soon.</w:t></w:r></w:p><w:p w:rsidR="00971B91" w:rsidRPr="00971B91" w:rsidRDefault="00971B91"><w:pPr><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">You owe me </w:t></w:r><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/><w:b/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>${debt}</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">. Pay back </w:t></w:r><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/><w:i/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>soon.</w:t></w:r></w:p><w:sectPr w:rsidR="00971B91" w:rsidRPr="00971B91"><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/><w:cols w:space="708"/><w:docGrid w:linePitch="360"/></w:sectPr></w:body></w:document>'

EDIT2: I looked more closely at the XML code above and realized that there was an unusual "b'" at the beginning and a close parentheses at the end. I removed these anomalies and ran the code again. Now Word is giving me a more sensible error, namely that there's a problem with "line 1, column 56." That corresponds to the "\r\" in the XML code above.
So obviously my code isn't extracting the XML properly. Anyone know how to fix this?

A: By casting "zip.read("word/document.xml")", you cast a byte to string so you keep the 'b' as a char.
def getXml(docxFilename):
zip = zipfile.ZipFile(open(docxFilename,"rb"))
xmlString = str(zip.read("word/document.xml"))
return xmlString

So that's why the "xmlString" has no attribute because it's a string.
You have to remove you cast an decode before return:
def getXml(docxFilename):
zip = zipfile.ZipFile(open(docxFilename,"rb"))
xmlString = zip.read("word/document.xml")
return xmlString.decode('utf-8')

Hope it will be helpful for others !


text:
Q: How to keep Entity Framework and database aligned in early development stages the database is subject to continuous changes. I'm toying around with LinqToSQL and in most cases the Entity Model is just a 1:1 representation of the DB.
How can i keep the model up to date with the db changes?
Thanks.

A: I noticed that there is an "update model from database" command available if you right-click the Entity Framework design surface. I couldn't find such a thing for LINQ to SQL, so you might have to maintain by hand.
OTOH, it's just XML, so you could "just write some code".

The other thing to add is that I prefer the fact that in EF, I don't have to keep up to date with the physical database. I'm defining the entities that developers will use to access the data, and separately I'm defining the mapping between those entities and the logical database structure.
They don't need to be the same. If I want to split a table into two, or combine two entities into one table, I can do this, without requiring developers to rewrite their code.


text:
Q: per process configurable core dump directory Is there a way to configure the directory where core dump files are placed for a specific process?
I have a daemon process written in C++ for which I would like to configure the core dump directory. Optionally the filename pattern should be configurable, too.
I know about /proc/sys/kernel/core_pattern, however this would change the pattern and directory structure globally.
Apache has the directive CoreDumpDirectory - so it seems to be possible.

A: No, you cannot set it per process. The core file gets dumped either to the current working directory of the process, or the directory set in /proc/sys/kernel/core_pattern if the pattern includes a directory.
CoreDumpDirectory in apache is a hack, apache registers signal handlers for all signals that cause a core dump , and changes the current directory in its signal handler.
/* handle all varieties of core dumping signals */
static void sig_coredump(int sig)
{
    apr_filepath_set(ap_coredump_dir, pconf);
    apr_signal(sig, SIG_DFL);
#if AP_ENABLE_EXCEPTION_HOOK
    run_fatal_exception_hook(sig);
#endif
    /* linuxthreads issue calling getpid() here:
     *   This comparison won't match if the crashing thread is
     *   some module's thread that runs in the parent process.
     *   The fallout, which is limited to linuxthreads:
     *   The special log message won't be written when such a
     *   thread in the parent causes the parent to crash.
     */
    if (getpid() == parent_pid) {
        ap_log_error(APLOG_MARK, APLOG_NOTICE,
                     0, ap_server_conf,
                     "seg fault or similar nasty error detected "
                     "in the parent process");
        /* XXX we can probably add some rudimentary cleanup code here,
         * like getting rid of the pid file.  If any additional bad stuff
         * happens, we are protected from recursive errors taking down the
         * system since this function is no longer the signal handler   GLA
         */
    }
    kill(getpid(), sig);
    /* At this point we've got sig blocked, because we're still inside
     * the signal handler.  When we leave the signal handler it will
     * be unblocked, and we'll take the signal... and coredump or whatever
     * is appropriate for this particular Unix.  In addition the parent
     * will see the real signal we received -- whereas if we called
     * abort() here, the parent would only see SIGABRT.
     */
}

A: It is possible to make it using the "|command" mechanism of the core_pattern file. The executed command can create the directories and files as needed. The command can be passed the following specifiers in the parameters (cf. man 5 core):

%% a single % character
%c core file size soft resource limit of crashing process
%d dump mode—same as value returned by prctl(2) PR_GET_DUMPABLE
%e executable filename (without path prefix)
%E pathname of executable, with slashes ('/') replaced by exclamation marks ('!')
%g (numeric) real GID of dumped process
%h hostname (same as nodename returned by uname(2))
%i TID of thread that triggered core dump, as seen in the PID namespace in which the thread resides
%I TID of thread that triggered core dump, as seen in the initial PID namespace
%p PID of dumped process, as seen in the PID namespace in which the process resides
%P PID of dumped process, as seen in the initial PID namespace
%s number of signal causing dump
%t time of dump, expressed as seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
%u (numeric) real UID of dumped process

For example, it possible to create a script (e.g. named crash.sh) as follow:
#!/bin/bash

# $1: process number on host side (%P)
# $2: program's name (%e)

OUTDIR=/tmp/core/$2
OUTFILE="core_$1"

# Create a sub-directory in /tmp
mkdir -p "$OUTDIR"

# Redirect stdin in a per-process file:
cat > "$OUTDIR"/"$OUTFILE"

exit 0

In the shell:
$ chmod +x crash.sh
$ mv crash.sh /tmp  # Put the script in some place
$ sudo su
# echo '|/tmp/crash.sh %P %e' > /proc/sys/kernel/core_pattern
# cat /proc/sys/kernel/core_pattern
|/tmp/crash.sh %P %e
# exit
$

Create an example program which crashes (e.g. fail.c):
int main(void)
{
  char *ptr = (char *)0;

  *ptr = 'q';

  return 0;

}

Compile the program (make several executables) and adjust the core file size in the current shell:
$ gcc fail.c -o fail1
$ gcc fail.c -o fail2
$ ulimit -c
0
$ ulimit -c unlimited
$ ulimit -c
unlimited

Run the failing programs several times to have multiple processes ids:
$ ./fail1
Segmentation fault (core dumped)
$ ./fail2
Segmentation fault (core dumped)
$ ./fail1
Segmentation fault (core dumped)
$ ./fail2
Segmentation fault (core dumped)

Look at /tmp where the core_pattern redirect the core dumps:
$ ls -l /tmp/core
total 8
drwxrwxrwx 2 root root 4096 nov.    3 15:57 fail1
drwxrwxrwx 2 root root 4096 nov.    3 15:57 fail2
$ ls -l /tmp/core/fail1/
total 480
-rw-rw-rw- 1 root root 245760 nov.    3 15:57 core_10606
-rw-rw-rw- 1 root root 245760 nov.    3 15:57 core_10614
$ ls -l /tmp/core/fail2
total 480
-rw-rw-rw- 1 root root 245760 nov.    3 15:57 core_10610
-rw-rw-rw- 1 root root 245760 nov.    3 15:57 core_10618


text:
Q: PyQt4 - function have not executed which connected to a signal As title, I use
 self.connect(MorePushButton, SIGNAL("clicked"), MorePushButton_toggled)
and
self.connect(MorePushButton, SIGNAL("clicked"), self.MoreFrame.setVisible)
to execute the function "MorePushButton_toggled" and set property when MorePushButton clicked.
But, here's the problem I can't figure out:
when I pushed the button MorePushButton, it did nothing!
And it also had no error message.
Did I put the code on the wrong side?
If someone can help me, I would appreciate!
Here's my code below:
    from PyQt4 import QtCore, QtGui
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from ui_extention2 import Ui_Dialog

    class Main(QDialog, Ui_Dialog):
        def __init__(self, parent=None):
            super(Main, self).__init__(parent)
            self.connect(MorePushButton, SIGNAL("clicked"), MorePushButton_toggled)
            self.connect(MorePushButton, SIGNAL("clicked"), self.MoreFrame.setVisible)
            self.setupUi(self)

    def MorePushButton_toggled(self):
        if self.MorePushButton.isChecked() == True:
            #self.Dialog.setGeometry(QtCore.QRect(0,0,400,280))
            Dialog.resize(400, 280)
            print("Resize 400*280")
        else:
            #self.Dialog.setGeometry(QtCore.QRect(0,0,400,100))
            Dialog.resize(400, 100)
            print("Resize 400*100")

    if __name__ == "__main__":
        import sys
        app = QtGui.QApplication(sys.argv)
        Dialog = QtGui.QDialog()
        ui = Ui_Dialog()
        ui.setupUi(Dialog)
        Dialog.show()
        sys.exit(app.exec_())

Remark:
(1)the .ui file was designed by QT Designer
(2)Python version:4.3
(3)PyQt version:GPL 4.11.4


text:
Q: How to file copy from a column of files in a data table in R I am trying to create a new folder with all the files I need. I have a datatable called newlist with a column called fullpath which has the file path for each file.
I have tried the code below but the error message says "'from' path too long" so I don't think it recognises the values as separate file paths.
file.copy(from=newlist[,"fullpath"], to=destination, overwrite=TRUE, recursive=TRUE)

I think I need to specify the files to copy first using the list.files() function but I am unsure how to do this with a column of files in a datatable.

A: Try this:
lapply(newlist[,"fullpath"], function(x) file.copy(from=x, to=destination, overwrite=TRUE, recursive=TRUE))

Edit:
If your paths do not contain extensions, you can use this code instead:
lapply(newlist[,"fullpath"], function(x) {
  # Find the file in the given directory with the basename and add a wildcard extension
  f <- file.path(dirname(x), list.files(dirname(x), paste0(basename(x), ".*")))
  file.copy(from=f, to=destination, overwrite=TRUE, recursive=TRUE)
})


text:
Q: Python, "If if line is called on first time, do something else" So the title is pretty self explanatory, but i'll go into more detail. I am creating a text dependent game and I will have millions of areas. And each time you enter a new area, you will be greeted with a one time only different reaction than if you came into the same place again later, and I need to find a way to to this:
if len(line) == 1:
    do exclusive thing
else:
    do normal thing

Sure, I could use a counter system like "a = 0" but then I would need to create a separate counter for every single area I create, and I don't want that.

A: You could just store a single dict to keep track of room visits, and probably even better to use a defaultdict
from collections import defaultdict

#Using a defaultdict means any key will default to 0
room_visits = defaultdict(int)

#Lets pretend you had previously visited the hallway, kitchen, and bedroom once each
room_visits['hallway'] += 1
room_visits['kitchen'] += 1
room_visits['bedroom'] += 1

#Now you find yourself in the kitchen again
current_room = 'kitchen'
#current_room = 'basement' #<-- uncomment this to try going to the basement next

#This could be the new logic:
if room_visits[current_room] == 0: #first time visiting the current room
    print('It is my first time in the',current_room)
else:
    print('I have been in the',current_room,room_visits[current_room],'time(s) before')

room_visits[current_room] += 1 #<-- then increment visits to this room

A: You need static var : What is the Python equivalent of static variables inside a function?
def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate

@static_var("counter", 0)
def is_first_time():
    is_first_time.counter += 1
    return is_first_time.counter == 1

print(is_first_time())
print(is_first_time())
print(is_first_time())


text:
Q: Windows - track program usage by time and user I do some admin work for a volunteer emergency services organization, and they've decided to migrate their "public" (available for the use of all 35+ members) workstations to Linux.
Is there any Windows tool that I can use to track which programs are used by which users, and how often? As the end result, I'm looking to come up with a list of software that's used, and how often it's used, to determine what sort of backwards compatibility (Wine, dual-boot, etc.) I'll have to implement.

A: Check out Rescuetime, it does all of that and more.

A: You could do this using NTFS auditing, assuming that the PCs use NTFS.  This is available under Security | Advanced | Auditing, and you'll want auditing on the Traverse Folder/Execute File action for the Everyone security principal.
A dedicated app to monitor it would be preferable though.

A: There's no built-in tool in Windows to do what you're looking for, per se.
You could crib something together by turning on the "Process Tracking" success auditing and then mining the event log data. You're going to get a LOT of data to wade through, but what you're looking for would be in there.
If you have experience parsing logs you could probably work out a solution to export and parse the event logs from the various computers to get what you're looking for. If you don't have such experience you're going to find this a challenging and daunting task.
The "C:\WINDOWS\PreFetch" directory will show you a lot of names of programs users are running, but it's not as exacting as the event log / auditing method. I don't recall the mechanism by which it gets cleaned out, but records don't linger in there permanently. (some more information about the "Prefetch" behavior is available here: http://windowshelp.microsoft.com/Windows/en-US/help/0ec5b471-ed65-43c4-a59b-c1fd975c42621033.mspx)

A: Two things I forgot to add that greatly complicate this:
1) This is a zero-budget project, so buying software is out of the question.
2) The three machines are running Windows XP home.
Perhaps the only solution here is to write some sort of daemon ("service" for windows?) that grabs a process list and dumps it to a database?


text:
Q: Large Mail Merge via Google Script (Sheets -> Docs), anyway to speed it up and add formatting? So I'm trying to produce a mail merge that will pull questions from a spreadsheet, and give each student a breakdown of the question number, topic of the question, and mark.
I have managed to get to a point where it will produce the documents and merge them into a PDF, just with the completely the wrong information.
I'm looking to ideally pull the information from the spreadsheet to fill the document. I've tried using a loop for the body2.replacetext but to be honest, I'm learning the language as I'm going along (and probably butchering it along the way!) Importantly, I want the colours of each number to appear on the new Google Doc Document.
Link to Spreadsheet
Link to Document
Here is my current code - it will produce pdfs but with completely the wrong information (on purpose, I'm just trialling it!)
const tempFolder2 = DriveApp.getFolderById("1YSdJIXDANzzgSLYK0cWC9VkcoKyGbAkv");
const currentSheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Question Level Entry");
const data2 = currentSheet2.getRange(4, 1,currentSheet2.getLastRow(),31).getValues();
const docFile2= DriveApp.getFileById("1l6SqU_sepOBA8jhSRArSzMte7zPz19KBQJaLKfsK5zM");
const pdfFolder2 = DriveApp.getFoldersByName("Feedback Sheets").next();

function createBulkQLA(){
  let errors = [];
 data2.forEach(row => {
   try{
createQLA(row[0],row[1],row[2],row[3],row[4],docFile2,tempFolder2,pdfFolder2,row[0]+' '+row[1]);
errors.push([""]);
} catch(err){
  errors.push([""])}

 });
combineDocs();
cleanup();
cleanup2();
}

function createQLA(studentName1,class1,n_1,topic_1,m_1,docFile2,tempFolder2,pdfFolder2,pdfName2) {
  const tempFile2 = docFile2.makeCopy(tempFolder2);
  const tempDocFile2 = DocumentApp.openById(tempFile.getId());
  const body2 = tempDocFile.getBody();
  body2.replaceText("{test_name}",testName1)
  body2.replaceText("{student_name}",studentName1);
  body2.replaceText("{class1}",class1);
  body2.replaceText("{n_1}", n_1);
  body2.replaceText("{topic_1}", topic_1);
  body2.replaceText("{m_1}", m_1);

  tempDocFile2.saveAndClose();
  tempFile2.makeCopy(pdfFolder2).setName(pdfName2);
  removeFile(tempFile2);
  removeFile(tempDocFile2);

}

function getDocsRec(pdfFolder2) {
  var docs = [];

  function iter(pdfFolder2) {
    var childFolders = pdfFolder2.getFolders();
    while (childFolders.hasNext()) {
      iter(childFolders.next());
    }

    var childFiles = pdfFolder2.getFiles();
    while (childFiles.hasNext()) {
      var item = childFiles.next();
      var docName = item.getName();
      var docId   = item.getId();
      var doc     = {name: docName, id: docId};
      docs.push(doc);
    }
  }

  iter(pdfFolder2);
  return docs;
}
function combineDocs2() {
  if (pdfFolder2 == null) { Logger.log("Failed to get root folder"); return; }
  var combo = DocumentApp.create("Full Class Feedback");
  var comboBody = combo.getBody();

  var docArr = getDocsRec(pdfFolder2);

  docArr.forEach(function(item) {
    Logger.log(item.name)
  });

  for (var j = 0; j < docArr.length; j++) {

    if (j % 50 == 0) {
      combo.saveAndClose();
      combo = DocumentApp.openById(combo.getId());
      comboBody = combo.getBody();
    }

    var entryId = docArr[j].id;
    var entry = DocumentApp.openById(entryId);
    var entryBody = entry.getBody();
    var elems = entryBody.getNumChildren();
    for (var i = 0; i < elems; i++) {
      var elem = entryBody.getChild(i).copy();
      switch (elem.getType()) {
        case DocumentApp.ElementType.HORIZONTAL_RULE:
          comboBody.appendHorizontalRule();
          break;
        case DocumentApp.ElementType.INLINE_IMAGE:
          comboBody.appendImage(elem);
          break;
        case DocumentApp.ElementType.LIST_ITEM:
          comboBody.appendListItem(elem);
          break;
        case DocumentApp.ElementType.PAGE_BREAK:
          comboBody.appendPageBreak(elem);
          break;
        case DocumentApp.ElementType.PARAGRAPH:
          comboBody.appendParagraph(elem);
          break;
        case DocumentApp.ElementType.TABLE:
          comboBody.appendTable(elem);
          break;
        default:
          var style = {};
          style[DocumentApp.Attribute.BOLD] = true;
          comboBody.appendParagraph("Element type '" + elem.getType() + "' could not be merged.").setAttributes(style);
      }
    }
   comboBody.appendPageBreak();

  }
}
function cleanup(){
var originalSpreadsheet = SpreadsheetApp.getActive();
var combinedTitle = originalSpreadsheet.getRange("D1").getValue();
var fils=DriveApp.getFilesByName("Full Class Feedback");
  while (fils.hasNext()) {
    var file = fils.next();
var newFileId = file.getId();
var newFile = DriveApp.getFileById(newFileId);
newFile.setName(combinedTitle + ' ' + 'QLA Broadsheet');
newFile.moveTo(destination);
  }
}
function cleanup2() {
  const getAllFiles = folder => {
    const files = folder.getFiles();
    while (files.hasNext()) {
      const file = files.next();
      console.log(file.getName());
      file.setTrashed(true);
    }
    const folders = folder.getFolders();
    while (folders.hasNext()) getAllFiles(folders.next());
  }

  var folder = pdfFolder2;
  getAllFiles(folder);
}


text:
Q: Create Eloquent model from complex raw SQL-query I am thinking about the right design of the method which gives user a list of clients who's last appointment was long time ago.
So I have 2 table (simplified):

*

*Clients (id, first_name)

*Appointments (id, client_id, datetime)

What I am trying to do: get the list of 3 clients who's last appointment was long time ago.
So what I do: I select users with the oldest appointments and return them (with complex SQL query). Then I create models from them.
Is it good design for this case?
use Illuminate\Database\Eloquent\Collection;

class ClientRepository {

    /**
     * Get clients with no appointments in the near history (sort by the date of last appointment ASC)
     *
     * @todo Make a better way to find falling clients (more Laravelish maybe?)
     * @param $count How many clients should method return
     * @return Illuminate\Database\Eloquent\Collection
     */
    static public function getLost($count=3) {

        //this SQL looks too long but works as charm
        //solution based on http://stackoverflow.com/questions/1066453/mysql-group-by-and-order-by
        $sql = "
            SELECT * FROM (
                SELECT clients.*, clients.id AS cli_id , appointments.datetime AS last_appointment_datetime
                FROM clients
                INNER JOIN appointments ON clients.id=appointments.client_id
                ORDER BY appointments.datetime ASC
            ) AS tmp_table
            GROUP BY cli_id
            ORDER BY last_appointment_datetime ASC
            LIMIT ?
        ";

        $users = \DB::select($sql,[$count]);
        foreach($users as $key=>$user) {
            $user_array = (array)$user;
            $users[$key] = new Client();
            $users[$key]->forceFill($user_array);
        }
        $collection = new Collection($users);

        return $collection;
    }

}

A: You can do it without subselect and using Eloquent's query builder:
//select clients joined with their appointments
$users = Client::join('appointments', 'appointments.client_id', '=', 'clients.id')
  //group rows by client ID (if client has multiple appointments then client would appear multiple times in the result set
  ->groupBy('clients.id')
  //sort them by date of last appointment in descending order
  ->orderByRaw('MAX(appointments.datetime)')
  ->get();


text:
Q: Are minidump files useful for analysing .NET WinForms app crashes? Are minidump files useful for analysing .NET WinForms app crashes? I notice that NBug has the option of producting them, but if I was to receive one, I'm not sure how it could help over looking at the stack trace.
How would one use this file for .NET debugging?

A: A mini dump is a very broad category of dumps. You can create a mini dump with full process memory, and you can create a mini dump that doesn't contain anything except loaded modules and some stack pages. To debug managed dumps, you need the regions of memory that contain JIT-ted code to be available to the debugger in the dump file. The easiest way to do this is to create a full dump (mini dump with full memory). You can then inspect it using the SOS extension in WinDbg, or you can simply drag-and-drop it into Visual Studio 2010 or higher.


text:
Q: Creating polygons with Geodesic measurements? I'm using ArcGIS Pro 2.9 to translate plats into GIS. I've begun to notice some measuring inconsistencies.
Having projected in WGS 1984 World Mercator, I would expect when I create polygons they would measure in geodesic, yet they do not.
How do I create polygons that measure in geodesic?

A: I created a process to insert Geodesic polygons in Mercator using lines and the buffer tool:

*

*Select the Insert tab-> Measurements group-> Distance and Direction. Then ensure that the line type is geodesic, and that the distance/length is what you need.

*Use a Buffer Tool, I like the Pairwise Buffer to dissolve features into one polygon, and then Merge the polygon(s) into your wanted layer.

*Edit the polygon(s) as needed.


text:
Q: How to make a method for image scaling using the closest neighbor system the method starts with and its supposed to return an array of size [img[0].length*factor_h]*[img.length*factor_w]
public static int[][] scaleup(double factor_j,double factor_w,int [][]img)}//the method
    int[][] answer= new int[img.length][img[0].length];
    for (int i = 0; i < img.length; i++) {
        for (int j = 0; j < img[0].length; j++) {
            for (int f_w = 0; f_w<=img[0].length; f_w++) {//f_w is smaller than the factor_w
                for (int f_h = 0; f_h <= img.length; f_h++) {
                    answer[(int) (i * factor_h) + f_h][(int) (j * factor_w) + f_w] = img[j][i];
                }
            }
        }
    }
    return answer;
    }
}

im having trouble making this method to work but it goes out of bounds

A: your problem lies in this line:
int[][] answer= new int[img.length][img[0].length];

there you say your answer has the same size as your old img (let us assume 64x64 as an example). So you have now an array 64x64. So the last field/pixel is answer[63][63].
In this line of code:
answer[(int) (i * factor_h) + f_h][(int) (j * factor_w) + f_w] = img[j][i];

you say the first index is i * factor_h + f_h.
your variable i goes from 0 to 63 and your f_h goes from 0 to 64.
I don't think you can choose a factor_h that you won't get an out of bound error at all. So yeah initialize your answer array in the right way otherwise it won't work.
The same for the 2nd index as well with j and factor_w / f_w.

A: public static int[][] scaleup(double factor_h, double factor_w, int[][] im) {

    int[][] answer = new int[(int) (im.length * factor_h) + 1][(int) (im[0].length * factor_w) + 1];
    for (int i = 0; i < im.length; i++) {
        for (int j = 0; j < im[0].length; j++) {
            for (int f_w = 0; f_w < factor_h; f_w++) {
                for (int f_h = 0; f_h < factor_w; f_h++) {
                    answer[(int) (i * factor_h + f_w)][(int) (j * factor_w + f_h)] = im[i][j];
                }
            }
        }
    }
    return answer;
}


text:
Q: How to make "sticky" pages (and query by them) I have query_posts() with page_type set as 'page'. Is there any way I can make certain pages appear higher and thus, make them sticky?

A: It doesn't appear that there is any obvious way to enable "sticky post" support for Pages, e.g. via add_post_type_support().
However, Pages support both hierarchy and menu order. I would recommend using menu order to output Pages in your preferred order.

A: Convert Page to Post type.
Warning: May not preserve Custom Fields and Revision History, depending on which WP Converter plugin you use. To be careful, copy manually or with a WP Clone plugin the page before conversion, and Export your database for if you need to go back.


text:
Q: Delegates and Events with multiple classes This has taken me quite a few days to develop a demo of communicating between classes with delegates and events.  I would like to know if this is the best practices way of accomplishing this passing of data between classes or not. If there is a better method please let me know. Specifically, if something happens in a subclass how do you get it back to the main class.  This would be particularly useful when doing n-tier architecture by separating out the User Interface from the Business Logic Level, and the Data Access Level.
I have a form that has 3 text boxes: tb1, tb2, and tbAnswer.
I also have a button that says "Add" and it is just button1.
The main form is:
namespace DelegateTest
{
    public delegate void ShowMessage(object sender, Form1.AnswerEventArgs e);

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void a_OnShowMessage(object sender, AnswerEventArgs e)
        {
            tbAnswer.Text = e.answer;
        }

        public class AnswerEventArgs :EventArgs
        {
            public string answer { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddClass a = new AddClass();
            a.OnShowMessage += new ShowMessage(a_OnShowMessage);
            a.AddMe(Convert.ToInt16(tb1.Text), Convert.ToInt16(tb2.Text));
        }
    }
}

and the subform called AddClass.cs is:
namespace DelegateTest
{
    class AddClass
    {
        public event ShowMessage OnShowMessage;
        public void AddMe(int a, int b)
        {
            Form1.AnswerEventArgs e = new Form1.AnswerEventArgs();
            e.answer = (a+b).ToString();
            OnShowMessage(this, e);
        }
    }
}

A: Your approach is sound except for two details.
First, a NullPointerException will occur if your event is raised before any handlers are added.  You can get around this in one of two ways.
1) Make a local copy (to avoid race condition) and check it for null:
var showMessage = OnShowMessage;
if (showMessage != null)
{
    showMessage(this, e);
}

2) Initialize your event to an empty delegate:
public event ShowMessage OnShowMessage = delegate { };

Second, you do not need to declare your own delegate in this case.  You can simply create a standard EventHandler with your own event args:
public event EventHandler<Form1.AnswerEventArgs> OnShowMessage = delegate { };

See How to: Publish Events that Conform to .NET Framework Guidelines for more information.


text:
Q: Angular6 Synchronously Load Route Data Okay, I recently implemented SSR into my Angular6 application, with the intention of rendering dynamic HTML in a crawlable manner. All seems to be working fine, but my issue is rendering data from an API endpoint.
As soon as a user arrives on my site, a list of top posts that have been retrieved from a Node server will be displayed. In order to retrieve the data before page load, I implemented a resolver for my posts service. The resolver will resolve an Observable, which will then be accessed by my component.
resolver.service.ts :
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { PostService } from '../services/post.service';
import { of } from 'rxjs';

@Injectable()
export class ResolverService implements Resolve<any> {
  constructor(private postService: PostService) { }

  resolve (){
    return of(this.postService.getPosts());
  }
}

This Observable will be correctly resolved and can be accessed in my component like so,
content.component.ts :
  ...
  posts: any;

  constructor(private route:ActivatedRoute){}

  ngOnInit() {
    this.route.snapshot.data['posts'].subscribe(
      data =>{
        this.posts = JSON.parse(JSON.stringify(data));
      }
    );
  }
  ...

Then the posts variable will be rendered in the html. The problem is, when using a subscription, my data is not rendered in the source because subscriptions work asynchronously. I need the data to be extracted before page load.
If anyone can point me in the correct direction, it would be much appreciated. Thanks.

A:
Add ngIf Condition in HTML may solve your problem.

Example :

Title : {{posts.title}}

Refrence Link : here

check the file contacts-detail.component.ts in a provided demo for more understanding.

A: Found the solution. I was previously using the HttpClient module to handle api calls, it turns out that I needed to use the Http module with the following approach I discovered thanks to @IftekharDani 's example.
resolver.service.ts:
import { Http } from '@angular/http';

...

getPosts(): Observable<any> {
    return this.http.get("<your site>/api/posts/all", { })
    .pipe(
      map(
      res => {
        return res.json();
      },
      err => {
        return err;
      }
      )
    );
  }

  resolve (route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.getPosts();
  }

content.component.ts:
...
ngOnInit() {
    this.posts = this.route.snapshot.data['posts'];
}
...

app-routing.module.ts
import { ResolverService } from './services/resolver.service';

const routes: Routes = [
  ...
  { path: '**', component: ContentComponent, resolve: { posts: ResolverService}}
];


text:
Q: C language modulus not showing right answer when tested against large number This program
long a = 20202020200;
b = (a / 100) % 10;

printf("%d", b);

prints "5" instead of printing "2". Why is that?

A: If you look at the Binary 20202020200  = 0100_1011_0100_0010_0010_0101_1101_0110_1000
Which is 36 bit.
So if you have a 32-bit system you will have 1011_0100_0010_0010_0101_1101_0110_1000 or 0100_1011_0100_0010_0010_0101_1101_0110.
In your case, it is the second one that represents 315656565 /100 = 3156565 % 10 = 5


text:
Q: Gson.toJsonTree(intValue) throws Null pointer exception when trying to pass Integer parameter value We are automating rest APIs using Rest Assured. During this process, trying to have a re-usable method created to pass different JSON nodes with different values.
Interger variable created:
Integer amt = 50;

Method created:
public void replaceValues_gson(String mainNode, String childNode, Integer amt) {

        if(amt != null){
            jsonObjectNew.getAsJsonObject("mainNode").add("childNode", gson.toJsonTree(amt));
            }
//here 'amt' throws an error as java.lang.NullPointerException; Also the amt it shows as 9 assigned to variable amt in the debugger where as it supposed to assign 50 value

    }

Calling above method as:
replaceValues_gson("bInfo", "bEx", amt );

Request JSON payload for the above is:
{
 "bInfo":{
  "bEx":9,
  "oriDate":"2020-07-08"

}
}

Getting NullPointerException for 'amt' variable and Request JSON payload value is getting assigned rather assigning Integer amt value which is 50.
It works if directly trying like below:
jsonObjectNew.getAsJsonObject("bInfo").add("bEx", gson.toJsonTree(amt));

here amt variable value correctly goes as 50, but when trying to create re-usable method then throws an error.
Please guide.

A: You can use the following method. But it does not support when the value that need to be updated is inside a json array.
public void replaceValues_gson(JsonObject jsonObjectNew, String[] keyArray, Object updatingValue) {

    Gson gson = new Gson();

    JsonObject jsonObject = jsonObjectNew;

    for (int i = 0; i < keyArray.length - 1; i++) {
        jsonObject = jsonObject.getAsJsonObject(keyArray[i]);
    }

    jsonObject.add(keyArray[keyArray.length - 1], gson.toJsonTree(updatingValue));

    System.out.println(jsonObjectNew.toString());

}

Here;
jsonObjectNew - the JsonObject converted from initial json request.
keyArray - String array of json node names from the root (in the exact order) including the key that need to be updated
updatingValue - value that will be updated
Eg:-
String[] keyArray = {"bInfo", "bEx"};
replaceValues_gson(jsonObjectNew, keyArray, 50);


text:
Q: Хук состояния не изменяет состояние, React Есть страница создания новости, при отправке формы, на сервер приходит объект такого типа:
{
   title: 'текст примера',
   text: 'текст примера'
}

хотя он должен быть таким:
{
   title: 'текст примера',
   text: 'текст примера',
   posted: {
       fullDate: "9 сентября 2020 г., 21:56:36",
       timestamp: 1599681396,
       timeZone: 2,
       year: "2020",
       month: "9",
       day: "9",
       hour: "21",
       minutes: "56",
       seconds: "36"
   }
}

Что я делаю не так? Может я не правильно использую хуки состояния?
И ещё по приходу успешного ответа с сервера input[name="title"] почему-то не хочет отчищаться...
Страница создания новости:
import React, { useEffect, useState } from 'react';
import classes from './CreateNews.module.scss';
import classNames from 'classnames';
import { createPostedTime } from '../../functions';
import { createPost } from '../../posts';
import 'react-quill/dist/quill.snow.css';
import UserForm from '../../components/UI/UserForm/UserForm';
import GoBackToAdmin from '../../components/UI/GoBackToAdmin/GoBackToAdmin';

const CreateNews = () => {
    const [post, setPost] = useState({
        title: '',
        text: ''
    });

    const changeTitleHandler = (e) => {
        setPost({
            ...post,
            title: e.target.value
        });
    }

    const changeTextHandler = (e) => {
        setPost({
            ...post,
            text: e
        });
    }

    const submitHandler = async (e) => {
        e.preventDefault();

        setPost({
            ...post,
            posted: createPostedTime()
        });

        try {
            await createPost(post).then((res) => {
                setPost({
                    title: '',
                    text: ''
                });
            });
        } catch (e) {
            console.log(e);
        }
    }

    return (

            <GoBackToAdmin />
            <UserForm
                title={post.title}
                text={post.text}
                buttonText="Создать новость"
                changeTitle={changeTitleHandler}
                changeText={changeTextHandler}
                onSubmit={submitHandler}
            />

    )
}

export default CreateNews;

Код компонента UserForm:
import React from 'react';
import classes from './UserForm.module.scss';
import classNames from 'classnames';
import Input from '../Input/Input';
import ReactQuill from 'react-quill';

const modules = {
    toolbar: [
        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
        ['blockquote', 'code-block'],

        [{ 'header': 1 }, { 'header': 2 }],               // custom button values
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
        [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
        [{ 'direction': 'rtl' }],                         // text direction

        [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

        [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
        [{ 'font': [] }],
        [{ 'align': [] }],

        ['image', 'video'],

        ['clean']                                         // remove formatting button
    ]
};

const UserForm = ({title, text, buttonText, changeTitle, changeText, onSubmit}) => {

    return (
        <form className={classNames(classes.UserForm)}>
            <Input
                className={classes.UserForm__Title}
                title="Название новости"
                placeholder="Введите название новости..."
                type="text"
                name="title"
                value={title}
                onChange={changeTitle}
            />

                    Контент новости

                <ReactQuill
                    id="text"
                    modules={modules}
                    theme="snow"
                    value={text}
                    onChange={changeText}
                />

            <button
                type="submit"
                className={classNames('btn', classes.UserForm__SubmitBtn)}
                onClick={onSubmit}
            >
                {buttonText}
            </button>
        </form>
    )
}

export default UserForm;

Функция createPostedTime():
export function createPostedTime() {
    const date = new Date();
    const timeZone = -date.getTimezoneOffset() / 60;
    const fullDate = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
    };
    const year = {
        year: 'numeric',
    }
    const month = {
        month: 'numeric',
    }
    const day = {
        day: 'numeric',
    }
    const hour = {
        hour: 'numeric',
    }
    const minutes = {
        minute: 'numeric',
    }
    const seconds = {
        second: 'numeric'
    }

    const posted = {};

    function timeSave(named, item) {
        posted[named] = date.toLocaleString("ru", item);
    }

    timeSave('fullDate', fullDate);
    timeSave('year', year);
    timeSave('month', month);
    timeSave('day', day);
    timeSave('hour', hour);
    timeSave('minutes', minutes);
    timeSave('seconds', seconds);
    posted.timestamp = Math.floor(Date.now() / 1000);
    posted.timeZone = timeZone;

    return posted;
}

A: setPost работает асинхронно, и createPost(post) получает старую версию (от последнего рендера).
Можно использовать const postToSend = {...post, .

Или можно делать пост из useEffect, но тут важно не зациклить.
И вообще форма setPost(wasPost=>({...wasPost,title})) безопаснее.