text:
Q: How to build AngleSharp CSS (or HTML) DOM programmatically All AngleSharp examples and tests I found start with parsing a CSS or HTML snippet and access the DOM reading. How can I build a CSS (or HTML5) document programmatically and get the resulting output as string?
I want something like this (pseudo code):
var rule = new CssRule();
rule.Selector = ".my-class";

var style = new CssStyle("margin-top", "10px");

rule.add(style);

A: For HTML you need to use the W3C specified API:
var context = BrowsingContext.New();
// get new document, not completely empty (has head and body)
var document = await context.OpenNewAsync();
var element = document.CreateElement("strong");
element.TextContent = "Hello World!";
document.Body.AppendChild(element);

As this is a little verbose some helpers (in form of extension methods) exist to make it more fluent. Also the CreateElement is available as a generic method looking like:
var paragraph = document.CreateElement<IHtmlParagraphElement>();

Unfortunately, for CSS currently no such API (factory methods or similar) exist. The only way to manipulate it is by using strings. This is not ideal (I know) and I will add useful extension methods to provide such functionality in the future.


text:
Q: Multer storage is not uploading file on server directory Multer is not uploading files on server directory below my source code to upload file. file object is created that means when i log req.files file are present but not uploading to directory.im using POSTMAN for API Testing  sending file through formdata->uploadfiles and with key "uploadfiles" destinition function is not called because log inside function is not console the name "Hello "
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        console.log("Hello Umesh");
        cb(null, '../resources/uploads'); // Absolute path. Folder must exist, will not be created for you.
      },
      filename: function (req, file, cb) {
        console.log("Hello Umesh");
        cb(null, file.fieldname + '-' + Date.now());
      }
});

const upload = multer({
                         storage: storage,
                         limit:{filesize:10}

                    }).single('uploadfiles');

router.post('/save', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            res.json({
                success: false,
                message:err
            });
        }
        else{
        res.json({
            success: true,
            message: req.file
        });
    }
    })
});

A: Try to use the absolute path to the storage location:
cb(null, require('path').join(__dirname, '..', 'resources', 'uploads'));

instead:
cb(null, '../resources/uploads');

Update:
Since the working directory for functions from the fs module is the project's root folder (if you run the project with the npm start command), you can simply use this:
cb(null, 'resources/uploads');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable certains items in listbox control when binding i have an datatable with valuees like this
names
------
kumar
kiran
ram
bala
----
anu
sita
geetha
-----
asha
abc
tsdf
dsf
sdf
sdfrt
sdfsdfd
sdfdsfsdf
--------

i am binding my table to listview  like this
ListItem ddlItem;
foreach (DataRow dr in dt.Rows)
{
ddlItem = new ListItem(dr["names"].ToString())
lbx.Items.Add(ddlItem);
}

here  even i need to  bind my datatable wih all the values except"-----" these values .
it should be in disable mode  even though user tries to selected it will  not get selected
how can we get it achived.
 any help on this would be great
 thank you

A: The standard listbox control does not have the ability to do this.  You can set the Enabled property on the ListItem to False, but that removes the item from the list.  The best solution is to use some JavaScript to change the selectedIndex of the listbox whenever one of the dashes is selected.
Add an OnClick handler to your listbox control:
<asp:ListBox ID="lbTesting" runat="server" OnClick="testSelectedItem();">

Then add the following JavaScript function to check for the selected item:
<script language="javascript" type="text/javascript">
    function testSelectedItem() {
        var lbTesting = document.getElementById('lbTesting');
        if (lbTesting[lbTesting.selectedIndex].innerText == '----') {
            lbTesting.selectedIndex = 0;
        }
    }
</script>

Obviously, you can play with the JavaScript function a bit if you need to test for different numbers of dashes, or if you want different functionality when a user selects a dashed entry - currently it just resets to the first item in the list.
Finally, you should add an edit on the server side to ensure that a dashed entry was not selected, as the user might have JavaScript disabled.


text:
Q: Changing Redirect After Form Submittal On my Wordpress website I have users fill out a form which ultimately generates a product. One of the form fields is a "Title" for the product. I'm trying to change the redirect for where the user is sent after they submit the form.
The URL for products are based on the "Title" of the product (e.g. http://example.com/product/My-Great-Product-Title/)
The issue with my current code is that I get a returned URL of... http://example.com/product/My%Great%Product%Title/
This returns a page not found 404 error.
Naturally a product title with no spaces in between the words works just fine but for obvious reasons every title can't be limited to one word.
My current code for redirecting which results with the 404 error...
$redirect = "http://example.com/product/$title";
How can I get my URL to be "My-Great-Product-Title" instead of "My%Great%Product%Title" which doesn't seem to work.

A: Assuming that the URL is generated by WordPress whenever the Product is created and now created by some other method you should be able to use sanitize_title() which is what WordPress uses to create their friendly permalinks.
The drawback to this is if there's a duplicate, it won't detect this but WordPress will append a -2 to the url. A better solution would be to get the ID after the product has been created and use get_permalink() which will be more accurate.


text:
Q: Measure Bluetooth Signal Strengths (RSSI) in Real Time I want to be able to walk around a room with an android device in my hand, click a button that says room 1 and then start discovering bluetooth devices around me and getting their RSSI values. I then want to save this information as a text file. Then repeat for different rooms.
That's the easy part.
The part I'm having trouble with is finding out how to (or if it's possible) to do this but have a timer set so that the discovery process doesn't necessarily finish itself, but so I can  time it to start and stop the discovery repeatedly by itself to get new values until I pess finish. Most of the values that are close by USUALLY appear within about 5 seconds or so, which I'm happy enough with for what I'm trying to do at the moment.
I've found this question but there's no answer.
To make it a bit clearer a simple example would be:

*

*Press "Room1" button

*Start Discovery

*After 5 seconds, stop discovery and start again

*Do this over and over until...

*"Stop" button pressed

Does anyone know if this is possible? And if so what would be the best way?
I've looked at Timer and TimerTask and they look useful.
Also I'm asking a bit before I start getting too deep into it as I've done that before n had to revert back to the start. :(
Thanks

A: You could use something like this:
private void start() {
    mBluetoothAdapter.startDiscovery();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mBluetoothAdapter.isDiscovering())
                mBluetoothAdapter.cancelDiscovery();
            if (repeat) start();
        } }, 5000);
}

Make a variable repeat that is set to false by the stop button. The start button sets repeat to true and calls start().
As far as I know the bluetooth discovery runs indefinitely so you don't need to stop and restart it.


text:
Q: CW complex structure on standard sphere identifying the south pole and north pole I need to find CW complex structure in the sphere by identifying the north and south pole.
First of all I tried to visualize what it looks like and if I am not wrong gluing the poles together will result in something looking sort of like a torus but without a hole. Now from a question that another user has posed namely(Cell Structure on Sphere with Two points identified) I saw that the CW complex structure is the following attach the boundary of the one cell to the zero cell and then attach the boundary of the two cell to the zero cell. To me this structure results to a wedge of a sphere and a circle because attaching the one cell to the zero cell gives a circle and then attaching the two cell to the zero cell will result to a sphere. As such this structure will result to the wedge of a sphere and a circle. Can you please explain to me what's wrong with my reasoning and how the structure above actually results to the sphere with the poles identified??
Thanks in advance

A: Start with a 0-cell $x$.
Attach an oriented 1-cell $e$ with both endpoints identified to $x$.
Attach a 2-cell $\sigma$ with attaching map defined on its oriented boundary circle $\partial\sigma$ as follows:

*

*Subdivide $\partial\sigma$ as a concatenation of two arcs $\partial\sigma = \partial_1 \sigma * \partial_2 \sigma$,

*Map $\partial_1 \sigma$ to $e$,

*Map $\partial_2 \sigma$ to $\bar e$.

ADDED LATER: To see why this CW complex $X$ is homeomorphic to the sphere with north and south pole identified, this is the case where a picture is worth a large number of words, in order to convey the intuition. Yet it can be done with intuitive rigor also, with a few carefully chosen words, which I will attempt to supply.
First note that the characteristic map of the 2-cell $f : \sigma \to X$ is a surjective continuous map and is therefore a quotient map. So, $X$ can be reconstructed by starting with the 2-dimensional disc $\sigma$ and making the same identifications on $\sigma$ as are made by the map $f$. What are these identification? They are of two different types:

*

*Identify the two oriented arcs $\partial \sigma_1$, $\partial\bar\sigma_2$ to a single arc (which will be the 1-cell of $X$).

*Identify the two points $\partial(\partial \sigma_1) = \partial(\partial\sigma_2)$ to a single point (which will be the $0$-cell of $X$).

So, how do we see that this is the 2-sphere with the north and south poles identified? First do just identification 1: the quotient is the 2-sphere, and the arcs $\partial\sigma_1$, $\partial\sigma_2$ each map to a longitude line connecting the north and south poles. Next do identification 2: identify the north and south poles.


text:
Q: Извлечь данные combobox item У меня есть Combobox в нем есть ComboBoxItem, помимо Content можно как то вытащить другие данные например DataContext, а затем присвоить переменной

A: Конечно, можно:
foreach (ComboBoxItem item in comboBox1.Items)
{
    var x = item.DataContext;
    //...
}

Только зачем присваивать свойству DataContext какие-то строки? Обычно свойству DataContext присваивается объект для привязки, и не на уровне ComboBoxItem, а на уровне элемента управления или окна в целом. Если вам нужно хранить произвольные данные в ComboBoxItem, используйте свойство Tag.


text:
Q: bridgeOS not updating? I just updated my Mojave machine to Security Update 2020-006 but my bridgeOS has not updated, it remains on 18P50347c which I got when I tried Big Sur DP4/PB1 on 7 August 2020?
I don't have any other Macs so "downgrading (from beta to release) bridgeOS using Apple Configurator 2" isn't an option.
How can I get the latest bridgeOS on my Mojave Mac mini?

A: Due to the fact that you have previously installed a beta release, it looks like the bridgeOS update is skipped. Try to install the latest macOS Big Sur 11.0.1 (20B29) release on a external drive.

A: I have had decent success downloading the full installer. Usually that works without going to recovery but sometimes that is easier for people. But I only go to newer bridge, not regress so you might need someone to hack together a regression step if the full installer doesn't get your the briegeOS you seek.
Your process is the same to retry an install if Big Sur (or any oter upgrade) fails.
softwareupdate --fetch-full-installer --full-installer-version 10.14.6

Or you could go to the Mojave install page:

*

*https://support.apple.com/en-us/HT211683


text:
Q: How to add motion blur to numpy array I have a numpy array from image
So, is there a good way to do so:
from PIL import Image
a = Image.open('img')
a = a.filter(MOTION_BLUR)

A: draw a rotated line as kernel, then apply a convolution filter to an image with that kernel.
The code below uses opencv framework.
import cv2
import numpy as np

#size - in pixels, size of motion blur
#angel - in degrees, direction of motion blur
def apply_motion_blur(image, size, angle):
    k = np.zeros((size, size), dtype=np.float32)
    k[ (size-1)// 2 , :] = np.ones(size, dtype=np.float32)
    k = cv2.warpAffine(k, cv2.getRotationMatrix2D( (size / 2 -0.5 , size / 2 -0.5 ) , angle, 1.0), (size, size) )
    k = k * ( 1.0 / np.sum(k) )
    return cv2.filter2D(image, -1, k)

A: import cv2
import numpy as np

img = cv2.imread('input.jpg')
cv2.imshow('Original', img)

size = 15

# generating the kernel
kernel_motion_blur = np.zeros((size, size))
kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
kernel_motion_blur = kernel_motion_blur / size

# applying the kernel to the input image
output = cv2.filter2D(img, -1, kernel_motion_blur)

cv2.imshow('Motion Blur', output)
cv2.waitKey(0)

explanation you can found here

A: if you want to apply vertical, you can use this kernel:
kernel_motion_blur = np.zeros((size, size))
kernel_motion_blur[int(:, (size-1)/2)] = np.ones(size)
kernel_motion_blur = kernel_motion_blur / size

A: I would use matplotlib:
from PIL import Image
img = Image.open('your_image')
imgplot = plt.imshow(img, interpolation="bicubic")


text:
Q: How can I pass a variable I get from a function to an onclick event I have a function to get a specific section of a URL and I save the results to a variable,
function getQueryVariable(variable) {
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
   }
   return(false);
}
var inputId = getQueryVariable("elementId");
alert(inputId);

The problem is that I can not add the variable inputId to my onClick event,
test
Note that test is a dummy string so nothing to worry about.

A: Assuming inputId is a global variable, remove the single quotes from it in the onclick handler:
test

You can also exclude the word Javascript.


text:
Q: Explicit expression for the inverse of an $N\times N$ block matrix $A$ where each $M\times M$ block in $A$ is a diagonal matrix? I want to invert a non-singular $N\times N$ block matrix $A$ where each $M\times M$ block in $A$ is a diagonal matrix. That is, I have an $N\times N$ block matrix
$$
A =
\begin{pmatrix}
A^{11} & A^{12} & \cdots & \cdots & A^{1N} \\
A^{21} & A^{22} &  &  &  \\
\vdots &  & \ddots &  &  \\
\vdots &  &  & \ddots &  \\
A^{N1} &  &  &  & A^{NN}
\end{pmatrix},
$$
where for $i,j \in \{1,\dots,N\}$, each $M\times M$ block $A_{ij}$ is of the form
$$
A_{ij} =
\begin{pmatrix}
a_{11} & 0 & \cdots & \cdots & 0 \\
0 & a_{22} &  &  &  \\
\vdots &  & \ddots &  &  \\
\vdots &  &  & \ddots &  \\
0 &  &  &  & a_{MM}.
\end{pmatrix}
$$
A very simple explicit example where $N=3$ and $M=3$ (with the non-zero diagonals in red for clarity) would be
$$
A =
\begin{pmatrix}
\color{red}{1} & 0 & 0 & \color{red}{2} & 0 & 0 & \color{red}{3} & 0 & 0 \\
0 & \color{red}{2} & 0 & 0 & \color{red}{3} & 0 & 0 & \color{red}{4} & 0 \\
0 & 0 & \color{red}{3} & 0 & 0 & \color{red}{4} & 0 & 0 & \color{red}{5} \\
\color{red}{4} & 0 & 0 & \color{red}{5} & 0 & 0 & \color{red}{6} & 0 & 0 \\
0 & \color{red}{5} & 0 & 0 & \color{red}{6} & 0 & 0 & \color{red}{7} & 0 \\
0 & 0 & \color{red}{6} & 0 & 0 & \color{red}{7} & 0 & 0 & \color{red}{8} \\
\color{red}{7} & 0 & 0 & \color{red}{8} & 0 & 0 & \color{red}{9} & 0 & 0 \\
0 & \color{red}{8} & 0 & 0 & \color{red}{9} & 0 & 0 & \color{red}{0} & 0 \\
0 & 0 & \color{red}{9} & 0 & 0 & \color{red}{0} & 0 & 0 & \color{red}{1} \\
\end{pmatrix}.
$$
Is there a special formula for the inverse a matrix like this, i.e. is it possible to obtain a special explicit expression for the inverse of an $N\times N$ block matrix $A$ where each $M\times M$ block in $A$ is a diagonal matrix?

A: Since user1551 doesn't seem to show up anymore, let me make precise their idea here. Each row of your matrix follows a specific pattern. The first one starts with some entry and then $M-1$ zeros, followed by some entry and then $M-1$ zeros and so on. Let's call this Pattern(1). The next row follows Pattern(2) which is just a shifted version of Pattern(1). And so on until Pattern(M) in the $M$-th row. Then we start again with Pattern(1) in the $(M+1)$-th row. Let's now permute the rows such that we sort by patterns. So, first $N$ times Patten(1), then $N$ times Pattern(2) and so on. Then we obtain a $M\times N$ block matrix with blocks of size $N\times M$:
$$
B =
\begin{pmatrix}
B^{11} & B^{12} & \cdots & \cdots & B^{1N} \\
B^{21} & B^{22} &  &  &  \\
\vdots &  & \ddots &  &  \\
\vdots &  &  & \ddots &  \\
B^{M1} &  &  &  & B^{MN}
\end{pmatrix}.
$$
Here, for any block-row $k$, $B^{k1},\ldots,B^{kN}$ all have the same form, namely each column being zero except the $k$-th. Now, let us consider the columns of $B$. They are all of the form
$$
\begin{bmatrix}v_1\\ \vdots\\ v_M\end{bmatrix}
$$
with each $v_j$ being an $N\times 1$-vector and only one of them is not the zero vector. Sorting the columns by pattern will then result in an $M\times M$ block-diagonal matrix with $N\times N$-matrices as entries.


text:
Q: connecting to Google Cloud Storage using gsutil from on premises server through border firewall I am trying to connect from on premises linux server to Google Cloud Platform Storage (bucket) using gsutil. We have a border firewall which need to opened to connect to Cloud Storage. Firewall team is asking for destination details with port.
eg: through gs utility if I want to download the or upload the file I used the command gsutil cp test.txt gs://testbucket
Thanks,
Sahayam.J

A: Under the hood gsutil makes HTTPS requests to Cloud Storage API. So whitelisting storage.googleapis.com should suffice.


text:
Q: Keyboard response rate is too low, and character suggestion popups appear periodically I'm typing on my Retina MacBook Pro, and the response rate on the keyboard is terrible. It's like typing on an LCII that is trying to run Mac OS X. As I type, the computer seems to be thinking ridiculously hard about what it is doing. Periodically, these silly character suggestions will appear next to the cursor:

The response rate is so bad that I am literally typing this message one painstaking character at a time, and waiting for it to appear on the screen before typing the next. I estimate < 20 WPM. Keys are randomly repeating as well.
Any idea what this is or why it is happening? This is the second time  I've had this issue. I haven't been able to find any info in the Apple forums about it, I'm guessing because I don't know what this phenomenon is called.

A: The characters appear when a key is held down, it's the same as on an iPhone to make it easier to type accents and things. Those are alternative S characters.
You can turn it off using:
defaults write -g ApplePressAndHoldEnabled -bool true

in Terminal.
However, that doesn't explain the overall response rate, just the characters.
For the keyboard rate check Accessibility in System Prefs. You might have Slow Keys enabled in the Keyboard section. You might also want to check under options at the Acceptable Delay in that panel.


text:
Q: Deserialize javascript string rather then JSON using C# Actually I've implmented ios in-app purchase & upon success, I receive json response.
The json response contains PurchaseToken, which is basically a base64 encoded javascript string.
{
    "Id": "1000000872920320",
    "TransactionDateUtc": "2021-09-06T14:42:17Z",
    "ProductId": "1",
    "AutoRenewing": false,
    "PurchaseToken": "ewoJInNpZ25hdHVyZSIgPSAic29tZSBsb25nIGJhc2U2NCBzdHJpbmciOwoJInB1cmNoYXNlLWluZm8iID0gImV3b0pJbTl5YVdkcGJtRnNMWEIxY21Ob1lYTmxMV1JoZEdVdGNITjBJaUE5SUNJeU1EQXdMVEF4TFRBeElEQXhPakF4T2pBeElFRnRaWEpwWTJFdlRHOXpYMEZ1WjJWc1pYTWlPd29KSW5WdWFYRjFaUzFwWkdWdWRHbG1hV1Z5SWlBOUlDSnpiMjFsVlVsRUlqc0tDU0p2Y21sbmFXNWhiQzEwY21GdWMyRmpkR2x2YmkxcFpDSWdQU0FpVTI5dFpWUkpSQ0k3Q2draVluWnljeUlnUFNBaU15NDJJanNLQ1NKMGNtRnVjMkZqZEdsdmJpMXBaQ0lnUFNBaVUyOXRaVlJKUkNJN0Nna2ljWFZoYm5ScGRIa2lJRDBnSWpFaU93b0pJbWx1TFdGd2NDMXZkMjVsY25Ob2FYQXRkSGx3WlNJZ1BTQWlVRlZTUTBoQlUwVkVJanNLQ1NKdmNtbG5hVzVoYkMxd2RYSmphR0Z6WlMxa1lYUmxMVzF6SWlBOUlDSnpiMjFsSUc1MWJXVnlhV01nZEdsdFpTQnpkR0Z0Y0NCcGJpQnRjeUk3Q2draWRXNXBjWFZsTFhabGJtUnZjaTFwWkdWdWRHbG1hV1Z5SWlBOUlDSnpiMjFsSUZWSlJDSTdDZ2tpY0hKdlpIVmpkQzFwWkNJZ1BTQWlNU0k3Q2draWFYUmxiUzFwWkNJZ1BTQWljMjl0WlNCVmJtbHhkV1VnU1hSbGJTQkpSQ0k3Q2draWRtVnljMmx2YmkxbGVIUmxjbTVoYkMxcFpHVnVkR2xtYVdWeUlpQTlJQ0l3SWpzS0NTSnBjeTFwYmkxcGJuUnlieTF2Wm1abGNpMXdaWEpwYjJRaUlEMGdJbVpoYkhObElqc0tDU0p3ZFhKamFHRnpaUzFrWVhSbExXMXpJaUE5SUNKemIyMWxJRzUxYldWeWFXTWdkR2x0WlNCemRHRnRjQ0JwYmlCdGN5STdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTSWdQU0FpTWpBd01DMHdNUzB3TVNBd01Ub3dNVG93TVNCRmRHTXZSMDFVSWpzS0NTSnBjeTEwY21saGJDMXdaWEpwYjJRaUlEMGdJbVpoYkhObElqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURBd0xUQXhMVEF4SURBeE9qQXhPakF4SUVWMFl5OUhUVlFpT3dvSkltSnBaQ0lnUFNBaWFYQmhJR0Z3Y0NCaWRXNWtiR1VnYm1GdFpTSTdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTMXdjM1FpSUQwZ0lqSXdNREF0TURFdE1ERWdNREU2TURFNk1ERWdRVzFsY21sallTOU1iM05mUVc1blpXeGxjeUk3Q24wPSI7CgkiZW52aXJvbm1lbnQiID0gIlNhbmRib3giOwoJInBvZCIgPSAiMTAwIjsKCSJzaWduaW5nLXN0YXR1cyIgPSAiMCI7Cn0=",
    "State": 0,
    "ConsumptionState": 0,
    "IsAcknowledged": false,
    "Payload": null
}

I deserialize the above object & decode the base64 purchaseToken, but the decoded string is javascript string rather then json (look at the = & ;).
{
    "signature" = "some long base64 string";
    "purchase-info" = "ewoJIm9yaWdpbmFsLXB1cmNoYXNlLWRhdGUtcHN0IiA9ICIyMDAwLTAxLTAxIDAxOjAxOjAxIEFtZXJpY2EvTG9zX0FuZ2VsZXMiOwoJInVuaXF1ZS1pZGVudGlmaWVyIiA9ICJzb21lVUlEIjsKCSJvcmlnaW5hbC10cmFuc2FjdGlvbi1pZCIgPSAiU29tZVRJRCI7CgkiYnZycyIgPSAiMy42IjsKCSJ0cmFuc2FjdGlvbi1pZCIgPSAiU29tZVRJRCI7CgkicXVhbnRpdHkiID0gIjEiOwoJImluLWFwcC1vd25lcnNoaXAtdHlwZSIgPSAiUFVSQ0hBU0VEIjsKCSJvcmlnaW5hbC1wdXJjaGFzZS1kYXRlLW1zIiA9ICJzb21lIG51bWVyaWMgdGltZSBzdGFtcCBpbiBtcyI7CgkidW5pcXVlLXZlbmRvci1pZGVudGlmaWVyIiA9ICJzb21lIFVJRCI7CgkicHJvZHVjdC1pZCIgPSAiMSI7CgkiaXRlbS1pZCIgPSAic29tZSBVbmlxdWUgSXRlbSBJRCI7CgkidmVyc2lvbi1leHRlcm5hbC1pZGVudGlmaWVyIiA9ICIwIjsKCSJpcy1pbi1pbnRyby1vZmZlci1wZXJpb2QiID0gImZhbHNlIjsKCSJwdXJjaGFzZS1kYXRlLW1zIiA9ICJzb21lIG51bWVyaWMgdGltZSBzdGFtcCBpbiBtcyI7CgkicHVyY2hhc2UtZGF0ZSIgPSAiMjAwMC0wMS0wMSAwMTowMTowMSBFdGMvR01UIjsKCSJpcy10cmlhbC1wZXJpb2QiID0gImZhbHNlIjsKCSJvcmlnaW5hbC1wdXJjaGFzZS1kYXRlIiA9ICIyMDAwLTAxLTAxIDAxOjAxOjAxIEV0Yy9HTVQiOwoJImJpZCIgPSAiaXBhIGFwcCBidW5kbGUgbmFtZSI7CgkicHVyY2hhc2UtZGF0ZS1wc3QiID0gIjIwMDAtMDEtMDEgMDE6MDE6MDEgQW1lcmljYS9Mb3NfQW5nZWxlcyI7Cn0=";
    "environment" = "Sandbox";
    "pod" = "100";
    "signing-status" = "0";
}

And the purchase info:
{
    "original-purchase-date-pst" = "2000-01-01 01:01:01 America/Los_Angeles";
    "unique-identifier" = "someUID";
    "original-transaction-id" = "SomeTID";
    "bvrs" = "3.6";
    "transaction-id" = "SomeTID";
    "quantity" = "1";
    "in-app-ownership-type" = "PURCHASED";
    "original-purchase-date-ms" = "some numeric time stamp in ms";
    "unique-vendor-identifier" = "some UID";
    "product-id" = "1";
    "item-id" = "some Unique Item ID";
    "version-external-identifier" = "0";
    "is-in-intro-offer-period" = "false";
    "purchase-date-ms" = "some numeric time stamp in ms";
    "purchase-date" = "2000-01-01 01:01:01 Etc/GMT";
    "is-trial-period" = "false";
    "original-purchase-date" = "2000-01-01 01:01:01 Etc/GMT";
    "bid" = "ipa app bundle name";
    "purchase-date-pst" = "2000-01-01 01:01:01 America/Los_Angeles";
}

I'm facing this issue with deserializing of the javascript string into a C# object.
Any proper way to handle this deserialization?
Newtonsoft.Json is not able to handle it & I have looked its docs again & again to find any suitable methods but no success.
Is there any way other then to replace characters & make its json like?
Any help would be highly appreciated.

A: As others already mentioned, it's not JSON. But based on the example you provided you should be able to transform it to a readable JSON. It's not the most pretty solution, but it seems to work. It have some draw-backs:

*

*It will only work when " = " is the separator.

*It will only work when each field is separated by ; followed by line-break (windows-style).
  private string MakeReadableJson(string base64Input)
  {
      var data = System.Convert.FromBase64String(base64Input);
      string readableString = Encoding.UTF8.GetString(data);
      var json = readableString.Replace("\" = \"", "\":\"").Replace(";\n", ",");
      return json;
  }

I use System.Text.JsonSerializer. Use it like so:
            string json = @"{
                   ""Id"": ""1000000872920320"",
                   ""TransactionDateUtc"": ""2021-09-06T14:42:17Z"",
                   ""ProductId"": ""1"",
                   ""AutoRenewing"": false,
                   ""PurchaseToken"": ""ewoJInNpZ25hdHVyZSIgPSAic29tZSBsb25nIGJhc2U2NCBzdHJpbmciOwoJInB1cmNoYXNlLWluZm8iID0gImV3b0pJbTl5YVdkcGJtRnNMWEIxY21Ob1lYTmxMV1JoZEdVdGNITjBJaUE5SUNJeU1EQXdMVEF4TFRBeElEQXhPakF4T2pBeElFRnRaWEpwWTJFdlRHOXpYMEZ1WjJWc1pYTWlPd29KSW5WdWFYRjFaUzFwWkdWdWRHbG1hV1Z5SWlBOUlDSnpiMjFsVlVsRUlqc0tDU0p2Y21sbmFXNWhiQzEwY21GdWMyRmpkR2x2YmkxcFpDSWdQU0FpVTI5dFpWUkpSQ0k3Q2draVluWnljeUlnUFNBaU15NDJJanNLQ1NKMGNtRnVjMkZqZEdsdmJpMXBaQ0lnUFNBaVUyOXRaVlJKUkNJN0Nna2ljWFZoYm5ScGRIa2lJRDBnSWpFaU93b0pJbWx1TFdGd2NDMXZkMjVsY25Ob2FYQXRkSGx3WlNJZ1BTQWlVRlZTUTBoQlUwVkVJanNLQ1NKdmNtbG5hVzVoYkMxd2RYSmphR0Z6WlMxa1lYUmxMVzF6SWlBOUlDSnpiMjFsSUc1MWJXVnlhV01nZEdsdFpTQnpkR0Z0Y0NCcGJpQnRjeUk3Q2draWRXNXBjWFZsTFhabGJtUnZjaTFwWkdWdWRHbG1hV1Z5SWlBOUlDSnpiMjFsSUZWSlJDSTdDZ2tpY0hKdlpIVmpkQzFwWkNJZ1BTQWlNU0k3Q2draWFYUmxiUzFwWkNJZ1BTQWljMjl0WlNCVmJtbHhkV1VnU1hSbGJTQkpSQ0k3Q2draWRtVnljMmx2YmkxbGVIUmxjbTVoYkMxcFpHVnVkR2xtYVdWeUlpQTlJQ0l3SWpzS0NTSnBjeTFwYmkxcGJuUnlieTF2Wm1abGNpMXdaWEpwYjJRaUlEMGdJbVpoYkhObElqc0tDU0p3ZFhKamFHRnpaUzFrWVhSbExXMXpJaUE5SUNKemIyMWxJRzUxYldWeWFXTWdkR2x0WlNCemRHRnRjQ0JwYmlCdGN5STdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTSWdQU0FpTWpBd01DMHdNUzB3TVNBd01Ub3dNVG93TVNCRmRHTXZSMDFVSWpzS0NTSnBjeTEwY21saGJDMXdaWEpwYjJRaUlEMGdJbVpoYkhObElqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURBd0xUQXhMVEF4SURBeE9qQXhPakF4SUVWMFl5OUhUVlFpT3dvSkltSnBaQ0lnUFNBaWFYQmhJR0Z3Y0NCaWRXNWtiR1VnYm1GdFpTSTdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTMXdjM1FpSUQwZ0lqSXdNREF0TURFdE1ERWdNREU2TURFNk1ERWdRVzFsY21sallTOU1iM05mUVc1blpXeGxjeUk3Q24wPSI7CgkiZW52aXJvbm1lbnQiID0gIlNhbmRib3giOwoJInBvZCIgPSAiMTAwIjsKCSJzaWduaW5nLXN0YXR1cyIgPSAiMCI7Cn0="",
                   ""State"": 0,
                   ""ConsumptionState"": 0,
                   ""IsAcknowledged"": false,
                   ""Payload"": null
               }";

            var info = JsonSerializer.Deserialize<ResultFromApple>(json);

            var purchaseTokenJson = MakeReadableJson(info.PurchaseToken);
            PurchaseToken purchaseToken = JsonSerializer.Deserialize<PurchaseToken>(purchaseTokenJson, new JsonSerializerOptions()
            {
                AllowTrailingCommas = true
            });

            var purchaseInfoJson = MakeReadableJson(purchaseToken.PurchaseInfo);
            PurchaseInfo purchaseInfo = JsonSerializer.Deserialize<PurchaseInfo>(purchaseInfoJson, new JsonSerializerOptions()
            {
                AllowTrailingCommas = true
            });

And your models:
public class PurchaseToken
{
    public string signature { get; set; }

    [JsonPropertyName("purchase-info")]
    public string PurchaseInfo { get; set; }
    public string environment { get; set; }
    public string pod { get; set; }

    [JsonPropertyName("signing-status")]
    public string SigningStatus { get; set; }
}

public class ResultFromApple
{
    public string Id { get; set; }
    public DateTime TransactionDateUtc { get; set; }
    public string ProductId { get; set; }
    public bool AutoRenewing { get; set; }
    public string PurchaseToken { get; set; }
    public int State { get; set; }
    public int ConsumptionState { get; set; }
    public bool IsAcknowledged { get; set; }
    public object Payload { get; set; }
}

public class PurchaseInfo
{
    [JsonPropertyName("original-purchase-date-pst")]
    public string OriginalPurchaseDatePst { get; set; }

    [JsonPropertyName("unique-identifier")]
    public string UniqueIdentifier { get; set; }

    [JsonPropertyName("original-transaction-id")]
    public string OriginalTransactionId { get; set; }
    public string bvrs { get; set; }

    [JsonPropertyName("transaction-id")]
    public string TransactionId { get; set; }
    public string quantity { get; set; }

    [JsonPropertyName("in-app-ownership-type")]
    public string InAppOwnershipType { get; set; }

    [JsonPropertyName("original-purchase-date-ms")]
    public string OriginalPurchaseDateMs { get; set; }

    [JsonPropertyName("unique-vendor-identifier")]
    public string UniqueVendorIdentifier { get; set; }

    [JsonPropertyName("product-id")]
    public string ProductId { get; set; }

    [JsonPropertyName("item-id")]
    public string ItemId { get; set; }

    [JsonPropertyName("version-external-identifier")]
    public string VersionExternalIdentifier { get; set; }

    [JsonPropertyName("is-in-intro-offer-period")]
    public string IsInIntroOfferPeriod { get; set; }

    [JsonPropertyName("purchase-date-ms")]
    public string PurchaseDateMs { get; set; }

    [JsonPropertyName("purchase-date")]
    public string PurchaseDate { get; set; }

    [JsonPropertyName("is-trial-period")]
    public string IsTrialPeriod { get; set; }

    [JsonPropertyName("original-purchase-date")]
    public string OriginalPurchaseDate { get; set; }
    public string bid { get; set; }

    [JsonPropertyName("purchase-date-pst")]
    public string PurchaseDatePst { get; set; }
}

A: It's a bit embarrassing. I saw the problem as the opposite before. Try this, I think this can meet the needs:
Parse JavaScript string
static void Main(string[] args)
{
    var jsStr = @"{
                    ""signature"" = ""some long base64 string"";
                    ""purchase-info"" = ""ewoJIm9yaWdpbmFsLXB1cmNoYXNlLWRhdGUtcHN0IiA9ICIyMDAwLTAxLTAxIDAxOjAxOjAxIEFtZXJpY2EvTG9zX0FuZ2VsZXMiOwoJInVuaXF1ZS1pZGVudGlmaWVyIiA9ICJzb21lVUlEIjsKCSJvcmlnaW5hbC10cmFuc2FjdGlvbi1pZCIgPSAiU29tZVRJRCI7CgkiYnZycyIgPSAiMy42IjsKCSJ0cmFuc2FjdGlvbi1pZCIgPSAiU29tZVRJRCI7CgkicXVhbnRpdHkiID0gIjEiOwoJImluLWFwcC1vd25lcnNoaXAtdHlwZSIgPSAiUFVSQ0hBU0VEIjsKCSJvcmlnaW5hbC1wdXJjaGFzZS1kYXRlLW1zIiA9ICJzb21lIG51bWVyaWMgdGltZSBzdGFtcCBpbiBtcyI7CgkidW5pcXVlLXZlbmRvci1pZGVudGlmaWVyIiA9ICJzb21lIFVJRCI7CgkicHJvZHVjdC1pZCIgPSAiMSI7CgkiaXRlbS1pZCIgPSAic29tZSBVbmlxdWUgSXRlbSBJRCI7CgkidmVyc2lvbi1leHRlcm5hbC1pZGVudGlmaWVyIiA9ICIwIjsKCSJpcy1pbi1pbnRyby1vZmZlci1wZXJpb2QiID0gImZhbHNlIjsKCSJwdXJjaGFzZS1kYXRlLW1zIiA9ICJzb21lIG51bWVyaWMgdGltZSBzdGFtcCBpbiBtcyI7CgkicHVyY2hhc2UtZGF0ZSIgPSAiMjAwMC0wMS0wMSAwMTowMTowMSBFdGMvR01UIjsKCSJpcy10cmlhbC1wZXJpb2QiID0gImZhbHNlIjsKCSJvcmlnaW5hbC1wdXJjaGFzZS1kYXRlIiA9ICIyMDAwLTAxLTAxIDAxOjAxOjAxIEV0Yy9HTVQiOwoJImJpZCIgPSAiaXBhIGFwcCBidW5kbGUgbmFtZSI7CgkicHVyY2hhc2UtZGF0ZS1wc3QiID0gIjIwMDAtMDEtMDEgMDE6MDE6MDEgQW1lcmljYS9Mb3NfQW5nZWxlcyI7Cn0="";
                    ""environment"" = ""Sandbox"";
                    ""pod"" = ""100"";
                    ""signing-status"" = ""0"";
                }";

    var model = GetModelFromJsStr<PurchaseToken>(jsStr);
}

public class PurchaseToken
{
    [JsonPropertyName("signature")]
    public string Signature { get; set; }
    [JsonPropertyName("purchase-info")]
    public string PurchaseInfo { get; set; }
    [JsonPropertyName("environment")]
    public string Environment { get; set; }
    [JsonPropertyName("pod")]
    public int Pod { get; set; }
    [JsonPropertyName("signing-status")]
    public int SigningStatus { get; set; }
}

public static T GetModelFromJsStr<T>(string jsStr) where T : new()
{
    var model = new T();
    var rows = jsStr.Split("\n").Select(item => item.Trim()).ToList();
    foreach (var prop in typeof(T).GetProperties())
    {
        var jsonProperty = prop.GetCustomAttribute<JsonPropertyNameAttribute>();

        if (jsonProperty != null)
        {
            var matchRow = rows.FirstOrDefault(row => row.StartsWith(@$"""{jsonProperty.Name}"" ="));
            if (matchRow != null)
            {
                var pattern = @$"^""{jsonProperty.Name}"" = ""(.*)"";$";
                var match = Regex.Match(matchRow, pattern);
                if (match?.Groups?.Count > 1)
                {
                    // convertible types can be extended
                    if (prop.PropertyType == typeof(int))
                    {
                        int.TryParse(match.Groups[1].Value, out var propValue);
                        prop.SetValue(model, propValue);
                    }
                    else
                    {
                        prop.SetValue(model, match.Groups[1].Value);
                    }
                }
            }
        }
    };

    return model;
}

A: I would use Pidgin to parse something like this.
Here's some code that parses your data into a Dictionary<string, string> and prints out the results:
using System;
using System.Collections.Generic;
using System.Linq;
using Pidgin;
using static Pidgin.Parser;

namespace NotQuiteJsonParsing
{
    class Program
    {
        const string PurchaseInfo = @"{
            ""original-purchase-date-pst"" = ""2000-01-01 01:01:01 America/Los_Angeles"";
            ""unique-identifier"" = ""someUID"";
            ""original-transaction-id"" = ""SomeTID"";
            ""bvrs"" = ""3.6"";
            ""transaction-id"" = ""SomeTID"";
            ""quantity"" = ""1"";
            ""in-app-ownership-type"" = ""PURCHASED"";
            ""original-purchase-date-ms"" = ""some numeric time stamp in ms"";
            ""unique-vendor-identifier"" = ""some UID"";
            ""product-id"" = ""1"";
            ""item-id"" = ""some Unique Item ID"";
            ""version-external-identifier"" = ""0"";
            ""is-in-intro-offer-period"" = ""false"";
            ""purchase-date-ms"" = ""some numeric time stamp in ms"";
            ""purchase-date"" = ""2000-01-01 01:01:01 Etc/GMT"";
            ""is-trial-period"" = ""false"";
            ""original-purchase-date"" = ""2000-01-01 01:01:01 Etc/GMT"";
            ""bid"" = ""ipa app bundle name"";
            ""purchase-date-pst"" = ""2000-01-01 01:01:01 America/Los_Angeles"";
        }";

        private static string IEnumerableCharToString(IEnumerable<char> value)
        {
            // Feel free to swap this with an alternative answer to https://stackoverflow.com/questions/8108313
            return new string(value.ToArray());
        }

        // Parsers can be slow to build, so minimise the
        // number of times this setup method is called.  See
        // https://github.com/benjamin-hodgson/Pidgin#speed-tips
        private static Parser<char, Dictionary<string, string>> BuildBlockParser()
        {
            var stringParser = Char('"').Then(AnyCharExcept('"').AtLeastOnceUntil(Char('"')));

            var lineParser = Map(
                (key, value) => new KeyValuePair<string, string>(IEnumerableCharToString(key), IEnumerableCharToString(value)),
                stringParser.Before(SkipWhitespaces).Before(Char('=')).Before(SkipWhitespaces),
                stringParser.Before(SkipWhitespaces).Before(Char(';')).Before(SkipWhitespaces));

            var linesParser = lineParser.AtLeastOnce().Map(pairs => new Dictionary<string, string>(pairs));

            var blockParser = SkipWhitespaces.Then(Char('{')).Then(SkipWhitespaces).Then(linesParser).Before(Char('}'));
            return blockParser;
        }

        static void Main()
        {
            var blockParser = BuildBlockParser();
            var result = blockParser.ParseOrThrow(PurchaseInfo);
            foreach (var (key, value) in result)
            {
                Console.WriteLine($"{key} = {value}");
            }
        }
    }
}

This parser has the following limitations:

*

*Values in key-value pairs are always strings, not numbers, booleans or anything else.

*There is no support for escaped " characters in keys or values.  I don't know how they would be escaped.

*There is no support for escape sequences such as \r, \n, \t or \u0123.

A: Was able to handle this by with following code using Newtonsoft.Json.JsonConverter:
Create models for the data
public class InAppPurchaseToken
{
    public string Signature { get; set; }
    [JsonProperty("purchase-info")]
    public string PurchaseInfo { get; set; }
    public string Environment { get; set; }
    public string Pod { get; set; }
    public string SigningStatus { get; set; }
}

public class InAppPurchaseInfo
{
    [JsonProperty("original-purchase-date-pst")]
    public string originalpurchasedatepst { get; set; }
    [JsonProperty("unique-identifier")]
    public string uniqueidentifier { get; set; }
    [JsonProperty("original-transaction-id")]
    public string originaltransactionid { get; set; }
    public string bvrs { get; set; }
    [JsonProperty("transaction-id")]
    public string transactionid { get; set; }
    public string quantity { get; set; }
    [JsonProperty("in-app-ownership-type")]
    public string inappownershiptype { get; set; }
    [JsonProperty("original-purchase-date-ms")]
    public string originalpurchasedatems { get; set; }
    [JsonProperty("unique-vendor-identifier")]
    public string uniquevendoridentifier { get; set; }
    [JsonProperty("product-id")]
    public string productid { get; set; }
    [JsonProperty("item-id")]
    public string itemid { get; set; }
    [JsonProperty("version-external-identifier")]
    public string versionexternalidentifier { get; set; }
    [JsonProperty("is-in-intro-offer-period")]
    public string isinintroofferperiod { get; set; }
    [JsonProperty("purchase-date-ms")]
    public string purchasedatems { get; set; }
    [JsonProperty("purchase-date")]
    public string purchasedate { get; set; }
    [JsonProperty("is-trial-period")]
    public string istrialperiod { get; set; }
    [JsonProperty("original-purchase-date")]
    public string originalpurchasedate { get; set; }
    public string bid { get; set; }
    [JsonProperty("purchase-date-pst")]
    public string purchasedatepst { get; set; }
}

And the handle the parsing using following code (assuming you have deserialized the initial json as inAppPayData C# object):
public string GetJsonFromBase64JsStr(string base64JsStr)
{
    if (string.IsNullOrWhiteSpace(base64JsStr))
        return "";

    var decodedStr2Parse = Encoding.UTF8.GetString(Convert.FromBase64String(base64JsStr));

    //var ConvertedJsonStrComplete = decodedStr2Parse.Replace("\" = \"", "\":\"").Replace(";\n", ",").Replace(",}", "}");  //more error prone
    var ConvertedJsonStrPartial = decodedStr2Parse.Replace("\" = \"", "\":\"").Replace(";\n", ",");
    var ConvertedJsonStrComplete = ConvertedJsonStrPartial.Remove(ConvertedJsonStrPartial.LastIndexOf(",}"), 1);

     return ConvertedJsonStrComplete;
}

//call the above function with base64JsString
var purchaseJsonStr = GetJsonFromBase64JsStr(inAppPayData.PurchaseToken);

var purchaseTokenObj = JsonConvert.DeserializeObject<InAppPurchaseToken>(purchaseJsonStr);

var purchaseInfoJsonStr = GetJsonFromBase64JsStr(purchaseTokenObj.PurchaseInfo);

var purchaseInfoObj = JsonConvert.DeserializeObject<InAppPurchaseInfo>(purchaseInfoJsonStr);


text:
Q: Search a substring using SQL in C# OleDb I have a Customers Database in MS Access.
I want to make a sql query that searches a substring from my primary key field.
For Example :
I want to select all the IDs that contain the number "35".
My DataBase before the SELECT statement :

My DataBase after the SELECT statement :

Is it possible ?

A: Since the Access wildcard is * and not % and, AFAIK, Access doesn't support CONTAINS I think you really want:
SELECT * FROM MyTable WHERE ID like "*35*"

Though based on our discussion in comments, other options (for when the ID field isn't a string) are:
SELECT * FROM MyTable WHERE Str(ID) like "*35*"

And
SELECT * FROM MyTable WHERE CStr(ID) like "*35*"

A: Assuming that the ID field is numeric,
In MsAccess:
Select * from myTable
where str(ID) like "*35*"

in SQL Server
Select * from myTable
where str(ID, 12, 0) like '%35%'

A: SELECT *
FROM your_table
WHERE CAST(ID AS VARCHAR(20)) LIKE '%35%';


text:
Q: On the restriction of field homomorphisms to subfields Let $F/L/K$ be field extensions with $L/K$ finite. Let $H=\text{Hom}_K(L,F)$ be the set of field homomorphisms $L\rightarrow F$ that fix $K$. Take $\alpha\in L$, and let $\lbrace \alpha_1,\dots,\alpha_n\rbrace=\lbrace \sigma(\alpha):\sigma\in H\rbrace$. Under what circumstances is $n_i=|\lbrace \sigma\in H:\sigma(\alpha)=\alpha_i\rbrace|$ constant for all $i$?
More generally, fix an intermediate field $L/M/K$, and let $\lbrace \tau_1,\dots,\tau_m\rbrace=\lbrace \sigma|_M:\sigma\in H\rbrace$. Under what circumstances is $m_i=|\lbrace \sigma\in H:\sigma|_M=\tau_i\rbrace|$ constant for all $i$?

For example, if $L/K$ is a normal extension, then $\sigma(L)\subseteq L$, and so $\sigma(L)=L$ since $L/K$ is algebraic. Then, $H=\text{Aut}_K(L)$ is a group, and it is easy to see that $n_i$ and $m_i$ are constant for all $i$. I would like to know how much this condition can be weakened.


text:
Q: Why are all WCF exceptions "Bad Request" even when more info is given? No matter how nice and orderly my WCF service is about throwing exceptions:
throw new FaultException<SapphireServiceFault>(fault, new FaultReason(fault.Message))

They always wind up in the client handler as "400 - Bad Request".  If you walk the chain of InnerException, it leads to one 400-BadRequest and then null.  No mention of the FaultException.
My interface is decorated with the FaultContract attribute:
    [WebInvoke(Method = "POST", UriTemplate = "action/execute/{actionID}")]
    [OperationContract]
    [FaultContract(typeof(SapphireServiceFault))]
    void ExecuteActionGroup(string actionID);

The implementation of that interface just throws the Fault for testing:
    public void ExecuteActionGroup(string groupID)
    {
        SapphireServiceFault fault = new SapphireServiceFault("Bad Mojo");
        throw new FaultException<SapphireServiceFault>(fault, new FaultReason("Hello World"));
    ...
    }

In the client, I can even try to catch that specific exception, but it comes through at a 400, not a FaultException:
        try
        {
            Program.SapphireService.ExecuteActionGroup(actionGroup.ActionGroupName);
        }
        catch(FaultException<SapphireServiceFault> ex)
        {
            // Does not catch anything
            MessageBoxEx.Show("Failed to execute action: " + ex.Message);
        }

There must be something I'm overlooking!
As I am using programmatic binding I cannot add anything to the app.config, but anything that can be done there can usually be done in the bindings.  For what it is worth, I have IncludeExceptionDetailInFaults turned on.
What am I missing to get more meaningful results back to the client?

A: It looks like you're trying to build RESTful service using WCF (hence usage of WebInvoke attribute).
You need to throw WebFaultException to get faults properly communicated over WebHttpBinding.


text:
Q: How to display Parameter Window data to a Label in VISIO I am trying to assign value to a LABEL in VISIO. But it is not working. Can you help me.
After I drag and drop my component on the right click I am giving an option "ADD STATION" this will add a LABEL to the component and after that I want to get value from the Parameter window and display it into the LABEL.
I am able to generate the LABEL on a button click I want some help to display the Value.
 Public Sub AddParameterToLabel(ByRef oLabel As Visio.Shape, ByRef sObjID As String, ByRef sParameterName As String, ByVal sPreText As String, ByVal bShow As Boolean)

    Dim sRowName As String = "Parameter"
    Dim iCurrentRow As Integer = oLabel.AddNamedRow(visSectionUser, sRowName, 0)

    If (Err.Number <> 0) Then
        Err.Clear()
        Dim iAddRow As Integer = oLabel.AddNamedRow(visSectionUser, "VisioSucks3", 0)
        oLabel.CellsSRC(visSectionUser, iAddRow, 1).RowName = sRowName
        iCurrentRow = iAddRow
    End If
    Dim ovCell As Visio.Cell = oLabel.CellsSRC(visSectionUser, iCurrentRow, visUserValue)

    Dim sParent As String = sObjID
    If (Len(sObjID) > 0) Then
        sParent = sObjID & DOT
    End If

    Dim oParam As Object.Interop.Param
    oParam = g_oObject.Param(sParent & sParameterName)
    Dim sPacked As String
    If (Err.Number <> 0) Then
        sPacked = "|-1|1|0|||||"
    Else
        'Add parameters with the unit conversions, as specified by the current choice
        sPacked = sParameterName & "|" &
                  oParam.SigFigs & "|" &
                  oParam.MultiplierToUserUnit & "|" &
                  oParam.AdderToUserUnit & "|" &
                  "|" &
                  sPreText & "|" &
                  "|" &
                  "g" & oParam.SigFigs & "|" &
                  "User" & "|" &
                  oParam.UserUnitsString
    End If

    If Not oParam Is Nothing Then
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oParam)
        oParam = Nothing
    End If

    ovCell.FormulaU = FormatStringForVisioOrSQL(sPacked)
    oLabel.CellsSRC(visSectionUser, iCurrentRow, visUserPrompt).Result(visNoCast) = Math.Abs(CInt(bShow))
    oLabel.Cells("Actions.Action[1]").Trigger()

End Sub

The "ParameterName = Compressor.StationFrom" which I am getting here.
and the value StationFrom will be having is DOUBLE i.e 1.2,1.3 etc..


text:
Q: How to Handle Automator Errors with Applescript I'm still pretty much a newbie, so I hope my question makes sense.
I created a simple Automator application. I have iCal set to run it during the night. Because other things are running at the same time, I sometimes get "The action "blah blah blah" encountered an error...."
Is there a way (with Applescript) to either: (1) ignore the error and have the application continue or (2) click the "OK" button on the error and restart the application?
EDIT: I basically want Applescript to run the Automator-created app and, if/when that app has a "The action "blah blah blah" encountered an error"-type message, I want Applescript to continue or restart the Automator-created app. This includes getting rid of the error message box that popped up during the running of the Automator-created app.
Thanks.

A: If your code is within an Applescript, you can try something like this:
repeat with i from 1 to 5
    try
        --insert your code here
        set thrownError to 1 / 0

        -- If code completes without error, exit repeat
        exit repeat
    on error
        beep
        delay 3
    end try
end repeat

A: If you just want to ignore an error in applescript, just use try
try
  --do what ever
on error
  --continue with code
end


text:
Q: How to fetch all messages from SQS queue till the queue is empty? Say I have the following code:
    final ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
    receiveMessageRequest.withMaxNumberOfMessages(10);
    final List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    for (final Message message : messages) {
        System.out.println("Message");
        System.out.println("  MessageId:     " + message.getMessageId());
        System.out.println("  ReceiptHandle: " + message.getReceiptHandle());
        System.out.println("  MD5OfBody:     " + message.getMD5OfBody());
        System.out.println("  Body:          " + message.getBody());
        for (final Entry<String, String> entry : message.getAttributes().entrySet()) {
            System.out.println("Attribute");
            System.out.println("  Name:  " + entry.getKey());
            System.out.println("  Value: " + entry.getValue());
        }
    }

This code returns 10 messages from my understanding. If the SQS queue has 1000 messages then do I need another loop ?
Is there a way to know the SQS queue size?

A: Yes you would need another (outer) loop to continue getting messages in batches of 10, until there were no messages left. You don't need to know the queue size for that, just use a while loop and iterate until get you get a response with no messages.
Something like this:
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
receiveMessageRequest.withMaxNumberOfMessages(10);
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
while (messages.size() > 0) {
    for (final Message message : messages) {
        System.out.println("Message");
        System.out.println("  MessageId:     " + message.getMessageId());
        System.out.println("  ReceiptHandle: " + message.getReceiptHandle());
        System.out.println("  MD5OfBody:     " + message.getMD5OfBody());
        System.out.println("  Body:          " + message.getBody());
        for (final Entry<String, String> entry : message.getAttributes().entrySet()) {
            System.out.println("Attribute");
            System.out.println("  Name:  " + entry.getKey());
            System.out.println("  Value: " + entry.getValue());
        }
    }

    receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
    receiveMessageRequest.withMaxNumberOfMessages(10);
    messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
}

If you do need to get the number of messages still in the queue you can query the AWS SDK for the queue attribute ApproximateNumberOfMessages. like:
GetQueueAttributesResult attrResult = sqs.getQueueAttributes(queueUrl, ["ApproximateNumberOfMessages"]);
System.out.println("Messages in queue: " + attrResult.getAttributes()["ApproximateNumberOfMessages"]);

A: No messages / empty messages may be misguiding. The retrieval may not have happened due to different reasons like-
Visibility timeout  due to another consumer polling
Distributed nature of SQS infrastructure


text:
Q: How to fix Error processing element Flume: CLASS_NOT_FOUND? We are unable to get a flumeappender to work using log4j2. using log4j.properties things configure file however, not via log4j2.xml. The error we get is: Error processing element Flume: CLASS_NOT_FOUND
Following are my maven dependencies:
<dependencies>
        <dependency>
            <groupId>org.apache.flume</groupId>
            <artifactId>flume-ng-sdk</artifactId>
            <version>1.5.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flume.flume-ng-clients</groupId>
            <artifactId>flume-ng-log4jappender</artifactId>
            <version>1.5.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>

Following is my log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug" name="CE" packages="net.ahm.ce.server">
    <Appenders>
        <Flume name="eventLogger" compress="true" type="Embedded">
            <Agent host="192.168.4.16" port="41414" />
            <RFC5424Layout enterpriseNumber="18060" includeMDC="true"
                appName="CE" />
        </Flume>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="eventLogger" />
        </Root>
    </Loggers>
</Configuration>

The log at startup:
2014-09-17 10:41:27,339 DEBUG Starting configuration XmlConfiguration[location=C:\dev\AHM\FlumePOC\server\target\classes\log4j2.xml]
2014-09-17 10:41:27,339 DEBUG Generated plugins in 0.001350 seconds, packages: [net.ahm.ce.server], preload: false.
2014-09-17 10:41:27,339 DEBUG Found Plugin Map at jar:file:/C:/Users/droy/.m2/repository/org/apache/logging/log4j/log4j-core/2.0.2/log4j-core-2.0.2.jar!/META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat
2014-09-17 10:41:27,588 DEBUG Generated plugins in 0.243478 seconds, packages: [net.ahm.ce.server, org.apache.logging.log4j.core], preload: true.
2014-09-17 10:41:27,604 ERROR Error processing element Flume: CLASS_NOT_FOUND
2014-09-17 10:41:27,697 DEBUG Generated plugins in 0.100369 seconds, packages: [net.ahm.ce.server, org.apache.logging.log4j.core], preload: false.
2014-09-17 10:41:27,697 DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin]. Searching for builder factory method...
2014-09-17 10:41:27,697 DEBUG No builder factory method found in class org.apache.logging.log4j.core.config.AppendersPlugin. Going to try finding a factory method instead.
2014-09-17 10:41:27,697 DEBUG Still building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin]. Searching for factory method...
2014-09-17 10:41:27,697 DEBUG Found factory method [createAppenders]: public static java.util.concurrent.ConcurrentMap org.apache.logging.log4j.core.config.AppendersPlugin.createAppenders(org.apache.logging.log4j.core.Appender[]).
2014-09-17 10:41:27,697 DEBUG Calling createAppenders on class org.apache.logging.log4j.core.config.AppendersPlugin for element Appenders with params(={})
2014-09-17 10:41:27,697 DEBUG Built Plugin[name=appenders] OK from factory method.
2014-09-17 10:41:27,697 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef]. Searching for builder factory method...
2014-09-17 10:41:27,697 DEBUG No builder factory method found in class org.apache.logging.log4j.core.config.AppenderRef. Going to try finding a factory method instead.
2014-09-17 10:41:27,697 DEBUG Still building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef]. Searching for factory method...
2014-09-17 10:41:27,697 DEBUG Found factory method [createAppenderRef]: public static org.apache.logging.log4j.core.config.AppenderRef org.apache.logging.log4j.core.config.AppenderRef.createAppenderRef(java.lang.String,org.apache.logging.log4j.Level,org.apache.logging.log4j.core.Filter).
2014-09-17 10:41:27,713 DEBUG Calling createAppenderRef on class org.apache.logging.log4j.core.config.AppenderRef for element AppenderRef with params(ref="eventLogger", level="null", null)
2014-09-17 10:41:27,713 DEBUG Built Plugin[name=AppenderRef] OK from factory method.
2014-09-17 10:41:27,713 DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger]. Searching for builder factory method...
2014-09-17 10:41:27,713 DEBUG No builder factory method found in class org.apache.logging.log4j.core.config.LoggerConfig$RootLogger. Going to try finding a factory method instead.
2014-09-17 10:41:27,713 DEBUG Still building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger]. Searching for factory method...
2014-09-17 10:41:27,713 DEBUG Found factory method [createLogger]: public static org.apache.logging.log4j.core.config.LoggerConfig org.apache.logging.log4j.core.config.LoggerConfig$RootLogger.createLogger(java.lang.String,org.apache.logging.log4j.Level,java.lang.String,org.apache.logging.log4j.core.config.AppenderRef[],org.apache.logging.log4j.core.config.Property[],org.apache.logging.log4j.core.config.Configuration,org.apache.logging.log4j.core.Filter).
2014-09-17 10:41:27,713 DEBUG Calling createLogger on class org.apache.logging.log4j.core.config.LoggerConfig$RootLogger for element Root with params(additivity="null", level="DEBUG", includeLocation="null", ={eventLogger}, ={}, Configuration(CE), null)
2014-09-17 10:41:27,713 DEBUG Built Plugin[name=root] OK from factory method.
2014-09-17 10:41:27,713 DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin]. Searching for builder factory method...
2014-09-17 10:41:27,713 DEBUG No builder factory method found in class org.apache.logging.log4j.core.config.LoggersPlugin. Going to try finding a factory method instead.
2014-09-17 10:41:27,713 DEBUG Still building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin]. Searching for factory method...
2014-09-17 10:41:27,713 DEBUG Found factory method [createLoggers]: public static org.apache.logging.log4j.core.config.Loggers org.apache.logging.log4j.core.config.LoggersPlugin.createLoggers(org.apache.logging.log4j.core.config.LoggerConfig[]).
2014-09-17 10:41:27,713 DEBUG Calling createLoggers on class org.apache.logging.log4j.core.config.LoggersPlugin for element Loggers with params(={root})
2014-09-17 10:41:27,713 DEBUG Built Plugin[name=loggers] OK from factory method.
2014-09-17 10:41:27,713 ERROR Unable to locate appender eventLogger for logger

A: I think the flume log4j appender you configured is for log4j-1.2. Try removing this section
    <dependency>
        <groupId>org.apache.flume.flume-ng-clients</groupId>
        <artifactId>flume-ng-log4jappender</artifactId>
        <version>1.5.0.1</version>
    </dependency>

and instead configuring the flume log4j appender that is included in log4j2. I think this should work:
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-flume-ng</artifactId>
        <version>2.0.2</version>
    </dependency>

The log4j2 Flume Appender manual page has more details: http://logging.apache.org/log4j/2.x/log4j-flume-ng/index.html


text:
Q: Onchange Event of Select Box I am using an onchange event of select box with jquery.
On change I have given display property = none in other div.
Problem is that when I got data from database and set it in select box so onchange property is not applied for given value. Why?
My code
<select id="patientType" name="Patient_Type">
<option value="">--SELECT--</option>
<option value="OPD">OPD</option>
<option value="IPD">IPD</option>
</select>

Script
$('#patientType').change(function() {
 if ($('#patientType').val() == 'IPD') {
  if ($('#roomInfo').hasClass('inactive')) {
   $('#roomInfo').removeClass('inactive');// CSS Property Display None in this class
   $('#roomInfo').addClass('active');
  }
 } else {
  if ($('#roomInfo').hasClass('active')) {
     $('#roomInfo').removeClass('active');
     $('#roomInfo').addClass('inactive');
    }
 }
});

now i got data From database and set it this select patientType
$('#patientType').val(data fetch From the database);
can not apply onchange event apply and not display my roomInfo div
so it is possible or not .
or another method for getting that method.
Please help.
Thanks In Advance.

A: Since you changing the value manually. You need to trigger the .change() event of select box.
Refer the following link.
http://api.jquery.com/change/
or else
if you loading the data through ajax use like following
$('#patientType').on("change",function() {
   //Your code here
});

A: Set an change event in jQuery:
$("#ddl").change(function(){
    alert($(this).val());
});

A: Get Value of Select Box and set it like this:
$("#patientType option[value='`OPD']").attr("selected","selected");


text:
Q: g++ : command not found in angstrom on beagleboard I am using angstrom on beagle board.. but when I try to run any command on the terminal I get this error:
Sh:g++:not found
I tried installing g++ Using opkg install g++ but no use!!

A: Do opkg install task-native-sdk or, if you only need g++, opkg install g++-symlinks.


text:
Q: Unable to return nil in generic function I am trying to understand generics better and am writing a function, that finds a key in a given dictionary with a given value.
If the value is not found it should return nil.
func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil //ERROR: Nil is incompatible with Type 'Key'
}

I reveice this error:

Nil is incompatible with Type 'Key'

A: Your function is set to return a Key as indicated by -> Key
You cannot return a nil because Key is an unwrapped variable. Instead, you can set the function to return an Optional which means that it can either have a Key, or it can be nil. Simply add a ? after the return type
func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil
}

A: In order to return nil you need to return a Key Optional " Key? "
You can read more about optionals here.
func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? {
   for set in dictionary {
       if set.value == value {
           return set.key
       }
   }
   return nil
}

A: Alternative implementation:
extension Dictionary where Value: Equatable {
    func key(forValue v: Value) -> Key? {
        return self.first(where: { $0.value == v})?.key
    }
}

["a": 1, "b": 2, "c": 3].key(forValue: 3) // => Optional("c")

Note that in the case where two Keys map to the same Value v, it's not deterministic which of the two Keys will be returned. To get all Keys mapping the Value v, you can do this:
extension Dictionary where Value: Equatable {
    func keys(forValue v: Value) -> [Key] {
        return self.filter{ $0.value == v}.map{ $0.key }
    }
}

["a": 1, "b": 2, "c": 3, "d": 3].keys(forValue: 3) // => ["d", "c"]


text:
Q: Text Input onSubmit while using fetch React Native I am trying to update my state for nickname and email through textInput and then submit it through a post request to my server. Both keep coming back as undefined. I'm totalling lost as to what I'm doing wrong here.
export default class Add extends Component {
  constructor(props){
    super(props);
    this.state ={
      isLoading: true,
      nickname: "",
      email: ""
    }
  }

  static navigationOptions = {
    title: 'Add Contacts',
  };

  componentDidMount(){
        this.setState({
          isLoading: false
        })
  }

  onSubmit = () => {
    console.log('on submit')
    return fetch(`...`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json, text/plain */*',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(this.state)
        })
        .then((response) => response)
        .then((responseJson) => {
          return responseJson
        })
        .catch((error) => {
          throw error;
        })
  }

  render() {
    const { navigate } = this.props.navigation;
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return(
      <View
        style={styles.container}
      >
        <Text
          style={{fontSize:30}}>
          New Contact
        </Text>
            <View>
              <TextInput
                ref= {(el) => { this.nickname = el; }}
                onChangeText={(nickname) => this.setState({nickname}, function () {console.log('Nickname updated')})}
                value={this.state.nickname}
              />
              <TextInput
                value={this.state.email}
                onChangeText={(text) => this.setState({email: text})}
                />
            </View>
        <Button
          text = {
            <Text
              style={{color:colors.textColor, textAlign: 'center'}}
              >
              Save
            </Text>
          }
          onPress= { () => {
              this.onSubmit()
              navigate('Home')
           }
          }
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    marginTop: 20,
    alignItems: 'center',
    justifyContent: 'center',
  }
});

A: .then((response) => response)

Should be:
.then((response) => response.json())

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Making_fetch_requests


text:
Q: Show / Hide images randomly using jQuery I want to create a function that grabs all the instances of an image class on the page. As default these will be hidden, then randomly after a certain interval show one of those images (can be any image). Then the function will rerun and show another image. (whilst hiding the image that was shown on the first run through.
I've got to this stage with the function (not currently working)
(function randomShow() {
var showDiv = $('.show'),
    el = showDiv.eq(Math.floor(Math.random() * showDiv.length));
    el.show().delay(2000).show(randomShow);
})();

Thanks

A: I put together a jsFiddle using divs in place of images to demonstrate (pure js):
http://jsfiddle.net/oogley_boogley/az9gd8wf/
the script:
var divs = document.getElementsByClassName('square');
var arrLength = divs.length;
var randomNumberLimit;
var interval_speed = 1000;

setInterval(function(){
randomNumberLimit = Math.floor((Math.random() * arrLength) + 1);
for(i=0;i<arrLength;i++){
    var matchingDiv = divs[i];
    if(matchingDiv.id == randomNumberLimit){
        matchingDiv.setAttribute("class","showing square blue");
    }
    if(matchingDiv.id != randomNumberLimit){
        matchingDiv.setAttribute("class","hiding square blue");
    }
}
}, interval_speed);


text:
Q: how to remove wild characters from mysql somehow wild characters has cropped up in my mysql table while storing UNC path in my table.
and all the \r onces are showing up a square in the fields. Can anyone tell me how to fix these please?
Thanks.

A: Are you looking for REPLACE(str,from_str,to_str)


text:
Q: How does one create a record, based on custom provided key and value data? I'm still a beginner in JavaScript and I need to create an object based on what the user types in the input fields.
Here are the input fields on my form:

After the user enters the values for column and value, this is how the data is being received:
[
  [{
      label: "Column",
      value: "column1",
      name: "01",
    },
    {
      label: "Value",
      value: "value1",
      name: "02",
    },
  ],
  [{
      label: "Column",
      value: "column2",
      name: "10",
    },
    {
      label: "Value",
      value: "value2",
      name: "11",
    },
  ],
];

But that's not how it can be saved to send the database, the way I need to send it is like this:
{
  // other data

  "column_names": {
    "column1": "value1",
    "column2": "value2"
  }
}

Could you tell me how can I create an Object based on what the user types? But in the structure I showed in the second code snippet?

A: The data structure provided by the OP can be seen as an array of object entries where each entry holds a tuple of key and value related meta data.
Thus a straightforward approach does reduce the provided data into the desired record.

const receivedData = [
  [{
    label: "Column",
    value: "column1",
    name: "01",
  }, {
    label: "Value",
    value: "value1",
    name: "02",
  }], [{
    label: "Column",
    value: "column2",
    name: "10",
  }, {
    label: "Value",
    value: "value2",
    name: "11",
  }],
];

const recordData = {

  // other data

  "column_names": receivedData
    .reduce((data, [ keyData, valueData ]) => {
      const key = keyData.value;
      const { value } = valueData;
      return Object.assign(data, { [key]: value });
    }, {})
};
console.log({ recordData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: your expected result is object design based where you can group value by their names which is a bit more lengthy but if you wanted to improve object design to do same task i have a suggested code try this
use data attribute on input fields with their name
then get all the values in one object with their corresponding key names see an example below

function getData(root){
    const Els = root.querySelectorAll("[data]"),newOb = {}
    Els.forEach(each=>{
        let key = each.getAttribute("data"), val = each.value
        newOb[key] = val
    })
    return newOb
}
const main = document.querySelector(".root")
main.oninput = function(){console.log(getData(main))}
<div class="root">
    <input class="border" data="col1" type="text">
    <input class="border" data="col2" type="text">
    <input class="border" data="col3" type="text">
    <input class="border" data="col4" type="text">
</div>


text:
Q: Making a short URL similar to TinyURL.com I'm building a new web app that has a requirement to generate an internal short URL to be used in the future for users to easily get back to a specific page which has a very long URL. My initial thoughts are to store a number in a database and output it in a HEXADECIMAL value to keep it shorter than an integer. TinyURL.com seems to use something other than HEXADECIMAL (multiple case letters mixed with numbers). Is there an easy way to generate something similar what TinyURL does?

A: Please, check out this good explanation on subject: Random TinyURL Browser (Updated) .
Important part:

As we have established, there are 62,193,780 possible values for TinyURL's. TinyURL's are generated by a Base 36 hash (36 indicating the number of characters a-z and 0-9, the array of possible values out of which a TinyURL can be constructed), autoincremented by MySQL with an initial value count of zero.

BTW, another SO similar question, through a mathematical view : Creating your own Tinyurl style uid. And here some .NET source code: Base 36 type for .NET (C#)

A: They use base 36 encoding, and you can make your app more robust by using base 64.
Here's what I'd try in Python (I do see your language tags, forgive me):
#!/usr/bin/python

from base64 import b64encode
from hashlib import sha1

for i in range(5):
    salted_int = "<salt>%s</salt>" % i
    print b64encode(sha1(salted_int).hexdigest())[:6]

Outputs:
NTUwMz
ZTVmZD
OGEzNm
Njc2MT
YzVkNj

So you can autoincrement an integer and feed it to some kind of function like this, and end up with a good chance of a random group of strings. See also my answer to this question.  Some base64 implementations have the potential to emit a slash / or a plus sign +, and therefore you should keep an eye out for these in your implementation as they're dangerous in URLs.
Hashes are really flexible and prevent your users from guessing the next URL (if this is important to you).

A: Another asp.net open-source one for you to investigate:
mini url

A: I recently saw something like this on codeplex for sharepoint and they seemed to use hexadecimal numbers for the url shortener. It might be worth taking a look at how they do it here http://spurlshortener.codeplex.com/

A:
My initial thoughts are to store a number in a database and output it in a HEXADECIMAL value to keep it shorter than an integer.

What is the point of keeping something shorter than an integer?
So you want to have URL like: http://here.there/12D687 instead of http://here.there/1234567?
If you'll ask me which one is easier for me I'll tell the latter one.
But honestly I do not see the point in my example as both are pretty much the same.

Is there an easy way to generate something similar what TinyURL does?

Yes. Ask the user to provide it.
If it is not possible just use the plain integer id. What can be easier...


text:
Q: SharePoint 2007 - Upgrading directly to SP2 I have a SharePoint 2007 environment which has not been updated for quite long time (Aug 2007 CU installed).
Now we are in the process of migrating those SharePoint 2007 instance onto SharePoint 2010 farm.  One of the prerequisites are to update our SharePoint 2007 instances to at least SP2,
Is it advisable to upgrade directly onto SP2 instead of going through SP1 --> SP2 path ?
I read in Microsoft site that SP2 includes all the SP1 related changes (of course it should)
Any suggestions ?
Thanks in Advance...
Sudhir Kesharwani

A: There is an official blog from Microsoft SharePoint Team, which says - Yes, you can.
Visit this blog for all detailed steps that you need to watchout for -
http://blogs.msdn.com/sharepoint/archive/2009/04/28/announcing-service-pack-2-for-office-sharepoint-server-2007-and-windows-sharepoint-services-3-0.aspx
As the blog says, SP2 can be installed directly on any build before Febrary 2009.
NOTE: Take DB backups on each step of your upgradation process, so that you can revert to the previous working condition without any issues. Also, remember to run the SharePoint configuration wizard or psconfig in command line on each server in your farm for complete upgradation.


text:
Q: Can email be hosted on a different server than the website? While of course the answer in general is a resounding yes, this is my particular issue.
A person has a website "example.com" that is hosted unfortunately at hostgator. There email "@example.com" is hosted on that same server on hostgator which uses cpanel to manage the site and email.
The new website will be hosted on a separate robust and optimized DigitalOcean server. Normally, we would simply point the a record for example.com to point to the new server. The problem I see is that I imagine the email system would go down. Normally, if people use a third party service like Google Apps it's not a problem.
In this scenario however, is there anyway to point the website to the new server, but leave the email system intact on the previous server without having to have the 200+ people have to change any settings on their end? In the host gator DNS "example.com" and "webmail.example.com" and "mail.example.com" all point to the same ip. Theoretically, if I leave webmail and mail alone and just change "example.com" to point to the new server ip, the email should remain working exactly as before but with the website now be served at the new server? Or would the email stop working for reason? Any advice would be most helpful.

A: OK. Right now email goes to wherever example.com resolves to. If you're going to change the example.com DNS record to resolve to the new web host then you'll want to change the MX record to be mail.example.com. That way after the change to example.com email will continue to flow to mail.example.com, which will remain unchanged. Do this now while they're both resolving to the same host. That way when you change the example.com DNS record there won't be any interruption in mailflow to example.com recipients.
Do the email clients connect to mail.example.com or example.com?

After all is said and done, this is whay you want:
example.com = new web host
www.example.com = new web host
mail.example.com = unchanged
webmail.example.com = unchanged
MX = mail.example.com

A: What you said is correct. If you just change the A record pointing to the new IP, only the website pointing will be changed, taking into account that there is an existing MAIL.domain.com record and any Webmail CNAME's (if any).


text:
Q: How can Raycast interact with Unity's Canvas UI elements? I created a Raycast that shoots from an object(not main camera) and I want it to hit UI elements. Example below.
Example
UI outlined in orange, big grey plane is a test object, red head is placed upon user's head and green is DrawRay of my raycast attached to an eye. I am trying to make it so user looks at a UI button and raycast can hit that button.
I've been playing around with Graphic raycast but nothing seems to work. Grey plane is still being hit by the raycast. I tried playing with OnPointerEnter but the thing is that my eye raycast is not a mouse/finger touch and is a second pointer.
Any ideas how to make it work with either isPointerOverGameObject or Graphic Raycaster or any other method?? Or how to create a second pointer that will be the eye raycast?
Current code below.
private void FixedUpdate()
{
    GraphicRaycaster gr = this.GetComponent<GraphicRaycaster>();

    PointerEventData pointerData = new PointerEventData(EventSystem.current);

    pointerData.position = Input.mousePosition;

    List<RaycastResult> results = new List<RaycastResult>();
    gr.Raycast(pointerData, results);
    //EventSystem.current.RaycastAll(pointerData, results);
    if (results.Count > 0)
    {
        if (results[0].gameObject.tag == "Test tag")
        {
            Debug.Log("test");
        }
    }

    //----- Failed Graphic raycast experiments above; working RaycastHit below --------

    RaycastHit hit;

        Debug.DrawRay(transform.position, transform.forward * -10000f, Color.green);

        if (Physics.Raycast(transform.position, transform.forward * -1, out hit))
        {

            Debug.Log(hit.transform.name);
        }

}

A: This is actually much more complicated if you want to do proper interaction with the canvas elements.
I suggest you do not try to roll out the solution yourself, but look at some already made solutions. Most VR toolkits have their own implementations, you could look into VRTK's example scene 007 - Interactions. You don't have to use VR to use it - just use the fallback SDK.
For more details on how this works, I might point you to the article from Oculus: Unity Sample Framework (a bit out of date).


text:
Q: No match to call for template member function for operator<< overload I am trying to write an output function for a matrix class by overloading the operator<< overload. The matrix class also has an indexing function, which is created by overloading the `op.
The code is as follows:
template<typename T, unsigned int N>
T& LU_Matrix<T, N>::operator() (unsigned int i, unsigned int j)
{
    return data_[N * i + j];
}

template<typename T, unsigned int N>
std::ostream& operator<< (std::ostream& os, const LU_Matrix<T, N> mat)
{
    for (unsigned int i = 0; i < N; ++i)
    {
        for (unsigned int j = 0; j < N; ++j)
        {
            os << mat(i, j) << " ";
        }
        os << std::endl;
    }
    return os;
}

int main()
{
    LU_Matrix<double, 3> lu_mat();
    // instantiate lu_mat here
    std::cout << lu_mat << std::endl;
    return 0;
}

When I run this, it throws the error
no match to call for '(const LU_Matrix<double, 3>) (unsigned int, unsigned int)'

It seems like the compiler should have created the stated function, given the templated function overloading operator<<. What's going wrong here?

A:
What's going wrong here?

As others have pointed out in comment section, Your LU_Matrix::operator() isn't const-qualified, therefore it cannot be used with const qualified  LU_Matrix objects.
In your operator<< overload, you have the above-mentioned case:
std::ostream& operator<< (std::ostream& os, const LU_Matrix<T, N> mat)
//                                          ^^^^^^ --------------------> this

Here the compiler does not find a const operator() operator overload to call with the const object, hence the error!
You need to change the declaration and definition to:
const T& operator() (unsigned int i, unsigned int j) const;
^^^^^^^^^                                            ^^^^^^

Not that, the return parameter also must be const qualified, as you return the element from a member of the class from a const member function.

In addition, as an improvement operator<<,  neither modify the object nor
require a copy, therefore you can actually pass const-ref to LU_Matrix<T, N> to the operator<< overload:
template<typename T, unsigned int N>
std::ostream& operator<< (std::ostream& os, const LU_Matrix<T, N>& mat) /* noexcept */
{
    // ...
    return os;
}

(See a demo)


text:
Q: How to use ngClass with css? I have a css code that looks like this:

:host >>> a.ng2-smart-sort-link.sort::after {
    content: '';
    right: 0.75rem;
    position: absolute;
    display: inline-block;
    width: 0;
    height: 0;
    border-bottom-color: #1a2138;
    border-bottom: solid rgba(0, 0, 0, .3);
    border-left: solid transparent;
    border-right: solid transparent;
    border-width: 0.375rem;
    margin-bottom: 2px;
    top: 50%;
    -webkit-transform: translate(0, -50%) rotate(180deg);
    transform: translate(0, -50%) rotate(180deg);
  }

 a.sort.asc::after {
    -webkit-transform: translate(0, -50%);
    transform: translate(0, -50%);
 }
 <ng2-smart-table [ngClass]="{class: settings.columns.device.showSortIcon == true}"></ng2-smart-table>

How can I implement a class in css to use it with ngClass to display this css if a condition is true?

A: Use className to toggle your css class. If your css class name is class then :
<ng2-smart-table [className.class]="{!!settings.columns.device.showSortIcon }"</ng2-smart-table>

Or angular directive ngClass :
<ng2-smart-table [ngClass]="{'class': !!settings.columns.device.showSortIcon }"</ng2-smart-table>

I tend to prefer className when I only have one conditional class.

A: Try this:
<ng2-smart-table [ngClass]="{'class':settings.columns.device.showSortIcon == true}"</ng2-smart-table>

A: ngClass directive will add the class to the element it self so the class selector will be like this
:host >>> component-tag.calss .. {
  // something magical will happen ♂
}

ngClass Class will add the class base of the condition is true

as an example consider this
template
<app-title [ngClass]="{'blue-text' : color === 'blue', 'green-text' : color == 'green'}">
</app-title>

style
:host >>> app-title.blue-text p {
  color: blue
}
:host >>> app-title.green-text p {
  color: green
}

demo


text:
Q: Pyshp draws polygons out of order after intersection of two shapefiles I have two shapefiles. One contains electoral borders but not coastline and the other contains provinces and coastlines. I am plotting the electoral districts using Python's pyshp and filling in the colors according to some data. That all works on the original shapefile:

And here is the important part of my plotting script:
sf = shp.Reader(shapefile)
records = []
shapes = []
for i,j in zip(sf.records(),sf.shapeRecords()):
    records.append(i)
    shapes.append(j)

plt.figure()
for rec,shape in zip(records,shapes):
    xy = [[i[0],i[1]] for i in shape.shape.points]
    plt.fill([i[0] for i in xy], [i[1] for i in xy], lw=0.2, edgecolor='white', facecolor=cmap(<some numbers from a list>))

I wanted the electoral districts to have nicer looking borders on the coasts so I used the intersect feature in QGIS to create a new shapefile of the electoral district file as an input layer and the coastline file as the intersecting layer. The result of that displays just fine in QGIS:

Here are the original shapefiles that I intersected shown overlapping in QGIS:

As you can hopefully see from the screen grab, some electoral districts get broken into multiple polygons because they contain islands, for example, but maintain their attributes (which is what I want).
However, when I use the same Python script above it seems that the plotting order of the points is all messed up resulting in oddly shaped polygons. It looks like the drawing is jumping across points previously part of the same electoral district and the same polygon but now apart of different polygons but still the same district.

Can anyone help? I can provide more details upon request.
EDIT:
I've narrowed the problem down to the way I'm handling multipart polygons. The intersection didn't break up polygons into new polygons, it just created multiple parts for each one and I'm not sure how to use pyshp to draw the parts separately.

A: Okay, I figured it out after my last edit. It was indeed a problem with polygons containing multiple parts. Here is my fixed figure.

So my first attempt at a solution was to apply a Multipart-to-Single-Polygon function in QGIS. That improved things but did not eliminate the fractured appearance entirely. A quick look at sf.shapeRecords[i].shape.parts showed that there were still multipart shapes in my shapefile. Fortunately the shape.parts attribute is a list containing indices of where new parts begin in the shape.points list. So you simply need to break up your shape drawing at the appropriate index and restart drawing the next part until the next index. If the shape.parts attribute contains the list [0] then there is only one part. Here's a minimal example of my implementation:
for shape in sf.shapeRecords:
    if len(shape.shape.parts) == 1:
        x = [i[0] for i in shape.shape.points]
        y = [i[1] for i in shape.shape.points]
        plt.fill(x, y)
    else:
        for index in range(len(shape.shape.parts)):
            try:
                x = [i[0] for i in shape.shape.points[shape.shape.parts[index]:shape.shape.parts[index+1]]]
                y = [i[1] for i in shape.shape.points[shape.shape.parts[index]:shape.shape.parts[index+1]]]
            except:
                x = [i[0] for i in shape.shape.points[shape.shape.parts[index]:]]
                y = [i[1] for i in shape.shape.points[shape.shape.parts[index]:]]
            plt.fill(x, y)

In words, you iterate through your shapes and check each one to see if its parts list has only one entry. If it has one entry it means there is only one part so you can plot as normal. If it has more than one entry then you break the points list into sections according to the indices given in the parts list and plot each one separately.
Hopefully this saves someone some trouble later on.


text:
Q: How to Access Script Tags in Header IN my Wordpress blog,  I am looking to update a link in header that I believe is outdated:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?ver=3.5.1'></script>
How do I get to this link? What file is it in?  In my header.php file, I see wp_head() -- I track that down and it doesn't lead me to anything that I can understand....

A: If done right there should be a callback hooked to wp_enqueue_scripts which has either wp_enqueue_script or both wp_register_script and wp_enqueue_script in it. Something like the following from the Codex:
function themeslug_enqueue_script() {
    wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );

You will need to find that callback function in your theme or in one of your plugins. You should be able to narrow things down by disabling plugins one by one, and by switching themes to a default theme like Twenty Twelve. Once you find it it should be obvious how to change the path.
If not done right, I have no way to guess what was done or how to alter it.

A: Open your theme's functions.php file (usually located in /wp-content/themes/my_theme/functions.php, replacing my_theme with the directory name of your theme) and do a text search in that file for the function containing the link to the jQuery library.


text:
Q: How to debug JavaScript asynchronously? (many scripts are loading) Generally I know how set breakpoints, inspect variables, step into functions etc...
Default.htm consists of hundreds of scripts and empty  placeholders.
Ideally I would like to proceed step-by-step. Setting breakpoint in the first line like that doesn't work:

When I step over next function call it is long gone (everything has loaded).

Generally how do I debug asynchronously loading scripts? (timeline clearly indicates that they are loading simultaneously)
Maybe I should use HTTP proxy such as Fiddler? I know how to set simple breakpoint (BPU) and then?

In other words - which approach - How can I debug my JavaScript code? - is tailored to my needs?

A: If you are using chrome dev tools:

*

*let the site load

*Put a break point at the entry point of your js. (if you don't know where this is, but a breakpoint at the outermost scope of each of the files under the Sources tab.

*F5 (refresh the web page)

*First break point that gets hit is your entry point. F11 - step into, F10 = step over.

Hope this helps.


text:
Q: how to set resource relations through annotations in Spring Hateoas? Is there a way to set resource relations through annotations? I made a similar question a some time ago but i've not been clear enough. I want to have something like this:
public class UserResource {

     private String username;

     @Relation(value = "{servicebaseUrl}/classes/${value}", rel = "class")
     private String classId;

     // Getters and setters
}

And then add a message converter which would add links only if client sends Accept = application/hal+json, avoiding  the fact of doing two different controller endpoints for application/hal+json and application/json. Does Spring offers something like that? I found that it actually offers this @Relation annotation(or similar one) but it seems that it is not for the same purposes.

A: No this is not possible - you would have to implement a ResourceAssembler to add links to your resources.
Usually your resources extend ResourceSupport.
class PersonResource extends ResourceSupport {

  String firstname;
  String lastname;
}

Then your create ResourceAssembler to control the creation of that resource:
class PersonResourceAssembler extends ResourceAssemblerSupport<Person, PersonResource> {

  public PersonResourceAssembler() {
    super(PersonController.class, PersonResource.class);
  }

  @Override
  public PersonResource toResource(Person person) {

    PersonResource resource = createResource(person);
    // … do further mapping and add links
    resource.add(new Link("http://myhost/people"));
    return resource;
  }
}

See the spring hateoas documentation for details


text:
Q: How to exclude tags folder from triggering build in Teamcity? I recently installed Teamcity 5.0.3. I am trying to setup automated build for a .NET 2.0 VS2005 project. I use NAnt and MSBuild task to perform the build. The project structure is a typical SVN structure
svn://localhost/ITools is my repository and the project structure is
VisualTrack
 trunk

 branches

 tags

I created a new project in Teamcity and then created a build configuration for that project. I asked it to kick off a build everytime there is a change detected in SVN VisualTrack VCS. I also configured it to create a label in VisualTrack/tags for every successful build. The problem I am running into is that the build is getting trigerred everytime teamcity is creating a new label under tags. I only want the build to be triggered if some developer commits his or her changes into trunk. Next step I took was to create a build trigger rule to exclude the tags path by specifying a trigger pattern as -:VisualTrack/tags/**, but looks like its not working. I believe the pattern I specified is not correct. Can someone please help me resolve this issue?
Thanks,
Jaya.

A: Another approach you can use, which works for VCS systems that don't typically use a trunk (such as mercurial), is to prevent triggering on the VCS username that you give to TeamCity.
To do this:

*

*Go into your build setup in TeamCity

*Click on Build Triggering (on the right in TeamCity 6.0.3)

*Under Trigger Rules, click on Add Trigger Rules

*Choose "Do not Trigger Build"

*Under VCS username put either the username you gave to TeamCity or you can macro it with: %vcsroot.username%

If you use this, you'll just want to make sure that you give TeamCity it's own account for using your VCS.  That's good practice anyway.

A: I'd suggest that you change your TeamCity VCS root URL for this project to be:
svn://localhost/ITools/VisualTrack/trunk

Which is a more typical setup.  You can easily setup multiple VCS root configurations in TeamCity.  This VCS root would only be concerned with building the trunk area of your project, which it sound like it what you want.


text:
Q: Visual Studio with Database Projects Post Biz Spark We will be finishing our BizSpark programme later this year.
We currently use Visual Studio 2013 Update 4 and within that, amongst other things, have a Database Project.
I have questions related to its use after graduation and also which versions of Visual Studio support Database Projects.
The advice from Microsoft says:

Once you complete the graduation process, you will get a license to keep, at no charge, most of the software you downloaded during the three years you were in the BizSpark program.
However, because all versions of Visual Studio 2013 and later now require you to sign in using a Microsoft account associated with an active MSDN subscription, startups will need to renew their MSDN subscription for each user running Visual Studio after graduation.

So it seems that we will need to buy an MSDN subscription for each developer.  If we do that, I assume we can use either 2013 or later editions such as 2015.  i.e. there would be no benefit in staying with 2013 as its no longer free. If we don't buy the subscription, I assume it will just stop working.  This is frustrating as its not what we were told when we started.
The next question is which edition we need.  In 2010, I understand that the Professional Edition did not support Database Projects.  But in the documentation for 2013 and beyond, I can't see any such distinction.  The implication is that we Professional will support Database Projects, but I'm not certain.
Finally, we also use TFS (on our server, not the cloud service), so I want to confirm that we can use that too with the Professional Edition.
Has anyone else been through this?
Thanks.

A: Actually the database projects or SQL Server Data Tools (SSDT) is not really "a part" of Visual Studio and you do not need to have Visual Studio to use it.
You can download it separately.
It is built in the VS Shell but "You can install and run SSDT as a free, standalone designer to create databases, models, reports, and packages."
It will still work with TFS as well.

A: I've not done the BizSpark program, but I do know that VS 2015 Professional does support both database projects and TFS.


text:
Q: HTML checkbox tick/untick with PHP code Everyone, hello!
I'm trying to tick/untick a HTML checkbox with help from my PHP code.
The option if a checkbox has to be ticked or unticked I get from a config.ini file, which looks like this:
config.ini
[com]
p_ip = x.x.x.x.
p_port = xxx
p_username = xxx
p_password = xxx

[trigger]
string1_enable = no
string2_enable = yes
string3_enable = no

And I've activated the config.ini file in my index.php file as such:
index.php
<?php $ini = parse_ini_file('config.ini'); ?>

Now, as far as the HTML is concerned, I've tried this:

<input type="checkbox" class="categories-checkbox" name="chk2" id="chk2"<?php if ($ini['string2_enable']=="yes") echo 'checked="yes"';?>>Enable

It doesn't throw an error, but it certainly won't enable. However, a simple:
<?php $ini = parse_ini_file('config.ini'); ?>
<?php echo $ini['string2_enable']; ?>

yields a yes on my PHP page.
Any help would be greatly appreciated!

A:
String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE.

Problem
The value of your $ini['string2_enable'] is converted to boolean (true) so your if case will fail as it's not equal to yes anymore.
Solution 1
So you have to replace your if case with this:
if($ini['string2_enable'])

Solution 2
If for some reason you want to keep your yes value when parsing, you could add a INI_SCANNER_RAW flag to your function:
$ini = parse_ini_file('config.ini', false, INI_SCANNER_RAW);

With this option, your if case will now work properly.
Source
For more information: http://php.net/manual/en/function.parse-ini-file.php

A:
<input type="checkbox" class="categories-checkbox" name="chk2" id="chk2"<?php if ($ini['string2_enable']=="yes") echo 'checked=true';?>>Enable

Notice "checked=true".  Just "checked" would also work.