text:
Q: Can I access Windows Kernel system calls directly? I have been doing research into Windows internals, and have just recently learned about system calls and I am wondering if it is possible to use these system calls like functions? I understand they aren't really meant to be accessed externally.
For instance: NtUserEmptyClipboard is a system call in Win32k.sys, and it's address is 0x117f
If I wanted to use this call like a function, how could I do so?

A: EmptyClipboard is one of so-called "Win32 API" and NtUserEmptyClipboard is a corresponding "native API".

*

*http://en.wikipedia.org/wiki/Native_API
Unlike Linux syscall(2), we are rarely supposed to directly call "native API".  I heard they are in ntdll.dll rather than win32k.sys.  But we should be able to invoke them just like normal functions defined in a normal DLL.

*

*Is there any way to call the Windows Native API functions from the user mode?

A: What you want to do depends heavily on the architecture you're interested, but the thing to know is, that ntdll.dll is the user-mode trampoline for every syscall - i.e. the only one who actually makes syscalls at the end of the day is ntdll.
So, let's disassemble one of these methods in WinDbg, by opening up any old exe (I picked notepad). First, use x ntdll!* to find the symbols exported by ntdll:
0:000> x ntdll!*
00007ff9`ed1aec20 ntdll!RtlpMuiRegCreateLanguageList (void)
00007ff9`ed1cf194 ntdll!EtwDeliverDataBlock (void)
00007ff9`ed20fed0 ntdll!shortsort_s (void)
00007ff9`ed22abbf ntdll!RtlUnicodeStringToOemString$fin$0 (void)
00007ff9`ed1e9af0 ntdll!LdrpAllocateDataTableEntry (void)
...

So, let's pick one at random, NtReadFile looks neato. Let's disassemble it:
0:000> uf ntdll!NtReadFile

ntdll!NtReadFile:
00007ff9`ed21abe0 4c8bd1          mov     r10,rcx
00007ff9`ed21abe3 b805000000      mov     eax,5
00007ff9`ed21abe8 0f05            syscall
00007ff9`ed21abea c3              ret

Here, we see that we stuff away rcx, put the syscall number into eax, then call the syscall instruction. Every syscall has a number that is assigned arbitrarily by Windows (i.e. this number is a secret handshake between ntdll and the kernel, and changes whenever Microsoft wants)
None of these instructions are "magic", you could execute them in your app directly too (but there's no practical reason to do so, of course - just for funsies)

A: I strongly doubt that 0x117f is the address you're looking for. I suspect it might be the value which you need to pass to GetProcAddress. But I don't know for sure, since those things vary across Windows versions (that's why ordinary people use documented functions instead)

A: The main part of the native API is exported via normal functions from ntdll.dll. You can load this dll into your process and call these functions just like any other API functions. As long as you have the right function prototypes and parameters, the calls will work just fine. What they do internally is transition from usermode to kernelmode and then they use an offset into the system service descriptor table (SSDT) to find the address of the function in kernel mode memory, and then the function is called. There is an open source project http://nativetest.codeplex.com/ that makes calls to the native api that you might refer to.
The functions in win32k.sys are not exposed in ntdll.dll. As far as I can tell they are not exposed anywhere. The address you have listed - I believe - is actually an offset into the SSDT. If you really needed to call this function, you would have to make the transition from usermode to kernelmode yourself, putting all the parameters for the function and the SSDT offset into the right places.
As others have recommended, I would suggest to find the usermode API to help accomplish what you want to do. FWIW, in user32.dll the function EmptyClipboard appears to forward directly to NtUserEmptyClipboard, according to the link /dump output.
1731   DF 0002018A EmptyClipboard = _NtUserEmptyClipboard@0


text:
Q: charter font with mathastext and upright txgreeks I would like charter font with upright math, both on greek and latin symbols.  are txgreek upright and mathdesign-charter mutually incompatible?  or is mathdesign's functionality voided by upright txgreeks?
\documentclass[12pt]{article}

\usepackage{lmodern}
\usepackage{charter} %% the main font, scaleable
%% not compatible?: \usepackage[charter]{mathdesign}
\usepackage{mathastext}
\usepackage[upright]{txgreeks}

\begin{document}

P G and L: $ P(G,L) = G\cdot\frac{1-\beta^L}{\beta^G - \beta^L} $

\end{document}

advice, as always, appreciated.

A: You don't have to load all these packages: the relevant options already exist in mathdesign:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[charter, lowercase = upright, uppercase = upright, greeklowercase = upright]{mathdesign}

\begin{document}

P G and L: $ P(G,L) = G\cdot\frac{1-\beta^L}{\beta^G - \beta^L n} $

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: POI Copy Images do not resize I am working with the POI API to copy many Excel Workbooks into 1 large Excel Workbook. For one of my requirements there are images that are placed and sized specifically in the document. I am using the combination of the below code to transfer all of the images necessary. They will only be pictures and ALL of the pictures are found.
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; // only important class you need to know about.

private static void transferShape (XSSFSheet sheet, XSSFSheet newSheet) {
    XSSFDrawing drawing = sheet.createDrawingPatriarch();

    for(XSSFShape shape : drawing.getShapes()) {
        if(shape instanceof XSSFPicture) {
            XSSFPicture picture = (XSSFPicture) shape;
            transferPicture(picture, newSheet);
        }
    }
}

private static void transferPicture(XSSFPicture picture, XSSFSheet newSheet) {
    XSSFPictureData xssfPictureData = picture.getPictureData();
    XSSFClientAnchor anchor = picture.getPreferredSize();

    int col1 = anchor.getCol1();
    int col2 = anchor.getCol2();
    int row1 = anchor.getRow1();
    int row2 = anchor.getRow2();

    int x1 = anchor.getDx1();
    int x2 = anchor.getDx2();
    int y1 = anchor.getDy1();
    int y2 = anchor.getDy2();

    XSSFWorkbook newWb = newSheet.getWorkbook();
    XSSFCreationHelper newHelper = newWb.getCreationHelper();
    XSSFDrawing newDrawing = newSheet.createDrawingPatriarch();
    XSSFClientAnchor newAnchor = newHelper.createClientAnchor();

    newAnchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

    // Row / Column placement.
    newAnchor.setCol1(col1);
    newAnchor.setCol2(col2);
    newAnchor.setRow1(row1);
    newAnchor.setRow2(row2);

    // Fine touch adjustment along the XY coordinate.
    newAnchor.setDx1(x1);
    newAnchor.setDx2(x2);
    newAnchor.setDy1(y1);
    newAnchor.setDy2(y2);

    double imageX = 0;
    double imageY = 0;

    if(anchor.getSize() != null) {
        newAnchor.setSize(anchor.getSize());
    } else {
        int width = 0;
        int height = 0;

        for(int col = col1; col <= col2; col++) {
            width += Math.round(Units.columnWidthToEMU(newSheet.getColumnWidth(col)));
        }

        width -= x1 - x2;

        for(int row = row1; row <= row2; row++) {
            height += Math.round(Units.TwipsToEMU(newSheet.getRow(row).getHeight()));
        }

        height -= y1 - y2;

        CTPositiveSize2D ps2D = CTPositiveSize2D.Factory.newInstance();

        ps2D.setCx((long) 0);
        ps2D.setCy((long) 0);

        newAnchor.setSize(ps2D);
    }

    int newPictureIndex = newWb.addPicture(xssfPictureData.getData(), xssfPictureData.getPictureType());

    XSSFPicture newPicture = newDrawing.createPicture(newAnchor, newPictureIndex);
    newPicture.resize();
}

However, the main issue is that the images are not sizing correctly any more. Something happened that broke that functionality. I had to add the following else to work on a new solution.
else {
    int width = 0;
    int height = 0;

    for(int col = col1; col <= col2; col++) {
        width += Math.round(Units.columnWidthToEMU(newSheet.getColumnWidth(col)));
    }

    width -= x1 - x2;

    for(int row = row1; row <= row2; row++) {
        height += Math.round(Units.TwipsToEMU(newSheet.getRow(row).getHeight()));
    }

    height -= y1 - y2;

    CTPositiveSize2D ps2D = CTPositiveSize2D.Factory.newInstance();

    ps2D.setCx((long) 0);
    ps2D.setCy((long) 0);

    newAnchor.setSize(ps2D);
}

Yet... even setting Cx and Cy to 0 nothing is being resized still. I am unsure what is going on.
newAnchor.setSize(anchor.getSize()) used to work all by itself. Not sure what changed for it to return null.

A: This was a case of too much code from the API! Basically the size of the image is defined by its location and distance pushed by the dx and dy variables.
The below functions are the final product and works very well.
private static void transferShape (XSSFSheet sheet, XSSFSheet newSheet) {
    XSSFDrawing drawing = sheet.createDrawingPatriarch();

    for(XSSFShape shape : drawing.getShapes()) {
        if(shape instanceof XSSFPicture) {
            transferPicture(shape, newSheet);
        }
    }
}

private static void transferPicture(XSSFShape shape, XSSFSheet newSheet) {
    XSSFPicture picture = (XSSFPicture) shape;

    XSSFPictureData xssfPictureData = picture.getPictureData();
    XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();

    int col1 = anchor.getCol1();
    int col2 = anchor.getCol2();
    int row1 = anchor.getRow1();
    int row2 = anchor.getRow2();

    int x1 = anchor.getDx1();
    int x2 = anchor.getDx2();
    int y1 = anchor.getDy1();
    int y2 = anchor.getDy2();

    XSSFWorkbook newWb = newSheet.getWorkbook();
    XSSFCreationHelper newHelper = newWb.getCreationHelper();
    XSSFDrawing newDrawing = newSheet.createDrawingPatriarch();
    XSSFClientAnchor newAnchor = newHelper.createClientAnchor();

    // Row / Column placement.
    newAnchor.setCol1(col1);
    newAnchor.setCol2(col2);
    newAnchor.setRow1(row1);
    newAnchor.setRow2(row2);

    // Fine touch adjustment along the XY coordinate.
    newAnchor.setDx1(x1);
    newAnchor.setDx2(x2);
    newAnchor.setDy1(y1);
    newAnchor.setDy2(y2);

    int newPictureIndex = newWb.addPicture(xssfPictureData.getData(), xssfPictureData.getPictureType());

    XSSFPicture newPicture = newDrawing.createPicture(newAnchor, newPictureIndex);
}

Hoping this helps someone. This was a really weird problem that I haven't yet found.


text:
Q: Updating dimensions of a rotated view I have several Switch views in my app that have been rotated 270 degrees. The dimensions of the switch are, however, still laid out based on the original orientation (as expected in Android layouts):

How can I flip the width and height of the switch? I've not been able to find a way in the layout XML, and attempts to do so programmatically in the containing fragment have failed, as the returned width and height (even in onCreateView() and onViewCreated()) is always 0. I am aware that getting a 0 width and height is usually caused by querying too early, but, if a programmatic approach is needed to solve this problem, where should I actually execute the code to flip the dimensions?

A: Try to requestLayout() on your switches or swap the width and height in layoutParams of switches.


text:
Q: Managing commit rights in svn by delegating to project managers We have multiple projects in svn repo.And for each project there are many users.As number of users is large so its troublesome to manage their commit rights using "Auth file".
I have read somewhere that we can delegate user's rights to their managers by creating a text file.But i am not sure how to achieve this and perhaps hOOKS need to be configured for this .As i am new to SVN so need your expert advice.Please guide me how to achieve this and if you have hook already confgiured p,kindly provide.
How to setup access control in SVN?
I have seen this link and answer by VonC is great and perfect for me.But i dont know how to start .. can anybody help me out here as i am not pro in svn and unix .
Thanks in advance

A: Preface

*

*Using single repository for multiple projects is Bad Idea (tm): one repo - one project

*Forget immediately about old as mammoth's shit SVN 1.5 - use at least 1.6 on client and server (1.8 may be best choice)

Face
Simplified user-management for SVN-users can be reached using LDAP-based authentication instead of ordinary file (in case of "repository per project" <location> from answer will be location of each repo with SVNPath, in case of old structure <location> must be linked to every root of project) and having different groups for different repositories in Require ldap-group directive - read also Apache 2.2 docs in Apache Module mod_authnz_ldap part. From management POV, LDAP-auth and permissions means: each developer must be in LDAP-tree, included in one or more related to repositories groups
In case of additional requirement for Path-Based Authorization within repositories and using groups inside authz-file, you may find useful LDAP Groups to Subversion Authz Groups Bridge, which allow you to regenerate authz-groups from LDAP-data
As result, most (if not all) SVN-related ACLs can be managed in LDAP-side only


text:
Q: Web UI for Raspberry Pi with PHP script to send data over serial pins I am currently building a project using a Raspberry Pi 3. I am using Apache as a web server to host a php website. A few of the pages need to send a command to the serial port of the pi. When ssh into the pi and use minicom (to test my functions) all commands work perfectly. When I put those commands in my web page php script I get garbage (some of the data comes along with additional characters). An example a command is "m123456". Below is a sample of my php script, I used the sleep function to mimic the time between keystrokes when I ssh and use minicom to type the command. Could someone help please.
<?php
echo system("echo 'm' > /dev/ttyAMA0");
sleep(2);
echo system("echo '1' > /dev/ttyAMA0");
sleep(2);
echo system("echo '2' > /dev/ttyAMA0");
sleep(2);
echo system("echo '3' > /dev/ttyAMA0");
sleep(2);
echo system("echo '4' > /dev/ttyAMA0");
sleep(2);
echo system("echo '5' > /dev/ttyAMA0");
sleep(2);
echo system("echo '6' > /dev/ttyAMA0");
?>


text:
Q: what is the L1 cache throughput in Nvidia's Kepler? I would like to know the throughout, latency, and the number of banks in Kepler's L1 cache (read only 'texture' and normal cache).
in a CUDA program, I'm reading the same data multiple times by different threads, I need to know if i'm bound by the L1 throughput, I couldn't find this information in any of Nvidia's documents, any help would be appreciated.
Edit: I'm using the K20 card.

A: I myself don't know the number of banks in Kepler.
But I think you don't need to care about L1 cache. As below,
L1 caching in Kepler GPUs is reserved only for local memory accesses, such as register spills and stack data. Global loads are cached in L2 only (or in the Read-Only Data Cache)
http://docs.nvidia.com/cuda/kepler-tuning-guide/


text:
Q: How can I load input data from a file in Terraform? I defined a aws_cloudwatch_event_target in terraform to fire an event to lambda from cloudwatch. The input field is the event parameter for example:
resource "aws_cloudwatch_event_target" "data" {
  rule      = "${aws_cloudwatch_event_rule.scheduler.name}"
  target_id = "finance_producer_cloudwatch"
  arn       = "${aws_lambda_function.finance_data_producer.arn}"
  input     = "{\"test\": [\"111\"]}"
}

I wonder how I can load the input json data from an external file.

A: You can use the file() operator to pull data from an external file:
input = "${file("myjson.json")}"

Just make sure myjson.json exists on disk in the same directory as the rest of your Terraform files.

A: I would use the data template_file resource. Like so...
data "template_file" "my_file" {
  template = "${file("${path.module}/my_file.json")}"
  vars = {
    var_to_use_in_file = "${var.my_value}"
  }
}

Then in your resource block....
resource "aws_cloudwatch_event_target" "data" {
  rule      = "${aws_cloudwatch_event_rule.scheduler.name}"
  target_id = "finance_producer_cloudwatch"
  arn       = "${aws_lambda_function.finance_data_producer.arn}"
  input     = "${data.template_file.my_file.rendered}"
}

A: The answer here depends on a few different questions:

*

*Is this file a static part of your configuration, checked in to version control alongside your .tf files, or is it dynamically generated as part of the apply process?

*Do you want to use the file contents literally, or do you need to substitute values into it from elsewhere in the Terraform configuration?

These two questions form a matrix of four different answers:
             |  Literal Content            Include Values from Elsewhere
-------------|----------------------------------------------------------
Static File  |  file(...) function         templatefile(...) function
Dynamic File |  local_file data source     template_file data source

I'll describe each of these four options in more detail below.
A common theme in all of these examples will be references to path.module, which evaluates to the path where the current module is loaded from. Another way to think about that is that it is the directory containing the current .tf file. Accessing files in other directories is allowed, but in most cases it's appropriate to keep things self-contained in your module by keeping the data files and the configuration files together.
Terraform strings are sequences of unicode characters, so Terraform can only read files containing valid UTF-8 encoded text. For JSON that's no problem, but worth keeping in mind for other file formats that might not conventionally be UTF-8 encoded.
The file function
The file function reads the literal content of a file from disk as part of the initial evaluation of the configuration. The content of the file is treated as if it were a literal string value for validation purposes, and so the file must exist on disk (and usually, in your version control) as a static part of your configuration, as opposed to being generated dynamically during terraform apply.
resource "aws_cloudwatch_event_target" "data" {
  rule      = aws_cloudwatch_event_rule.scheduler.name
  target_id = "finance_producer_cloudwatch"
  arn       = aws_lambda_function.finance_data_producer.arn
  input     = file("${path.module}/input.json")
}

This is the most common and simplest option. If the file function is sufficient for your needs then it's the best option to use as a default choice.
The templatefile function
The templatefile function is similar to the file function, but rather than just returning the file contents literally it instead parses the file contents as a string template and then evaluates it using a set of local variables given in its second argument. This is useful if you need to pass some data from elsewhere in the Terraform configuration, as in this example:
resource "aws_cloudwatch_event_target" "data" {
  rule      = aws_cloudwatch_event_rule.scheduler.name
  target_id = "finance_producer_cloudwatch"
  arn       = aws_lambda_function.finance_data_producer.arn
  input     = templatefile("${path.module}/input.json.tmpl", {
    instance_id = aws_instance.example.id
  })
}

In input.json.tmpl you can use the Terraform template syntax to substitute that variable value:
{"instance_id":${jsonencode(instance_id)}}

In cases like this where the whole result is JSON, I'd suggest just generating the whole result using jsonencode, since then you can let Terraform worry about the JSON escaping etc and just write the data structure in Terraform's object syntax:
${jsonencode({
  instance_id = instance_id
})}

As with file, because templatefile is a function it gets evaluated during initial decoding of the configuration and its result is validated as a literal value. The template file must therefore also be a static file that is distributed as part of the configuration, rather than a dynamically-generated file.
The local_file data source
Data sources are special resource types that read an existing object or compute a result, rather than creating and managing a new object. Because they are resources, they can participate in the dependency graph and can thus make use of objects (including local files) that are created by other resources in the same Terraform configuration during terraform apply.
The local_file data source belongs to the local provider and is essentially the data source equivalent of the file function.
In the following example, I'm using var.input_file as a placeholder for any reference to a file path that is created by some other resource in the same configuration. In a real example, that is most likely to be a direct reference to an attribute of a resource.
data "local_file" "input" {
  filename = var.input_file
}

resource "aws_cloudwatch_event_target" "data" {
  rule      = aws_cloudwatch_event_rule.scheduler.name
  target_id = "finance_producer_cloudwatch"
  arn       = aws_lambda_function.finance_data_producer.arn
  input     = data.local_file.input.content
}

The template_file data source

NOTE: Since I originally wrote this answer, the provider where template_file was implemented has been declared obsolete and no longer maintained, and there is no replacement. In particular, the provider was archived prior to the release of Apple Silicon and so there is no available port for macOS on that architecture.
The Terraform team does not recommend rendering of dynamically-loaded templates, because it pushes various errors that could normally be detected at plan time to be detected only during apply time instead.
I've retained this content as I originally wrote it in case it's useful, but I would suggest treating this option as a last resort.

The template_file data source is the data source equivalent of the templatefile function. It's similar in usage to local_file though in this case we populate the template itself by reading it as a static file, using either the file function or local_file as described above depending on whether the template is in a static file or a dynamically-generated one, though if it were a static file we'd prefer to use the templatefile function and so we'll use the local_file data source here:
data "local_file" "input_template" {
  filename = var.input_template_file
}

data "template_file" "input" {
  template = data.local_file.input_template.content
  vars = {
    instance_id = aws_instance.example.id
  }
}

resource "aws_cloudwatch_event_target" "data" {
  rule      = aws_cloudwatch_event_rule.scheduler.name
  target_id = "finance_producer_cloudwatch"
  arn       = aws_lambda_function.finance_data_producer.arn
  input     = data.template_file.input.rendered
}

The templatefile function was added in Terraform 0.12.0, so you may see examples elsewhere of using the template_file data source to render static template files. That is an old pattern, now deprecated in Terraform 0.12, because the templatefile function makes for a more direct and readable configuration in most cases.
One quirk of the template_file data source as opposed to the templatefile function is that the data source belongs to the template provider rather than to Terraform Core, and so which template features are available in it will depend on which version of the provider is installed rather than which version of Terraform CLI is installed. The template provider is likely to lag behind Terraform Core in terms of which template language features are available, which is another reason to prefer the templatefile function where possible.
Other Possibilities
This question was specifically about reading data from a file, but for completeness I also want to note that for small JSON payloads it can sometimes be preferable to inline them directly in the configuration as a Terraform data structure and convert to JSON using jsonencode, like this:
resource "aws_cloudwatch_event_target" "data" {
  rule      = aws_cloudwatch_event_rule.scheduler.name
  target_id = "finance_producer_cloudwatch"
  arn       = aws_lambda_function.finance_data_producer.arn
  input     = jsonencode({
    instance_id = aws_instance.example.id
  })
}

Writing the data structure inline as a Terraform expression means that a future reader can see directly what will be sent without needing to refer to a separate file. However, if the data structure is very large and complicated then it can hurt overall readability to include it inline because it could overwhelm the other configuration in the same file.
Which option to choose will therefore depend a lot on the specific circumstances, but always worth considering whether the indirection of a separate file is the best choice for readability.
Terraform also has a yamlencode function (experimental at the time of writing) which can do similarly for YAML-formatted data structures, either directly inside a .tf file or in an interpolation sequence in an external template.


text:
Q: Why isn't this a type mismatch? I answered this question, apparently to OP's satisfaction, but still find their question puzzling. Their question involved an expression in which a workbook object was being concatenated with a string, triggering Run-time Error '438': Object doesn't support this property or method. You can reproduce this sort of error by simply typing
?"Hello, " & ThisWorkbook

In the Immediate Window.
My question is -- why does this raise that error, instead of a error 13 -- type mismatch? A reasonable guess is that VBA tries to find a default property for a workbook object and that a default property doesn't exist. But, if so, I would expect it to be the following error from Microsoft's list of Visual Basic 6.0 error codes: Automation object doesn't have a default value (Error 443).
It is mostly of academic interest, but if the result of concatenating an object without a default property with a string is always Error 438, and that is the only way of triggering Error 438 rather than possibly another error when concatenating a string with an object, then the following code might be of use:
Function HasDefault(O As Variant) As Boolean
    Dim i As Long
    If Not IsObject(O) Then Exit Function
    On Error Resume Next
    i = Len("Hello, " & O)
    If Err.Number = 438 Then
        HasDefault = False
    Else
        HasDefault = True
    End If
End Function

I've tested this on a variety of objects, and for those I've tested it on it has returned False exactly when _Default doesn't show up as a (hidden) member of the object when viewed in the Object Browser. Nevertheless, I don't quite trust this function and am still puzzled by what is going on here.

A: VBA will try and convert the expressions on each side of the & operator to a data value. The language spec states that:

*

*If the value type of the expression's target variable is a class:

*If the declared type of the target is Variant, runtime error 9
(Subscript out of range) is raised.

*If the declared type of the target is not Variant, and the target has
a public default Property Get or function, the data value's value is
the result of invoking this default member for that target with this
argument list. This consumes the argument list.

*Otherwise, runtime error 438 (Object doesn't support this property or
method) is raised.

As regards your function, I'd just use:
callbyname(O, "_Default", VbGet)

which will raise a 438 error as appropriate.


text: Q: Node app can not access local json file json file containing data and index.html in the Node app are in the same top directory. Using d3 js i am calling the json file to load data for visualization. But i am getting  http error 404 while loading the node app. Any suggestions?


text:
Q: Migrating to Vite from Vue CLI (Vue 3): Uncaught (in promise) TypeError: Cannot destructure property 'default' of 'undefined' as it is undefined I was migrating my Vue 3 project from Vue CLI to Vite and upon testing, I kept getting this error:

Uncaught (in promise) TypeError: Cannot destructure property 'default' of 'undefined' as it is undefined.

My .vue file that is having the problem looks like this:
<template>

Projects

    <ProjectList/>
</template>


text:
Q: VBA Rename File saving wrong Filetype This script should go into a folder full of excel files, rename the files by the author name & a count, and save them to a new folder.
However, this now saves the file not as an excel document, but the filetype is also the name of the author and the count.
I have edited the code from the suggested comments but now I receive this error:
Runtime Error
Did I edit the code wrong?
    Sub RenameExcelFilesbyAuthor()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim Counter As Integer

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.CalculateBeforeSave = False
Application.AskToUpdateLinks = False
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
.Title = "C:\Users\Name\Documents\Excel Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
 myPath = myPath
 If myPath = "" Then GoTo ResetSettings

 'Target File Extension (must include wildcard "*")
 myExtension = "*.xlsx*"

 'Target Path with Ending Extention
 myFile = Dir(myPath & myExtension)

 Counter = 1

 'Loop through each Excel file in folder
 Do While myFile <> ""
  'ReadOnly = False
    Set wb = Nothing
    On Error Resume Next
    'Set variable equal to opened workbook
     Set wb = Workbooks.Open(Filename:=myPath & myFile)
    On Error GoTo 0
    If wb Is Nothing Then
        On Error Resume Next
        wb.Close
    Else
    Counter = Counter + 1
    'Ensure Workbook has opened before moving on to next line of code
     DoEvents

   'Change First Worksheet's Background Fill Blue
   ThisWorkbook.BuiltinDocumentProperties("Author") = Author
     wb.SaveAs Filename:="C:\Users\max\Documents\New folder\" & wb.BuiltinDocumentProperties("Author") & Counter & myExtension, FileFormat:=xlWorkbookDefault

   'Save and Close Workbook
     wb.Close SaveChanges:=True

   'Ensure Workbook has closed before moving on to next line of code
     DoEvents
    End If

   'Get next file name
     myFile = Dir

 Loop

 'Message Box when tasks are completed
 MsgBox "Task Complete!"

ResetSettings:
 'Reset Macro Optimization Settings
   Application.EnableEvents = True
   Application.Calculation = xlCalculationAutomatic
   Application.ScreenUpdating = True
   Application.DisplayAlerts = True
End Sub

  [1]: https://i.stack.imgur.com/XVPT1.png


text: Q: Git config synced without permission between Macs I have two Macs, one used by me and one by someone else, sharing the same Apple ID, but with different git configurations and OS versions. After using "Screen Share" for a quick code review, the code was pushed, but under the other Mac's git config. Checking global configurations revealed the git config changed to the ones on the other Mac. I can't understand how this happened. There were no command executions or file configurations and the pair session ended before the push was done. Is this an Apple auto sync thing? Any settings I can check to prevent such things?


text:
Q: Proving that a sequence converges This is what I've tried:
(a) Using mathematical induction, I can show that $b_{i+1}$ is smaller than $b_i$.
Therefore, $b_i$ is monotonically decreasing.
Then, I thought it's kind of obvious that $b_i$ is bounded because $\{a_i\}$ is a bounded sequence in $\mathbb{R}$.
Is this correct?
(b) Since $b_i$ converges, I can say $\lim _{i\to \infty} b_i  = p$ for some $p \in\mathbb{R}$. And this $p$ will equal to $\sup a_k$ when $k$ is large enough.
Hence, by definition, (b) is proven. Is this correct?
Thank you so much!

*I added the definition of lim sup below.

+Theorem 3.17

A: (a) You are right, you can formalise your second sentence by applying the monotone convergence theorem.
(b) As you point out, this follows just from the definition of the limit superior and of $\{b_n\}$,
$$\limsup_{n\rightarrow\infty}a_n:=\lim_{n\rightarrow\infty}\left(\sup_{m\geq n}a_m\right)=\lim_{n\rightarrow\infty} b_n.$$
EDIT 2: In what follows I am assuming that $(*)$ is finite. However, if $(*)=+\infty$ then one can re-do the proof by following the same steps.
EDIT: We can show that both definitions are equivalent, that is
$$\lim_{n\rightarrow\infty}\left(\sup_{m\geq n}a_m\right)=\sup\{x:\exists\{a_{n_k}\}\subseteq\{a_n\},a_{n_k}\rightarrow x\text{ as }k\rightarrow\infty\},\quad\quad (*)$$
simply by using the triangle inequality and the definitions of the supremum of a set and the limit of a sequence. We do this in two steps:

By the definition of the supremum, we have that
$$\sup\{x:\exists\{a_{n_k}\}\subseteq\{a_n\},a_{n_k}\rightarrow x\text{ as }k\rightarrow\infty\}=p$$
implies that for every $\varepsilon>0$ there exists a subsequence $\{a_{n_k}\}$ of $\{a_n\}$ such that
$$\left|\lim_{k\rightarrow\infty}a_{n_k}-p\right|\leq \varepsilon.$$
By the definition of limit, we have that there exists a $K$ such that
$$\left|a_{n_k}-\lim_{k\rightarrow\infty}a_{n_k}\right|\leq \varepsilon,$$
for all $k\geq K$. In particular, we have that for every $n\geq0$ we can find an $N$ (just pick any in $\{n_k\geq n:k\geq K\}$) such that
$$\left|a_{N}-p\right|= \left|a_{N}-\lim_{k\rightarrow\infty}a_{n_k}+\lim_{k\rightarrow\infty}a_{n_k}-p\right| =\left|a_{N}-\lim_{k\rightarrow\infty}a_{n_k}\right|+\left|\lim_{k\rightarrow\infty}a_{n_k}-p\right|\leq2\varepsilon$$
So, for any $n$, pick the corresponding $N$ as above, and we have that
$$\sup_{m\geq n}a_m\geq a_N\geq p-2\varepsilon.$$
Since the $\varepsilon$ was arbitrary we have that for any $n$, $\sup_{m\geq n}a_m\geq p$. Hence,
$$\lim_{n\rightarrow\infty}\left(\sup_{m\geq n}a_m\right)\geq p=\sup\{x:\exists\{a_{n_k}\}\subseteq\{a_n\},a_{n_k}\rightarrow x\text{ as }k\rightarrow\infty\}.$$

We can establish the other inequality in a very similar fashion. Let
$$\lim_{n\rightarrow\infty}\left(\sup_{m\geq n}a_m\right)=q.$$
Then, for each $k>0$ we can find an $m_k$ such that
$$\left|\sup_{m\geq m_k}a_m-q\right|\leq \frac{1}{2k}.$$
Similarly, we can find an $n_k\geq m_k$ such that
$$\left|a_{n_k}-\sup_{m\geq m_k}a_m\right|\leq\frac{1}{2k}.$$
So,
$$\left|a_{n_k}-q\right|\leq \left|a_{n_k}-\sup_{m\geq m_k}a_m+\sup_{m\geq m_k}a_m-q\right|\leq \left|a_{n_k}-\sup_{m\geq m_k}a_m\right|+\left|\sup_{m\geq m_k}a_m-q\right|\leq \frac{1}{k}. $$
Hence, we have constructed a subsequence $\{a_{n_k}\}$ such that $a_{n_k}\rightarrow q$ as $k\rightarrow\infty$. Thus,
$$\sup\{x:\exists\{a_{n_k}\}\subseteq\{a_n\},a_{n_k}\rightarrow x\text{ as }k\rightarrow\infty\}\geq q =\lim_{n\rightarrow\infty}\left(\sup_{m\geq n}a_m\right).$$
Putting together both inequalities we get $(*)$.

A: You're defining $$\ell^*=\limsup\limits_{n\to\infty}s_n$$ as the greatest upper bound of all subsequential limits of $\langle s_n\rangle$. We want to prove that, $\lim\limits_{n\to\infty}x_n=\ell^*$.
First, we show

LEMMA1 Let $\langle s_n\rangle$ be a sequence. Then there exists a subsequence $n_k$ such that $$\lim\limits_{k\to\infty}s_{n_k}=\ell^*=\sup S$$ where $S=\{x:x\text{ is a subsequential limit of }s_n\}$.

P If $\ell^*=+\infty$ then the sequence is unbounded and we can obtain a sequence $n_k$ such that $s_{n_k}>k$ and the claim is true. Now suppose the sequence is bounded. Then $\ell^*$ exists finitely. By definition, given $N>0$ there exists $x\in S$ such that $$x \leq \ell^*<x+\frac 1{2N}$$
Thus $0 \leq x-\ell^*<\dfrac 1{2N}$ so we can say $|x-\ell^*|<\dfrac 1{2N}$. Let $j_k$ be such that $$s_{j_k}\to x$$
Then there exists $M=M_N$ such that implies $$|s_{j_M}-x|< \dfrac 1{2N}$$
But then $$\left| {{\ell ^*} - {s_{{j_M}}}} \right| \leqslant \left| {{\ell ^*} - x} \right| + \left| {x - {s_{{j_M}}}} \right| < \frac{1}{2N} + \frac{1}{2N} = \frac 1N$$
Now let $N$ vary throughout $1,2,\ldots$. We construct a sequence $M_1,M_2,\ldots$ as follows. Let $M_1$ be the number promised such that $$\left| {\ell ^*} - s_{m_{1,M_1}} \right| \leqslant 1$$ where $s_{m_{1,k}}\to x_1$ for some $x_1\in S$ as before. Now let $M_2$ be first number such that $m_{2,M_2}>m_{1,M_1}$ and $$\left| {{\ell ^*} - {s_{{m_{{2,M_2}}}}}} \right| \leqslant \frac{1}{2}$$ where $s_{m_{2,k}}\to x_2$ for some $x_2\in S$. Continue like this: we obtain a sequence $n_k=m_{k,M_k}$ such that $$\left| {{\ell ^*} - {s_{{n_k}}}} \right| \leqslant \frac{1}{k}$$ which means $$\mathop {\lim }\limits_{k \to \infty } {s_{{n_k}}} = {\ell ^*}$$ $\hspace{15.5 cm} \blacktriangle$
By the same token, we can show

LEMMA2 There exists a subsequence such that $s_{m_k}\to \lim\limits_{n\to\infty}x_n$. I leave the proof to you, since it is very similar to the above.

Now all is clear to prove

PROP Let $\langle s_n\rangle $ be a sequence. Define $x_n=\sup\limits_{k\geq n}\{s_k\}$ and$\lim\limits_{n\to\infty}x_n=\ell$. Then $\ell=\ell^*$

P By the previous LEMMA there exist subsequences such that $$\lim\limits_{k\to\infty}s_{n_k}=\ell^*\\ \lim\limits_{j\to\infty}s_{m_j}=\ell$$
By definition of $\ell^*$, we must have $\ell\leq \ell^*$. It remains to show $\ell^*\leq \ell$.  Pick $n>0$. By the very definition of the $\langle x_n\rangle $ we must have $$x_n\geq s_k$$ for each $k\geq n$. In particular $$x_n\geq s_{n_j}$$ for each $n_j>n$. This means that $$x_n\geq \ell^*$$
Since $n$ was arbitrary, $x_n\geq \ell^*$ for each $n$, so $\ell\geq \ell^*$ $\hspace{15.5 cm} \blacktriangle$


text:
Q: Adding new ROWID to SQLite SELECT statement based on the UNION of several tables Consider the following SQLite statement where each product_id may appear at least once in each table. The purpose of our SELECT statement being to merge all the product_id's into one table.
SELECT product_id
  FROM product_id_table_UK
UNION
SELECT product_id
  FROM product_id_table_DE
UNION
SELECT product_id
  FROM product_id_table_ES
UNION
SELECT product_id
  FROM product_id_table_IT
UNION
SELECT product_id
  FROM product_id_table_FR

How can one add an ID INTEGER column to the resulting view?
Each table has it's own ID INTEGER column but if we SELECT ID column then we will have duplicate product_id columns in the new view with separate ID's.
Addding ROWID doesn't work since it returns the IDs of the tables.
Furthermore views do not have rows stored in them.

A: This is painful in older versions of SQLite (pre-row_number() days).  You can do:
with p as (
      SELECT product_id
      FROM product_id_table_UK
      UNION
      SELECT product_id
      FROM product_id_table_DE
      UNION
      SELECT product_id
      FROM product_id_table_ES
      UNION
      SELECT product_id
      FROM product_id_table_IT
      UNION
      SELECT product_id
      FROM product_id_table_FR
     )
select p.*,
       (select count(*) from p p2 where p2.product_id <= p.product_id)
from p;


text:
Q: MVC Ajax Combining Form Data I'm trying to append data to a form collection via ajax, My code is as follows:
var AjaxSendData = $('form').serialize();

$.ajax({
    data: {
        'searchtext': searchtext,
        'numofres': numofres,
        'orderbydesc': orderbydesc,
        'columnnum': columnnum,
        'pagenum': pageNum,
        'contenttype': contenttype,
        'MediaFilterType': MediaTypeID,
        'status': status,
        'ResultsFilterID': ResultsFilterID,
        'FilterIdType': FilterIdType
    },
    type: 'POST',
    url: $('#hiddenajaxurl').val() + '?' + AjaxSendData,
    cache: false,
    dataType: 'json',
    success: function (result) {
        //...
    }
});

My Issue is that on the C# side it only sees the things in ajax data: as a form collection the rest of the request is not there.  I tried sending AjaxSendData as the ajax data and append to it using an Associative array ie:
//AjaxSendData['searchtext'] = searchtext;

However this cause a 500 error.  Does anybody know how I can combine these so I can get the data back out of the FormCollection?


text:
Q: Is there still any development on SIMD in Mono? I want to know if there has been/is any development on Mono.SIMD (or SIMD-support in general inside Mono) ever since it came out 5(!) years ago. I personally think this was a great step in improving speed for c#. However, I've used it for some time now and I'm feeling that Mono.SIMD is falling behind, as lots of functions are missing.
Some of the problems i'm facing include:

*

*The lack of a dot product, which can be implemented in 1 operation ever since SSE4.1 (which came out in 2006 and is now supported on 70% of the computers), while it takes 3 operations inside Mono.SIMD. In addition to this, the programmer has to write a function for every version of SSE, a job the JIT should do (since it is created specifically to let the programmer stop worrying about CPU-versions).

*No possibility of adding/multiplying Vector4f and Vector4i (or any other vectors that are different).

*No proper casting of vectors (the bits don't seem change at all, so the results are very strange and almost entirely useless).

*Lots of other function which are not included, such as rounding.

So, does anyone know if something is happening with Mono.SIMD or SIMD-support in general(and if so, what)? Or, alternatively, does anyone know a good solution for any of the problems mentioned?

A: AFAIR the development is not in progress. The project is open source and the machinery is not too complicated, so one can improve current implementation. I considered adding some instructions, but then, as usual, there was not enough time to do that (also the application was eventually canceled). You may be interested in looking at the thread: http://lists.ximian.com/pipermail/mono-devel-list/2012-February/038632.html

A:
The other answer was made a few years ago. Thus, I wrote this one to list all the necessary bits for 2018 readers.

When Mono started to support SIMD, they were requested by Unity guys,
http://tirania.org/blog/archive/2008/Nov-03.html
It seemed to be in a hurry, so the overall API design still has room to grow.
Microsoft started to work on a more complete and standardized SIMD enabled library, and that was a few years later in 2014,
https://www.infoq.com/news/2014/04/SIMD-CLR
Therefore, attention should be paid to this newer option.
Microsoft open sourced .NET Core in 2015, and since then the SIMD work has been accelerated.
It was in last year that Mono 5.0 announced the obsoleteness of Mono.SIMD in favor of Microsoft's work,
http://www.mono-project.com/docs/about-mono/releases/5.0.0/ (SIMD Acceleration support section).


text:
Q: MF doesn't play video from my source I'm developing a media foundation-based h264 player to play h264 video and HE-AAC audio from my own custom media source.
My prototype doesn't play video, only audio.
How to fix that?
Here's the problem. I open my URL.
The framework creates and initializes my media source, which in turn creates and initializes my 2 streams, audio and video.
Then it asks for video samples until the end of the file is reached.
The log is filled with CMFTransformDetours::ProcessOutput failed hr=0xC00D6D72 MF_E_TRANSFORM_NEED_MORE_INPUT
Then after my video stream sends MEEndOfStream, the framework asks for a few more audio samples, finally transitions the state to playing, and starts to play audio only.
What does the framework tries to find in my video stream that isn't there?
The same file plays OK by the same player code if opened by the built-in stream source.
mftrace.exe says when the built-in stream source plays the file, the first video sample is 38 bytes longer then when my stream source plays it (all other samples are exactly the same length).
38 bytes is exactly the size of my MF_MT_MPEG_SEQUENCE_HEADER for my video (i.e. 00 00 01 + SPS + 00 00 01 + PPS). I've tried to prepend MF_MT_MPEG_SEQUENCE_HEADER value to my first frame, didn't help.
System-provided stream source sets undocumented attribute on video samples, GUID = {19124E7C-AD4B-465F-BB18-20186287B6AF}, values are 8-bytes binary values like "09 00 00 00 29 0d 00 00", and change each frame — what's that and can it be the reason?
What else can I try?
Is there any documentation on what exactly does the MF h264 decoder wants on input?
Thanks in advance.

A: There were two major problems in my code.

*

*My stream source didn't output those attributes with GUID = {19124E7C-AD4B-465F-BB18-20186287B6AF}
The attribute is documented, just the MFTrace.exe logging tool isn't aware so it prints GUID instead of name. The GUID stands for MF_NALU_LENGTH_INFORMATION attruibute.

My video stream descriptor had MF_NALU_LENGTH_SET attribute set to TRUE. That's why h264 decoder skipped all my video samples - it looked for MF_NALU_LENGTH_INFORMATION attribute on them, and it wasn't there.
Simple way to fix — remove MF_NALU_LENGTH_SET from the descriptor, the decoder is OK without that data.

*For this prototype, I read video samples from .mp4 container. NALUs in the container are preceded by their length in bytes. The MS decoder requires NALUs to be preceded by the start code "00 00 00 01". See this SO answer for more information about that. In the samples I feed to decoder, I had to replace NALU lengths with "00 00 00 01".


text:
Q: powershell command parameter with spaces I am trying to call a powershell script using -command argument from a batch file. The powershell script accepts an argument which may contain spaces. The command fails to accept argument with spaces.
Here is there the batch file.
@echo off
set arg1=%*
call powershell.exe -ExecutionPolicy Bypass -command ".\build.ps1 %arg1%; exit $LASTEXITCODE"
exit /b %ERRORLEVEL%

This is how the batch file is called - .\build.bat '-testToolPath=as sdaf'
I am using -command instead of -file just to return the LASTEXITCODE

A: Have you tried to use escaped doublequotes?
call powershell -ExecutionPolicy Bypass -command ".\build.ps1 ^"%arg1%^"; exit $LASTEXITCODE"

Maybe you have to remove the other quotes before:
set "arg1=%arg1:'=%"


text:
Q: Bad parentheses in macro definition I was reading this tutorial of stanford where they say :
Common coding mistakes:
Bad parentheses in macro definition
#define min(a, b) a<b?a:b // incorrect
#define min(a, b) (((a)<(b))?(a):(b)) // correct

I even ran this in a program, It worked fine.
Can anybody explain what they are trying to say!

A: The first version fails if you combine it with other operators:
min(a , b) + c

and translates to:
a<b?a:b+c

which is identical to:
a<b?a:(b+c)

which is an unexpected outcome given the starting parenthesis.
The second version isn't much better. It evaluates one of the parameters twice which can cause unexpected behavior if a function or i++ is passed to the macro.
An inline function should be used instead of those macros.


text:
Q: deploying python code to heroku not working I have added the buildpack for python, it works.
But when i do a git push it doesnt work.
I get the below error all the time.
(venv) D:\Projects\ecommerce\clone\cut_veggies>heroku buildpacks:set heroku/python
Buildpack set. Next release on cutveggie will use heroku/python.
Run git push heroku master to create a new release using this buildpack.

(venv) D:\Projects\ecommerce\clone\cut_veggies>git push heroku master
Counting objects: 308, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (305/305), done.
Writing objects: 100% (308/308), 410.14 KiB | 0 bytes/s, done.
Total 308 (delta 193), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Failed to detect set buildpack https://codon-        buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to cutveggie.
remote:
To https://git.heroku.com/cutveggie.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/cutveggie.git'

Can anyone tell what i am missing?

A: I've had this problem with my application too. Adding a requirements.txt file with the dependencies to the root of the project solved it. Check here for more details. You can check here for an example too.

A: I too had (and still have) this problem of not being able to push the app live through Heroku CLI.
A fix I found for this was to log on to Heroku using a browser and link your GitHub account and repo to the app. Then deploy this through GitHub.
They offer two possibilities. One is manual deployment where you deploy manually through the website after running thorough tests. Another is automatic deployment where the app is deployed as soon as you push your changes to the branch you linked to the app.
I have been using this ever since Windows decided to go crazy on me and prevent me from pushing the app to heroku master.


text:
Q: IN statement from CASE result inside Where clause Oracle I have a sample of the table and problem I am trying to solve in Oracle.
CREATE TABLE mytable (
id_field number
,status_code number
,desc1 varchar2(15)
);

INSERT INTO mytable  VALUES (1,240,'desc1');
INSERT INTO mytable  VALUES (2,242,'desc1');
INSERT INTO mytable  VALUES (3,241,'desc1');
INSERT INTO mytable  VALUES (4,244,'desc1');
INSERT INTO mytable  VALUES (5,240,'desc2');
INSERT INTO mytable  VALUES (6,242,'desc2');
INSERT INTO mytable  VALUES (7,245,'desc2');
INSERT INTO mytable  VALUES (8,246,'desc2');
INSERT INTO mytable  VALUES (9,246,'desc1');
INSERT INTO mytable  VALUES (10,242,'desc1');

commit;

SELECT *
FROM mytable
WHERE status_code IN CASE WHEN desc1 = 'desc1' THEN (240,242)
                          WHEN desc1 = 'desc2' THEN (240,245)
                            END

Basically I need to select a subset of status codes for each condition.
I could solve this with separate statements but the actual table I am doing this on has multiple descriptions and would result in around 20 unioned queries.
Any way to do this in one statement like I have attempted?

A: I believe that a CASE statement can only return one value (corresponding to one column in the result set).  However, you can achive this in your WHERE clause without using a CASE statement:
WHERE (desc1 = 'desc1' AND status_code IN (240,242)) OR
      (desc1 = 'desc2' AND status_code IN (240,245))

A: I like Tim answer better, but at least in postgres you can do this. Couldnt try it on oracle
Sql Fiddle DEMO
SELECT *
FROM mytable
WHERE CASE WHEN desc1 = 'desc1' THEN status_code IN (240,242)
           WHEN desc1 = 'desc2' THEN status_code IN (240,245)
      END
ORDER BY  desc1

OUTPUT
| id_field | status_code | desc1 |
|----------|-------------|-------|
|        1 |         240 | desc1 |
|        2 |         242 | desc1 |
|       10 |         242 | desc1 |
|        5 |         240 | desc2 |
|        7 |         245 | desc2 |


text:
Q: How can I retrieve a collection of records whose last record of an association meets a criteria? I have built the query for the join but I don't know how to build the part that checks for only the last record of the association.
Job.where('balance != 0').joins(:ledgers).to_sql

=> "SELECT \"jobs\".* FROM \"jobs\" INNER JOIN \"ledger_entries\" ON \"ledger_entries\".\"job_id\" = \"jobs\".\"id\" AND \"ledger_entries\".\"type\" IN ('LedgerEntry::JobAccount') WHERE \"jobs\".\"deleted_at\" IS NULL AND (balance != 0)"
Pseudo-coding the rest:
Job.where('balance != 0').joins(:ledgers).where_last_ledger_balance_equals_0


text:
Q: Selecting Features within distance and direction using ArcPy? Is there a way to select features in a layer by location based on their proximity to another feature and the direction? E.G., select all features within 10 meters north of current selection?
I am using ArcMap 10.3.1
I am selecting points, and I have scripting abilities.

A: If you define "north of" as being simply that a newly selected point has a Y coordinate greater than any of the originally selected features, then this should be doable by:

*

*using Select By Location within a distance of 10 meters to get them first

*then use ArcPy to work out the Y coordinate of the northernmost point

*then use ArcPy to examine the Y coordinate of each of the newly selected points to determine whether they need to be selected.

If your algorithm is more complicated than that then I think it would be best illustrated with a picture.


text:
Q: Possible to instantiate a class given class name? Is it possible to perform reflection in c++, and instantiate a class given the name of it as a string?
Cheers,

A: There's no language feature that lets you do this. You can, however, write your own set of factory functions and put those in a string-indexed map.

A: If you can use MFC, it has a object serialization framework that allows you to do this. This is documented here. Just to clarify, MFC can be used for a UI less application and I have seen it being used in this way quite successfully.
If you can't use MFC, you can consider boost serialization library. But to my knowledge it does not provide a factory function that allows you to create classes given their names. However, it does have the mechanisms to dynamically create classes from their names which you may be able to adapt to your unique needs. The relevant doc is here.


text:
Q: ¿Cómo mostrar un efecto de cargando.. antes de cargar el contenido fetch API con javascript? Tengo una API donde la petición la hago desde un archivo Javascript utilizando fetch.
el asunto o el problema es que en ocasiones son muchos los datos que necesito mostrar y eso demora un poco en cargar e incluso yo sabiendo que esta haciendo el proceso por abajo aveces dudo si esta ejecutando o no, entonces me gustaría que mientras el API fetch hace todo el proceso, primero se muestre un efecto de spinner de un gif, png o un diseño con CSS lo que sea, lo único que quisiera es saber como poder hacer, que utilizar y el resto lo podría hacer yo.
CÓDIGO (es un ejemplo no son los datos que estoy usando):

fetch("https://api.covid19api.com/summary")
.then((response) => response.json())
.then((datos) => {
    var cov19 = datos.Global
    cadena = `

        <input type="number" value="${cov19.NewConfirmed}">
        <input type="number" value="${cov19.TotalConfirmed}">
        <input type="number" value="${cov19.NewDeaths}">
        <input type="number" value="${cov19.TotalDeaths}">
        <input type="number" value="${cov19.NewRecovered}">
        <input type="number" value="${cov19.TotalRecovered}">

`
    document.getElementById('generar_datos').innerHTML= cadena
})
.catch(error => console.error('Error:', error));

                Nuevos Confirmados
                Total Confirmados
                Nuevos Fallecidos
                Total Fallecidos
                Nuevos Recuperados
                Recuperados

La idea es casi la misma uso fetch obtener y luego mostrar datos pero de otra forma (utilizo for y foreach, no se si eso haga una diferencia).
lo que estoy mostrando (código) es un ejemplo no es lo que estoy haciendo realmente, fue lo primero que se me ocurrió.

Espero me puedan ayudar con esa duda Gracias!

A: Puedes usar await y controlar de forma clara y sencilla cuando ha finalizado la carga de datos, poniendo un Spinner o algún texto que informe al usuario y ocultándolo una vez los datos hayan sido cargados.

const cargarDatos = async () => {
    const response = await fetch("https://api.covid19api.com/summary");
    const datos = await response.json();

    // Fuerzo artificialmente a que dure más para que se pueda observar el Spinner
    await accionAsincrona();

    var cov19 = datos.Global;
    cadena = `

        <input type="number" value="${cov19.NewConfirmed}">
        <input type="number" value="${cov19.TotalConfirmed}">
        <input type="number" value="${cov19.NewDeaths}">
        <input type="number" value="${cov19.TotalDeaths}">
        <input type="number" value="${cov19.NewRecovered}">
        <input type="number" value="${cov19.TotalRecovered}">

`

        // línea ocultando el spinner
    document.getElementById("spinner").style.display="none";
    document.getElementById('generar_datos').innerHTML= cadena;
}

const accionAsincrona = async () => {
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 3000);
  });
}

cargarDatos();
.lds-dual-ring {
  display: inline-block;
  width: 80px;
  height: 80px;
}
.lds-dual-ring:after {
  content: " ";
  display: block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  border: 6px solid black;
  border-color: black transparent black transparent;
  animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

&nbsp

Si quieres seguir usando promesas en vez de usar async y await:

fetch("https://api.covid19api.com/summary")
    .then((response) => response.json())
    .then(async (datos) => {
            // Fuerzo artificialmente a que dure más para que se pueda observar el Spinner
        await accionAsincrona();

        var cov19 = datos.Global;
        cadena = `

            <input type="number" value="${cov19.NewConfirmed}">
            <input type="number" value="${cov19.TotalConfirmed}">
            <input type="number" value="${cov19.NewDeaths}">
            <input type="number" value="${cov19.TotalDeaths}">
            <input type="number" value="${cov19.NewRecovered}">
            <input type="number" value="${cov19.TotalRecovered}">

`;

        // línea ocultando el spinner
            document.getElementById("spinner").style.display="none";
        document.getElementById('generar_datos').innerHTML= cadena;

        // Añadir línea de código ocultando el mensaje de cargando
    })
    .catch(error => console.error('Error:', error));

const accionAsincrona = async () => {
    return new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 3000);
  });
}
.lds-dual-ring {
  display: inline-block;
  width: 80px;
  height: 80px;
}
.lds-dual-ring:after {
  content: " ";
  display: block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  border: 6px solid black;
  border-color: black transparent black transparent;
  animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

&nbsp

A: Solo tienes que agregar un estilo de cargando y dependera de donde quieres que se vea desde un gift hasta una imagen vectorial, y adicional a esto el truco para esto es usar las bondades del .then().
La idea de usar el .finally() es por si falla el servicio tambien devolvamos los estilos como estaban

const $tabla = document.getElementById('generar_datos');
const $cargando = document.getElementById("cargando");
$cargando.style.display = 'block'
$tabla.parentElement.style.display = 'none'
fetch("https://api.covid19api.com/summary")
  .then((response) => response.json())
  .then((datos) => {
      var cov19 = datos.Global
      cadena = `

          <input type="number" value="${cov19.NewConfirmed}">
          <input type="number" value="${cov19.TotalConfirmed}">
          <input type="number" value="${cov19.NewDeaths}">
          <input type="number" value="${cov19.TotalDeaths}">
          <input type="number" value="${cov19.NewRecovered}">
          <input type="number" value="${cov19.TotalRecovered}">

`
      $tabla.innerHTML= cadena
  })
  .catch(error => console.error('Error:', error))
  .finally(()=>{
    $cargando.style.display = 'none';
    $tabla.parentElement.style.display = 'block';
  })

Cargando

                Nuevos Confirmados
                Total Confirmados
                Nuevos Fallecidos
                Total Fallecidos
                Nuevos Recuperados
                Recuperados

En javascript usualmente se antepone el signo '$' para saber que la variable es un elemento del DOM

A: Simplemente puedes tener un elemento que contenga tu elemento de carga, sea un gif o una animación con CSS (como en el ejemplo) y lo que haces es mantenerla oculta con display: none ese debe ser su estado por defecto, luego cuando ejecutes tu función para traer datos justo antes que esta se ejecute cambias la propiedad del display por algo visible, en este caso flex, pero bien podría ser alguno de los otros valores de display. Una vez se termine la carga vuelves a ocultar tu contenedor de la animación.
Para tu caso tendrías que hacer envolver fetch en una función así:
function fetchData() {
  /* Mostrar contenedor de carga */

  fetch("https://api.covid19api.com/summary")
  .then((response) => response.json())
  .then((datos) => {
    var cov19 = datos.Global;
    cadena = `

        <input type="number" value="${cov19.NewConfirmed}">
        <input type="number" value="${cov19.TotalConfirmed}">
        <input type="number" value="${cov19.NewDeaths}">
        <input type="number" value="${cov19.TotalDeaths}">
        <input type="number" value="${cov19.NewRecovered}">
        <input type="number" value="${cov19.TotalRecovered}">

`;
    document.getElementById('generar_datos').innerHTML = cadena;

    /* Ocultar contenedor de carga */
  })
  .catch(error => console.error('Error:', error));
}

A continuación te dejo un ejemplo funcional

function fetchData() {
  const loader = document.getElementById('loader');

  loader.style.display = 'flex';

  setTimeout(() => {
    loader.style.display = 'none';
  }, 2000);
}
.loader-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: none;
    justify-content: center;
    align-items: center;
    background: cadetblue;
}

.loader,
.loader:before,
.loader:after {
  background: #ffffff;
  -webkit-animation: load1 1s infinite ease-in-out;
  animation: load1 1s infinite ease-in-out;
  width: 1em;
  height: 4em;
}
.loader {
  color: #ffffff;
  text-indent: -9999em;
  margin: 88px auto;
  position: relative;
  font-size: 11px;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}
.loader:before,
.loader:after {
  position: absolute;
  top: 0;
  content: '';
}
.loader:before {
  left: -1.5em;
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}
.loader:after {
  left: 1.5em;
}
@-webkit-keyframes load1 {
  0%,
  80%,
  100% {
    box-shadow: 0 0;
    height: 4em;
  }
  40% {
    box-shadow: 0 -2em;
    height: 5em;
  }
}
@keyframes load1 {
  0%,
  80%,
  100% {
    box-shadow: 0 0;
    height: 4em;
  }
  40% {
    box-shadow: 0 -2em;
    height: 5em;
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">

  <button onclick="fetchData()">Cargar datos</button>

A: Actualizo la respuesta de @Sergio.
Hay que tratar siempre el caso de error.
Definiendo las siguientes funciones,
const showLoading = _ => {
    // Aquí se muestra el GIF, PNG
    // spinner, etc ...
}

const showError = error => {
    // Aquí se muestra el error
    // (si se necesita...)
}

const showData = data =>  {
    // Aquí se tratan los datos obtenidos
    // por la llamada HTTP
}

const hideLoading = _ => {
    // Aquí se oculta de nuevo
    // el PNG, GIF, etc.
}

La función principal quedaría del siguiente modo.
const load = async _ => {
    showLoading();

    try {
        const response = await fetch('...');
        const data = await response.json();
        showData(data);
    } catch (e) {
        showError(e);
    }

    // Haya excepción o no, el "loading" debe desaparecer.
    hideLoading();
}

Con sintaxis then y catch
const load = _ => {
    showLoading();
    fetch(`...`)
        .then(response => response.json())
        .then(showData)
        .catch(showError)
        .then(hideLoading); // Haya excepción o no, el "loading" debe desaparecer.
}

Y finalmente, para nota. Usar un decorator pattern para la separación de lógicas.
const wrapWithLoading = callback =>
    async _ => {
        showLoading();
        await callback();
        hideLoading();
    }

const load = wrapWithLoading(async () => {
    try {
        const response = await fetch('...');
        const data = await response.json();
        showData(data);
    } catch (e) {
        showError(e);
    }
});

Espero que sirva.


text:
Q: HttpClient not getting response when POST I want to receive response from server. With Postman works great:
Request:
{
    "name": "antonio",
    "username": "antonio",
    "email": "antonio@antonio.pl",
    "password": "antonio"
}

Response:
{
    "success": true,
    "message": "User was successfully registered"
}

Im trying to implement same thing in Angular, so I got:
  this.http.post('http://localhost:8090/api/auth/signup',
  JSON.stringify({name: name, username: username, password: password, email: email}),
  {headers: new HttpHeaders({'Content-Type': 'application/json'})})
  .subscribe(res => alert(res[0]));

Checked backend API, works great but alert still is not appearing. Any ideas?

A: You shouldn't need to JSON.stringify() the request if you are sending it as 'application/json'. I don't know how your backend interprets it.

this.http.post('http://localhost:8090/api/auth/signup',
  {name: name, username: username, password: password, email: email},
  {headers: new HttpHeaders({'Content-Type': 'application/json'})})
  .subscribe(res => alert(res[0]));

https://angular.io/api/common/http/HttpClient#post


text:
Q: PHP: connect X.pdf to X.png in a chosen directory I am looking for a PHP script that connects *.PDF to *.PNG files in a directory. Due to lack of PHP knowledge, I only know how to do this manually in HTML. Could PHP do this for me automatically by connecting A.pdf with A.png, B.pdf with B.png, C.pdf with C.png and so on? Then all I need to be able doing is to change the folder name in PHP.

etcetera...

A: I'm not sure if I understood this correctly, but the code below will get all .pdf files from a directory and return the HTML for each .pdf file.  This will also check to see if the .png exists, but will not echo anything if it does not exist.
// get all .pdf files from directory
$directory = "directory/";
$files = glob($directory."*.{[pP][dD][fF]}", GLOB_BRACE);
foreach ($files as $item) {
    // get pathinfo to get the filename
    $fileInfo = pathinfo($item);
    $fileName = $fileInfo['filename'];
    // check if the .png exists
    if (file_exists($directory.$fileName.".png")) {
        // echo
        echo "

";
    }
}


text:
Q: I'm getting an undefined error when console the state variable and show correct value when i console acutall variable used for state I'm getting an undefined error on value variable which is a state but when i console the variable in which data is Store it Give Correct Data From Data Base but when a put that varible to set state it show undefined Value.
import React, { useState } from "react";
import { useEffect } from "react";

const TodoList = () => {
  const [Printed, SetDbData] = useState();

  const getData = async () => {
    try {
      const getDbContent = await fetch("/getData", {
        method: "GET",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        credentials: "include",
      });

    const getDbData = await getDbContent.json();

      const [object] = getDbData;

      SetDbData(object);

      console.log(object);

//************** when i console object is Show data **************

{
    "_id": "62d145c8ea501901f8ad650d",
    "todoText": "hello",
    "__v": 0
}

console.log(Printed);

//************* but when i console state varriable (Printed )is Show undefined Data***********

(undefined)

    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <>

Todo List

          <form className="inner_card" method="POST" >
            <input
              type="text"
              name="todoText"
              placeholder="Add Items"
              autoComplete="off"
            />
            <button type="submit" >
              +
            </button>

              WARNING : Please Add Something

          </form>

    </>
  );
};

export default TodoList;

plaese Can Anyone tell my where i'm doing mistake i'm seriously stuck in this problem please help me


text:
Q: Convert date from access to SQL Server with SSIS I want to convert a database from access to SQL Server using SSIS. I cannot convert the date/time columns of the access db. SSIS says something like:
conversion between DT_Date and DT_DBTIMESTAMP is not supported.

(Its translated from my German version, might be different in English version). In Access I have Date/Time column, in SQL Server I have datetime. In the dataflow chart of the SSIS I have a OLE DB source for the access db, an sql server target and a data conversion. In the data conversion I convert the columns to date[DT_DATE]. They are connected like this:
AccessDB -> conversion -> SQL DB

What am I doing wrong? How can I convert the Access date columns to SQL Server date columns?

A: Looks like you'll need to add a specific conversion to convert this column to the correct type.  It's the DT_DBTIMESTAMP that you need to convert to, not DT_DATE.  Using a Derived Column Transformation for instance, you could use an expression like:
(DT_DBTIMESTAMP)YourDateColumn

A: You use another Provider on the source side. I used the JET provider. I am doing this on a computer where no Access is installed. When I try to create a data connection using the Office 12.0 Access Database Engine OLE DB Provider I get an error message that the workgroup information file is missing. I get this message on the connection test.
The question is if the conversion depends on the db driver you use to get the data. I cannot install Access on the server I am working, so I cannot try it. Could this be the cause of the problem?

A: Casting D_Date column to DT_DBTIMESTAMP solve the same problem for me.


text:
Q: Unity Animation Transition Weird bug I'm trying to make it so the character will go from being idle to picking something(ive tried doing it myself with animation rigging but it didn't work for some reason) and for some reason whenever the transition is happening instead of doing the animation my character just glitches to the ground like that(I got all the animations from mixamo)

A: In the Rig section change the type from Generic to Humanoid.

A: you should make sure that the animations and your avatar are retargeted to humanoid. A helpful article can be found in the Unity Manuals.
https://docs.unity3d.com/Manual/Retargeting.html

One of the most powerful features of Mecanim is retargeting of humanoid animations
. This means that with relative ease, you can apply the same set of animations to various character models. Retargeting is only possible for humanoid models, where an Avatar
has been configured, because this gives us a correspondence between the models' bone structure.

A: If you dont have your character as a kinematic, do it, maybe it fix your problem


text:
Q: if else return practice Noob question I know, but I need it confirmed since this occurs so often to me. Is there any point in using elif: if you know that code won't be reached when previous block is true? Eg.
if foo:
  return x
elif bar:
  return y

Should just be:
if foo:
  return x
if bar:
  return y

A: I can see at least three reasons to prefer if/elif:

*

*It makes it clear to readers of the code that the writer intended the conditions to be mutually exclusive

*If the code is later refactored, changing early returns to a single late return, the semantics of if/elif won't break, but if/if might

*It keeps the code style consistent with the rest of the codebase you're working in

and at least two reasons to prefer if/if:

*

*It's less typing

*It keeps the code style consistent with the rest of the codebase you're working in

That said, here's some recommended reading:

*

*Should I return from a function early or use an if statement?

*Python Guide. Code Style - Returning values

*In Python, should I use else after a return in an if block? (take this one with a healthy pinch of salt)

A: There isn't any difference to the python interpreter; in fact, the two code snippets will internally compile to the same instructions (the compiler is smart enough to know that the code after the return will never be reached, and will optimize the else part away completely.).
It's a matter of style, and readability.

A: From the standpoint of the Python interpreter, no, there's no difference--or at least, there's no difference in terms of execution, though there may be some subtle difference in the way the two constructs are implemented.
But keep in mind that you are writing not just to the interpreter; you're writing for other programmers to read your code later. Write whatever you think makes your intention most clear.

A: If you know it won't be true, then don't waste the interpreter's time with checking it.  If you use if it will be evaluated every time; however, elif will only be evaluated if the previous if condition was False.  In this case you are using return, so you should be safe from that, but by changing logical flow based on a return is bad.  You should have as few (preferably only one) code paths as possible.  Also, it gives a clean, readable structure and makes the code path explicit.  Readability counts, and explicit is better than implicit.

A: Multiple IF statements means your code will check all the IF conditions, whereas in case of elif:, if one IF condition satisfies it would not check other conditions. (As has been pointed out to me, this is ONLY true if none of the IF statements has to return from the code block)
In your case, it is OK to use the multiple IF statement.


text:
Q: Auto button press based on value of Scope Variable using CSJS / SSJS I have page pendingData.xsp, when user clicks on adjust button system sets value of scope variable and move to page adjustpending.xsp. On adjustpending.xsp I want to press button retreive data automatically based on value of scope variable e.g. if scope variable is having value true than click button otherwise not.
I am unable to find any event where variable can be checked and button pressed.
Following CSJS code is working perfectly fine but on change, focus, mouse over or other events of field etc. Moreover I have also tried on  this code on On Client load but failed to achieve desired results.
document.getElementById('#{id:button7}').click();
Can any body guide me how to address this issue.
Thanks in advance
Best Regards,
Qaiser

A: I realise I'm not directly answering your question, but you'd probably be better off putting your code into a function and then calling that directly.
If the button needs to run it, just make the button call it directly. You can include this in a SSJS script library or in a scrips block on the xpage.
example ..
library code:
function doSomething() {
 // .. does something
}

button code :
doSomething()

beforePageLoad (or whichever is best event) :
doSomething()

This is ultimately the same as auto-clicking a button, but your doDomething() routine is now available to be called from wherever you like without having to figure out how to auto click a button.


text:
Q: Unit testcases on Pyspark dataframe operations I have written some code in python with sql context i.e pyspark to perform some operations on csv by converting them into pyspark dataframes(df operations such as pre-processing,renaming column names,creating new column and appending them to same dataframe and so on). I wish to write unit test cases for it. I have no idea of writing unit testcases on dataframes. Can anyone help me out how to write unit testcases on dataframes in pyspark? Or give me some sort of sources for testcases on dataframes?

A: Dataframes are not different from anything else in pyspark land. You can start by looking at Python section of spark-testing-base. There are several interesting projects that have dataframe tests, so you can start at peeking how they do it: Sparkling Pandas is one, and here is another example. There is also find-spark that will help locate your spark executable context. But the basic idea is to setup path properly before you start your test:
def add_pyspark_path():
    """
    Add PySpark to the PYTHONPATH
    Thanks go to this project: https://github.com/holdenk/sparklingpandas
    """
    import sys
    import os
    try:
        sys.path.append(os.path.join(os.environ['SPARK_HOME'], "python"))
        sys.path.append(os.path.join(os.environ['SPARK_HOME'],
            "python","lib","py4j-0.9-src.zip"))
    except KeyError:
        print "SPARK_HOME not set"
        sys.exit(1)

add_pyspark_path() # Now we can import pyspark

And normally you would have one base test case class:
import logging

from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql import SQLContext, HiveContext

def quiet_py4j():
    """ turn down spark logging for the test context """
    logger = logging.getLogger('py4j')
    logger.setLevel(logging.WARN)

class SparkTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        quiet_py4j()

        # Setup a new spark context for each test
        conf = SparkConf()
        conf.set("spark.executor.memory","1g")
        conf.set("spark.cores.max", "1")
        #conf.set("spark.master", "spark://192.168.1.2:7077")
        conf.set("spark.app.name", "nosetest")
        cls.sc = SparkContext(conf=conf)
        cls.sqlContext = HiveContext(cls.sc)

    @classmethod
    def tearDownClass(cls):
        cls.sc.stop()


text:
Q: Having issues with Apache Tomcat log i accidently clicked on x and closed my apache tomcat log where i can see all the exceptions netBeans throws and i am having a big problem finding on internet how to enable it again. Does anybody know?

A: go to services tab/window, open servers and right click on the server you want. Then click 'View Domain Server Log'


text:
Q: Wait for ThreadPool to finish and start SingleThread I am currently trying to make a program check if a number is prime or not, by using a ThreadPool of 10 threads and a second run where I check only with one thread. The idea here is that I also check the difference in speed between using ThreadPool of 10 threads and 1 single thread.
My issue is that I am a bit stuck on how I would go about waiting for the PoolThread to finish before launching the single thread operation.
I tried to synchronized a function in my PrimeTask class, but I am still very new to threads, and not sure why I am not getting the desired behaviour. I would love some insight what I am missing and why.
import java.util.concurrent.*;

public class PrimeChecker
{
    private static ExecutorService executor;
    private final static long number = 9223372036854775783L;
    private final static int numberOfThreads = 10;
    private static long startValues;
    private static long endValues;
    static long startTime;
    static long endTime;

    private PrimeChecker() { };

    public static void main(String[] args)
    {
        init();
        runThreads();
    }

    private static void init()
    {
        startValues = 3L;
        endValues = (long) Math.sqrt(number) / 10L;
    }

    private static void runThreads()
    {
        startTime = System.currentTimeMillis();
        executor = Executors.newFixedThreadPool(numberOfThreads);
        System.out.print("Chekcing if " + number + " is a prime number, multithreaded.\n");
        for (int x = 1; x < 10; x++)
        {
            executor.execute(new PrimeTask(number, startValues, endValues));
            startValues = ((endValues / 10) * x);
            endValues = ((endValues / 10) * (x + 1));
        }
        executor.shutdown();

        singlethreadedPrime();
    }

    private static void singlethreadedPrime()
    {
        startTime = System.currentTimeMillis();
        executor = Executors.newFixedThreadPool(1);
        System.out.println("Chekcing if " + number + " is a prime number, singlethreaded.");
        executor.execute(new PrimeTask(number, startValues, endValues));
        executor.shutdown();
    }

    static class PrimeTask implements Runnable
    {
        private long number;
        private long startValue;
        private long endValue;

        public PrimeTask(long Numb, long startVal, long endVal)
        {
            number = Numb;
            startValue = startVal;
            endValue = endVal;
        }

        @Override
        public void run()
        {
            if (isPrime(number, startValue, endValue))
            {
                endTime = System.currentTimeMillis();
                System.out.printf("Time millisecond: %d\n", (endTime - startTime));
                System.out.println(number + " is Prime");
            }
            else
            {
                endTime = System.currentTimeMillis();
                System.out.printf("Time millisecond: %d\n" + (endTime - startTime));
                System.out.println(number + " not Prime");
            }
        }

        public static synchronized boolean isPrime(long n, long sV, long eV)
        {
            if((n % 2) == 0)
            {
                return false; // not prime
            }
            else
            {
                for(long i = sV; i*i <= eV; i+=2)
                {
                    if(n%i==0)
                        return false; // not prime
                }
                return true; // prime
            }
        }
    }
}

A: You used "execute", but you seem to want to wait for results.
So you can use submit() which returns a future.
You can thus wait for the future.get() (which is blocking).
With only one future, it's trivial. For 10 futures, you would pile up futures in a list, then when all submitted, it's fairly simple to call .get() on each one. The first ones will take some time, but the later ones will be faster, or not even block in .get() if already completed. (of course you could poll for future.isDone() but that's wasteful)
The executor.shutdown() which you use should wait for all in-progress task to complete, but the problem could be that they are not all in-progress but merely queued.
Finally, you could use a CountDownLatch to wait for all completions. Pass the countdown latch to all tasks.


text:
Q: Batch file to download files? I have a batch file, and I'd like to make a part of it save/download a file from a website...
eg.
example.com/file.jpg
This would then be saved to a location on my computer. Is there a way to do this? I've tried using the copy/xcopy/ROBOCOPY commands, but to no avail.
My operating system is Windows 8.1

A: You can use bitsadmin /? it's native in windows but not sure in windows8
bitsadmin.exe /transfer "JobName" http://download.url/here.exe C:\destination\here.exe

A: It is operating system specific. On POSIX systems, you might use curl or wget to download files; perhaps they exist on your OS (even if it not POSIX compliant, e.g. Windows, to which both utilities have been ported)
Both curl & wget are free software. You can download their source code, perhaps adapt it to your additional needs (I guess you won't have to do that, but who knows?), compile them into some executable, and run that executable on the command line.


text:
Q: check if array has this value and then grab it and place it an a variable I have a string like the one below
20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424
I will explode it and it will then be turned into an array.
But I want to check if the array has Ref:675743957424 and then place it inside a variable like for example $a.
I want to do this since the string might change from one point to another so the position of Ref is not fixed.
How Can i obtain such thing?
Thanks.
Edited
I tried not exploding it but instead try grabbing the data see code below
<?php
 $line = "20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424";
 // perform a case-Insensitive search for the word "Vi"

  if (preg_match("/\bRef\b/i", $line, $match)) :
  print "Match found!";
   //how can I grab the Ref part?
  endif;

?>

A: You have to use:
preg_match ('/Ref:[\d]*/', $line, $matches);

The matches will be saved to variable $matches and then you can operate with said matches.
The RegExp, you just need to look for string Ref: followed by any amount of numbers (\d looks for any digit and * looks for zero or more ocurrences of the previous operator, digits in this case).
If you know the exact number of digits that you must to find and it is not varying you could use the pattern {NUMBER}, like:
preg_match ('/Ref:[\d]{12}/', $line, $matches);

This case, you are looking for 12 digits after Ref:.

A: You can use strpos() to check whether the substring present in the string. If it is true, you can assign that to your variabble. Pleas see the below code, it may help you.
 $line = "20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424";
 $string_to_check ='Ref:675743957424'
 if (strpos($line,$string_to_check) !== false) { //Ref is present
  $a = $line;
 }


text:
Q: how to build compiled rpm of gcc 8.2 I am trying to make an rpm of gcc 8.2 for centos 7.
Honestly I am trying my best to understand how to use rpmbuild and .spec file, but it's too hard for me to understand.
I tried packaging my hello world program using fedoraproject's tutorial and succeded.
But when I tried building wget rpm using ibm's Packaging software with RPM tutorial, I failed.
I am trying to build gcc 8.2(https://ftp.gnu.org/gnu/gcc/gcc-8.2.0/gcc-8.2.0.tar.gz)
I use this process to build gcc, and I want the packaged rpm to do exactly like this, precompiled.
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++ --prefix=/opt/gcc-8.2.0

make -j 12

make install

Can anyone write an example spec file for me?

A: May I suggest that you use the src.rpm for it and the spec in it?
Unpack everything in the src.rpm but the spec file itself to ~/rpmbuild/SOURCES/
Now unpack the spec file to your desired location (e.g Desktop) and edit it in the desired file editor (GUI based or text based doesn't matter).
I prefer nano or pluma.


text:
Q: Unsupported framework error creating .net Class library Just adding a new Class Library (.net Core ) project to my solution generate two errors:
Error NU1002 The dependency xxx.Web.Services 1.0.0 in project xxx.Web.Services does not support framework DNX,Version=v4.5.1.
Error NU1008 "netstandard1.5" is an unsupported framework.
project.json file content:
{
    "version" : "1.0.0-*",

    "dependencies" : {
        "NETStandard.Library" : "1.5.0-rc2-24027"
    },

    "frameworks" : {
        "netstandard1.5" : {
            "imports" : "dnxcore50"
        }
    }
}

Project.lock.json file content:
{
    "locked" : false,
    "version" : 2,
    "targets" : {
        "DNX,Version=v4.5.1" : {
            "NETStandard.Library/1.5.0-rc2-24027" : {
                "type" : "package"
            }
        },
        "DNX,Version=v4.5.1/win7-x86" : {
            "NETStandard.Library/1.5.0-rc2-24027" : {
                "type" : "package"
            }
        },
        "DNX,Version=v4.5.1/win7-x64" : {
            "NETStandard.Library/1.5.0-rc2-24027" : {
                "type" : "package"
            }
        }
    },
    "libraries" : {
        "NETStandard.Library/1.5.0-rc2-24027" : {
            "type" : "package",
            "sha512" : "SD27bvP2gNnlpC7HZUbnPOXS1M7VbBZoi0bdlqe5tj7weJQ2EyGDGw8mi7K1yUmeqjL6jPWBLSC28TDaLnyqwA==",
            "files" : ["dotnet_library_license.txt", "NETStandard.Library.1.5.0-rc2-24027.nupkg", "NETStandard.Library.1.5.0-rc2-24027.nupkg.sha512", "NETStandard.Library.nuspec", "ThirdPartyNotices.txt"]
        }
    },
    "projectFileDependencyGroups" : {
        "" : ["NETStandard.Library >= 1.5.0-rc2-24027"]
    }
}

A: You need to change version in global.json (Solution items).
example:
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview1-002702"
  }
}

also, probably need to change
 \DNX\Microsoft.DNX.Props –> \DotNet\Microsoft.DotNet.Props

\DNX\Microsoft.DNX.targets –> \DotNet.Web\Microsoft.DotNet.Web.targets

in your xproj file.
Best solution (not project), would be to create brand new solution and see how it's all done there.

A: You need to install .NET Core RC2 Tools for Visual Studio 2015 in order to use RC2.
You can find Instructions on the Microsoft .NET Core Website.


text:
Q: How to use describe() for a pandas dataframe? How can I use the describe function for a pandas dataframe? I need to get statistical information (mean, standard deviation, etc) for one variable of the data frame, but specifically for two groups of another variable.
So basically there is a column called "X" that contains numbers and another column called "Y" that contains categories like "full" and "empty". And I need to use describe() to get the information.
I know how the get the information of X using df.X.describe() but not from the rest.
UPDATE:
enter image description here I want to know the statistical information of the "model_type_index" based on the "mfr_code", so for ASX and MBX

A: This can be achieved using the .groupby() function on the DataFrame and passing the column name to be grouped; in this case 'y'.
Sample data setup:
# Setup
x = list(range(10))
y = ['full', 'empty']*5
df = pd.DataFrame({'x': x, 'y': y})

Example usage:
# Describe the groups of data, based on Y.
df.groupby('y').describe().reset_index()

Output:
The results show the stats data for column 'x', where the values have been grouped by column 'y'.
       y     x
         count mean       std  min  25%  50%  75%  max
0  empty   5.0  5.0  3.162278  1.0  3.0  5.0  7.0  9.0
1   full   5.0  4.0  3.162278  0.0  2.0  4.0  6.0  8.0

Sample DataFrame:
   x      y
0  0   full
1  1  empty
2  2   full
3  3  empty
4  4   full
5  5  empty
6  6   full
7  7  empty
8  8   full
9  9  empty


text:
Q: c# Logmanager.Configure exception Method not found: 'System.String System.AppDomainSetup.get_ConfigurationFile() In .net core 3.1 wpf app i want to configure nlog with the following code
I have appsettings.json
{
  "LogConfiguration": {
    "factoryAdapter": {
      "type": "Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog4412",
      "arguments": {
        "configType": "FILE",
        "configFile": "./nlog.config"
      }
    }
  }
}

and in app.xaml.cs OnStartup(StartupEventArgs e)
IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();

            LogConfiguration logConfiguration = new LogConfiguration();
            config.GetSection("LogConfiguration").Bind(logConfiguration);
            LogManager.Configure(logConfiguration);

when i call:
ILog Log = LogManager.GetLogger<App>();

i get following Exception
Method not found: 'System.String System.AppDomainSetup.get_ConfigurationFile()

anybody has a hint on this?


text:
Q: Database shared locks being acquired on database I'm currently working on a system that suffers from timeout issues.. some appear to be related to long running queries that are locking frequently updated tables.
I recently ran sp_lock on the production server and noticed a lot of sessions that appear to be locking the whole database?
An example of the output:
spid: xxx
dbid: x
ObjId: 0
IndId: 0
Type: DB
Mode: S
Status: GRANT
Is this unusual? Surely we would be having bigger issues than intermittent timeouts if the whole db is being locked?

A: Don't normally use sp_lock and checked it on our DB and you are correct that all connection have Type = DB which is database lock but our DB doesn't have any issues with locks. You may want to look into DMV (Dynamic Management Views). In Documentation sp_lock will be removed in future Msoft sp_lock


text:
Q: Find the work done by the force field $\vec{F}(x, y, z) = (x, y)$ when a particle is moved along the straight line-segment from $(0,0,1)$ to $(3,1,1)$ Find the work done by the force field $\vec{F}(x, y, z) = (x, y)$ when a particle is moved along the straight line-segment from $(0,0,1)$ to $(3,1,1)$
Attempt:
$\vec{C}(t) = (3t, t, 1), 0 \leq t \leq 1$
Work done is
$\int_{C} \vec{F}(\vec{C}(t)) = \int_{C} \vec{F}(\vec{C}(t)) \cdot \vec{C}'(t) dt = \int_{0}^{1} (3t, t, 0)(3,1,0) dt = \int_{0}^{1} (9t + t) = 5$
yay or nay?

A: Your answer is correct, nicely done. Just as some feedback:
Comments:

*

*To be correct you should write $F(x,y,z)=(x,y,0)$. You can't omit the third coordinate in $\mathbb{R}^3$.

*As far as the computation is concerned, a more correct notation might be as follows: let $\vec{r}(t)=(3t,t,1)$ for $0\le t \le 1$ denote the parametrization you proposed:
$$\int_C \vec{F}\cdot d\vec{r}=\int_C\vec{F}(\vec{r}(t))\cdot d\vec{r}=\int_C\vec{F}(\vec{r}(t))\cdot \vec{r}'(t)dt=\int_0^1(3t,t,0)\cdot (3,1,0)dt=\int_0^19t+tdt=5.$$
Sometimes it is useful to distinguish between the curve $C$ and its parametrization $\vec{r}(t)$.


text:
Q: RavenDB progmatically empty database Is there a command in RavenDB that empties everything in a store? Something like Store.Empty?

A: No, and there wouldn't be one.
That would assure accidental data loss.
You probably want to run in memory for tests, right? We have explicit support for that.


text:
Q: Creating a new view with to subviews, get graphics context destroys original view? I hope that title makes some sense.
I have UIView (created in IB) where I add stuff (images). Then, I have a UILabel with some text. Now, I want to make a UIImage out of that, which I do like this:
UIView *comp = [[UIView alloc] initWithFrame:self.previewView.frame];
    [comp addSubview:self.previewView];
    [comp addSubview:self.lblCaption];

    UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0);
    [comp.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

self.previewView and self.lblCaption are both created in IB. previewView is just a screen-filling view.
The code-block is executed in an IBAction after a button-tap.
Which works wonderful, I get the image as expected and can process it further.
But after that, the contents of «self.previewView» are gone? When I do an NSLog, everything seems to be there, but it's not visible on screen anymore.
Does anyone have an idea what's going on here?
[Edit]
As the answer below states, the view was added to self.view before, so it was removed when I added it to the comp. The solution is pretty easy, actually, I changed the code to the following: (created a function that returns a UIImage. That's a bit cleaner than doing it in code....
-(UIImage *)imageFromView:(UIView *)theView andLabel:(UILabel *)theLabel{

    UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    [theLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return viewImage;
}

A: I am just guessing assuming possible situations...
Assuming you were showing self.previewView on some other view, say self.view.
When you added self.previewView to comp, it may have been removed from self.view. (Considering that UIView.superview is only single instance, I am thinking this is very likely).
If this is the case, re-adding self.previewView to self.view after obtaining image would solve the problem.


text:
Q: QEMU startup zoom automation Each time I start QEMU I do the same series of clicks: View->Zoom to fit, and then grab the corner of the QEMU window and drag to zoom about 2.5 times. Can this be automated so qemu just starts zoomed 2-3 times? Or at least in zoom to fit mode.

A: qemu -display gtk,zoom-to-fit=on


text:
Q: How to open an embedded SWF file in mobile browser? I am trying to embed a SWF file in HTML by using JavaScript, but mobile browsers  doesn't support it and so the swf file cannot be opened ever.
In mobile browsers it is only showing the below error message:

This plugin is not supported

If browser does not support, it is showing button to download player.
This is my code :
<script type="text/javascript">
    AC_FL_RunContent( 'codebase','http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,18,0','width','100%','height','100%','src','images/map','quality','high','scale','exactfit','pluginspage','http://www.macromedia.com/go/getflashplayer','movie','images/map' ); //end AC code
</script>
<embed allowFullScreen="true" src="img/swf/map.swf" alt="Virtual Tours Of Chianti" quality="high" scale="exactfit" allowFullScreen="true" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash">
<noscript>
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,18,0" width="750" height="380">
    <param name="movie" value="images/map.swf" />
    <param name="quality" value="high" />
    <param name="allowFullScreen" value="true">
    <embed src="img/swf/map.swf" alt="Virtual Tours Of Chianti" quality="high" type="application/x-shockwave-flash" width="100%" height="100%" allowFullScreen="true" SCALE="exactfit" pluginspage="http://www.macromedia.com/go/getflashplayer" />
    </object>
</noscript>

How to fix it?

A: Flash is not supported so you will need to have a fall back to mp4 video.