text:
Q: Decode ebcdic to ascii/readable text in python I have a IBM mainframe file encoded in 'cp500' (I was informed) which is to be decoded to ascii or readable text. The file is taken from unix server transferred to windows using IPSwitch tool.
I already tried the below codes and couldn't achieve what I desire:
sample data = 'ðñðòðõÅäù@@@@@@@ððð :BÄÑðò÷øò@@@JaÈK' - in txt file

import codecs

with open(file, "rb") as ebcdic:
    ascii_txt = codecs.decode(ebcdic, "cp500")
    print(ascii_txt)

This is producing type error
"TypeError: decoding with 'cp500' codec failed (TypeError: a bytes-
like object is required, not '_io.BufferedReader')"

Then I tried these two,
with open(file, 'r', encoding='cp500') as f:
    for line in f:
        print(line)

with codecs.open(file, 'r', encoding='cp500')
    for line in f:
        print(line)

I also tried International encoding "cp1140" format as well -
with open(file, 'r', encoding="cp1140") as f:
    for line in f:
       print(line)

I expect a readable output - a copybook layout - something like this...
0001***********
0002...........
0003...........

But All the above three are printing output as :
C¢C£C¢C¥C¢C§CeCuC¾       C¢C¢C¢âCdCjC¢C¥C¼C½C¥   [/Ch.

And I also tried reading the file in "rb" mode:
with open(file, 'rb') as f:
    for line in f:
        print(line)

And this is producing below output -
b'\xc3\xb0\xc3\xb1\xc3\xb0\xc3\xb2\xc3\xb0\xc3\xb5\xc3\x85\xc3\xa4\xc3\xb9@@@@@@@\xc3\xb0\xc3\xb0\xc3\xb0 :B\xc3\x84\xc3\x91\xc3\xb0\xc3\xb2\xc3\xb7\xc3\xb8\xc3\xb2@@@Ja\xc3\x88K'

This is the first time I'm dealing with ebcdic/mainframe files - Any help in decoding this would be appreciated!
Thanks in Advance :)

A: I suspect the EBCDIC data were decoded with Latin-1 and saved with UTF-8 in the TXT file you are using right now.
Let's try to reconstruct with an abbreviated version of your example:
>>> copybook = '0102 [/H.'

This is what was originally produced.
This text was encoded with EBCDIC:
>>> '0102 [/H.'.encode('cp500')
b'\xf0\xf1\xf0\xf2@Ja\xc8K'

So that's the sequence of bytes that was written in the original mainframe file.
You could also write it like this in a general (non-Python) representation:
F0 F1 F0 F2 40 4A 61 C8 4B

Now these bytes were decoded with Latin-1, or maybe CP-1252 ("Windows Latin-1").
That's what might happen if you do this on a Windows machine:
>>> with open(file) as f:
...     text = f.read()
>>> text
'ðñðò@JaÈK'

You can simulate this mis-encoding like this:
>>> '0102 [/H.'.encode('cp500').decode('latin1')
'ðñðò@JaÈK'

That's the string you show in the beginning of your post.
It's already worse than the mere problem of having to deal with mainframe files – it's a mojibake of a mainframe file!
Now, to make things even worse, this string was saved to a file using UTF-8.
Let's try that too:
>>> '0102 [/H.'.encode('cp500').decode('latin1').encode('utf8')
b'\xc3\xb0\xc3\xb1\xc3\xb0\xc3\xb2@Ja\xc3\x88K'

These are the bytes that are contained in your TXT file, according to the last snippet (where you open with 'rb' mode and print the output).
Now these bytes aren't valid EBCDIC anymore.
The encoding round-trip with Latin-1 and UTF-8 distorted the contents:
>>> '0102 [/H.'.encode('cp500').decode('latin1').encode('utf8').decode('cp500')
'C¢C£C¢C¥ [/Ch.'

That's the output you got in the first attempt shown in the question.
In order to recover from the situation, you need to undo the distortion:
>>> distorted = '0102 [/H.'.encode('cp500').decode('latin1').encode('utf8')
>>> distorted
b'\xc3\xb0\xc3\xb1\xc3\xb0\xc3\xb2@Ja\xc3\x88K'
>>> recovered = distorted.decode('utf8').encode('latin1').decode('cp500')
>>> recovered
'0102 [/H.'

... or when reading from file, you can let open do the first decode step for you:
>>> with open(file, encoding='utf8') as f:
...     data = f.read()
...     text = data.encode('latin1').decode('cp500')

For the full example line, this yields the following text:
'010205EU9       000\x80\x9aâDJ02782   [/H.'

I'm not 100% sure this is the original text.
It contains some control characters (80, 9A) and a non-ASCII letter ("â").
Maybe the 000...782 block has to be interpreted as a binary blob.
But I hope this analysis helps you get further in this problem!


text:
Q: Why this code is showing me undefined and type error? This code is showing error and giving me undefined can anyone pls give me logic for this:

const data = ['1','2','3','4','6'];

const consoleItem = (item, index ,arr) =>{
    console.log(item);
    console.log(index);
    console.log(arr);
}
data.forEach(consoleItem())

A: Your syntax was incorrect.  The way you have it setup, it only calls consoleItem once and it calls it with no parameters, and the return value is used as a parameter to foreach.
The way I am using it below, consoleItem is acting as a callback to the forEach method and I am passing it the three parameters implicitly given by each iteration of the forEach method.
Try it like this.

const data = ['1','2','3','4','6'];

const consoleItem = (item, index ,arr) =>{
    console.log(item);
    console.log(index);
    console.log(arr);
}
data.forEach(consoleItem)
//data.forEach((x,y,z) => {consoleItem(x,y,z)})  Same as above

A: The function forEach require a function definition, but you are invoking the function in forEach it self you can use something like this

const data = ['1','2','3','4','6'];

const consoleItem = (item, index ,arr) =>{
    console.log(item);
    console.log(index);
    console.log(arr);
}
data.forEach(consoleItem)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to interface to web-based predictive endpoints using Python The following web-page provides example code for using a predictive endpoint using c#
https://learn.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/use-prediction-api
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CVSPredictionSample
{
    public static class Program
    {
        public static void Main()
        {
            Console.Write("Enter image file path: ");
            string imageFilePath = Console.ReadLine();

            MakePredictionRequest(imageFilePath).Wait();

            Console.WriteLine("\n\nHit ENTER to exit...");
            Console.ReadLine();
        }

        public static async Task MakePredictionRequest(string imageFilePath)
        {
            var client = new HttpClient();

            // Request headers - replace this example key with your valid Prediction-Key.
            client.DefaultRequestHeaders.Add("Prediction-Key", "<Your prediction key>");

            // Prediction URL - replace this example URL with your valid Prediction URL.
            string url = "<Your prediction URL>";

            HttpResponseMessage response;

            // Request body. Try this sample with a locally stored image.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response = await client.PostAsync(url, content);
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }

        private static byte[] GetImageAsByteArray(string imageFilePath)
        {
            FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    }
}

How can it be done using Python code ?
Many thanks

A: A similar documentation exists for Python:

*

*For classification projects here

*For object detection projects here
See language selector in the page:


text:
Q: Permission error while deploying to app enginewith service account I want to deploy my app via google service account. I am using the test-version of googlecloud with billing enabled. I granted the following permissions to my service account:

*

*App Engine Administrator

*App Engine Deployer

*App Engine Service Administrator

*Cloud Build Service Account

*Cloud Build Editor

*Storage Administrator

When I try to login via keyfile with gcloud auth activate-service-account --key-file file.json and then trying to deploy the app with the service account with the following command: gcloud --quiet --project projecid app deploy app.yaml I get the following error:
(gcloud.app.deploy) Permissions error fetching application [apps/projectid]. Please make sure you are using the correct project ID and that you have permission to view applications on the project.

Also I might have to say, that I am using a account ID which was used before.
Do you guys have an idea what I could do? It works, when I deploy it with my normal google account and a normal login. But I need that because of gitlab-ci

A: I have tried to reproduce your situation by creating a new service account and giving it the roles you listed. I have authorized access to GCP with its key using the gcloud auth activate-service-account --key-file=<KEY-FILE> command but the deployment has been successful for me.
Run the gcloud auth list command to make sure you're authorized with the correct service account. Also you can try adding the --verbosity=debug flag to the deployment command to see if you can find anything useful in the error logs if the error occurs.
From the error description, however, it seems that you might also have passed an incorrect project ID when deploying the application:
gcloud --quiet --project projecid app deploy app.yaml

- make sure it is not the case.


text:
Q: The difference in using first and firstly
One should first use the tool which...

Is it right in using the word "first"?
Both firstly and first seem to have the same adverbial meaning.

A: Yes, that phrase sounds perfectly fine.
I've never actually heard or used the word "firstly".  This says that Chicago Manual of Style and other style guides recommend against using it.  It sounds old and overly formal.
(It might be used in British English, but I am not British, so I don't know.)


text:
Q: Solve $\tan(2t)=1$ My textbook is listing solutions to this equation as $2t=\pm \frac{\pi}{4}$ and $2t=\pm \frac{5\pi}{4}$ however this doesn't seem correct at all, I believe the only solutions should be $2t=\frac{\pi}{4}$ and $2t=\frac{5\pi}{4}$ since the other solutions will result in $\tan(2t)=-1$
In case it's of any importance this came from parameterizing $x^2+y^2<1$ with $x=\cos t$ and $y=\sin t$ and then plugging these into $f(x,y)=xy-y^2$ to obtain $g(t)=\frac{1}{2}(\sin 2t+\cos 2t+1)$ and then attempting to solve for when max/min occur.

A: Yes you are right but the better solution is $2t=\pi/4+k\pi, k\in \mathbb{Z}. $


text:
Q: How do I deploy NServicebus Hosts from Visual Studio to my Server? I'm running Visual Studio 2012 and my Server is Windows Server 2012 Essentials. I've installed MSMQ and then ran the NServicebus4 installer (the release notes says to install MSMQ first).
Everything works fine on my workstation, and I want to deploy to a server. My assumption is that all I need to do is copy everything from bin to my server, and install the host.exe as a service. That seems clunky.
Surely there is an established recommended procedure for deployement, and that someone will tell me to RTFM, except I'm not sure where the manual is. I saw that for version 3 there was an interface I could implement, but is deprecated for version 4, and version 4 has powershell commandlets, but that seems to be for preparing a server for first run. I need to install actual host services now.

A: See the Installation heading in The NServiceBus Host in the documentation. It's a ways down the page. TL;DR: You run the same command line host with the /install parameter. There are additional options to customize. Is that what you're referring to as clunky because it's pretty straightforward as far as installing services goes.
As far as RTFM, there is a book on the subject now. (Disclaimer: I wrote it.)


text:
Q: Scan DynamoDB table for results from the current month using PHP I have a table in AWS DynamoDB, and every item in this table has a String-type "date" attribute, which contains the date when the specific item was created. The date in this attribute is being saved in this format: dd/mm/YYYY.
What I want to do is to scan this table, and get all of the results from the current month. I also want to do 2 more individual scans. One for results from the last month (for example, now it is July, so I want to get results from June), and from 2 months ago (for example, I want to get all the results from May).
In the DynamoDB PHP SDK documentation, they are demonstrating a scan, and in the example they are filtering the scan according to an attribute called "time" using this code:
'time' => array(
    'AttributeValueList' => array(
        array('N' => strtotime('-15 minutes'))
    ),
    'ComparisonOperator' => 'GT'
)

So I thought that I could replace -15 minutes with -1 month, but the problem with it is that, as you can see in the code above, the "time" attribute is a Number-type, and not String-type, so I can't perform this action.
What can I do to get results only from the current month?

A: If you store data in yyyy/mm/dd format you can use begin_with function to filter your data:

begins_with ( sortKeyName, :sortkeyval ) - true if the sort key value
  begins with a particular operand. (You cannot use this function with a
  sort key that is of type Number.) Note that the function name
  begins_with is case-sensitive.

Otherwise I don't see how it is possible on data of this format.
Another option is to convert it into Unix timestamps and then you can use <,<=,>,>= or between operators


text:
Q: android sqlite save image in database or path i am making an android chat application that shows list of friends with image from mysql database..... i want to also store it locally i just want to know if i show store the images in the sqlite database or on the sdcard and save the path in the sqlite database .... I know saving the path is better but the thing is the user can delete the folder or some images int the folder which i dont want any advice.
and this is the code i found that should work
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet("your image url");
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  HttpEntity entity = mHttpResponse.getEntity();
    if ( entity != null) {
      // insert to database
      ContentValues values = new ContentValues();
      values.put(MyBaseColumn.MyTable.ImageField, EntityUtils.toByteArray(entity));
      getContentResolver().insert(MyBaseColumn.MyTable.CONTENT_URI, values);
    }
}

A: you can use cache folder and user can't delete this  folder
if image an avatar, you can use picasso + okhttp (picasso  uses the okhttp  for disk caching )


text:
Q: Mediawiki thumbnail directory is almost as big as the image directory itself Mediawiki installed with Softaculous (very recently upgraded to 1.35.0)
I was running out of space on my webhosting earlier so I ran
$ php deleteArchivedFiles.php --delete --force
$ php cleanupUploadStash.php

which saved me quite some storage but today I noticed that the images/thumb/ directory is 922MB while the folders actually holding the images (images/[...]/) are all together 1.2GB.
Also the biggest file in the thumb folder is 4MB. Why are these thumbnails so big?
Can I just delete all the contents of this folder as suggested on this old post?

A: If $wgGenerateThumbnailOnParse is false, there is no harm in deleting thumbnails; they will be regenerated when needed. If it is true, thumbnails will only be generated when the page is parsed; you'll end up with broken image links if you delete them. (You can e.g. set $wgCacheEpoch or use action=purge to re-parse pages, or just wait long enough for the parser cache to expire.) It probably won't help much in any case, those thumbnails will be regenerated eventually.
There are a lot more thumbnails than originals (every different size is a separate thumbnail) so taking up a lot of space is normal. A 4MB thumbnail is strange but maybe it is a large image that is displayed in almost-full-size on some page?


text:
Q: Select option issue I created a small code that for some strange reason it works badly.
With the first var declare variables, but it is just to let you see for what they are, aren't declared there. Opt is an array containing all the values read from a file, alunno is a select , and trovata it's a counter that tells me how many rows there are.
Everything so far works fine, but in the while loop, where am I going to perform the adding in the select if I have for example two values to be loaded, the first option is replaced with the second so instead of finding myself:
John, Antoine in the select, I find:

Antoine, Antoine.

Which is quite strange considering that John is added initially, but then is replaced by the last value.
What's wrong with this code?
var opt, elaborazione;
var alunno = document.getElementById('alunno');
var trovata = 0;

while(true)
{
    opt = new Option();
    elaborazione = v[count].split(";");
    elaborazione = elaborazione.slice(0,2);
    elaborazione = elaborazione.join(" ");
    opt.text = elaborazione;
    alunno.add(opt);
    trovata--;
    if(trovata == 0){break;}
}

more details:
while(!flow.AtEndOfStream)
        {
            var lettura = flow.ReadLine();
            opts = lettura.split(';');
            count++;
            v[count] = lettura;
        }

A: You are not changing count in the loop:
while(true)
{
    opt = new Option();
    elaborazione = v[count].split(";"); //The count is the same here
    //...
    trovata--;
    if(trovata == 0){break;}
}

Thus you always use the last item of v, which is always the same.


text:
Q: What is wrong with this attempt to render rotated ellipses in Qt? 1. Goal
My colleague and I have been trying to render rotated ellipsoids in Qt. The typical solution approach, as we understand it, consists of shifting the center of the ellipsoids to the origin of the coordinate system, doing the rotation there, and shifting back:
http://qt-project.org/doc/qt-4.8/qml-rotation.html
2. Sample Code
Based on the solution outlined in the link above, we came up with the following sample code:
// Constructs and destructors
RIEllipse(QRect rect, RIShape* parent, bool isFilled = false)
: RIShape(parent, isFilled), _rect(rect), _angle(30)
{}

// Main functionality
virtual Status draw(QPainter& painter)
{
   const QPen& prevPen = painter.pen();
   painter.setPen(getContColor());
   const QBrush& prevBrush = painter.brush();
   painter.setBrush(getFillBrush(Qt::SolidPattern));

   // Get rectangle center
   QPoint center = _rect.center();

   // Center the ellipse at the origin (0,0)
   painter.translate(-center.x(), -center.y());
   // Rotate the ellipse around its center
   painter.rotate(_angle);
   // Move the rotated ellipse back to its initial location
   painter.translate(center.x(), center.y());

   // Draw the ellipse rotated around its center
   painter.drawEllipse(_rect);

   painter.setBrush(prevBrush);
   painter.setPen(prevPen);
   return IL_SUCCESS;
}

As you can see, we have hard coded the rotation angle to 30 degrees in this test sample.
3. Observations
The ellipses come out at wrong positions, oftentimes outside the canvas area.
4. Question
What is wrong about the sample code above?
Best regards,
Baldur
P.S. Thanks in advance for any constructive response?
P.P.S. Prior to posting this message, we searched around quite a bit on stackoverflow.com.
Qt image move/rotation seemed to reflect a solution approach similar to the link above.

A: In    painter.translate(center.x(), center.y()); you shift your object by the amount of current coordinate which makes (2*center.x(), 2*center.y()) as a result. You may need:
painter.translate(- center.x(), - center.y());

A: The theory of moving an object back to its origin, rotating and then replacing the object's position is correct. However, the code you've presented is not translating and rotating the object at all, but translating and rotating the painter. In the example question that you've referred to, they're wanting to rotate the whole image about an object, which is why they move the painter to the object's centre before rotating.
The easiest way to do rotations about a GraphicsItem is to initially define the item with its centre in the centre of the object, rather than in its top left corner. That way, any rotation will automatically be about the objects centre, without any need to translate the object.
To do this, you'd define the item with a bounding rect for x,y,width,height with (-width/2, -height/2, width, height).
Alternatively, assuming your item is inherited from QGraphicsItem or QGraphicsObject, you can use the function setTransformOriginPoint before any rotation.


text:
Q: Proper way to call firestore functions inside React components I am developing a React project with firestore as a backend, and I'm quite new on this technology.
How is the recommended way to call firestore functions (addDoc, updateDoc, specific fetch queries, etc...) inside a React component?
I want to avoid using firestore methods directly, and replace that with a custom hook, class or similar but I need to know the prper way of doing that in terms of good code practices and/or performance.


text:
Q: Quantiles of a Brownian Motion I am looking for the p-th percentile of a stochastic process $X_t$ that satisfies $dX_t = \mu(X_t) dt + \sigma(X_t) dW_t$ where $W_t$ is a standard Brownian motion.
I believe that the p-th percentile of $dX_t = \mu dt + \sigma dW_t$ is given by $X_0 + \mu t +\sigma \sqrt{t} \Phi^{-1}(p)$ where $\Phi$ is the standard normal cdf, and that the p-th percentile of $dX_t = \mu X_t dt + \sigma X_t dW_t$ is given by $X_0 \exp( (\mu-\frac{1}{2}\sigma^2) t +\sigma \sqrt{t} \Phi^{-1}(p))$.
But I am having trouble generalizing this to more general processes. In particular, I am trying to obtain the p-th percentile of the Ornstein–Uhlenbeck process $dX_t = \lambda(\bar{X}-X_t) dt + \sigma dW_t$.
Thank you for your help.


text:
Q: Angular 7 how to specify folder for images in dist When I build project by ng build command in dist folder I got my js files both with all other resources, but I want to move all images and fonts in separate folder like assets. Can anybody help me?

Update:
angular.json

 "assets": [
   "src/favicon.ico",
   "src/assets"
],
in scss of component I have:
background-image: url('assets/img/no-notifications.svg');
but in result I got in dist folder next file:
no-notifications.7e08682a570485d1c108.svg
Goal is keep image path same as he has been specified in scss file:
 assets/img/no-notifications.svg

A: try this
create  img folder inside assets
and use path like ./assets/img/your_image
it will work.

A: If you didn't already know, a new option was added into angular cli configuration (since v7.2.1) to copy css resources into another folder (relative to the output path).
"outputPath": "wwwroot",
"resourcesOutputPath": "images"

https://angular.io/cli/build

A: The given solution "resourcesOutputPath": "images" works fine for image. But unfortunately if we need to do the same for other resources like *.js or *.ttf files etc... it will not work.
Here is how I do that for *.js files : in the file package.json, below the scripts node, I add a script called postbuild that will :

*

*Move the files in the dedicated folder (resources in my example)

*Search and replace <script src="*.js"></script> in index.html by <script src="resources/*.js"></script>. The search and replace is done with sed commande line (please be aware that there are some difference with sed commande lin on linux or MacOS).

Here is the final look of my package.json file :
{
  "name": "my-project",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "postbuild": "mv ./dist/my-project/*.js ./dist/my-project/*.js.map ./dist/my-project/resources; sed -i -e 's/src=\"/src=\"resources\\//g' dist/my-project/index.html",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }
}

A: By default, using 'ng build' command 'assets' and their 'sub-folders' will be automatically copied to 'dist' folder. If you want to create another folder in the same root level, let say 'resources'.
In angular.json, there is 'assets' configuration where we can define 'src/resources'.
angular.json
"assets": ["src/resources"],

A: set "rebaseRootRelativeCssUrls": true in options  of "build" of angular.json


text:
Q: Sort algorithms illustration on wikipedia? Can anyone explain to me what the "Graphical illustrations" of sorting algorithms on Wikipedia mean? I can't understand them.
Bubble sort

Insertion sort

A: These are the locations of the various elements in an array (and looks like the gray tone indicates the numerical value). The lines show the process of the sort, the X axis is the time, and on each time step one or more elements are moved, until on the right hand side you can see them sorted by the tone.
The distinction here is that a bubble-sort would take a single element and start swapping adjacent elements (so you can see the dark gray element slowly propagating to the end, until it hits a darker one, and you continue with that one).
Insertion sort, on the other hand, takes a single element, decides where to insert it, and shifts the rest of the elements accordingly, you can see this represented by several parallel diagonal lines all moving at the same time.
This is a nice illustration, but try to read the algorithmic description - it's not very complicated, and maybe then the illustration would make more sense to you.
Another possible benefit of these illustrations is that they may give you a hunch on the number of actions needed to sort an array - even though it's for a single given example and not necessarily the worst case. Both bubble sort and insert sort are of the magnitude of O(n^2), n being the number of elements. This means that as n grows, you're looking into quite a lot of actions (swaps or insertions).
This is why they came up with other sort algorithms with better complexity (up to O(n*logn), you can't beat that in the general case), see for e.g. quick sort; and also algorithms relying on additional constraints, such as that the sorted numbers are bounded from above (bin sort / radix sort)


text:
Q: Checkbox click function not working I have a group of checkboxes with same name. One textbox is associated with each checkbox. On page load, I am disabling all the textboxes. On click of each checkbox, the textbox corresponding to the checkbox should be enabled.
The problem is that, I tried with different codes to enable the textbox on checkbox click. But the checkbox click function is not working.
The code is as given below (I am using MVC framework):
{loopstart:setting:100}
 {if($setting%2==0)}

 {endif}

 <input type="checkbox" name="settingcheck" id="setting{$setting[0]}" value="{$setting[0]}"/>{$setting[1]}

<input type="text" size="2px" id="text{$setting[0]}">

                                                {if($setting%2==1)}

                                                {endif}
                                    {loopend:setting}

JQuery
$(document).ready(function(){
    $("INPUT[type=text]").prop("disabled",true);
    $("INPUT[type=text]").css("background-color", "#ccc");

});

This code is for disabling all textboxes on page load and is working fine.
$('input[name='settingcheck']:checked').click(function() {

}

I wrote the above function for enabling the text box on corresponding checkbox click. But this function is not working. I tried alerting some text in this function.
Is there any problem in the code. Can anyone help me to solve this. Thanks in advance.

A: Your string literal is not properly formed: since you have used '' to enclose the literal all occurrences of ' within the string have to be escaped('input[name=\'settingcheck\']:checked') or you can use "" instead
$(document).on('change', 'input[name="settingcheck"]', function() {
    if(this.checked){
        //this is checked now
    } else {
        //this is unchecked now
    }
});

A: If not already checked you can try this
$('input[name="settingcheck"]').click(function() {
    if($(this).is(':checked')){
        alert('checked');
    }
})

see demo

A: try this
$('input[name="settingcheck"]:checked').click(function() {

}

A: Try this:
$("input[name='settingcheck']:checked").click(function() {
}

A: Try this
$('input[name="settingcheck"]:checked').on('click',function() {

});

OR
$(document).on('click', 'input[name="settingcheck"]:checked', function() {

});

OR
$(document).on('change', 'input[name="settingcheck"]', function() {

}

A: Working Demo

You can try like this :

            <input type="checkbox" onclick="checkBoxClicked1(this)" />

            <input type="text" style="display: none">

            <input type="checkbox" onclick="checkBoxClicked1(this)" />

            <input type="text" style="display: none">

Javascript:

 function checkBoxClicked1(checkbox) {
        debugger;
        var a = $(checkbox).is(':checked');
        var textBox = $(checkbox).closest("tr").children()[1].children[0];
        if (a) {
            $(textBox).show();
            $(checkbox).prop("checked", true);
        } else {
            $(textBox).hide();
            $(checkbox).prop("checked", false);
        }

    }


text:
Q: $\dim(R/x) = \dim(R)-1$ for Noetherian integral domains? Let $R$ be a Noetherian integral domain of finite Krull-dimension and $0 \neq x \in R$ a non-unit. Do we have $\dim(R/x) = \dim(R) -1$ in general?
If this is wrong, does it change something if we further assume that $R$ is positively graded, finitely generated by homogeneous elements of degree one over $R_0$, which is Artinian local, and $x$ is homogeneous of degree one?
Context: This dimension formula is used here.

A: In general $\dim R/(x)$ can be $< \dim R - 1$ - see here. However it does hold if $R$ is (in addition) local. Thus in the specific setting, where $R$ is a standard graded Noetherian domain (so that $R_0$ is a field, not just Artinian), then if $\DeclareMathOperator{\m}{\mathfrak{m}}$$\m$ is the homogeneous maximal ideal (which is maximal), we have $\dim R - 1 = \dim R_m - 1 = \dim R_m/xR_m = \dim (R/x)_m = \dim R/(x)$ (since $\dim R = {}^*\!\dim R$ if $R$ is positively graded with $R_0$ local).


text:
Q: Normal random variable as argument of standard normal cdf Let $X$ be a standard normal random variable with cumulative distribtuion function $\Phi$. That is, $X\sim N(0,1)$ and the standard normal cdf is denoted by $\Phi(x)$. We know that $\Phi(X) \sim \operatorname{Uniform}(0,1)$. But can we say anything about the distribution of $\Phi(a+bX)$ where $a$ and $b>0$ are arbitrary real numbers? Can we express the cdf of $\Phi(a+bX)$ using other (known) functions?

A: Same basic way you show $\Phi(X)$ is $U(0,1)$ or more generally calculate the CDF of a monotonic function of a random variable whose CDF you know.
Let $Y = \Phi(a+bX)$ and calculate $$ P(Y\le y) \\= P(\Phi(a+ bX) \le y) \\= P(a+bX\le \Phi^{-1}(y)  )\\=P\left(X\le \frac{\Phi^{-1}(y) -a}{b}\right) \\=\Phi\left(\frac{\Phi^{-1}(y) -a}{b}\right)$$ (assuming $b>0$). If $a=0$ and $b=1$, this gives $y$ which is the CDF of the uniform distribution.


text:
Q: How should change the ID of DIV in jQuery I have to swap the div.
Swapping is working fine( I am using Jquery Swap Plugin for that).
After swap I want to swap the ID of DIVs too.
Please find JQuery Code. Kindly help me out how should I swap the DIV IDs.
 $(".arrowIMG").click(function() {
                    var arr = this.id.split("_");
                    if(arr[0] == 'down'){

                        var div1 = $('#'+'div_' +arr[1]);
                        var next = (parseInt(arr[1]) + 1);
                        alert(next)
                        var div2 = 'div_' + next;

                        div1.swap({
                        target: div2,
                        opacity: "0.5",
                        speed: 1000,
                        callback: function() {
                         //Now Here i want to swap the id of div (div1 and dev2)

                        }
                    });

                    }else if(arr[0] == 'up') {
                        alert('up');
                    }

                });

Kindly help me out the way to swap the DIV IDs.

A: I'm not sure exactly what the desired behavior of your function is - but the following should work to change an ID:
$(element).attr('id', 'new_id');

A: callback: function() {

    var div2selector = $('#'+div2); //making both selectors in same format as div2='div_' + next
    var tempid = div1.attr('id');
    div1.attr('id',div2selector.attr('id'));
    div2selector.attr('id',tempid );

                    }

EDIT:
div1 and div2 are not in same format. so made similar

A: Use jQuery .attr() to Get the value of an attribute for the first element in the set of matched elements.
Check this:

 s,dfsd

    src

    dest

jQuery Code:
$("#my").attr('id','mynewid');
$("#mynewid").html("this new content");

var temp = $(".div1").attr('id');
$(".div1").attr('id',$(".div2").attr('id'));
$(".div2").attr('id', temp);

Check this jsFiddle
Adjust your click event behavior using this code snippet. in your function() code you have already accessed those elements so you can directly access the id of those elements.
var temp = div1.attr('id');
    div1.attr('id',div2.attr('id'));
    div2.attr('id', temp);


text:
Q: StreamReader is too greedy I'm trying to process part of a text file, and write the remainder of the text file to a cloud blob using UploadFromStream.  The problem is that the StreamReader appears to be grabbing too much content from the underlying stream, and so the subsequent write does nothing.
Text file:
3
Col1,String
Col2,Integer
Col3,Boolean
abc,123,True
def,3456,False
ghijkl,532,True
mnop,1211,False

Code:
using (var stream = File.OpenRead("c:\\test\\testinput.txt"))
using (var reader = new StreamReader(stream))
{
    var numColumns = int.Parse(reader.ReadLine());
    while (numColumns-- > 0)
    {
        var colDescription = reader.ReadLine();
        // do stuff
    }

    // Write remaining contents to another file, for testing
    using (var destination = File.OpenWrite("c:\\test\\testoutput.txt"))
    {
        stream.CopyTo(destination);
        destination.Flush();
    }

    // Actual intended usage:
    // CloudBlockBlob blob = ...;
    // blob.UploadFromStream(stream);
}

When debugging, I observe that stream.Position jumps to the end of the file on the first call to reader.ReadLine(), which I don't expect.  I expected the stream to be advanced only as many positions as the reader needed to read some content.
I imagine that the stream reader is doing some buffering for performance reasons, but there doesn't seem to be a way to ask the reader where in the underlying stream it "really" is.  (If there was, I could manually Seek the stream to that position before CopyingTo).
I know that I could keep taking lines using the same reader and sequentially append them to the text file I'm writing, but I'm wondering if there's a cleaner way?
EDIT:
I found a StreamReader constructor which leaves the underlying stream open when it is disposed, so I tried this, hoping that the reader would set the stream's position as it's being disposed:
using (var stream = File.OpenRead("c:\\test\\testinput.txt"))
{
    using (var reader = new StreamReader(stream, Encoding.UTF8,
        detectEncodingFromByteOrderMarks: true,
        bufferSize: 1 << 12,
        leaveOpen: true))
    {
        var numColumns = int.Parse(reader.ReadLine());
        while (numColumns-- > 0)
        {
            var colDescription = reader.ReadLine();
            // do stuff
        }
    }

    // Write remaining contents to another file
    using (var destination = File.OpenWrite("c:\\test\\testoutput.txt"))
    {
        stream.CopyTo(destination);
        destination.Flush();
    }
}

But it doesn't.  Why would this constructor be exposed if it doesn't leave the stream in an intuitive state/position?

A: Sure, there's a cleaner way. Use ReadToEnd to read the remaining data, and then write it to a new file. For example:
using (var reader = new StreamReader("c:\\test\\testinput.txt"))
{
    var numColumns = int.Parse(reader.ReadLine());
    while (numColumns-- > 0)
    {
        var colDescription = reader.ReadLine();
        // do stuff
    }

    // write everything else to another file.
    File.WriteAllText("c:\\test\\testoutput.txt", reader.ReadToEnd());
}

Edit after comment
If you want to read the text and upload it to a stream, you could replace the File.WriteAllText with code that reads the remaining text, writes it to a StreamWriter backed by a MemoryStream, and then sends the contents of that MemoryStream. Something like:
    using (var memStream = new MemoryStream())
    {
        using (var writer = new StreamWriter(memStream))
        {
            writer.Write(reader.ReadToEnd());
            writer.Flush();
            memStream.Position = 0;
            blob.UploadFromStream(memStream);
        }
    }

A: You should never access the underlying stream of a StreamReader.  Trying to use both is going to have an undefined behavior.
What's going on here is that the reader is buffering the data from the underlying stream.  It doesn't read each byte exactly when you request it, because that's often going to be very inefficient.  Instead it will grab chunks, put them in a buffer, and then provide you with data from that buffer, grabbing a new chunk when it needs to.
You should continue to use the StreamReader throughout the remainder of that block, instead of using stream.  To minimize the memory footprint of the program, the most effective way of doing this would be to read the next line from the reader in a loop until it his the end of the file, writing each line to the output stream as you go.
Also note that you don't need to be disposing of both the stream reader and the underlying stream.  The stream reader will dispose of the underlying stream itself, so you can simply adjust your header to:
using (var reader = new StreamReader(
    File.OpenRead("c:\\test\\testinput.txt")))


text:
Q: Show alert icon in the field in Odoo? I wanted to show an alert icon in partner_id(Customer) field if the Tax ID of partner_id is empty. This icon should be similar to the icon we see in Invoice Date if a future date is given.

Conditions when  icon should be shown

*

*if partner_id's type is individual and has parent_id(Company) then Tax ID should be chosen from parent_id not from parntner_id. So, if the Tax ID of parent_id is empty, the alert icon should be shown.

*if partner_id is individual and has no parent_id(company) then Tax ID should be chosen from partner_id. And if it is empty, an alert icon should be shown.

*if partner_id is company type and has no Tax ID, an icon should be shown.

How can I achieve such feature?

A: You can add an onchange method, if you change the partner the icon is displayed
but if you want like the date icon it's a bit long because it's a widget
good for the method it's like this
class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.onchange('partner_id')
    def tax_check(self):
        if self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if not self.partner_id.parent_id.vat :
              #  display your icon
            else:
               # chose the tax for parent_id
        elif not self.partner_id.parent_id and self.partner_id.company_type == 'person':
            if self.partner_id.vat :
                # chose the tax in partner_id
            else:
                #  afficher votre icone
        elif not self.partner_id.vat and self.partner_id.company_type == 'company':
            #  display your icon

you want to display the TaxID in the report ?


text:
Q: Regex Match Whole Multiline Comment Cointaining Special Word I've been trying to design this regex but for the life of me I could not get it to not match if */ was hit before the special word.
I'm trying to match a whole multi line comment only if it contains a special word.  I tried negative lookaheads/behinds but I could not figure out how to do it properly.
This is what I have so far:
(?s)(/\*.+?special.+?\*/)
Am I close or horribly off base? I tried including (?!\*/) unsuccessfully.
https://regex101.com/r/mD1nJ2/3
Edit: I had some redundant parts to the regex I removed.

A: You were not totally off base:
/\*                 # match /*
(?:(?!\*/)[\s\S])+? # match anything lazily, do not overrun */
special             # match special
[\s\S]+?            # match anything lazily afterwards
\*/                 # match the closing */

The technique is called a tempered greedy token, see a demo on regex101.com (mind the modifiers, e.g. x for verbose mode !).

You might want to try another approach tough: analyze your document, grep the comments (using eg BeautifulSoup) and run string functions over them (if "special" in comment...).


text:
Q: Automorphisms of a Lie algebra.
Let $\mathfrak{g}$ be a Lie algebra. Then $\operatorname{Aut}(\mathfrak{g})$ is the space of automorphisms of $\mathfrak{g}$.

I'm a little confused on what an automorphism of a Lie algebra is. Does this mean that it is an automorphism of linear algebras, i.e. an automorphism is a linear invertible map. Or do we also require such a map to preserve the bracket structure on $\mathfrak{g}$.

A: If $\mathfrak{g} , \mathfrak{h}$ are Lie algebras, a homomorphism of Lie algebras is a map $T : \mathfrak{g} \to \mathfrak{h}$ which (a) is a linear homomorphism, and (b) satisfies $$[T(x), T(y)]_{\mathfrak{h}} = [x, y]_{\mathfrak{g}}$$ for all $x, y \in \mathfrak{g}$. A Lie algebra automorphism will be a Lie algebra homomorphism of a Lie algebra to itself which is also invertible.


text:
Q: Data Mysql not showing in recyclerview This application not showing data mysql and not error. please help me
how to fix this
This is class MainActivity
public class MainActivity extends AppCompatActivity {
    private static final String data_url = "http://192.168.1.9/uasazizah/android.php";
    RecyclerView mRecyclerView;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager mManager;
    ProgressDialog pd;
    ArrayList<Modeldata> mItems;
    private RequestQueue requestQueue;
    private StringRequest stringRequest;
    ArrayList<HashMap<String, String>> list_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "http://192.168.1.9/uasazizah/android.php";

        mRecyclerView = findViewById(R.id.bararecy);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        Adapterdata adapterdata = new Adapterdata(MainActivity.this, list_data);
        mRecyclerView.setAdapter(adapterdata);
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        list_data = new ArrayList<HashMap<String, String>>();

        stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("response ", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("azizah");
                    for (int a = 0; a < jsonArray.length(); a++) {
                        JSONObject json = jsonArray.getJSONObject(a);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("code", json.getString("code"));
                        map.put("groupname", json.getString("groupname"));
                        map.put("namag", json.getString("namag"));
                        list_data.add(map);
                        Adapterdata adapter = new Adapterdata(MainActivity.this, list_data);
                        mRecyclerView.setAdapter(adapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(stringRequest);
    }
}

this is class Adapterdata
in this class getcount if i write return list_data.size(), it is showing null or error
public class Adapterdata extends RecyclerView.Adapter<Adapterdata.ViewHolder> {

    Context context;
    ArrayList<HashMap<String, String>> list_data;

    public Adapterdata(MainActivity mainActivity, ArrayList<HashMap<String, String>> list_data) {
        this.context = mainActivity;
        this.list_data = list_data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_barang, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        DrawableCrossFadeFactory factory =
                new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
        Glide.with(context)
                .load("http://192.168.1.9/uasazizah/images/" + list_data.get(position).get("namag"))
                .transition(withCrossFade())
                .apply(new RequestOptions().override(100, 100)
                        .placeholder(R.drawable.ic_launcher_background)
                        .error(R.drawable.ic_launcher_background).centerCrop()
                )
                .into(holder.img);
        holder.txtkate.setText(list_data.get(position).get("groupname"));
        holder.tkscode.setText(list_data.get(position).get("code"));
    }

    @Override
    public int getItemCount() {
        return list_data == null ? 0 : list_data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtkate,tkscode;
        ImageView img;

        public ViewHolder(View itemView) {
            super(itemView);

            txtkate = itemView.findViewById(R.id.namatvv);
            tkscode = itemView.findViewById(R.id.code);
            img = itemView.findViewById(R.id.imgv);
        }
    }
}

how should i do? this code not showing data form mysql. no error but not showing

A: Did you add internet permission to manifest?
<uses-permission android:name="android.permission.INTERNET" />

A: simply I make activity using your code. and this code is working.
I don't use StringRequest and image library. So, If this code is not working,
you have to check

*

*get Data from server

*check image library

anyway my example code is here.
public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    Adapterdata adapterdata;
    ArrayList<HashMap<String, String>> list_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.bararecy);
        list_data = new ArrayList<HashMap<String, String>>();

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapterdata = new Adapterdata(MainActivity.this, list_data);
        mRecyclerView.setAdapter(adapterdata);

        String test = "{\"azizah\":[{\"0\":\"116\",\"code\":\"116\",\"1\":\"desk\",\"description\":\"desk\",\"2\":\"BBM\",\"groupname\":\"BBM\",\"3\":\"gajahh.jpg\",\"namag\":\"gajahh.jpg\"},{\"0\":\"123\",\"code\":\"123\",\"1\":\"test\",\"description\":\"test\",\"2\":\"Pupuk\",\"groupname\":\"Pupuk\",\"3\":\"jerapah.jpg\",\"namag\":\"jerapah.jpg\"},{\"0\":\"1234\",\"code\":\"1234\",\"1\":\"Hei\",\"description\":\"Hei\",\"2\":\"BBM\",\"groupname\":\"BBM\",\"3\":\"case.PNG\",\"namag\":\"case.PNG\"},{\"0\":\"222\",\"code\":\"222\",\"1\":\"aas\",\"description\":\"aas\",\"2\":\"Pupuk\",\"groupname\":\"Pupuk\",\"3\":\"harimau.jpg\",\"namag\":\"harimau.jpg\"}]} ";
        try {
            JSONObject jsonObject = new JSONObject(test);
            JSONArray jsonArray = jsonObject.getJSONArray("azizah");
            for (int a = 0; a < jsonArray.length(); a++) {
                JSONObject json = jsonArray.getJSONObject(a);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("code", json.getString("code"));
                map.put("groupname", json.getString("groupname"));
                map.put("namag", json.getString("namag"));
                list_data.add(map);

            }

            adapterdata.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

I didn't change adapter code and just make list_barang.xml file.
now this code is working
p.s] this is my test code so. i make this. I don't make ImageView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/namatvv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

A: Try this:
for (int a = 0; a < jsonArray.length(); a++) {
    JSONObject json = jsonArray.getJSONObject(a);
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("code", json.getString("code"));
    map.put("groupname", json.getString("groupname"));
    map.put("namag", json.getString("namag"));
    list_data.add(map);
 }
 Adapterdata adapter = new Adapterdata(MainActivity.this, list_data);
 mRecyclerView.setAdapter(adapter);
 adapter.notifyDataSetChanged();

A: list_barang.xml
 <?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="2dp"
    app:cardElevation="2dp"
    app:contentPadding="3dp"

    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="106dp"
        android:background="#FFFFFF"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imgv"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center"
            android:src="@drawable/ic_launcher_background" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFFFFF"
            android:orientation="vertical">

            <TextView
                android:id="@+id/namatvv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Kategori"
                android:textColor="@android:color/background_dark"
                android:textSize="12sp"
                android:textStyle="bold"
                app:fontFamily="@font/acme" />

            <TextView
                android:id="@+id/code"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Code"
                android:textColor="@android:color/background_dark"
                android:textSize="8sp"
                android:textStyle="bold"
                app:fontFamily="@font/acme" />

        </LinearLayout>

    </LinearLayout>

</androidx.cardview.widget.CardView>

activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFF"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="36dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:fontFamily="@font/acme"
        android:text="Data Barang"
        android:textColor="@android:color/background_dark"
        android:textSize="30sp"
        android:textStyle="bold"
        app:fontFamily="@font/acme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/bararecy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="48dp"
        android:layout_marginLeft="48dp"
        android:layout_marginTop="56dp"
        android:layout_marginEnd="48dp"
        android:layout_marginRight="48dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3">

    </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

A: this issue already done. because koneksi.php have html its cause data not showing


text:
Q: "Commands ignored until end of transaction block", with autocommit mode with psycopg2 I'm writing a setup script for my Postgres database. As part of this, I want to create a user if it doesn't exist, and create the database if it doesn't exist, using the "POSTGRES" user and database to do this from. According to the Psycopg docs, I need to have autocommit on, in order for this to work, so I do that here.
def postgres_create_user(username, conn, cur, password=None):
    """
    Create a postgres user, including a password if provided.
    """
    from psycopg2.sql import Identifier, Placeholder, SQL
    from psycopg2.errors import DuplicateObject, ProgrammingError

    # Run the CREATE USER
    try:
        if password:
            cur.execute(
                SQL("CREATE USER {} WITH ENCRYPTED PASSWORD {}").format(Identifier(username), Placeholder()),
                [password],
            )
        else:
            cur.execute(SQL("CREATE USER {}").format(Identifier(username)))

        print(f"User {username} created successfully")
    except DuplicateObject as e:
        # it's okay if user already exists
        print(f"User {username} already exists")

def postgres_create_database(conn, cur, database, user):
    """
    Create a Postgres database, with the given owner.
    """
    from psycopg2.sql import Identifier, SQL

    # create database
    cur.execute(SQL("CREATE DATABASE {} OWNER {}").format(Identifier(database), Identifier(user)))
    print("Database created successfully")

conn = default_engine.raw_connection()
conn.autocommit = True

with conn.cursor() as cur:
    print("Initializing the postgres user")
    postgres_create_user(
        config_url.username, conn=conn, cur=cur, password=config_url.password
    )
with conn.cursor() as cur:
    print("Initializing the postgres database")
    postgres_create_database(
        conn=conn, cur=cur, database=config_url.database, user=config_url.username
    )

The trouble is that either of these functions (postgres_create_user and postgres_create_database) could fail. If the first fails (because the user already exists), and I try to run the second (CREATE DATABASE), I get this error:
megaqc_1  | psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block

So it thinks I'm trying to use a failed transaction. But I enabled autocommit mode, so why is this happening? How can I successfully run both of these commands, ignoring failures?


text:
Q: InputStream not receiving EOF I am attempting to send an image from my android device to my computer via a socket. The problem is the input stream on my computer reads in every single byte but the last set of them.  I have tried trimming the byte array down and sending it, I've manually written out -1 to the outputstream multiple times but the inputstream never reads -1.  It just hangs waiting for data.  I've also tried not closing the stream or sockets to see if it was some sort of timing issue, but that didn't work as well.
Client side (Android Phone)
//This has to be an objectoutput stream because I write objects to it first
InputStream is = An image's input stream android
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(object);
objectOutputStream.flush();

byte[] b = new byte[socket.getSendBufferSize()];
int read = 0;
while ((read = is.read(b)) != -1) {
   objectOutputStream.write(b, 0, read);
   objectOutputStream.flush();
   b = new byte[socket.getSendBufferSize()];
}
//Tried manually writing -1 and flushing here
objectOutputStream.close();
is.close();
socket.close();

Server Side (Computer)  This bit of code takes place after the object input stream reads in the objects sent.  It only starts to read when the file starts to send
File loc = Location of where the file is stored on the computer
loc.createNewFile();
FileOutputStream os = new FileOutputStream(loc);
Socket gSocket = The socket
ObjectInputStream gInputStream = Object Input stream created from the sockets input stream already used to read in the previous objects

byte[] b = new byte[gSocket.getReceiveBufferSize()];
int read = 0;
while ((read = gInputStream.read(b)) != -1) {
   os.write(b, 0, read);
   os.flush();
   b = new byte[gSocket.getReceiveBufferSize()];
}

os.close();

This code never reads in -1 even if I write -1 directly and flush the stream.  The outcome is java.net.SocketException: Connection reset when the stream or socket from the android device is closed.  The picture is almost completely sent but the very last pixels of the picture are gray.  I also even tried using the out/input stream directly from the socket instead of using the already created objectinputstream/objectoutputstream and it still doesn't work.

A: Since you're already using ObjectInputStream and ObjectOutputStream, you can use their respective readObject and writeObject methods to read/write entire objects at a time. Maybe you could send/receive the entire byte array as an object?
On your android:
1) byte[] imageBytes = ...; // contains the Image
2) objectOutputStream.writeObject(imageBytes);
On your computer:
1) byte[] imageBytes = (byte[])readObject();
2) get image from imageBytes
Of course, you'll have to use readObject from within a thread since it'll block.

A: Firstly, I think you misunderstood the meaning of EOF (-1). It doesn't mean the server wrote a -1, it means the server closed the stream.
I think your main problem though is that both the server and the client are reading in a loop, and neither get to the point where they close the stream. They are deadlocked - both are waiting for the other one to close first.
Your client:

Your server:

If you know that you have no more data to write then just close the stream.

A: You are writing byte[] arrays as objects, bur reading bytes. You should be reading Objects and casting them to byte[]. EOS will cause an EOFException to be thrown.


text:
Q: NodeJS/SailsJS app database block Understand that NodeJS is a single thread process, but if I have to run a long process database process, do I need to start a web worker to do that?
For example, in a sails JS app, I can call database to create record, but if the database call take times to finish, it will block other user from access the database.
Below are a sample code i tried
var test = function(cb) {
                for(i=0;i<10000;i++) {
                    Company.create({companyName:'Walter Jr'+i}).exec(cb);
                }
            }
            test(function(err,result){

            });
            console.log("return to client");
            return res.view('cargo/view',{
                model:result
            });

On first request, I see the return almost instant. But if I request it again, I will need to wait for all the records being entered before It will return me the view again.
What is the common practice for this kinda of blocking issue?

A: Node.js has non-blocking, asynchronous IO.
read the article below it will help you to restructure your code
http://hueniverse.com/2011/06/29/the-style-of-non-blocking/
Also start using Promises to help you avoid writing blocking IO.


text:
Q: Query is neglecting one of where clause, any idea why it is happening? I have two tables, activity and users. I am trying to fetch data by using multiple where clauses.
SELECT SUM(activity.step_points) AS s_points
, `activity`.`user_id`
, `users`.`id`
, `users`.`app_id`
, `users`.`country_id`
FROM `activity`
LEFT JOIN `users` ON `users`.`id` = `activity`.`user_id`
WHERE `users`.`is_active` = 1 AND
`users`.`is_test_account` = 0 AND
`users`.`app_id` = 3 AND
`users`.`country_id` = 1 AND
`users`.`phone` NOT LIKE "%000000%" OR
`users`.`phone` IS NULL AND
`users`.`is_subscribed` = 1 AND
(`users`.`email` NOT LIKE "%@mycompanyname.net" OR
 `users`.`email` IS NULL) AND
YEAR(`activity`.`created_at`) = "2021" AND
MONTH(`activity`.`created_at`) = "06"
GROUP BY `activity`.`user_id`
ORDER BY `s_points` DESC LIMIT 100 OFFSET 0

But I think users.country_id = 1 is getting neglected. You can see I want only rows that belong to country id 1. But I am getting country id 2, 3 too.

Why is it happening?

A: You need to properly use parentheses in the WHERE clause so the OR does not dominate over the ANDs:
SELECT . . .
FROM activity a JOIN
     users u
     ON u.id = a.id
WHERE u.is_active = 1 AND
      u.is_test_account = 0 AND
      u.app_id = 3 AND
      u.country_id = 1 AND
      (u.phone NOT LIKE '%000000%' OR u.phone IS NULL) AND
      u.is_subscribed = 1 AND
      (u.email NOT LIKE '%@mycompanyname.net OR u.email IS NULL) AND
      (a.created_at >= '2021-01-01' AND a.created_at < '2022-01-01'

Note the other changes to the code:

*

*You are filtering on both tables, so an outer join is not appropriate.  The WHERE clause turns it into an inner join anyway.

*Table aliases make the code easier to write and to read.

*All the backticks just make the code harder to write and read and are not needed.

*SQL's standard delimiter for strings is single quotes.  Use them unless you have a good reason for preferring double quotes.

*For date comparisons, it can be faster to avoid functions, hence the change for the year comparison.  This helps the optimizer.


text:
Q: Using recursive promise loops with then There is a promise which returns a parameter for next loop. It is like:
promise1(){
    return axios.get('https://google.com').then(result=>{
     if (result == someValue){ // continues
       promise1();
     }
     else { //if result does not equal this value, just break this loop and return
       return "stackoverflow";
     }})}

In the end I want to call this promise and do something after then, it will be:
promise1().then(()=>{
//do something
})

However, promise1 returns in first loop when i call this function like above. How can i make to wait till else block runs and returning "stackoverflow"? Actually, I understand why it returns in first loop, but how can i make that returning in specific condition ?

A: The problem is that when you call promise1() from the inside, it doesn't wait for it (as it is asynchronous). Instead, discards the promise returned from the internal call and resolves to  undefined.
To await that call as well, return it from the then handler (then will await it as if it were chained):

function promise1() {
  return axios.get('https://google.com').then(result => {
    if (result !== '') { // continues
      return promise1();
    } else { //if result does not equal this value, just break this loop and return
      return "stackoverflow";
    }
  })
}
promise1().then(console.log, console.error)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


text:
Q: Best way to know that my Python Code base is using PyXML or not? I have a python code base and want to know whether pyxml is really used in the code any where. The python version i have is 2.6. pyxml's last binary distribution ended with 2.4 python version. Any clues or ideas to judge the code whether it is free of pyxml 0.8.4 on python 2.6 ?
Thanks in Advance.

A: When you run
python -v script.py

Python prints all the modules imported to stderr. You can then inspect that output for the string "import pyxml":
python -v script.py 2>&1 | grep "import pyxml"

This works even if script.py imported pyxml in an unconventional way, such as __import__('pyxml').
It even works if the import were buried inside of a function:
def foo():
    import pyxml
    ...

provided that function eventually gets called.

A: grep your codebase for from xml import or import xml.

A: Search pyxml.py (or .pyc or similar). Rename it to something else say pyxmltest.py. See if it something crashes or if you want to be more sure and more gentle. Put in the same place file pyxml.py:
print('pyxml imported')
import pyxmltest.py

After test remove the test file and rename back the original.
Alternatively you could put the same print in the beginning of the actual module if it is written in python (plain .py)
Also some editors like IDLE has search in files function where you can search for pyxml. It works recursively in subdirectories.


text:
Q: wordpress post/page content in code i am trying to insert a post/page into one of my themes files and it wont display shortcodes or php
i have created a page called home in the wordpress admin-paned and inserted into my code the following:
<div id="home_page"> <!-- echos the content from the page "home" id:43 -->
            <?php $home_id = 43;
            $home_page = get_page( $home_id );
            ?>
            <?php echo $home_page->post_content; ?>
    </div> <!-- end #home_page -->

and non of the shortcodes that i have in the page work.
i installed a php in post or page and tried useing php and it doesnt work.
when i insert
echo do_shortcode('[youtube_sc url=http://www.youtube.com/watch?v=Db3XGpt6nNU]');

directly into the code it works.
does anyone know y this happens?
thank you.

A: I got an answer in wordpress.stackexchange.com
I Quote:

You need to apply the filter the_content e.g.:
<?php echo apply_filters('the_content',$home_page->post_content); ?>
Also, you don't need custom shortcodes for youtube, just put the URL in the content (but not a hyperlink), and it'll be swapped out for a youtube player at runtime. No plugins or extra code needed thanks to oembed.

Thank You Tom J Nowell

A: The $home_page->post_content value is the exact post content as stored in the database. Echoing this does not give any of your shortcodes a chance to run.
You should use a "WordPress Loop" to display the content, as this sets things up to allow you to use template tags such as the_title() and the_content() - this will call the processing functions for shortcodes and other functions like wpautop() that "massage" post content for output.
If you don't want to use a Loop, you could output the content using
echo do_shortcode($home_page->post_content);
This will run the post content through the shortcode processor, giving the shortcodes a chance to run.
For more on how WordPress "massages" post content, you can look here: http://codex.wordpress.org/How_WordPress_Processes_Post_Content


text:
Q: RC differentiator / RC integrator explanation I am watching a Youtube video about a very simple RC differentiator.
Quote from: Dipayan Das

I really cannot understand how the output waveforms looks, where there is a negative part. I know it is a simple question but please help me to understand this basic circuit.

A: Let's assume the second resistor in the first circuit and the second capacitor in the second circuit are not there, it will make it easier to understand.
In the integrator the capacitor starts out uncharged and acts like a short, when the input goes high the current flows through the resistor and charges the capacitor.
When the input goes low the capacitor now discharges through the resistor. The rise and fall are exponential, so the output looks like a saw tooth, curving up and down.
In the differentiator he capacitor starts out as a short so when the input goes high the output goes high almost instantly and you see a sharp positive spike. As the capacitor now charges through the resistor the voltage across it will increase, and since it's in series the output voltage is the input minus the capacitor voltage so the output drops as the cap charges. You now end up with Vin across the capacitor and 0 V at the output. When the input goes low it pulls the left side of the capacitor to ground. Since that side of the capacitor is positively charged the other side is negative with respect to ground and you see a sharp negative spike. As the capacitor discharges the output returns to 0 V. Again the charge and discharge are exponential, but because the capacitor is in series with the signal the charge/discharge curves are inverted compared to the integrator (curves are concave rather than convex).
Now let's add the second resistor and cap back in.
In the integrator the resistors form a voltage divider, and if they're equal the output will be basically the same except the peak voltage will be half the input high voltage. At the same time, the resistance in the circuit is half what it was without the second resistor so the time constant is cut in half and the charge and discharge happen twice as quickly. Note the width of the curve from the start to where it flattens out.

In the differentiator the capacitors also form a divider, so the same thing happens, the output waveform peak voltages are half the input high voltage. In this case the capacitance is doubled, so the charge/discharge happens half as quickly.

A: As a interviewer, I have given the simpler RC and CR circuits earlier in the video as questions to prospective employees. I did not give values, but it was an interactive test, they could ask for clarification. I would ask what might the output look like. Only about 20% would get them both right. To be fair, most of the jobs were for digital design, but I still think that every EE should have some basic understanding of analog circuits.
The intuitive way to solve these is to remember that the capacitor voltage will be the same immediately after the step function. Then, it will charge/discharge to the new steady state.

For the differentiator, assuming that the time constant is small compared to the period (cap is at steady state before the next edge), when you apply a negative step function to a cap that is charged, the negative voltage step is transfered to the output.

For the first question in your post, it is easy if you realize that a Thevenin equivalent (input and 2 resistors) will have a voltage of 1/2 the original.
Unfortunately, the second question is not intuitive to me. IMO, it is considerably harder than a simple RC or CR. I would guess that only a few percent of people could solve it in 30 seconds. I am not one of them.

A: Notice that the transfer function of the circuits is given by:
$$\mathscr{H}_{\space\text{circuit}\space 1}\left(\text{s}\right):=\frac{\text{V}_{\text{o}_1}\left(\text{s}\right)}{\text{V}_{\text{i}_1}\left(\text{s}\right)}=\frac{\text{R}\space\text{||}\space\frac{1}{\text{sC}}}{\text{R}+\left(\text{R}\space\text{||}\space\frac{1}{\text{sC}}\right)}=\frac{1}{2+\text{CRs}}\tag1$$
$$\mathscr{H}_{\space\text{circuit}\space 2}\left(\text{s}\right):=\frac{\text{V}_{\text{o}_2}\left(\text{s}\right)}{\text{V}_{\text{i}_2}\left(\text{s}\right)}=\frac{\text{R}\space\text{||}\space\frac{1}{\text{sC}}}{\frac{1}{\text{sC}}+\left(\text{R}\space\text{||}\space\frac{1}{\text{sC}}\right)}=\frac{\text{CRs}}{1+2\text{CRs}}\tag2$$
Where \$\alpha\space\text{||}\space\beta:=\frac{\alpha\beta}{\alpha+\beta}\$.
Using the convolution theorem of the Laplace transform we can see that:
$$\text{v}_{\text{o}_1}\left(t\right)=\int_0^t\text{v}_{\text{o}_1}\left(\tau\right)\cdot\mathscr{L}_\text{s}^{-1}\left[\mathscr{H}_{\space\text{circuit}\space 1}\left(\text{s}\right)\right]_{\left(t-\tau\right)}\space\text{d}\tau=$$
$$\int_0^t\text{v}_{\text{o}_1}\left(\tau\right)\cdot\frac{\exp\left(-\frac{2\left(t-\tau\right)}{\text{CR}}\right)}{\text{CR}}\space\text{d}\tau\tag3$$
$$\text{v}_{\text{o}_2}\left(t\right)=\int_0^t\text{v}_{\text{o}_2}\left(\tau\right)\cdot\mathscr{L}_\text{s}^{-1}\left[\mathscr{H}_{\space\text{circuit}\space 2}\left(\text{s}\right)\right]_{\left(t-\tau\right)}\space\text{d}\tau=$$
$$\int_0^t\text{v}_{\text{o}_2}\left(\tau\right)\cdot\left(\frac{\delta\left(t-\tau\right)}{2}-\frac{\exp\left(\frac{\tau-t}{2\text{CR}}\right)}{4\text{CR}}\right)\space\text{d}\tau\tag4$$


text:
Q: Oracle ADF - Jdeveloper use shortdesc in input from the value of another attribute of the View object I have an input and I want to populate the shortDesc atttribute with the value of another attribute of the View Object, how can I do it?
Thanks in advance.

A: In the bindings on the page, create an attributeValues binding to the View Object. Then in shortDesc property, it will be:
shortDesc="#{bindings.nameOfAttributeValuesBinding.inputValue}"

As the View Object goes to a given row, the attributeValues binding updates with the value. You may need to put a partial trigger on the component so it will update when a UI action takes place depending on what you are doing.


text:
Q: Swift UDP NWListener issue I am working with Network framework to achieve UDP transfer. Right now I've successfully connected my application with one device (the device, in which we send the data through UDP connection and receive data from that device and display in the application), and data send/receive is working properly.
I have two device. But my issue is that, when I tried to connect with another device the data is sent to the device but I was not receive the data. My listener is not working with another device. I've tried with re-installing the app, then also not working.
And when I tried to connect with the first device again then it's working properly.
So, is there any issue in my NWConnection or NWListener ? Because it seems that the code which I wrote is only allow me to connect with one device.
Here, below I attached my code for UDP connection for your reference.
Please anyone that will solve my issue would be so grateful to me.
Thank you in advance..!!
import Foundation
import Network
import UIKit

protocol UDPListener: class {
     func handleResponse(_ client: UDPConnection, data: Data)
     func errorWhileSending(_ client: UDPConnection)
}

class UDPConnection: UIViewController {

    var connection: NWConnection?
    var listner: NWListener?
    weak var delegate: UDPListener?

    let parameters = NWParameters.udp
    var singleton = Singleton.shared

    // for connect with device
    func connect(withHost: NWEndpoint.Host, port: NWEndpoint.Port) {
        parameters.allowLocalEndpointReuse = true

        self.connection = NWConnection(host: withHost, port: port, using: parameters)
        self.connection?.stateUpdateHandler = { (newState) in
            switch (newState) {
            case .ready:
                print("connection ready")
            case .setup:
                print("connectionsetup")
            case .cancelled:
                print("connectioncancelled")
            case .preparing:
                print("connection Preparing")
            default:
                print("connection waiting or failed")

            }
        }
        self.connection?.start(queue: .main)
    }

    // for sending UDP string
    func sendUDP(_ content: String) {
        let contentToSendUDP = content.data(using: String.Encoding.utf8)
        self.connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Data was sent to UDP")
            } else {
                print("ERROR SEND! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
                self.delegate?.errorWhileSending(self)
            }
        })))
    }

    //for sending UDP data
    func sendUDP(_ content: Data) {
        self.connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Data was sent to UDP")
                //self.receiveUDP()
            } else {
                print("ERROR Send! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
                self.delegate?.errorWhileSending(self)
            }
        })))
    }

    //////////////// UDP LISTNER /////////////////////

    func listenUDP(port: NWEndpoint.Port) {
        do {
            parameters.allowLocalEndpointReuse = true

            self.listner = try NWListener(using: parameters, on: port)
            self.listner?.stateUpdateHandler = {(newState) in
                switch newState {
                case .ready:
                    print("Listner ready")
                case .failed:
                    print("Listner failed")
                case .cancelled:
                    print("Listner cancelled")
                default:
                    break
                }
            }
            self.listner?.newConnectionHandler = {(newConnection) in
                newConnection.stateUpdateHandler = {newState in
                    switch newState {
                    case .ready:
                        print("new connection establish")
                        self.receive(on: newConnection)
                    case .failed:
                        print("new connection failed")
                    case .cancelled:
                        print("new connection cancelled")
                    default:
                        break
                    }
                }
                newConnection.start(queue: DispatchQueue(label: "new client"))
            }
        } catch {
            print("unable to create listener")
        }
        self.listner?.start(queue: .main)
    }

    func receive(on connection: NWConnection) {
        connection.receiveMessage { (data, context, isComplete, error) in
            if !isComplete {
                print("Not Complete")
            }
            if let error = error {
                print("Error in REceive: - ",error)
                return
            }
            if let data = data, !data.isEmpty {
                print("Data receive in UDPConenction;")
                guard self.delegate != nil else {
                        print("Error Receive: UDPClient response handler is nil")
                        return
                 }
                  self.delegate?.handleResponse(self, data: data)
            }
            self.receive(on: connection)
        }

    }

}


text:
Q: Access a list element from an array of lists I have following problem. I made an array of lists:
public List<float>[,] translatedtexture = new List<float>[8, 8];

this is a 2 dimensional array which hold list in each cell, right?
later on i do this:
translatedtexture[i,j] = new List<float>(){0.0F, 0.0F, 0.0F, 0.0F};

what i am doing is basically create a list of floats in an array cell [i,j].
later on i need to apply these floats like this:
newtexture.SetPixel(i, j, new Color(HERE:translatedtexture[i,j]list.r, HERE:translatedtexture[i,j]list.g, HERE:translatedtexture[i,j]list.b, HERE:translatedtexture[i,j]list.a);

but the problem is, that i do not know the syntax to pull the values from list which is in this particular cell. i've tried everything, browsed forums and i cant find an answer to this.
any help would be greatly appreciated.

A: You usually use list[i] notation to access i-th element in list.
Use the same syntax here: list[i] where list is translatedtexture[i,j].
So, translatedtexture[i,j][k] will be the k-th item of list in translatedtexture[i,j].
The code will look like this:
newtexture.SetPixel(i, j, new Color(translatedtexture[i,j][0], translatedtexture[i,j][1], translatedtexture[i,j][2], translatedtexture[i,j][3]);

However, it looks a little big ugly. Better use Color[,] or use custom structs.
Or at least do it this way:
var colorRgba = translatedtexture[i,j];
newtexture.SetPixel(i, j, new Color(colorRgba[0], colorRgba[1], colorRgba[2], colorRgba[3]);

A: You would access the list elements like this:
translatedtexture[i,j][0] //red
translatedtexture[i,j][1] //green
translatedtexture[i,j][2] //blue
translatedtexture[i,j][3] //alpha

A: Try to do this:
public List<Color>[,] translatedtexture

Or this if you want save memory a little bit (Color class have methods, and etc.):
public class MyColor
{
    public float A;
    public float R;
    public float G;
    public float B;
}
public MyColor[,] translatedtexture


text:
Q: Veronese surfaces in $\mathbb{P}^5$ intersecting finitely I wondered if it were possible to clarify the basic first lemma in A note on the Intersection of Veronese Surfaces.
Setup: $X_1$ and $X_2$ are two Veronese surfaces in $\mathbb{P}^5$ intersecting along a zero-dimensional scheme $W$.
Statement: Viewing $W$ as a subscheme of $X_1\cong \mathbb{P}^2$, $h^1(I_{W/\mathbb{P}^2}(4))=0$. (So $W$ imposes independent conditions on plane quartics, bounding the length of $W$.)
The proof is just five lines. The argument is to restrict the minimal resolution of $I_{X_2}$ to $X_1$. Using the fact that $I_{X_2}$ is generated by quadrics (with linear relations, linear relations between the relations and so on), we are supposed to conclude something about the resolution of $I_{W/X_1}$.
However, I'm not even sure whether the restriction of the resolution to $X_1$ remains exact or whether that matters.

A: The restriction of the resolution of $\mathcal{O}_{X_2}$ to $X_1$ computes $\mathrm{Tor}_i(\mathcal{O}_{X_1},\mathcal{O}_{X_2})$. If the intersection $X_1 \cap X_2$ is dimensionally transverse, higher $\mathrm{Tor}_i$ vanish, so the restriction of the resolution is a resolution of $W$.
EDIT. As @DCT observed, if two Veronese surfaces in $\mathbb{P}^5$ intersect, this is not a dimensionally transverse intersection, so one needs to be more careful.
In fact, if the intersection is "almost dimensionally transverse" (in the sense that the dimension of intersection is by one bigger than the expected dimension) then
$$
\mathrm{Tor}_{\ge 2}(\mathcal{O}_{X_1},\mathcal{O}_{X_2}) = 0
$$
and $\mathrm{Tor}_1(\mathcal{O}_{X_1},\mathcal{O}_{X_2})$ is an invertible sheaf on the scheme $X_1 \cap X_2$ (this is a local statement, so it can be proved using the Koszul resolution when the schemes $X_1$ and $X_2$ are locally complete intersections and the ambient scheme is Cohen-Macaulay).
In the case of two Veronese surfaces this can be applied as follows. Recall the resolution
$$
0 \to \to \mathcal{O}(-4)^{\oplus 3} \to \mathcal{O}(-3)^{\oplus 8} \to \mathcal{O}(-2)^{\oplus 6} \to \mathcal{O} \to \mathcal{O}_{X_1} \to 0
$$
of a Veronese surface. Restricting it to $X_2$ we obtain the complex
$$
0 \to \to \mathcal{O}_{X_2}(-8)^{\oplus 3} \to \mathcal{O}_{X_2}(-6)^{\oplus 8} \to \mathcal{O}_{X_2}(-4)^{\oplus 6} \to \mathcal{O}_{X_2} \to 0
$$
whose cohomology is $\mathcal{O}_W$ in degrees $0$ and $-1$ (any invertible sheaf on a zero-dimensional scheme is trivial). Twisting by $\mathcal{O}_{X_2}(4)$ we obtain the complex
$$
0 \to \to \mathcal{O}_{X_2}(-4)^{\oplus 3} \to \mathcal{O}_{X_2}(-2)^{\oplus 8} \to \mathcal{O}_{X_2}^{\oplus 6} \to I_W(4) \to 0
$$
whose cohomology is the sheaf $\mathcal{O}_W$ in the term $\mathcal{O}_{X_2}^{\oplus 6}$. Then the hypercohomology spectral sequence gives you
$$
0 \to H^0(X_2,\mathcal{O}_W) \to \mathbb{C}^6 \to H^0(X_2,I_W(4)) \to \mathbb{C}^{9} \to 0
$$
(the last term is $H^2(X_2,\mathcal{O}_{X_2}(-4)^{\oplus 3})$) and $H^{>0}(X_2,I_W(4)) = 0$. In particular, this bounds the length of $W$ by 6.


text:
Q: What is Python equivalent of the C++ macro preprocessor directive? I have a repeated piece of code in my python code that I can't factorize in a function because it analyses the call stack.
from traceback import extract_stack as es, format_list as fl

class Pmf

    def __init__(self,...):
        if not name: name = fl(es(limit=2))[0].split('\n')[1].strip().split("=")[0].strip()
        ....

In order to avoid copy pasting this code more than 10 times in my case, I would like to use some kind of macro preprocessor directive as in C++.
I don't think that python Cython supports this feature but I was wondering if there was a python library or a workaround like a pycharm solution. Thanks.

A: No Python doesn't have macros.
You can 'simulate' them by 'messing' with the AST (Abstract Syntax Tree) but it isn't exactly nice and is overall to be honest. I have never found a need for them - there are other ways to do what you might use macros for.
eg
macro='''
a=1
b=54
c=a+b
d=a-b
s = "hi k".split()
print(c**2+d**2, s)
'''

Output:
exec(macro)
5834 ['hi', 'k']


text:
Q: window.open loads popup page completely after executing logic I am trying to popup aspx page using window.open in parent page
 var win = window.open("apConfirmInvoiceSubmit.aspx");
    win.focus();
    hWnd =window['rturn'];
    if((hWnd == 1) || (hWnd == 2))
     {
     document.getElementById("ctl00_hdnInvoiceSubmit").value = hWnd;
     document.getElementById("ctl00_btnOK").style.display = "none";
     document.getElementById("btnattach").style.display = "none";
     document.getElementById("txtAref").innerHTML="";
     document.getElementById("ctl00_txtWait").style.display = "";
     return true;
 }

In child page
function SendValue(i)
{

window.opener['rturn'] = i;

window.close();
}

Window.open failed to popup immediately. It popups after executing complete logic and returning undefined for the first time
Would appreciate anyone please help me with this issue.
Please let me know if my explanation is not clear or if more information is required


text:
Q: Why do I get the exiled queen ending in Undertale when I did a pacifist route? Why do I get the exiled queen ending in Undertale when I haven't killed anyone? All I've done is give myself the Real Knife and Locket at the end of the game.

A: I figured out, it was because I had not completed the true lab portion of Undertale.


text:
Q: Why does XCode not recognize this header file I am trying to learn XCode and I am following an online course. They are telling to use the #import command to point to a header file. I follow the instruction to the letter and I get an error saying"no such file or directory" but the file is listed under classes and the spelling is identical. I wanted to included a screenshot but could not. Please help!

A: You are getting that error because Xcode cannot find the file you are trying to import.
Correct usage:
#import "RootViewController.h"

or
#import <Foundation/Foundation.h>

You also have to make sure that the file(s) you try to import are in your Project list. If the file you are trying to import is not in this list, then you will always receive this error.

A: It is possible that the file has been renamed in XCode. When a file's name is changed in the XCode interface, it's actual name is no longer changed in the file system. It used to, but doesn't anymore. In order for the compiler to find the file, you have to use the path to the header in the file system. Make sure the files are in the same folder and use the name displayed by Finder.


text:
Q: Why wasn't I notified of new privileges I gained as a result of the recent reputation recalculation? FYI: In the rep recalculation for questions, privileges didn't follow.
Today, a single upvote on this question, which constitutes all my activity on that site since recalculation, triggered the message from crossing the 3K threshold, though the threshold is not actually crossed in the transition from 3,125 to 3,135.

This old question suggests that privileges can be lost in reputation recalculation; it seems like the reverse should also apply and this looks like a bug.

A: Just to add to animuson's answer: a new event that decreases one's reputation (e.g., a downvote) may also trigger a privilege notification. (It happened to me on Medical Sciences SE, if I recall correctly.)

A: You gained the privilege the moment you passed the reputation threshold due to the recalculation. You weren't notified of the privilege until now because recalculations do not trigger privilege notifications - it's incredibly rare that a recalculation would ever put a user in a situation where that would occur.
Only a new event that increases your reputation (in this case, the upvote) can trigger a privilege notification.


text:
Q: PHP jquery image effect on mouseover I want to make my original image to portrait when I mouse over on an image. Can anyone please tell me how to do this? I want to open whole image on mouseover with portrait effect.

A: You should use css transform.
.main:hover img {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

example jsfiddle here

A: You should use jQuery to this with method mouseover() and mouseout(), The rotate attribute doesn't let your picture horizontally.
Here my JSfiddle.
http://jsfiddle.net/gLj8n9s6/
CSS
#main {
    width: 300px;
    height: 200px;
    overflow: hidden;
}
#img {
    width:300px;
    height:200px;
}

HTML

jQuery
$('#main').mouseover(function() {
    $(this).animate({width : '200px'});
});
$('#main').mouseout(function() {
    $(this).animate({width : '300px'});
});

Or KISS by doing this in pure CSS without the animate method in jQuery

A: On mouse over of the image you can open a DIV with some z-index and then place the image and do some css styling to make that portrait effect. You can make the popup DIV size as per the image size as well. Check this for css property. I think this will help you.

A: This is pretty straight forward using css3
img:hover {
 transform: rotate(90deg);
}

have a look at css transform http://www.w3schools.com/css/css3_2dtransforms.asp
edit : actually that might not be what you want. The image would transform back to landscape on mouseout


text:
Q: Singlet gluon interaction If a ninth singlet gluon existed (U(3) instead of SU(3)) it would propagate freely interacting strongly. My question is: only with hadrons or, perhaps, with leptons (I.e, electrons) as well?

A: If there were a ninth gluon ...  The precise wording of your question predetermines the answer.  If the supernumerary gluon were the ninth generator of U(3), then it would couple to baryon number alone; but if it were the additional diagonal generator of a grand SU(4) broken to SU(3)xU(1), then it would couple to hypercharge.  There is a somewhat esoteric reason, connected with anomalies, to think that it would have to be the latter.  The renormalization group also has something to say:  Even if all gluons had equal couplings at the Planck scale, radiative corrections would weaken the U(1) gluon's coupling at lower energies, while strengthening the SU(3) gluons' coupling.


text:
Q: Using XPath select all elements that contains a child element with an attribute value I am trying to use xpath to select all the node elements that contain a child element that has any value for the restriction attribute other than an empty string.
Here is my xml:
<nodes code="C">
   <node code="A">
      <child restriction="" />
      <child restriction="value" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
   <node code="B">
      <child restriction="value" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
   <node code="C">
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
      <child restriction="" />
   </node>
</nodes>

My working xpath is:
nodes/node[(child/@restriction and string-length(child/@restriction) > 0)]

This only returns node B, presumably because B is the only element where the restriction value appears first.  My aim is to return both B and A but not C.
Can someone point out where I've gone wrong?

A: How about:
nodes/node[child/@restriction[string()]]

This tests each restriction attribute for the existence of a string content.
In your version, you try to convert the node-set of child/@restriction into a string to be used as the argument for string-length(). In XSLT 1.0, this would return the value of the first node in the set; in XSLT 2.0, this would produce an error.