text:
Q: XPath returns null in c# but works in XPath validator This is my first time using XPath.
This is my XML:
<content type="application/xml">
    <m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
        <d:Guid>YOIYOI-HNON-OIN</d:Guid>
        <d:ObjectId>6000009251</d:ObjectId>
        <d:ProcessType>ZMIN</d:ProcessType>
        <d:ProcessTypeTxt>Incident</d:ProcessTypeTxt>
        <d:Description>Test 2</d:Description>
        <d:IntroText>Incident</d:IntroText>
        <d:CreatedAtDateFormatted>08.05.18</d:CreatedAtDateFormatted>
        <d:ChangedAtDateFormatted>08.05.18</d:ChangedAtDateFormatted>
        <d:PostingDate>2018-05-08T00:00:00</d:PostingDate>
        <d:ChangedAtDate>2018-05-08T00:00:00</d:ChangedAtDate>
        <d:Priority>2</d:Priority>
        <d:PriorityTxt>2: High</d:PriorityTxt>
        <d:PriorityState>None</d:PriorityState>
        <d:Concatstatuser>New</d:Concatstatuser>
        <d:ActionRequired>false</d:ActionRequired>
        <d:StillOpen>true</d:StillOpen>
        <d:Icon></d:Icon>
        <d:SoldToPartyName></d:SoldToPartyName>
        <d:ServiceTeamName></d:ServiceTeamName>
        <d:PersonRespName></d:PersonRespName>
        <d:ConfigItemTxt></d:ConfigItemTxt>
    </m:properties>
</content>

There are other content nodes.
I need to retrieve specific tag values such as:

*

*d:Guid

*d:ProcessType

*d:Description

*and so on..

but I don't need all the tag values.
I tried an online Xpath validator where i posted my XML and used this expression:
//content/m:properties/d:Guid | //content/m:properties/d:ObjectId

This gives me the data that I needed but when I use it in c# application it returns null. Can somebody please explain to me why this happens? And if there's any other way to do so besides using XPath?
Here is my c# code :
string xml = System.IO.File.ReadAllText(startupPath);
StringBuilder sb = new StringBuilder();

using (var node = ChoXmlReader.LoadText(xml).WithXPath("//content/m:properties/d:Guid or //content/m:properties/d:ObjectId"))
{
    using (var w = new ChoCSVWriter(sb).WithFirstLineHeader())
    {
        w.Write(node);
    }
}

Console.WriteLine(sb.ToString());
Console.ReadLine();

A: In the online validator you use | but you use or in your code. Does ChoETL really change the way XPaths work? I could not find evidence for that in the documentation.
Also, I think the online tool automatically deduces the namespace prefixes but you need to tell ChoETL the namespaces:
.WithXNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices")

and similar.

A: You can create a Model for this XML file and then serialize that to object and then access the properties you want. Here is the model you can use:
[XmlRoot(ElementName = "properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
    public class Properties
    {
        [XmlElement(ElementName = "Guid", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string Guid { get; set; }
        [XmlElement(ElementName = "ObjectId", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ObjectId { get; set; }
        [XmlElement(ElementName = "ProcessType", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ProcessType { get; set; }
        [XmlElement(ElementName = "ProcessTypeTxt", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ProcessTypeTxt { get; set; }
        [XmlElement(ElementName = "Description", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string Description { get; set; }
        [XmlElement(ElementName = "IntroText", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string IntroText { get; set; }
        [XmlElement(ElementName = "CreatedAtDateFormatted", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string CreatedAtDateFormatted { get; set; }
        [XmlElement(ElementName = "ChangedAtDateFormatted", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ChangedAtDateFormatted { get; set; }
        [XmlElement(ElementName = "PostingDate", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string PostingDate { get; set; }
        [XmlElement(ElementName = "ChangedAtDate", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ChangedAtDate { get; set; }
        [XmlElement(ElementName = "Priority", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string Priority { get; set; }
        [XmlElement(ElementName = "PriorityTxt", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string PriorityTxt { get; set; }
        [XmlElement(ElementName = "PriorityState", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string PriorityState { get; set; }
        [XmlElement(ElementName = "Concatstatuser", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string Concatstatuser { get; set; }
        [XmlElement(ElementName = "ActionRequired", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ActionRequired { get; set; }
        [XmlElement(ElementName = "StillOpen", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string StillOpen { get; set; }
        [XmlElement(ElementName = "Icon", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string Icon { get; set; }
        [XmlElement(ElementName = "SoldToPartyName", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string SoldToPartyName { get; set; }
        [XmlElement(ElementName = "ServiceTeamName", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ServiceTeamName { get; set; }
        [XmlElement(ElementName = "PersonRespName", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string PersonRespName { get; set; }
        [XmlElement(ElementName = "ConfigItemTxt", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
        public string ConfigItemTxt { get; set; }
        [XmlAttribute(AttributeName = "m", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string M { get; set; }
        [XmlAttribute(AttributeName = "d", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string D { get; set; }
    }

    [XmlRoot(ElementName = "content")]
    public class Content
    {
        [XmlElement(ElementName = "properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
        public Properties Properties { get; set; }
        [XmlAttribute(AttributeName = "type")]
        public string Type { get; set; }
    }

and here is the C# code to convert this to object:
XmlSerializer serializer = new XmlSerializer(typeof(Content));
 Content resultingMessage = (Content)serializer.Deserialize(new XmlTextReader(@"XMLFile1.xml"));

and this is the code to access guid property:
string guid = resultingMessage.Properties.Guid;

hope this solve your problem.
PS: I have created model based on your XML file given, if this XML schema changes you need to modify your model accordingly.
Happy coding...

A: Here is how you can output selective xml nodes to csv file using Cinchoo ETL
var nsManager = new XmlNamespaceManager(new NameTable());
//register mapping of prefix to namespace uri
nsManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
nsManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");

StringBuilder csv = new StringBuilder();
using (var p = ChoXmlReader.LoadText(xml)
        .WithXPath("//entry/content/m:properties")
        .WithXmlNamespaceManager(nsManager)
        .WithField("Guid", xPath: "d:Guid")
        .WithField("ProcessType", xPath: "d:ProcessType")
        .WithField("Description", xPath: "d:Description")
    )
{
    using (var w = new ChoCSVWriter(csv)
        .WithFirstLineHeader()
        )
        w.Write(p);
}

Console.WriteLine(csv);


text:
Q: How to store a list of items in orders table (MySQL) I've got four tables:
Order [orderId, *itemId, totalPrice]
Item [itemId, *orderId, quantity]
Poster [posterId, *orderId, size, material]
Card [cardId, *orderId, size, text]
Item is essentially an abstract table that holds data relevant to every item. All items (posters and cards) have some unique properties.
Two questions:

*

*Is there a way to set up an inheritance relationship between Items table and poster / card? Such that Order table would only accept itemId of a an Item's child?

*An order can have multiple items, so it should hold a list of foreign item keys, rather than just one. How do I tackle that?

A: You can create a table for Items, and set up foreign key constraint in Poster/Card table to Items table.

Is there a way to set up an inheritance relationship between Items table and poster / card? Such that Order table would only accept itemId of a an Item's child?

Set a foreign key constraint on Order table to Item table.

An order can have multiple items, so it should hold a list of foreign item keys, rather than just one. How do I tackle that?

In a a many to one relationship mapping should be stored on one side i.e. Item side in your case not Order side. And if Item table is kind of static you should create a mapping table for managing the relationship between Item and Order, and not keep in Order table.

A: Better you remove itemId and orderId from Order and Item table respectively. Treat them both as Master. As you said an Order can have multiple items, create a third table e.g order_item and create two columns orderId & itemId and refer them to the corresponding master_tables
orderId|itemId|
-------+------+--
   1   |   1  |
   1   |   2  |
   1   |   3  |

This way you can have mulitple Items for single Order and you can do the same for other tables

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql - Check if String A contain String B or Substring B Is there any other way to perform this far from LIKE and REGEX , I am trying to check if string A contain string B or a little part of string B like example below

string A = "United State of America"
string B = "America"

String B should be checked if it exist in String A
Currently i have used REGEXP and LIKE but sometimes it give me false output, please check mycodes below and give any suggestion.
//Using REGEXP
$first_five = substr($data[0], -7, 7);
$query = mysql_query("SELECT * FROM 'football' WHERE 'TEAMS' REGEXP '$first_five'");
//Using LIKE
$query = mysql_query("SELECT * FROM 'football' WHERE 'TEAMS' LIKE '%$first_five%'");`

Any idea which query can perform same job like my above querys??????

A: mysql> SELECT INSTR('foobarbar', 'bar');
+---------------------------+
| INSTR('foobarbar', 'bar') |
+---------------------------+
|                         4 |
+---------------------------+
1 row in set (0.01 sec)

mysql> SELECT INSTR('xbar', 'foobar');
+-------------------------+
| INSTR('xbar', 'foobar') |
+-------------------------+
|                       0 |
+-------------------------+
1 row in set (0.00 sec)

A: First of all: Notice about deprecation warning:

mysql_query Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

In second place:
You should to escape parameters (be careful, also deprecated)
$sql = "SELECT * FROM football WHERE TEAMS LIKE '%" .
        mysql_real_escape_string($first_five) .
        "%'";
$query = mysql_query($sql);


text:
Q: Transport phenomenon What is the difference between heat transfer coefficient and the thermal diffusion coefficient? What is the practical thinking of this? How would we define it practically? Like Imagining the both , I would love to know their physical meanings?

A: The heat transfer coefficient is equal to the heat flux divided by the temperature difference driving force.  The thermal diffusion coefficient (aka thermal diffusivity) is equal to the thermal conductivity divided by the product of density and heat capacity, and is independent of the heat flux and temperature difference; it is a physical property of the material.


text:
Q: Sufficient conditions for derviative of this product to be in $L^2$. Let $I=(l_0,l_1)$, $y \in H^2(I)$ and $\rho(x) \in L^\infty(I)$ with $\rho(x)>c\geq 0$. Define $D_\rho(x)=\rho(x)\chi_{(a_0,b_0)}$ with $l_0\leq a_0<b_0\leq l_1$. Now, For any $\phi \in C_c^\infty(I)$ I have
$$ \left<(D_\rho y')',\phi\right>=\left<D_\rho'y',\phi\right>+\left<D_\rho y'',\phi\right>$$
this means that $(D_\rho y')'=D_\rho'y'+D_\rho y''$ in distributional sense. Since $D_\rho \in L^\infty$ and $y'' \in L^2(I)$ I get $D_\rho y'' \in L^2(I)$. But I can't say anything about $D_\rho'y'$, so I'm here asking for help in trying to figure out which conditions $\rho(x)$ must satisfy in order to guarantee that $D_\rho' y'$ is in $L^2(I)$.
I know that if I assume that $\rho'(x)$ is bounded almost everywhere, then $D_\rho' y' \in L^2(I)$, but this is a very strong condition and I want weak conditions.
I really appreciate any kind of help!

A: I don't know if I am missing something but if $l_0<a_0<b_0<l_1$, then I think that no assumption on $\rho$ can guarantee that the product is in $L^2$. Take $y(x)=x$, then $y'=1$. If $D'_\rho$ were in $L^2$, then the function $D_\rho$ would have to be equal almost everywhere to an absolutely continuous function, see this link ac , but your function has a bad discontinuity at $a_0$ and $b_0$


text:
Q: Does MediatR walk all classes in the project looking for matches? There are two parts to this question. First I am going to explain what I think is happening? And then second, in that explanation, I want to verify how it is finding a class it needs.
This is from Nick Chapsas' program Write cleaner APIs in .NET 7 with MediatR.
This code handles a request using MediatR as follows.
n program.cs it has:
app.MediateGet<ExampleRequest>("example/{name}");

which is called via the extension function:
public static WebApplication MediateGet<TRequest>(
    this WebApplication app,
    string template) where TRequest : IHttpRequest
{
    app.MapGet(template, async (IMediator mediator,
        [AsParameters] TRequest request) => await mediator.Send(request));
    return app;
}

where IHttpRequest is defined as:
public interface IHttpRequest : IRequest<IResult>
{
}

So what has occurred from all this is me have an app.MapGet() call for the url "example/{name}" and it will be handles by MediatR.
ExampleRequest.cs is a POCO containing the URL parameters, etc.
The handler must implement the interface IRequestHandler<ExampleRequest, IResult>. When that url is requested, it will instantiate the appropiate class and call its Handle() method passing in the ExampleRequest and getting a Task returned.
Question 1: Is that correct?
There is the following class in the program that is a handler that implements the require interface. And it is called by MediatR.
public class ExampleHandler : IRequestHandler<ExampleRequest, IResult>
{
    private readonly GuidService _guidService;

    public ExampleHandler(GuidService guidService)
    {
        _guidService = guidService;
    }

    public async Task<IResult> Handle(
        ExampleRequest request, CancellationToken cancellationToken)
    {
        await Task.Delay(10, cancellationToken);
        return Results.Ok(new
        {
            message = $"The age was: {request.Age} and the name was: {request.Name}",
            requestGuid = request.GuidService.Id,
            ctorGuid = _guidService.Id
        });
    }
}

Question 2a: How does MediatR find this class? It is not passed to anything or registered with anything. Does MediatR scan all classes looking for a match?
Question 2b: And if so, what if there are two matches?
Question 2c: Also if so, is there a way to register handler classes to speed up finding them and avoid duplicate matches?

A: 1. Effectively, yes. The idea is that you're tying individual endpoint operations to a responsible request/response handler, for which a concrete implementation class may implement one or several; the endpoint is abstracted from that responsibility and just needs to know about it's own required input and output pair, resolution is handled by MediatR.
2a. Reflection and assembly scanning. The registration process asks for assemblies to scan, and the MediatR library will locate and attempt to register classes that fulfill its interfaces
https://github.com/jbogard/MediatR/blob/master/src/MediatR/Registration/ServiceRegistrar.cs

MediatR supports Microsoft.Extensions.DependencyInjection.Abstractions
directly. To register various MediatR services and handlers:
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssemblyContaining()); or with an
assembly:
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly));
This registers:

*

*IMediator as transient

*ISender as transient

*IPublisher as transient

*IRequestHandler<,> concrete implementations as transient

*IRequestHandler<> concrete implementations as transient

*INotificationHandler<> concrete implementations as transient

*IStreamRequestHandler<> concrete implementations as transient

*IRequestPreProcessor<> concrete implementations as transient

*IRequestPostProcessor<,> concrete implementations as transient

*IRequestExceptionHandler<,,> concrete implementations as transient

*IRequestExceptionAction<,>) concrete implementations as transient

This also registers open generic implementations for:

*

*INotificationHandler<>

*IRequestPreProcessor<>

*IRequestPostProcessor<,>

*IRequestExceptionHandler<,,>

*IRequestExceptionAction<,>

2b. Which takes precedence depends on how you register them, but MediatR will only resolve one IRequestHandler for a given type. The assembly scanner will register the first located handler and will skip any additional ones it finds. If you manually register multiple, it will use the last registered.
2c. Yes. You do not have to use the automated assembly scanning via the registration extensions to register MediatR; you can manually register the implementations of IMediator, ISender, and IPublisher yourself, and then selectively register all of your various handlers manually into the IoC container.


text:
Q: Получение названия repository из которого установлен пакет rpm Всем привет!
Нужна помощь в получении названия репозитория для установленных в системе пакетов.
Я могу получить вот так:
repoquery --installed '*' --queryformat='%{installtime} %{name} %{evr} %{from_repo}'
Я так понимаю что repoquery обращается к базе данных /var/lib/rpm
Моя задача получить такую же информацию в python:

#!/usr/bin/python3

import sys
import rpm
import json
from datetime import datetime

if (len(sys.argv) != 3):
    print ('invalid amount of input arguments!')
    sys.exit()

# user inputs
dbtype = sys.argv[1]
dbpath = sys.argv[2]

# add macro to be used by rpm
rpm.addMacro("_db_backend", dbtype)
rpm.addMacro("_dbpath", dbpath)

# Open database
ts = rpm.TransactionSet()
ts.openDB()

# remove macro for future cases
rpm.delMacro("_db_backend")
rpm.delMacro("_dbpath")

allPackages = []
# retrieve all packages from BDB
mi = ts.dbMatch()

# build JSON object from all packages for easier parsing
for hdr in mi:
    pkgDict = {}
    allPackages.append(pkgDict)
    pkgDict['NAME'] = hdr[rpm.RPMTAG_NAME]
    pkgDict['VERSION'] = hdr[rpm.RPMTAG_VERSION]
    pkgDict['RELEASE'] = hdr[rpm.RPMTAG_RELEASE]
    pkgDict['ARCH'] = hdr[rpm.RPMTAG_ARCH]
    pkgDict['DISTRIBUTION'] = hdr[rpm.RPMTAG_VENDOR]
    pkgDict['OS'] = hdr[rpm.RPMTAG_PLATFORM]
    pkgDict['INSTALLTIME'] = datetime.utcfromtimestamp(hdr[rpm.RPMTAG_INSTALLTIME]).strftime('%Y-%m-%d %H:%M:%S')

print (json.dumps(allPackages, indent=4))

На выходе я получаю:
    {
    "NAME": "kernel-core",
    "VERSION": "4.18.0",
    "RELEASE": "348.el8",
    "ARCH": "x86_64",
    "DISTRIBUTION": "Oracle America",
    "OS": "x86_64-redhat-linux-gnu",
    "INSTALLTIME": "2022-05-26 10:56:39"
}


text:
Q: How to use ESM and TypeScript in Node.js with test coverage I'm trying to use ESM and TypeScript in Node.js v14. This is not hard and exist some questions for it:

*

*How to use ts-node ESM with node modules?

*Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
Try to summarize it in tsconfig.json:
{
  "compilerOptions": {
    "module": "es2022",
    "esModuleInterop": true
  },
  "ts-node": {
    "esm": true
  }
}

If not provide esm: true, you can use ts-node-esm instead of ts-node
For example: npx ts-node-esm my-code.ts

But main problem is that when using nyc, it can't correctly collect the statements/branches that have passed.
I have tried nyc-config-typescript and esm-loader-hook but none of these works.
How can I handle this problems?

A: I have tried to tackle this problem two days and finally "fix" it by using c8
You can see the example by example repo. In the example, I'm using jasmine but you can use other testing framework (e.g. mocha)
as you want.
Finally you can execute testing with coverage by:
npx c8 ts-node jasmine.ts


text:
Q: PHP dump unknown/undefined VARIABLE to file I have the following HTTP data:
POST /forum/post.php HTTP/1.1
Accept: text/xml, text/html, text/plain, */*
Host: myhost.com
Content-Length: 752
Cache-Control: no-cache

LxINAXyIgvOZQBF28yt0/NYmrYy7/dWENDNdFybIqYSWxLS6Ystk1pHfFDEBOJPgfJMWPQwqojMTvLugMOD7ZeXm33WYxFnjhR8C+Q8es49bGp8GiBmU7o3VYvJYKHSsknRXoB9tp9hhnzBJ4RMOhLbIIk5i6QwR8sFHxqUsL+i/8mKJDAcDsXXZcJXlXqhRN7fCDqLb/vTmnSTm+qA2HWU1AsBAGpWoQycRr0BT62lI2H3WnKevGi7fePJdCKWmwp5yoztKYCI3QJKrJbt5f60zb8TR5JHEs2S8ne0e6mssV7N4A3rwE+/O08pfHAmsVVtotpdqkPHWEWr+S7te9r01grfJt6GY0ozH0BPqSkP98wUwlrD385sRzf8M8uOw3hI1DWliZl0ea2Dc4b/7zVfwsqHl94Hk5x2p6nzXaW0vEsAVrodNIIcv3ZGGEkk97BOsHXP1rvJNiQLuM/7D3X9WFX/cYYqnNrIW84rhtbhty04r6JH37G9hPDlHjiYAogQ0lpMubsTNaW35Gn9G7X/qaH4+uQtYDVt67graNB3dDEBQRfXHw/sOM57hlxU/o/Q52RgAcekhGABXsLtXH3Sd5rurYg+qjMtceK9hC37ylXOJ+0bTKVf/A8nLlMarTtGhQK+oG8Rx8juy/USlCvg4++dCXS3qr0pFC9u2tcLAgND0g3tcBN1kYw2Ca4TTxP5m932pBTict7PE0jAXITmOoV3MGFE9AsKMJAVUdRK0sg==

How can I capture the BASE64 data and write it to a file, I tried to dump the $_POST variables but I get nothing, tried with $_REQUEST or serialize($_REQUEST) and all I get is:
Array
(
)

How can I capture an undefined post data? Thanks!

A: It can be found in $HTTP_RAW_POST_DATA:
echo $HTTP_RAW_POST_DATA;

Or:
echo file_get_contents("php://input");

Manual.
You can then write it to a file with file_put_contents() or any of the other methods to write to a file.


text:
Q: Set a minimum order limit for use of wallet "TeraWallet - For WooCommerce" If users try to pay via their wallet, then there should be a minimum order limit. this condition should only be apple only on when the user tries to pay via wallet.
Plugin Name: TeraWallet - For WooCommerce
Plugin URL: https://wordpress.org/plugins/woo-wallet/
hello everyone, If users try to pay via their wallet, then there should be a minimum order limit. this condition should only be apple only on when the user tries to pay via wallet.
Plugin Name: TeraWallet - For WooCommerce
Plugin URL: https://wordpress.org/plugins/woo-wallet/

A: You can try this code which I used on one of my sites:
add_filter( 'woocommerce_available_payment_gateways', 'disable_paypal_below_100' );

function disable_paypal_below_100( $available_gateways ) {
    $minimum = 100;
    if ( WC()->cart->total < $minimum ) {
        unset( $available_gateways['paypal'] ); //replace 'paypal' with 'wallet'
    }
    return $available_gateways;
}

You can extend it to match your requirements.
What does this code do?
This code will check if the order total on checkout is less than 100 then it'll remove PayPal from the payment gateway list.
UPDATE:
To enable the WooWallet as a payment gateway again, you can put this code in the functions.php file of your child theme.:
add_filter('woo_wallet_payment_is_available', '__return_true');


text:
Q: Android RelativeLayout button overlapping I have a layout like this :

i wish to make btn1 vertical align to center and elements under it will push below also. But after i put android:layout_centerVertical in btn1, it was vertical align to center but the element below it is not pushing down.
Layout after i put android:layout_centerVertical="true" in btn1 :

This is my xml:
<RelativeLayout
    android:id="@+id/layout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
                android:id="@+id/btn1"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="1" />

        <Button
                android:id="@+id/btn2"
                android:layout_centerHorizontal ="true"
                android:layout_below="@id/btn1"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Some Text 1" />

            <Button
                    android:id="@+id/btn3"
                    android:layout_below="@id/btn2"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="Some Text 2" />

            <Button
                    android:id="@+id/btn4"
                    android:layout_toRightOf ="@id/btn3"
                    android:layout_alignBottom="@id/btn3"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="Some Text 3" />

    </RelativeLayout>

</RelativeLayout>

I know that if i assign sufficient height in parent layout it will work normally but later on i will make this form as dynamically generate. Any way to make it automatically pushing down with wrap_content?

A: <RelativeLayout
    android:id="@+id/layout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
                android:id="@+id/btn1"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="1" />

        <Button
                android:id="@+id/btn2"
                android:layout_centerHorizontal ="true"
                android:layout_below="@id/btn1"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Some Text 1" />

            <Button
                    android:id="@+id/btn3"
                    android:layout_below="@id/btn2"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="Some Text 2" />

            <Button
                    android:id="@+id/btn4"
                    android:layout_toRightOf ="@id/btn3"
                    android:layout_alignBottom="@id/btn3"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="Some Text 3" />

    </RelativeLayout>

</RelativeLayout>

add centerInParent value to your relative layout as shown above

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true">

</RelativeLayout>

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/relativeLayout"
    android:layout_alignBottom="@+id/relativeLayout"
    android:layout_centerHorizontal="true"
    android:text="1" />

<Button
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/relativeLayout"
    android:layout_centerHorizontal="true"
    android:text="Some Text 1" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/btn2"
    android:layout_centerHorizontal="true">

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some Text 2" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/btn3"
        android:layout_toRightOf="@id/btn3"
        android:text="Some Text 3" />

</RelativeLayout>

A: Try this,
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/layout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="1" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/btn1"
            android:layout_centerHorizontal="true"
            android:text="Some Text 1" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/btn2"
            android:layout_centerHorizontal="true">

            <Button
                android:id="@+id/btn3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Some Text 2" />

            <Button
                android:id="@+id/btn4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/btn3"
                android:text="Some Text 3" />
        </RelativeLayout>

    </RelativeLayout>

A: Just remove your second relative layout or set that layout height and width to match_parent!


text:
Q: How to get all questions which have an answer by a specified user and with no accepted answer? I want to create a query in SE Data Explorer which does the follows:

Get all questions which have (at least) an answer by a specified user and with no accepted answer (by anyone).

I have never written such code and the documentation is lacking. Here is the line I mustered from examples and the slight documentation there is:
SELECT a.id AS [Post Link] FROM Posts a WHERE a.OwnerUserId = ##UserId## and PostTypeId = 2

This Gets all questions which have (at least?) an answer by a specified user, but I can't manage to filter only those with no accepted answer.
The type Posts has AcceptedAnswerId int, but no matter what int I put, I get nothing back. I couldn't even find what this property means or what values are legitimate. For PostTypeId I just tried and found that 1 is questions and 2 is answers.
I have also looked at the type Type question and found accepted_answer_id with no documentation as to what it is. Moreover, I don't understand how to use these question types (using FROM Questions gives an error) or if these the right way to go. I do know I retrieve them by calling one of of the "Methods That Return This Type".
Lastly, I wonder if what I wrote is even a correct approach. Is the order in which filters are applied matter or do they apply simultaneously? What is the "best practice" way of doing the call I want?

A: At the moment you only look at the posts of a user. But you need to get the AcceptedAnswerId field of the corresponding question. This field qoul be null if the question has no accepted answer until now. I edited your query by adding a JOIN on the Posts table to get the question and the questions' AcceptedAnswerId field.
SELECT q.Id as [Post Link]
  FROM Posts a
    JOIN Posts q on a.ParentId = q.Id
  WHERE a.OwnerUserId = ##UserId##
    and a.PostTypeId = 2
    and q.AcceptedAnswerId is null

At this point you could also exclude closed questions by adding and ClosedDate is null
You can also find and try my solution at the dataexplorer.


text:
Q: How to remove dots from a string in Java? In my program I want to remove all the dots(.) I've tried to do this but it's not working.
public class MyClass {
        public static void main(String args[]) {
            String str = " .Hello.World..Awesome!. ";
            System.out.println(str.replaceAll(".",""));
        }
    }

A: Replace all takes a regex as the first argument and you need to escape "." like
"\\."
str.replaceAll("\\.","")

A: This is not working because . is a special regex character. You must escape this using a backslash. The dot is used as a capture all in regex.
System.out.println(str.replaceAll("\\.",""));

You can read up on all of the special characters in regex here - https://www.regular-expressions.info/characters.html


text:
Q: Symfony2: intention of the TypeTestCase Since my last 3 attempts to implement a TypeTestCase all failed, I began to wonder about the intention of TypeTestCases like they were described in the doc.
The last one failed with errors like

*

*Could not load type "entity"

*The option "invalid_message" does not exist. Known options are: "a[...]

*The option "constraints" does not exist. Known options are: "ac[...]

Errors like the last 2 ones made me wonder if the Idea of having a TypeTestCase isn't really finished yet.
So what I want to know is, how to test Custom FormTypes most efficiently. (e.g. the following form)
namespace Acme\UserBundle\Form\Type;

use Acme\UserBundle\Entity\Legalform;
use Acme\UserBundle\Entity\User;

use Acme\UserBundle\Repository\LegalformRepository;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Validator\Constraints\NotBlank;

class RegistrationFormType extends BaseType
{
   [...] // constructor  + dep. Injection etc.

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'salutation',
            'choice',
            array(
                'empty_value' => 'Anrede',
                'constraints' => new NotBlank(),
                'choices' => array(
                    User::ENUM_FRAU => User::ENUM_FRAU,
                    User::ENUM_HERR => User::ENUM_HERR
                )
            )
        );
        [...]
        $builder->add(
            'password',
            'repeated',
            array(
                'required' => true,
                'type' => 'password',
                'first_options' => array('label' => 'fkjgkdgfskdhfsg'),
                'second_options' => array('label' => false),
                'invalid_message' => 'Die Passwörter stimmen nicht überein.'
            )
        );
        [...]

        $siteId = getMeSomeSiteId();
        $builder->add(
            'companyLegalForm',
            'entity',
            array(
                'class' => 'MyHammerUserBundle:LegalForm',
                'query_builder' => function (LegalformRepository $repository) use ($siteId) {
                    $queryBuilder = $repository->createQueryBuilder('l');
                    $queryBuilder->where('l.site = :site');
                    $queryBuilder->setParameter('site', $siteId);

                    return $queryBuilder;
                },
                'property' => 'title',
                'empty_value' => 'Rechtsform',
                'required' => true
            )
        );
    }
}

My TypeTestCase:
namespace Acme\UserBundle\Form;

use Acme\UserBundle\Entity\Legalform;
use Acme\UserBundle\Entity\User;
use Acme\UserBundle\Form\Type\RegistrationFormType;
use Symfony\Bridge\Doctrine\Tests\DoctrineOrmTestCase;
use Symfony\Component\Form\Test\TypeTestCase;

class RegistrationFormTypeTest extends TypeTestCase
{
    public function testSubmitValidData()
    {
        $formData = array(
            'companyLegalForm' => $this->getLegalformFake(),
            'salutation' => 'Herr',
            'password' => array(
                'first' => 'esellese14',
                'second' => 'esellese14'
            )
        );

        $query = $this->getMockBuilder('Doctrine\ORM\AbstractQuery')
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $query->expects($this->once())
            ->method('execute')
            ->will($this->returnValue(array($this->getLegalformFake())));

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $queryBuilder->expects($this->once())
            ->method('getQuery')
            ->will($this->returnValue($query));

        $legalformRepository = $this->getMockBuilder('Acme\UserBundle\Repository\LegalformRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $legalformRepository->expects($this->once())
            ->method('getQueryBuilderForRegistration')
            ->with(1)
            ->will($this->returnValue($queryBuilder));

        $type = new RegistrationFormType('Acme\UserBundle\Entity\User', $legalformRepository);
        $form = $this->factory->create($type);

        $object = new User();
        $object->fromArray($formData);

        // submit the data to the form directly
        $form->submit($formData);

        $this->assertTrue($form->isSynchronized());
        $this->assertEquals($object, $form->getData());

        $view = $form->createView();
        $children = $view->children;

        foreach (array_keys($formData) as $key) {
            $this->assertArrayHasKey($key, $children);
        }
    }

    /**
     * @return Legalform
     */
    private function getLegalformFake()
    {
        $legalform = new Legalform();
        $legalform->setId(1);
        $legalform->setTitle('wuff');
        return $legalform;
    }
}

My solution for now is to write a common unittest with asserting, that $builder->add() has been invoked correctly for all my formfields. Any Ideas?


text:
Q: How to put QgsCheckableComboBox() into standby I'm trying QgsCheckableComboBox() in my simple python script in QGIS. How to pause code execution while a comboBox-window is open (like a dialog box)? In my example, I want to ensure that the print() function is executed only after the comboBox-window is closed. Then the checkedItems list will not be empty and will contain the selected lines ("Venus", "Earth", "Mars"). How can I achieve this?
from qgis.PyQt import QtGui
from qgis.core import *

planet_list = ["Venus", "Earth", "Mars", "Jupiter", "Pluto"]
items = QgsCheckableComboBox()
items.addItems(planet_list)
items.showNormal()

print('\n\n-----------CheckedItems: ', items.checkedItems())

A: You can add the combobox to a dialog window. After closing the dialog, print prints the selected items.
from qgis.PyQt import QtGui
from qgis.core import *

planet_list = ["Venus", "Earth", "Mars", "Jupiter", "Pluto"]
items = QgsCheckableComboBox()
items.addItems(planet_list)

dlg = QDialog()
layout = QVBoxLayout()
layout.addWidget(items)
dlg.setLayout(layout)
dlg.exec_()

print('\n\n-----------CheckedItems: ', items.checkedItems())


text:
Q: Git does not ignore directory I'm trying to figure out why git does not ignore a directory (virtual environment). Before adding and pushing files, I've created a .gitignore file which contains the line: venv/
Then I did:
git add .
git commit
git push -u origin --all

As you can see, it's there:
Why is the directory not ignored, and how can I ignore it?

A: Remove the folder from being tracked locally...
git rm -r --cached folderName


text:
Q: Reserve BufferOverflow.com BufferOverflow.com is currently unregistered, and can be reserved. Possibly for "defensive registration", as Spudley suggests in the comment below. Until there's a use for it, it can be a redirect to StackOverflow.com.

A: Let's see...
bufferunderrun.com
stackoverflows.com
stack-overflow.com (hyphenated!)
nullreferenceexception.com
nullpointerexception.com
outofstackspace.com
accessviolation.com
undefined.com

Why again do you think bufferoverflow is special??

99.9% of stackoverflow/stackexchange traffic doesn't come from manually typing the URL. And of the 0.1%, 99% of the people who will type it actually know the correct name, and no sane person will go to bufferoverflow.com for no reason expecting to find help on the other end.


text:
Q: How do i animate scrollview? How can I create such animations or custom transitions in scroll view. You can see the expected animation in the GIF : https://gfycat.com/EveryBackLhasaapso
Expecting:
On longpress over the scrollview, it needs to get expand like the gif animation and the icon also need to get zoomin.
I have tried to attain this using a scrollview, but the animation doesn't matches as expected.
UIView.animate(withDuration: 0.2, delay: 0.2, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
            self.scrollViewHeight.constant = isExpanded == true ? ViewConstants.collectionViewHeightWithExpand : ViewConstants.collectionViewHeightWithcollapse
            self.scrollContentViewHeight.constant = isExpanded == true ? ViewConstants.collectionViewHeightWithExpand : ViewConstants.collectionViewHeightWithcollapse
            self.scrollContentView.transform = isExpanded == true ? CGAffineTransform(scaleX: 1.20, y: 1.20) : CGAffineTransform.identity
             self.view.layoutIfNeeded()
        }) { _ in}

A: Now run your application.
self.scrollViewHeight.constant = isExpanded == true ? ViewConstants.collectionViewHeightWithExpand : ViewConstants.collectionViewHeightWithcollapse
self.scrollContentViewHeight.constant = isExpanded == true ? ViewConstants.collectionViewHeightWithExpand : ViewConstants.collectionViewHeightWithcollapse

UIView.animate(withDuration: 0.2, delay: 0.2, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
             self.scrollContentView.transform = isExpanded == true ? CGAffineTransform(scaleX: 1.20, y: 1.20) : CGAffineTransform.identity
             self.view.layoutIfNeeded()
        }) { _ in}


text:
Q: Implementing a method of interface is overriding or not in java I know this might be crazy but today one of my friend puzzled by asking when we implement an interface in java is it considered as method overriding. I told him it is not overriding as we are providing working(definition) of method first time when we implement any interface. To support multiple inheritance java provide interface but he was not convinced and was arguing. Please bring some light on to the topic.

A: The term "overriding" applies when there is an existing implementation of the method . The correct term is "implementing" for interfaces and other abstract declarations.
The @Override tag is used for both cases - it is used when:

The method does override or implement a method declared in a supertype.  --javadocs

And from Wikipedia:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

Note that interfaces can have default methods - redefining these methods overrides them:

When you extend an interface that contains a default method, you can ... redefine the default method, which overrides it.

Besides linking to "canonical" sources, I'm not sure what advice to offer on winning a semantic argument with your friend. Perhaps you could ask him what the distinction is between "implementing" and "overriding", and what word he would use instead of "overriding" for the concept of redefining an existing method.

A: At first glance, interfaces just define API. Since there is no super method to override, the implementations is the first method.
But since Java 5, it's customary to add @Override annotations even for methods which come from interfaces. The main reason here is to catch problems which happen when people change an interface: Now you have a method which is "dangling" - there is no API which says that the method has to be there. The annotation causes an error if you remove a method from the interface, catching this so you can properly clean up all the code.
But that still doesn't mean the implementing method overrides anything.
Except that an interface is very much an abstract class with abstract methods in the byte code. And abstract methods do override.
My feeling is that you can argue both ways but the argument is moot unless you have a use case there the answer to the question actually has a real impact on the code. And here, it doesn't really matter since the compiler hides all the ugly details.


text:
Q: Installed fonts are not viewable on my machine I am building a website and just noticed that common web fonts are not viewable in my browsers.
There are numerous fonts installed in /usr/share/fonts. There are folders for cmap, truetype, opentype, type1 and X11. All of the fonts in those folders are installed. But when I try to build a page and use those fonts specifically, they are not viewable or usable.  They are also not viewable on my machine anywhere. It seems my whole machine, including browsers, only use 3 fonts, one generic serif, one generic sans-serif and one generic monospace. That's it.
The installed fonts only seem to work in LibreOffice and MuseScore (a music writing program)
How do I make the installed fonts viewable in my browsers to view my webpages?
I already know how to use Google Fonts. I want to know how to use the fonts already on my machine, and fonts that would already be on other people's machines.


text:
Q: Underscores do not get displayed with SendInput On C++ This is my first question I have posted on stackoverflow. I have been looking into SendInput for C++ in order to have my program 'type' into another program. I decided to start out by having it 'type' in a couple words with underscores into the terminal. I found no problem having it type upper and lowercase letters, as well as a period. But after getting to the underscore, typing in the number id 95 for the underscore letter, the underscore did not display, and acted completely like that letter was never pressed. Here is the code that I got off of cplusplus.com to that I based it off of, it is fully functional:
#include <iostream>
#include <windows.h>
using namespace std;

/* HWND = "Window Handle" */
HWND GameWindow = FindWindow(0, "Command Prompt");

/* This is a function to simplify usage of sending keys */
void GenerateKey(int vk, BOOL bExtended) {

    KEYBDINPUT  kb = {0};
    INPUT       Input = {0};

    /* Generate a "key down" */
    if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
    kb.wVk  = vk;
    Input.type  = INPUT_KEYBOARD;
    Input.ki  = kb;
    SendInput(1, &Input, sizeof(Input));

    /* Generate a "key up" */
    ZeroMemory(&kb, sizeof(KEYBDINPUT));
    ZeroMemory(&Input, sizeof(INPUT));
    kb.dwFlags  =  KEYEVENTF_KEYUP;
    if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
    kb.wVk = vk;
    Input.type = INPUT_KEYBOARD;
    Input.ki = kb;
    SendInput(1, &Input, sizeof(Input));

    return;
}

int main() {

    /*
       SetForegroundWindow will give the window focus for the
       keyboard/mouse! In other words, you don't have to have
       the game opened upfront in order to emulate key/mouse
       presses, it's very helpful if it's a game that runs
       in fullscreen mode, like StarCraft: Brood War does
    */

    SetForegroundWindow(GameWindow);

    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('I', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('A', FALSE);
    GenerateKey('M', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('C', FALSE);
    GenerateKey('O', FALSE);
    GenerateKey('O', FALSE);
    GenerateKey('L', FALSE);
    GenerateKey('E', FALSE);
    GenerateKey('R', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('T', FALSE);
    GenerateKey('H', FALSE);
    GenerateKey('A', FALSE);
    GenerateKey('N', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('Y', FALSE);
    GenerateKey('O', FALSE);
    GenerateKey('U', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('W', FALSE);
    GenerateKey('I', FALSE);
    GenerateKey('L', FALSE);
    GenerateKey('L', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('E', FALSE);
    GenerateKey('V', FALSE);
    GenerateKey('E', FALSE);
    GenerateKey('R', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey('B', FALSE);
    GenerateKey('E', FALSE);
    GenerateKey('n', FALSE);
    GenerateKey(' ', FALSE);

    GenerateKey(0x3A, FALSE); /* period key */
    GenerateKey(0x0D, FALSE); /* enter key */

    return 0;
}

And this is the code that I made that ran incorrectly:
#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

/* HWND = "Window Handle" */
HWND GameWindow = FindWindow(0, "Command Prompt");

/* This is a function to simplify usage of sending keys */
void GenerateKey(int vk, BOOL bExtended) {

    KEYBDINPUT  kb = {0};
    INPUT       Input = {0};

    /* Generate a "key down" */
    if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
    kb.wVk  = vk;
    Input.type  = INPUT_KEYBOARD;
    Input.ki  = kb;
    SendInput(1, &Input, sizeof(Input));

    /* Generate a "key up" */
    ZeroMemory(&kb, sizeof(KEYBDINPUT));
    ZeroMemory(&Input, sizeof(INPUT));
    kb.dwFlags  =  KEYEVENTF_KEYUP;
    if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
    kb.wVk = vk;
    Input.type = INPUT_KEYBOARD;
    Input.ki = kb;
    SendInput(1, &Input, sizeof(Input));

    return;
}

int main() {

    /*
       SetForegroundWindow will give the window focus for the
       keyboard/mouse! In other words, you don't have to have
       the game opened upfront in order to emulate key/mouse
       presses, it's very helpful if it's a game that runs
       in fullscreen mode, like StarCraft: Brood War does
    */

    SetForegroundWindow(GameWindow);

    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('N', FALSE);
    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('I', FALSE);
    GenerateKey('N', FALSE);
    GenerateKey('J', FALSE);
    GenerateKey('A', FALSE);
    GenerateKey(0xBE, FALSE);   // GenerateKey(0x3A, FALSE); did not work
    GenerateKey(' ', FALSE);
    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('H', FALSE);
    GenerateKey(VK_CAPITAL, TRUE);
    GenerateKey('I', FALSE);
    GenerateKey('1', FALSE);
    GenerateKey('2', FALSE);
    GenerateKey('3', FALSE);
    GenerateKey(95 , FALSE);   // GenerateKey('_', FALSE); did not work either
    GenerateKey('4', FALSE);
    GenerateKey('5', FALSE);
    GenerateKey('6', FALSE);
    return 0;
}

This outputs Ninja. Hi123456 instead of Ninja. Hi123_456.
Other things worthy of note:
1). For the period ('.') being 'typed' out the working id was 0xBE instead of 0x3A.
2). This was compiled on Windows 10 using Mingw.
I hope this was thorough enough, thank you in advance!

A: Virtual Key Code 0x3A is not a period character.  In fact, per Microsoft's documentation, 0x3A is NOT EVEN DEFINED at all.  For a period character, you must use VK_OEM_PERIOD instead:

VK_OEM_PERIOD
  0xBE
For any country/region, the '.' key

That being said, calling SendInput() with cInputs=1 is usually a logic bug. Certainly ALWAYS a bug when you are sending multiple input events back-to-back, as your example code is doing.  The whole reason SendInput() exists at all is to replace keybd_event() (and mouse_event()), which can only send one input event at a time.  When simulating multiple events, you don't want other events getting injected in between your events, and vice versa.  SendInput() is atomic with other input mechanisms, but when sending multiple events, that atomicity is only guaranteed when you send all of your events at one time.
You should put your INPUTs into an array and call SendInput() ONCE, with cInputs set to the total number of INPUTs you are sending.
Also, when sending key input for text characters, use need to use VkKeyScan/Ex() to get the correct virtual key code and shift state, though it is a lot easier to use the KEYEVENTF_UNICODE flag instead so you can send actual Unicode characters instead of virtual key codes.
Try something more like this instead:
#include <iostream>
#include <vector>
#include <string>
#include <windows.h>

/* HWND = "Window Handle" */
HWND GameWindow = FindWindow(NULL, TEXT("Command Prompt"));

void GenerateKeyDown(std::vector<INPUT> &inputQueue, int vk, bool bExtended = false)
{
    INPUT in = {};

    in.type = INPUT_KEYBOARD;
    in.ki.wVk = vk;
    if (bExtended) in.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    inputQueue.push_back(in);
}

void GenerateKeyUp(std::vector<INPUT> &inputQueue, int vk, bool bExtended = false)
{
    INPUT in = {};

    in.type = INPUT_KEYBOARD;
    in.ki.wVk = vk;
    if (bExtended) in.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
    in.ki.dwFlags |= KEYEVENTF_KEYUP;

    inputQueue.push_back(in);
}

void GenerateKey(std::vector<INPUT> &inputQueue, int vk, bool bExtended = false)
{
    INPUT in[2] = {};

    in[0].type = INPUT_KEYBOARD;
    in[0].ki.wVk = vk;
    if (bExtended) in[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

    in[1] = in[0];
    in[1].ki.dwFlags |= KEYEVENTF_KEYUP;

    inputQueue.insert(inputQueue.end(), in, in+1);
}

void GenerateString(std::vector<INPUT> &inputQueue, const std::wstring &str)
{
    int len = str.length();
    if (len == 0) return;

    inputQueue.reserve(inputQueue.size()+(len*2));

    INPUT in = {};
    in.type = INPUT_KEYBOARD;
    in.ki.dwFlags = KEYEVENTF_UNICODE;

    int i = 0;
    while (i < len)
    {
        WORD ch = (WORD) str[i++];

        if ((ch < 0xD800) || (ch > 0xDFFF))
        {
            in.ki.wScan = ch;
            in.ki.dwFlags &= ~KEYEVENTF_KEYUP;
            inputQueue.push_back(in);

            in.ki.dwFlags |= KEYEVENTF_KEYUP;
            inputQueue.push_back(in);
        }
        else
        {
            WORD ch2 = (WORD) str[i++];

            in.ki.wScan = ch;
            in.ki.dwFlags &= ~KEYEVENTF_KEYUP;
            inputQueue.push_back(in);

            in.ki.wScan = ch2;
            inputQueue.push_back(in);

            in.ki.wScan = ch;
            in.ki.dwFlags |= KEYEVENTF_KEYUP;
            inputQueue.push_back(in);

            in.ki.wScan = ch2;
            inputQueue.push_back(in);
        }
    }
 }

int main()
{
    /*
       SetForegroundWindow will give the window focus for the
       keyboard/mouse! In other words, you don't have to have
       the game opened upfront in order to emulate key/mouse
       presses, it's very helpful if it's a game that runs
       in fullscreen mode, like StarCraft: Brood War does
    */

    SetForegroundWindow(GameWindow);

    std::vector<INPUT> inputQueue;

    /*
    GenerateString(inputQueue, L"I Am cooler than you will ever ben .");
    GenerateKey(inputQueue, VK_RETURN);
    */

    GenerateString(inputQueue, L"NInja. HI123_456");

    /* alternatively:

    GenerateString(inputQueue, L"NInja");
    GenerateKey(inputQueue, VK_OEM_PERIOD);
    GenerateString(inputQueue, L" HI123");

    // see why using KEYEVENTF_UNICODE is easier?
    SHORT ret = VkKeyScanW(L'_');
    BYTE vk = LOBYTE(ret);
    BYTE shift = HIBYTE(ret);
    if (vk != -1)
    {
        SHORT state = GetKeyState(VK_SHIFT);
        bool bIsDown = (state & 0x800);

        if (shift & 1)
        {
            if (!bIsDown)
                GenerateKeyDown(inputQueue, VK_SHIFT);
        }
        else
        {
            if (bIsDown)
                GenerateKeyUp(inputQueue, VK_SHIFT);
        }

        GenerateKey(inputQueue, vk);

        if (shift & 1)
        {
            if (!bIsDown)
                GenerateKeyUp(inputQueue, VK_SHIFT);
        }
        else
        {
            if (bIsDown)
                GenerateKeyDown(inputQueue, VK_SHIFT);
        }
    }

    GenerateString(inputQueue, L"456");
    */

    SendInput(inputQueue.size(), &inputQueue[0], sizeof(INPUT));

    return 0;
}


text:
Q: How to handle drag events on iphone and ipad with javascript/jquery? I have a little app that has been under development for some time. My friends and I have been working really hard on this and are near release of the beta version.
I want to give some demos using iPhone and iPad to look cool :p
Now my problem is how to handle:

*

*Mouse Down

*Mouse Up

*Mouse Leave

The multitouch interface of the iPhone (which I expect is similar to the iPad) handles mouse move on a browser has a scrolling event. One could try to capture the scrolling event and use it to simulate the dragging but I don't even know if it will be doable or if it will only be a hack.
Any one knows of a more robust manner to manage dragging events on the iphone/ipad?

A: Apple's Developer pages have a lot of good info on handling just these types of issues.
Handling Events

A: I was having the same problem and I realized that in the short time-span I had, developing codes to handle raw mouse (down, move and up) events would take time. So, I went ahead and modified the ThreeDumsMedia jQuery.event.drag plugin to make it to work on iPhone.
Get the jQuery.event.drag from http://www.shamasis.net/2011/06/javascript-drag-events-on-iphone-and-other-touch-based-devices/ and the 'drag' event would work just fine on iOS devices.
let me know if this helped.

A: Try this :
jquery.event.drag - v 2.2
Three Dub Media - http://threedubmedia.com

A: If you are using jQuery, then use jquery.ui.mouse.touch.js with jquery UI 1.9.


text:
Q: failed to send the qLaunchSuccess packet, can't debug in the device When I run the application, it is installed in the device, but will crash immediately. I want to debug in the device, below is the information:

error: failed to launch
  '/Users/wujinjin/Library/Developer/Xcode/DerivedData/化龙巷-gyktkapynghuobbqslisrornfrut/Build/Products/Debug-iphoneos/化龙巷.app/化龙巷'
  -- failed to send the qLaunchSuccess packet

information from device:

Exception Type:  00000020 Exception Codes: 0x8badf00d Highlighted
  Thread:  0
Application Specific Information: 化龙巷 failed to launch in time
Elapsed total CPU time (seconds): 20.030 (user 17.830, system 2.200),
  100% CPU  Elapsed application CPU time (seconds): 0.000, 0% CPU
Backtrace not available
Unknown thread crashed with unknown flavor: 5, state_count: 1
Binary Images: 0x2fe00000 - 0x2fe25fff  dyld armv7
   /usr/lib/dyld

A: I was having the same error "-- failed to send the qLaunchSuccess packet"
I was able to fix by setting the Code Signing Entitlements to "iPhone Developer"
(I was using distribution by mistake)

A: Restart the device. Worked for me.

A: By accident I found a real simple and always working solution for this issue that happens constantly.
First thing to know is that it happens when I run the code on the real device while in debugging mode, then make some changes to the code in XCode while still running the app with some breakpoints, stop the running application and immediatly(!) start debugging the edited code on the iOS device. Don't do that! Instead give XCode some time (a few seconds) to quit the app properly.
If it is has been occurred already stop the debbuger from running. Wait for the app to quit properly on the device, this may take some seconds. On the device double-press the home button and quit the app in the task bar by tapping the red (-). Then run the debugger, stop it immediatly without finishing the compilation and wait for XCode to stop all tasks (you may omit this step). Then everything should be fine and you can start debbuging on the device without the need for a restart. It seems that it is essential for XCode to cleanup everything after it has been stopped while debugging with breakpoints so always give it a few seconds to finish properly. Maybe it sounds like some sort of magic trick but until now it always works for me without the need for a restart.

A: Go to your Target's info, and at the bottom, remove the checkmark for "Entitlement". Worked for me.

A: I see this error all the time IF I was stopped due to a breakpoint and I just hit the run button (not the debugger's resume button).  If I remember to hit stop before rerunning, I don't get the error.  I can't turn off entitlement as the app I'm developing is one that will be using iCloud.  Also, I can prevent the problem by resuming the app so that whatever Run does to stop an executing program handles it cleanly.

A: I solved it by

*

*remove derived data,

*quit Xcode,

*kill app on device,

*start Xcode again.

However this problem continues to happen for me, 0-4 times per week. A permanent solution to this problem would be nice.

A: my application was not getting launched on iPad but working normally on iPhone. I enabled entitlements and specified code signing entitlements as "iPhone Developer", then cleaned, restarted iPad and installed thru Xcode/cable directly on iPad and now its working as expected.


text:
Q: Sort table row with jquery I'm trying to sort table row using jquery which has function like this:
                var items = $('#dp_content_table > tbody > tr').sort(function(a, b) {
                    var vA = $(a).attr('id');
                    var vB = $(b).attr('id');

                    var arrA = vA.split('_');
                    var arrB = vB.split('_');

                    return (arrA[1] < arrB[1]) ? -1 : (arrA[1] > arrB[1]) ? 1 : (arrA[1] == arrB[1] && arrA[5] < arrB[5]) ? -1 : (arrA[1] == arrB[1] && arrA[5] > arrB[5]) ? 1 : 0;
                });

                    $('#dp_content_table > tbody > tr').append(items);

Basically, I'm using ID as attribute for sorting. The attribute contain day & time. attr[1] is day, and attr[5] is time. If day in row A is less than B, then no need for comparing the time, and return result, on the other hand, if days are same, then compare the second attribute which is the time, and so on.
But, so far I have no luck in sorting them. My table seems doesn't take effect at all.
Thanks before.

A: You can compare dates in jquery. Maybe it may help you.
https://stackoverflow.com/a/18913695/3617531
Anyway, in your code, you are using split, and then you are doing a string comparison, not a number one. You maybe should convert them to integers:
            var items = $('#dp_content_table > tbody > tr').sort(function(a, b) {
                var vA = $(a).attr('id');
                var vB = $(b).attr('id');

                var arrA = vA.split('_');
                var arrB = vB.split('_');

                return (parseInt(arrA[1]) < parseInt(arrB[1])) ? -1 : (parseInt(arrA[1]) > parseInt(arrB[1])) ? 1 : (parseInt(arrA[1]) == parseInt(arrB[1]) && parseInt(arrA[5]) < parseInt(arrB[5])) ? -1 : (parseInt(arrA[1]) == parseInt(arrB[1]) && parseInt(arrA[5]) > parseInt(arrB[5])) ? 1 : 0;
            });

                $('#dp_content_table > tbody > tr').append(items);

A: jQuery's sort is the built–in Array.prototype.sort, the values passed to it are the DOM elements returned by the selector, so very much more efficient to replace $(a).attr('id') with a.id. And much less to type as well.
If the IDs are ISO 8601 format date strings, they can be sorted as strings without converting to numbers or dates:

   2015-05-16T10:00:00.000Z

   2015-05-16T09:00:00.000Z

   2015-05-16T11:00:00.000Z

However, the id really shouldn't be used like that, much better to have the values in a data* attribute as you may wish to have identical values.
Edit
Add link to jsperf.


text:
Q: Can't send SSH key to Github with cURL I'm trying to send my public ssh key to Github. I set my key to a variable in shell but it gives key is invalid. You must supply a key in OpenSSH public key format error. I have authentication to send key but it doesn't work.
Lines that star with ➜  ~ are commands and rest are output.
➜  ~ key=$(cat .ssh/id_0001.pub)
➜  ~ echo $key
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDCk9BFg0PyDeOn186G+gx16KjeYPekGlPppNcg1shjqzVSppNJHXy08GqBNgxN14TU3UzQyRej6BjSi0YGlWVZAz1tDedaFsauwCYYRIO9Aej7HJcmU9V8Sv9npWBGjQZTS/KYRg790xo8zueoCzCXR+Sufxy6yn5xee+e938nkdY0O+/Lxv/3Ks6IQpvJlCOYdvvUC1liIQWd2nxc9T3vtjWtslG5/Yq4PzBT4ja5A0xMNerCrIXf7e7m+DtV2jIESYCwYMBOAioRdSDHIGHL4YOoikYeebUFe1ajTalZYEmsFW/0yu6GEhvoe9FP1IhPIN5nPI6h3EJWDDEpOOI6IdG4Ex5Slzg+TRYG6CoUhRb1d/iQrcSzdibP450GrqxaSMZicmOEj/7w6SvItd1qJ+my3W1RZmGhRQ8CaXMpZvJERFdS2tAmO42r3IC24Xe7ZU+vvlxgS+H7F19kAWWhL8Q8OGFmC9Zs5gkci/jxG6f7Wlnd35UHJ9VreCQl/t0= archie@PC
➜  ~ curl -H "Authorization: token 90********************" --data '{"title":"test-key","key":"${key[@]}"}' https://api.github.com/user/keys
{
  "message": "Validation Failed",
  "errors": [
    {
      "resource": "PublicKey",
      "code": "custom",
      "field": "key",
      "message": "key is invalid. You must supply a key in OpenSSH public key format"
    }
  ],
  "documentation_url": "https://docs.github.com/rest/reference/users#create-a-public-ssh-key-for-the-authenticated-user"
}

A: This is for Windows users, there are two things to consider

*

*your console should parse quotation and double quotation in the right order.

*curl needs quotation for JSON properties and keys.

So how can we debug it:

*

*Add "-v --trace-ascii -" to the curl command to see log for command.

*Use  echo or write-host for your data in cmd or PowerShell

Example for Windows PowerShell
$publicKey =Get-Content -Path "$HOME\.ssh\github.pub"

$data='{""title"":""script"",""key"":""' + $publicKey + '""}'

curl -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $userToken"  https://api.github.com/user/keys  -d $data -v --trace-ascii -

It is so important to make sure that curl receives valid JSON data.

A: I meet the same problem. I think you not correctly to generate a new SSH key. After you typing ssh-keygen -t rsa -C "your email@163.com", you will see that in follow.And you should use clip < ~/.ssh/id_rsa.pub to copy the keys.


text:
Q: ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=3 After inquiring into the questions already asked about this problem, I keep presenting it. Im trying to classify letters from A to D. All input images are 64x64 and graycolor.
The first layer of my CNN is:
model = Sequential()
model.add(Conv2D(32, (3,  3), input_shape = input_shape, activation = 'relu'))

And input_shape it's coming from:
# Define the number of classes
num_classes = 4
labels_name={'A':0,'B':1,'C':2,'D':3}

img_data_list=[]
labels_list=[]

for dataset in data_dir_list:
    img_list=os.listdir(data_path+'/'+ dataset)
    print ('Loading the images of dataset-'+'{}\n'.format(dataset))
    label = labels_name[dataset]
    for img in img_list:
    input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )
          input_img=cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
          input_img_resize=cv2.resize(input_img,(128,128))
          img_data_list.append(input_img_resize)
          labels_list.append(label)

img_data = np.array(img_data_list)
img_data = img_data.astype('float32')
img_data /= 255
print (img_data.shape)

labels = np.array(labels_list)
print(np.unique(labels,return_counts=True))

#convert class labels to on-hot encoding
Y = np_utils.to_categorical(labels, num_classes)

#Shuffle the dataset
x,y = shuffle(img_data,Y, random_state=2)

# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

#Defining the model
input_shape=img_data[0].shape
print(input_shape)

A: Conv2d expects input of  shape (batchsize, w, h, filters).
You need to add a reshape to fit the data before the conv layer:
 model.add(Reshape((64, 64, 1)))

This will set your model dimensions to [None, 64,64,1] and should be fine for Conv2d.

A: The CNN model needs a data set with dimensions greater when used multiple layer(Convolutional layers and pooling). To avoid the negative dimensional problems increase the image dimensions or reduce the CNN layers. It works..


text:
Q: Show that choosing any rational number in (0,1) has probability 0.
In the above proof, why is the last step necessary:

Why isnt saying that the probability of  any one number being chosen is 0, enough to prove that the probability of choosing a rational number is 0?
Is it because if two rational numbers have different probabilities associated, the total probability would be  more than 0? I think I just answered the question myself, but I just want to make sure I'm understanding this right.

A: It's important that the union is countable. When looking at uncountable unions the probability can be above 0. The simplest example is:
$$ (0, 1) = \bigcup_{r\in(0,1)} \{r\} $$
And of course $\mathbb{P}(\{r\})=0$ but $\mathbb{P}((0,1))=1$. The axiom of additivity is just a formal way to say that when looking at a countable union (of disjoint sets) the probabilities do just add up (and to 0 because all of them are 0 in this case).

A: Alexey's answer is correct, but I'm going to delve a bit into the motivation. The basic idea is that we want to preserve our intuition that the probability that either of two disjoint events $A$ and $B$ happen is equal to the sum of the probabilities of the individual events:
$$
P(A \cup B) = P(A) + P(B)
$$
By induction, we can extend that to any finite collection of events:
$$
P(A_1 \cup A_2 \cup \cdots \cup A_n) = P(A_1) + P(A_2) + \cdots + P(A_n)
$$
if $A_1, A_2, \ldots, A_n$ are disjoint. But what about the union of an infinite number of events? If the probability that a random variable $X$ equals a particular rational number $r$ is equal to $0$, regardless of which rational number we pick, what about the probability that $X$ equals any rational number? Given that we can enumerate the rational numbers—say, $r_1, r_2, \ldots$—can we claim the following?
\begin{align}
P(X = r_1 \cup X = r_2 \cup \cdots)
    & = P(X = r_1) + P(X = r_2) + \ldots \\
    & = 0 + 0 + \cdots \\
    & = 0
\end{align}
Note that unlike the previous rule, this requires us to be able to decompose a composite event into an infinite number of individual events (outcomes, in this case), and to add the probabilities accordingly.
This is what we need countable additivity for—because the rationals are countably infinite. Note that this does not work for the irrationals, which are uncountable. Probabilities are not uncountably additive. We can see that quite clearly in this case, because if the probability of choosing a rational value is $0$, then the probability of the complement—choosing an irrational value—must be $1$, even though the probability of choosing any particular irrational value is $0$ (just as it is for any particular rational value).


text:
Q: Update template text with user input I want my email template to prompt me for input, and replace specified fields with my input.
For example my email will be like:

Hello [name]

I want a box to pop up where I can enter the name and have it appear throughout the email, replacing [name].

A: Using my example, by saving "#0#" in your template in the "to:" section of the email, by clicking this template it will prompt you to change that entry with the "Email Address" question.
Sub CommandButton1_Click()

    Call OpenTemplate

End Sub

Sub OpenTemplate()

    Dim OutMail As Outlook.MailItem
    Set OutMail = Application.CreateItemFromTemplate("Template Location")

    On Error Resume Next
    With OutMail
        .To = Replace(.To, "#0#", InputBox("Email Address"))
        .CC = ""
        .BCC = ""
        .Subject = Replace(.Subject, "#1#", InputBox("Prompt 1"))
        .Body = Replace(.Body, "#2#", InputBox("Prompt 2"))
        .Body = Replace(.Body, "#3#", InputBox("Prompt 3"))
        .Body = Replace(.Body, "#4#", InputBox("Prompt 4"))

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub


text:
Q: Update dynamically generated list item (generated using PHP) after ajax call The following HTML code is being echoed using a while loop in PHP which is adding a list item after fetching data from database.
PHP:
echo '

'.$smallMsg.'

      '.$issueTitle.'

      <form id = "archiveIssueForm'.$i.'" issue-name = "'.$issueTitle.'" action = "archiveIssue.php">
        <input type = "hidden" value = "'.$issueID.'" name = "issueID"/>
      </form>

          archive

      edit

';

This is the preview image of the generated list:

Notice the cursor over the archive button which archives the list item. The class for that button is archiveIconButton (you can find it in the above code). When the button is clicked, archiveIssueForm is submitted via AJAX (each form has a unique identifier variable $i appended to its id).
Following is the JQuery AJAX code:
JQuery:

After archiving any list item, it gets deleted from the database. I want to update the ul element which contains these list items so that the list item which gets deleted doesn't gets displayed after the AJAX form submission.
Assume the id of ul to be issueListUL.
What i'm currently getting is the whole code of the html page displayed in the li item. I am certainly doing something wrong, any help would be appreciated!
After archiving a list item:

A: I was able to solve this issue in the following way, The JQuery script in the question should be changed like this:
JQuery:

When updating an element's html, just extract the element's updated html code from data attribute in the ajax code (as show in the above code) and update the existing element's html with it!
Hope this helps people with the same problem as mine! :D


text:
Q: How to get the window state of a C++ console application I'm writing a console app in C++ but can't seem to find how to figure out the console window state (i.e. normal, minimized, etc.).  Any idea on how to do this?

A: For Windows use GetConsoleWindow to get a handle to the window, then e.g. GetWindowPlacement.
But what on Earth are you planning to use this information for?


text:
Q: Missing ; before statement when I check response in Firebug? var on_show_info_agile = function() {
    alert("aa");
    request_meta_info = $.ajax({
        url: search_metadata + current_doc_info.id,
        type: 'GET',
        async: false,
        dataType: "jsonp",
        success: on_get_metadata,
        error: on_get_metadata_error
    });
};

How can I resolve this issue? I tried changing dataType to "script", I am getting the same error in firebug;

missing ; before statement

<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="T">3</int><lst name="params"><str name="q">83779616</str><str name="callback">jsonp1308182704622</str></lst></lst><result name="response" numFound="1" start="0"><doc><str name="number">2716837</str><str name="itle">Wire</str><str name="name">Designated </str><str name="name">S.</str><date name="">2009-03-03T08:00:00Z</date><str name="claims">8</str><str name="id">810414</str><str name="name">D.</str><date name="date">2010-08-24T07:00:00Z</date><str name="_id">83616</str><str name="name">Non Provisional</str><date name="_date">2008-03T08:00:00Z</date><arr name=id"><str>3260</str><str>290</str><str>2510</str></arr><str name="_number">08CA</str><date name="te">201-03T08:00:00Z</date><str name="e">M</str><str name="">Application</str><str name="ry_code">CA</str><str name="ame">Canada</str><str name="_claims">74</str><arr name="inventors"><str>Kd D.</str><str>G</str><str>Pi</str></arr><str name="key">83</str><arr name="owne"><str></str></arr><arr name="tors"><str>d D.</str><str>G</str><str>Pai</str></arr><arr name="ers"><str></str></arr><str name="url"/></doc></result>

</response>

Above is the XML that I am getting but with the error. Any suggestions will be appreciated.

A: You're requesting XML, but telling jQuery that it's JSON with Padding.  It throws a syntax error because it is not valid JavaScript code and therefore can't be parsed as JSONP.
It's obvious that you're trying to obtain data from a different domain, which is why it doesn't work when you switch to XML.  For cross-domain requests, you need to look into CORS, XMLHttpRequest Level 2 and IE's XDomainRequest.  For support in older browsers, I'm afraid you're out of luck unless you can modify the resource to output valid JSON with padding.


text:
Q: grails g:formatNumber by default tag  returns such format of specified number 1,224.37
I need to have as result following one 1 224,37
I was trying to use format field in g:formatNumber tag but without success.
Thank you for help.
Best Regards, Jakub.

A: You should add groupingUsed="false" attribute for g:formatNumber tag:
<g:formatNumber number="1224.37" type="number" maxFractionDigits="2" format="#" groupingUsed="false"/>

g:formatNumber documentation:
http://grails.org/doc/1.2.x/ref/Tags/formatNumber.html


text:
Q: How can I update the style of a styled-component based on scroll position without re-rendering an array of randomly placed sibling components? I have a simple component which performs these actions:

*

*Using hooks, sets state to keep track of window.scrollY

*Attaches scroll eventListener to window to update state

*Creates an array of 10 styled-components - each with a randomly assigned absolute position

*return/renders the 10 dots and another styled-component - a triangle whose height is calculated using the scroll state defined in step 1.

const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);

  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={getRandomIntInclusive(1, 199)}
        leftValue={getRandomIntInclusive(1, 99)}
      />
    );
  }

  return (

      {dots}
      <Triangle heightValue={scroll / 10} />

  );
};

What I want to happen
When I scroll down, the only thing I want to happen is the Triangle components height recalculates / re-renders. The originally rendered dots will not update or change.
My problem
As you might guess, the dots get re-rendered every scroll event, which is not only horrible for performance, but it causes the dots to have a new random position every single scroll event.
My questions

*

*How can I get the Triangle to re-render using the updated scroll value, but not have the Dot components re-render?

*More of a secondary question: If I also wanted to update some style in the Dot components on scroll (color, for example), but not update the random top and left positions that were created on the initial Mount, how would I do that?

I can accomplish something like this quite easily with vanilla JS, but I can't quite figure out the React way.
Complete working sandbox of this issue: https://codesandbox.io/embed/hopeful-greider-jb3td

A: What you need to do is calculate the dots position once and save it in an array so as to not recalculate them on each and every render when the scroll position changes
You can either use useEffect with empty deps array to do that like
// main component
const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);
  const [posArr, setPos] = useState([]);
  useEffect(() => {
    const pos = [];
    for (let x = 0; x < 10; x++) {
      pos.push({ topValue: getRandomIntInclusive(1, 199), leftValue: getRandomIntInclusive(1, 99)})
    }
    setPos(pos);
  }, [])
  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={posArr[x] && posArr[x].topValue}
        leftValue={posArr[x] && posArr[x].leftValue}
      />
    );
  }

  return (

Scroll to make triangle grow

Ideally, the dots would not rerender on scroll

      <Debug>Px scrolled: {scroll}</Debug>
      {dots}
      <Triangle heightValue={scroll / 10} />

  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working demo
or initialise the state by using a callback function to useState
// main component
const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);

  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  const [posArr, setPos] = useState(() => {
    const pos = [];
    for (let x = 0; x < 10; x++) {
      pos.push({ topValue: getRandomIntInclusive(1, 199), leftValue: getRandomIntInclusive(1, 99) })
    }
    return pos;
  });
  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={posArr[x].topValue}
        leftValue={posArr[x].leftValue}
      />
    );
  }

  return (

Scroll to make triangle grow

Ideally, the dots would not rerender on scroll

      <Debug>Px scrolled: {scroll}</Debug>
      {dots}
      <Triangle heightValue={scroll / 10} />

  );
};

Working demo


text:
Q: Allow the RSA v1.5 Key Transport Algorithm for WildFly / JBossWS / CXF / WSS4J stack In response to a security advisory (see http://cxf.apache.org/note-on-cve-2011-1096.html) regarding the RSA v1.5 key transport algorithm, both CXF and WSS4J projects have disallowed use of all related algorithms by default.
They have however supplied a configuration tag "ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM" which should re-allow these algorithms (see https://ws.apache.org/wss4j/config.html)
Our problem is getting these frameworks (JBossWS / CXF / WSS4J) to accept/use this configuration setting. We have tried using:

*

*jboss-webservice.xml

*custom CXF interceptor (setting the param after CXF creates its WSS4J interceptor)

*custom "hacked" WSS4J build  (hardcoding the parameter to "true")

But none of these options seem to actually re-enable support for the RSA v1.5 key transport algorithms.
Does anyone have any idea as to how we could/should specify this configuration parameter?

A: Here's a test I added to CXF:
https://git1-us-west.apache.org/repos/asf?p=cxf.git;a=commit;h=a73effb5
Note the server has set "allowRSA15KeyTransportAlgorithm" to "true".

A: This setting is only applied if the WSHandlerConstants.ENCRYPT action is included in the actions for the interceptor.
For instance:
Map<String, Object> inProps = new HashMap<>();
inProps.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM, "true");
inProps.put(WSHandlerConstants.ACTION,
    WSHandlerConstants.ENCRYPT + " " +
    WSHandlerConstants.SIGNATURE);
WSS4JInInterceptor wss4JInInterceptor = new WSS4JInInterceptor(inProps);


text:
Q: Como ver error exacto de una consulta X de SQL tengo una duda es la siguiente si yo tengo un PROC PERO DE MUCHOS DISTINTOS de SQL server envio unas variables pero el o alguno de los Procedure da error. mediante un codigo de x programa .exe que envia consultas varias y ocultas las cuales no son visibles solo se cierra los procesos de mssql y necesito ver donde esta el error. ejemplo de un codigo X que NO tiene nada que ver pero de error NO BUSCO (@chara) solo quiero ver donde se almacenan los registros de errores
  declare @char varchar(25) = 'name',
    @edad int = 18

    EXEC edad
    @edad, @chara

    CREATE PROC Char
    AS
    SELECT @Edad, @Char

Suponiendo que sean Miles de millones de consultas, procederes DISTINTOS y necesito ver donde se hizo el error que tabla o que Proc cometió el error ¿Dónde lo Veo? dicen que es algo con logs (creo que son archivos que registran los errores) pero el tema es donde los veo en SQL server 2008 R2

A: Raiserror te puede devolver ese tipo de información.
Create procedure dbo.cuatro
as
begin

    Declare @var int=0;
    -- aquí el error de división entre cero.
    Select 1 as result, 2/@var as divisonByZero
end
go
Create procedure dbo.tres
as
begin
    exec dbo.cuatro;
end
go
Create procedure dbo.dos
as
begin
    exec dbo.tres;
end
go

Ahora creamos un procedure que llamará a dos y así sucesivamente.
Create procedure dbo.uno
as
begin try
    begin tran
        exec dbo.dos;
    commit tran;
end try
begin catch
    if @@TRANCOUNT > 0
        rollback tran;

    -- Variables para recuperar información del sistema.
    DECLARE @ErrorMsg NVARCHAR(4000);
    DECLARE @ErrorSvr INT;
    DECLARE @ErrorStS INT;
    DECLARE @ErrorPrc NVARCHAR(128);
    DECLARE @ErrorLne INT;
    DECLARE @ErrorNmb INT;

-- Recuperamos la información.
    SELECT
        @ErrorMsg = ERROR_MESSAGE(),
        @ErrorSvr = ERROR_SEVERITY(),
        @ErrorStS = ERROR_STATE(),
        @ErrorPrc = ERROR_PROCEDURE(),
        @ErrorLne = ERROR_LINE(),
        @ErrorNmb = ERROR_NUMBER();

--Asignamos el mensaje.
    SET @ErrorMsg =
        CONCAT(
          N'Mensaje Personalizado: '
          , N'Procedimiento: '
          , @ErrorPrc
          , N' - Linea - '
          , CAST(@ErrorLne AS NVARCHAR(100))
          , N' - Núm - '
          , CAST(@ErrorNmb AS NVARCHAR(100))
          , N' - Msg - '
          , @ErrorMsg);

    -- Utililzamos Raiserror
        RAISERROR (@ErrorMsg,
                   @ErrorSvr,
                   @ErrorStS
                   )
            WITH LOG;
    /* El parámetro WITH log, nos permite guardarlo en el
    log de la aplicación */
end catch
go

En el procedimiento utilizamos un bloque try catch y en el catch recogemos lo que contienen las funciones ERROR_PROCEDURE y ERROR_LINE, para ver dónde ha ocurrido el error y presentar nuestro mensaje personalizado.
exec dbo.uno

El mensaje de error nos indica, en Mensaje Personalizado. dbo.cuatro - Linea - 6, que es donde se ha producido el error.
Además en nuestra aplicación cliente, en el caso Sql Management Studio, disponemos también del error, gracias a la utilización de Raiserror con with Log

RaisError


text:
Q: Windows won't boot without linux usb( I enter grub rescue) I tried to install parrot os on my usb. I succeded, but my laptop won't boot into windows without usb on which linux is installed. It says: unkown device:(some numbers), unkown file system. When my usb is in the laptop, I get dual boot option, then I can boot into windows. I tried troubleshoot with fixmbr, fixboot and rebuildbcd. Nothing worked.
It didn't work with extrernal usb repair
Os:Windows 11
Os 2: Parrot os 5


text:
Q: Read input within the command bound to a key in bash How can I read input within the command bound to a key?
I've tried:
bind -x '"\C-b":read x'

After Control-b hitted, bash hangs.

A: bind -x isn't designed to run interactive commands; it should only be used to run commands that produce output, then exit back to the shell. Also, read x would be executed in a subshell invoked by readline, so whatever value you input to set x would be lost when the subshell exits.


text:
Q: HTTP Status 404 - on Eclipse with Tomcat (with no generated web.xml) I'm working on an example with Eclipse and Tomcat 9.0, dynamic web module 4.0, without generating web.xml deployment.
The project directory is as follow:

where reverse.java is a servlet that get the input parameter send it back to the output page.
For some reason, after I hit the submit button, the "/reverse" servlet cannot be reached and tomcat prompts HTTP Status 404 - Not Found page. What did I do wrong?
After hitting the submit button on inputForm.jsp page, it got the error:

Type Status Report
Message /reverse
Description The origin server did not find a current representation
  for the target resource or is not willing to disclose that one exists.

URL I called on submit when enter input = "abcd": http://localhost:8080/reverse?input=abcd
What did I do wrong? Thanks.

A: If you didn't set set context root explicitly, it is set by default to the same name as your project. If your project name is "bla", then the URL to call the servlet should be following: http://localhost:8080/bla/reverse.


text:
Q: uninstall apk silently exception---(java.lang.AbstractMethodError: abstract method not implemented) I'm developing an application which supports uninstall other apk silently. My device is rooted and the app is placed under /system/app, with reflection i can use the deletePackage method to implement this.
But in the implement of deletePackage method, an exception occurs.The exception informations are as follows:
09-20 10:16:02.242: E/JavaBinder(1943): *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
09-20 10:16:02.242: E/JavaBinder(1943): java.lang.AbstractMethodError: abstract method not implemented
09-20 10:16:02.242: E/JavaBinder(1943):     at android.content.pm.IPackageDeleteObserver$Stub.packageDeleted(IPackageDeleteObserver.java)
09-20 10:16:02.242: E/JavaBinder(1943):     at android.content.pm.IPackageDeleteObserver$Stub.onTransact(IPackageDeleteObserver.java:57)
09-20 10:16:02.242: E/JavaBinder(1943):     at android.os.Binder.execTransact(Binder.java:338)
09-20 10:16:02.242: E/JavaBinder(1943):     at dalvik.system.NativeStart.run(Native Method)
09-20 10:16:02.242: W/dalvikvm(1943): threadid=9: thread exiting with uncaught exception (group=0x40a461f8)
09-20 10:16:02.242: E/AndroidRuntime(1943): FATAL EXCEPTION: Binder Thread #1
09-20 10:16:02.242: E/AndroidRuntime(1943): java.lang.AbstractMethodError: abstract method not implemented
09-20 10:16:02.242: E/AndroidRuntime(1943):     at android.content.pm.IPackageDeleteObserver$Stub.packageDeleted(IPackageDeleteObserver.java)
09-20 10:16:02.242: E/AndroidRuntime(1943):     at android.content.pm.IPackageDeleteObserver$Stub.onTransact(IPackageDeleteObserver.java:57)
09-20 10:16:02.242: E/AndroidRuntime(1943):     at android.os.Binder.execTransact(Binder.java:338)
09-20 10:16:02.242: E/AndroidRuntime(1943):     at dalvik.system.NativeStart.run(Native Method)

Relative code:
public void onBackgroundUninstallClick(View v) {
    PackageDeleteObserver observer = new PackageDeleteObserver();
    if (mPackageManager != null/* && mUninstallPackage != null*/) {
        try {
            mPackageManager.deletePackage("com.example.android.imagedownloader", observer, 0);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

class PackageDeleteObserver extends IPackageDeleteObserver.Stub {
    public void packageDeleted(boolean succeeded) throws RemoteException {
        Log.i(TAG, "packageDeleted");
        Message msg = mHandler.obtainMessage(UNINSTALL_COMPLETE);
        msg.arg1 = succeeded ? SUCCEEDED : FAILED;
        mHandler.sendMessage(msg);
    }
}

IPackageDeleteObserver.aidl code :

package android.content.pm;

interface IPackageDeleteObserver {
    void packageDeleted(boolean flag);
}

A: java.lang.AbstractMethodError: abstract method not implemented

somewhere missing a method implementation.
void packageDeleted(boolean flag);

doesn't match the signature of
public void packageDeleted(boolean succeeded) throws RemoteException

because of throws RemoteException
change to
interface IPackageDeleteObserver {
    void packageDeleted(boolean flag) throws RemoteException;
}

A: I found the app work well on sdk 2.3.5 but 4.0. Maybe the method packageDeleted is changed after sdk 4.0. Can anybody supply the source code of IPackageDeleteObserver.aidl in sdk 4.0.

A: I've tried this on both android 2.3.3 and android 4.0.3 emulators and it worked. Note that I've removed the @Override annotation.
I saw some answers indicating an Interface or Abstract Class to decide which one to use, depending on SDK version, but this seems to work as well.
class PackageDeleteObserver extends IPackageDeleteObserver.Stub {

    PackageDeleteObserver( ) {
        // nothing to do here
    }

    // android > 4
    public void packageDeleted( String name, int status ) throws RemoteException {
        synchronized (this) {
            this.notifyAll();
            // do your thing
        }
    }

    // android < 4
    public void packageDeleted( boolean status ) throws RemoteException {
        synchronized (this) {
            this.notifyAll();
            // do your thing
        }
    }

}


text:
Q: Galaxy S4 "Make Bug Report" dialog never initializes I am debugging an app on my Galaxy S4, I have enabled Developer Tools and have checked "Include bug reports in power menu". Once the app fails, I held down the power button and got the option to "Bug report". It notes that it might take some time, and I have done this before on my Nexus 7 and past Android phone.
The issue is, the Bug Report dialog to email the log+screenshot never shows. I've waited well over an hour, tested from the actual Developer Options menu to "Make bug report" (instead of through the power menu), and everything inbetween; patiently and multiple times with different approaches. I've searched far and wide for anyone reporting this same issue, or how long it takes for an S4 to collect this data, to no avail.
Has anyone else observed this issue? Would it be related to another installed app that is causing this to happen? Or does it take well over an hour to gather a log? I would suspect not.

A: Not exactly a solution for "Make Bug Report" problem, but you could use Samsung's custom bug report tool, SysDump*, to get the logs:

*

*Open the Dialer (Phone) and type *#9900#

*Run logcat/dumpstate. Once done,

*Copy to SD card

*Not my website and I'd not recommend trying all those codes, especially number 5.

A: The debug report is generated in the background. You will not see a popup screen, the notice displays in your notification bar. Drag down from the top of the screen to see your notifications and you will see "log report generated" when it is finished. It shouldn't take longer than a minute or two. When you click on that, you will have the option to share that report via the usual methods, such as email.


text:
Q: access httpContextAccessor claims - userid, UPN, email and name I am using a blazor wasm + core hosted- solution.(.net 6.0)
Here is my project structure:
  BlazorApp4.Client
  BlazorApp4.Server
  BlazorApp4.Shared

I am using windows authentication, since its not supported in wasm, i have enabled windows auth in the server project.
So to access who has logged on I am calling the webapi from the client project.
   windowsuser  = await httpClient.GetStringAsync("api/wuser");

I have a controller written on the server side
WUserController.cs
 namespace BlazorApp4.Server.Controllers
{
    [ApiController]
    [Route("api/wuser")]
    public class WUserController : ControllerBase
    {

        private readonly ILogger<WUserController> _logger;
        WindowsUser? windowsuser = null;

        public WUserController(ILogger<WUserController> logger, IHttpContextAccessor httpContextAccessor)
        {
            windowsuser = new WindowsUser(httpContextAccessor);
            _logger = logger;
        }

        [HttpGet]
        public  async  Task<string> Get()
        {
            return windowsuser.GetUserName();
        }
    }
}

WindowsUser.cs

 public class WindowsUser
    {

        private readonly IHttpContextAccessor? _httpContextAccessor;
        private readonly string? _userName;
        public WindowsUser(IHttpContextAccessor? httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
      _userName = httpContextAccessor?.HttpContext?.User.Identity?.Name;
            var userId =
      httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        }

        public string GetUserName()
        {
            return _userName;
        }
    }

program.cs (server project)

builder.Services.AddHttpContextAccessor();

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

this doesnot work
httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
trying to access upn and email
httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Upn).Value;
httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Email).Value;
all are giving null value exception. I guess it is not able to fetch the details.
_userName = httpContextAccessor?.HttpContext?.User.Identity?.Name;
This gives me domainname\username
This is the only property that I am able to get, rest all are null.