text:
Q: Searching on Stack Overflow Why are the instant question recommendations that appear when asking a question so much better/faster than the results from performing an actual query in the search field?
I understand that I can use quotes and tags to improve my search results. But if I simply type in "Detecting the end of a for loop in php" it returns "0 results". If, as recommended, I wrap the query in quotes I get "0 results". Let's simplify the query then and ask "for loop php", "0 Results". If I perform the same query in quotation marks with the tag [php] I start to get results, but not very good ones. This being a pretty vague query it returns vague results. In contrast if I click 'Ask Question' and start typing my query "Detecting the end of a for loop php.." I get instant, precise results.
Now I know that next to the query results you can click 'Advanced Search Tips' which gives you things like is:question and is:answer...but what does this mean? Do I prepend my question with "is:" or "is:question", both, either/or? SO offers things like tags and other various elements to assist in queries, but I will get a far more precise results if I simply click 'Ask Question' and start typing my question. Why isn't this query power available in the standard search field? Is it and am I simply not using it correctly?
How do YOU search on Stack Overflow? Please help me and the community become better Stack Overflow users. While I feel like this is a total noob question, I bet other people have experienced it as well so perhaps it's worthy of documentation.

A: This was a bug with our query parsing before the handoff to the lucene layer - it's now fixed in a build that just rolled out.
You'll now see there are 92 results for the query Detecting the end of a for loop in php.


text:
Q: How to get all element from div block which contains type=radio? maybe somebody can help me how to get all elements in Selenium in some block div with type="radio"  - For example:
I have divBlock = By.CssSelector("input[class='Vertical Radio']");
How to get all elements in divBlock and if element in divBlock have type="radio", click on this element?

A: Hope I understood you correctly: You want to get all child nodes from your div block, and among these you want to click the radio buttons...
here in Java, but I guess you can transform this into C# in a breeze:
you can use xpath to get all child nodes
By divBlock = By.CssSelector("input[class='textboxDate hasDatepicker']");
WebElement divElement = driver.findElement(divBlock);

//xpath to get all direct child nodes use "//" to get all child nodes and child of child nodes
String xpathExpression = "./*";
List<WebElement> elements = driver.findElements(By.xpath(xpathExpression));

for(WebElement element : elements) {
    if(element.getAttribute("type").equals("radio")) {
        element.click();
    }
}

A: You can write something like this:
foreach(var elem in driver.FindElement(divBlock).FindElements(By.XPath(".//*[@type='radio']")))
{
     elem.Click();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use elasticsearch for indexing formulas in MathML? I have a Q&A website that use Elasticsearch on it and also use MathML to type formulas. For example
<math xmlns="http://www.w3.org/1998/Math/MathML">
    <mi>d</mi>
    <mi>e</mi>
    <mi>t</mi>
    <mo> </mo>
    <mi>A</mi>
    <mo>≠</mo>
    <mn>0</mn>
</math>

is the MathML code for det A ≠ 0.
the problem is that elasticsearch is indexing it like a simple text(not formula), so the result of searching "det" is nothing.

A: Your MathML is not semantically correct for what you are doing.  It doesn't mean det A ≠ 0, but rather d * e * t A ≠ 0; that is the product of d, e, and t followed by A ≠ 0 (I'm not sure what the empty <mo> represents, but the space is ignored by MathML.)
A better representation would be
<math xmlns="http://www.w3.org/1998/Math/MathML">
    <mi>det</mi>
    <mo></mo>
    <mi>A</mi>
    <mo>≠</mo>
    <mn>0</mn>
</math>

That might resolve your issue with searching as well, since now det will match something.


text:
Q: getting filename count from multiple tables group by that file name I am trying to query the following in DB2. T28, T29 and T30 are table names. They have filename as a column which is in all tables. I have to find the count of filename in all three tables group by filename. Can you help?
Well, I am trying this in DB2.
I am looking for an output like this.

filename  T28COUNT   T29COUNT   T30COUNT

A: Try
SELECT filename,
       SUM(CASE WHEN t = 28 THEN 1 ELSE 0 END) t28count,
       SUM(CASE WHEN t = 29 THEN 1 ELSE 0 END) t29count,
       SUM(CASE WHEN t = 30 THEN 1 ELSE 0 END) t30count
  FROM
(
  SELECT 28 AS t, filename
    FROM t28
   UNION ALL
  SELECT 29 AS t, filename
    FROM t29
   UNION ALL
  SELECT 30 AS t, filename
    FROM t30
) q
 GROUP BY filename
 ORDER BY filename

Here is SQLFiddle demo for SQL Server, but I believe it should work pretty much the same for DB2.


text:
Q: Running a compiled c program (or .o) in an iOS app? I have a program written in c that I want to run in an iOS app. The program takes as parameters a path to an image, processes it and outputs another image in a provided location. I have the .o file and the compiled executable. Is it possible to include one of those in the app? If yes, how?

A: You have to include a header file with the function declaration and link the .c file. ie, #include headerfile.h in the class you need.


text:
Q: Variation of Antisymmetric tensor's trace? Does an action of the form $$S=\int f(\text{tensors})g^{ij}\nabla_kA^k_{ij}\ d^4x$$ where $A$ is antisymmetric in the lower indices produce, upon variation, any nontrivial equation?
Given that the covariant derivative annihilates the metric, one can bring it to the right and therefore take the "trace" of the antisymmetric tensor, making it zero. However, naïve variation and simplification of a specific Lagrangian that I was exploring led to what looked like a legitimate field equation. In other words: Is it thus necessarily true that there is some (tensor) identity which would reduce the "field equations" to something trivial?

A: OP's action $S$ is manifestly zero. Hence the variation $\delta S$ is also zero.


text:
Q: CS50 Recover runs and recovers all files except the first one My question is regarding the Recover assignment as part of CS50.
The code is running (finally) and it produces 50 JPEG files, and most of them are the correct images, except the first file is not an image, therefore it  doesn't pass check50.
I have spent a long time trying to figure out what the problem is but I cannot pinpoint it so I am hoping someone might be able to help me out so I can move on.
Thanks in advance! Here is my code:
    int main(int argc, char *argv[])
    {
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: Name of Memory Card File\n");
        return 1;
    }

    char *readfile = argv[1];

    // open memory card file
    FILE *card_ptr = fopen(readfile, "r");
    if (card_ptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", readfile);
        return 2;
    }

    //Declare a buffer to read into
    unsigned char *buffer = malloc(512);

    //to check if we have already found a file
    bool (jpgAlreadyNew) = false;

    //declare counter for the number of files found and a file pointer
    int filenumber = 0;
    FILE *new_jpg_ptr = NULL;
    char filename[8];

    //read in bytes until reach EOF
    while (fread(buffer, 1, 512, card_ptr) != 0x00)
    {
        //if we reach the header pattern of bytes
        if (buffer [0] == 0xff && buffer [1] == 0xd8 && buffer [2] == 0xff && (buffer [3] & 0xf0) == 0xe0)
        {

            //if there is not already a JPEG file found
            if (!jpgAlreadyNew)
            {
                //change the bool value
                (jpgAlreadyNew) = true;

                //open new file
                sprintf(filename, "%03i.jpg", filenumber);
                new_jpg_ptr = fopen(filename, "w");
                if (new_jpg_ptr == NULL)
                    {
                        return 3;
                    }
                //add to counter of files found
                filenumber++;

                //write files from buffer into new img file
                fwrite(buffer, 1, 512, new_jpg_ptr);

            }

            //if there is already a JPEG file found
            if (jpgAlreadyNew)

            {
                //close the previous file which would now be complete
                fclose(new_jpg_ptr);

                //open new file
                sprintf(filename, "%03i.jpg", filenumber);
                new_jpg_ptr = fopen(filename, "w");
                if (new_jpg_ptr == NULL)
                    {
                        return 4;
                    }
                //add to counter of files found
                filenumber++;

                //write files from buffer into new img file
                fwrite(buffer, 1, 512, new_jpg_ptr);

            }

        }

        // else if we do not see pattern of header bytes
        else
        {
            //if already found a jpg file which is open then write the bytes to that file
            if (jpgAlreadyNew)
              {
                  fwrite(buffer, 1, 512, new_jpg_ptr);
              }
            //if no file found yet, discard and move on
            if (!jpgAlreadyNew)
              {
                  continue;
              }
        }
    }

    //free memory
    free (buffer);

    //close pointers and end program successfully
    fclose(card_ptr);
    fclose(new_jpg_ptr);
    return 0;
}

A: Let's walk through the program starting with finding the first jpeg signature:
This if (!jpgAlreadyNew) evaluates to true, so it enters the if block; the first thing it does is (jpgAlreadyNew) = true;. When it is done creating the file and writing the first block, what happens next? This if (jpgAlreadyNew). Which also evaluates to true. So it closes 000.jpg and moves along.
Since jpgAlreadyNew is a boolean, an if {} else {} construct would suffice.


text:
Q: How to create a class decorating another class using python My goal is to implement a classic Decorator pattern (not functional @decorator, provided by python from the box). But I don't want to implement every method and attribute in decorator class. I want to make it in a more universal and elegant way.
My approach:
class AbstractDecorator:
    base_class: type = None

    def __init__(self, instance):
        self.instance = instance

    def __getattr__(self, item):
        # If there is no attribute or method in current object, lookup in base instance
        return getattr(self.instance, item)

class Original:
    def __init__(self):
        self.some_val = 1

class ConcreteDecorator(AbstractDecorator):
    base_class = Original

original = Original()
decorated = ConcreteDecorator(original)

print(decorated.some_val)
# prints 1, everything is OK

And everything here is working fine, instead of one thing:
print(isinstance(decorated, Original))
# Prints False

The first thing I thought I could use were magic methods. I've found isinstancecheck and issubclasscheck methods. But they only act, when an instance is checked to be class that uses them, e. g. isinstance(something, AbstractDecorator). But I need to modify the opposite: isinstance(decorated, some_other_class).
Is there a way to do it? I haven't found one...


text:
Q: Netsuite 24 hour clock in formula(text) I am looking for the proper syntax for the 24 clock in a formula(text) in a NetSuite saved search.
Here is a sample of what i am using that output the 12 hour clock...
TO_CHAR({datecreated},'MM/DD/YYYY HH:MI:SS')

And example output for this would be 12/31/2014 01:25:11
I would like the output to be 12/31/2014 13:25:11
Thanks in advance!

A: If anyone else finds this and needs to correct syntax it is
TO_CHAR({datecreated},'MM/DD/YYYY HH24:MI:SS')


text:
Q: Compiler understanding of empty function and function with compute statement Just I want to understand the function call for the following functions
public class Program{

    public void function1(){}

    public void function2(){

        //Some compute statment.
    }
}

If we are calling function1() then JVM will make the call or not because it's empty function.


text:
Q: aws-sdk for ruby. How to assign a public ip address with instance? After thoroughly reading the ruby aws-sdk docs, I dont see a way to associate a public ip address with an instance when creating inside a VPC. I dont want to manage elastic IP addresses, just have the good old random public ip.
instance = ec2.instances.create(
  count: 1,
  image_id: IMAGE_ID,
  instance_type: INSTANCE_TYPE,
  key_name: KEYNAME,
  subnet_id: SUBNET_ID,
  security_groups: security_group,
  user_data: USER_DATA
)

Anyone know the simplest way to associate a public address on ec2 instance creation?
thanks in advance.

A: From http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/Client/V20131015.html#run_instances-instance_method, Under run_instances method, Under :network_interfaces option, you can use :associate_public_ip_address input parameter to specify assignment of the Public IP address.
FYI, You are using older version of Ruby SDK. Use AWS SDK CORE as AWS is focusing more on Core SDK now a days. Above option for assigning Public ip address in AWS SDK CORE can be found here.

A: Here is some sample code to launch an instance in a VPC with a public IP address, using version 2.2 of the Ruby AWS SDK. As far as I can tell, this is the minimum amount of code needed in order to launch an instance that actually has a public IP address. All the variables named my-something would need to be set first, of course.
require 'aws-sdk'
@ec2 = Aws::EC2::Resource.new
@ec2.create_instances(dry_run: false,
                      min_count: 1,
                      max_count: 1,
                      image_id: my-image-id,
                      key_name: my-key-name,
                      network_interfaces: [{device_index: 0,
                                            subnet_id: my-subnet-id,
                                            groups: [my-security-group-id],
                                            delete_on_termination: true,
                                            associate_public_ip_address: true}]


text:
Q: Loop Through JSON List Of Urls With RobotFrameWork To Assert An Element Exists On Each Page I have a list of URLs in a JSON file laid out as such:
{
  "urls":
     [
        "https://www.fakesite.org",
        "https://www.fakesite.org/home",
        "https://www.fakesite.org/whatever"
    ]
}

I want to loop over them in robotframework and assert that an element exists. I am able to get it to open the browser, go to the first link and check the element. Then the test ends and doesn't continue its loop onto the next url.
The Robotframework keyword is written as such
I assert the element exists on the page
    ${url_list}=    load json from file    ../Json/myjson.json
    ${url_values}=  get value from json  ${url_list}  $.urls[:]
    FOR    ${urls}    IN    ${url_values[0]}
           Assert Oplists Are Visible On Pages  ${urls}
    END

I have it set to url_values[0]. If I removed the [0] it tries to throw in the whole list and tell me "WebDriverException: Message: unknown error: 'url' must be a string." so I know it trying to pass in the entire list.
This goes on to the keyword mentioned:
Assert Oplists Are Visible On State Pages
   [Arguments]  ${urls}
   Go To  ${urls}
   page should contain element      ${primary_element}

I have already opened the browser in a previous step, hence why you don't see the typical
open browser  url  chrome

It all opens up fine, does what i needs to do. The only issue I have is that is stops after the first URL and doesn't go onto the next one.
Any and all help is greatly appreciated.

A: Use @ to expand the list into individual arguments to FOR:
FOR    ${urls}    IN    @{url_values}
       Assert Oplists Are Visible On Pages  ${urls}
END

This is mentioned in the robot framework user guide, in a section titled Simple for loop


text:
Q: Failed to Open Stream using laravel install I am trying out Laravel and after installation I get the following when attempting to start a new application:
using code: laravel new blog
I get:
PHP Warning:  file_put_contents(/var/www/html/laravel_d4381b5ce250405766ef8b9fa784b256.zip): failed to open stream: Permission denied in /home/ren/.composer/vendor/laravel/installer/src/NewCommand.php on line 81
PHP Warning:  ZipArchive::extractTo(): Permission denied in /home/ren/.composer/vendor/laravel/installer/src/NewCommand.php on line 99
PHP Warning:  ZipArchive::close(): Invalid or unitialized Zip object in /home/ren/.composer/vendor/laravel/installer/src/NewCommand.php on line 101
Application ready! Build something amazing.

A: It seems the user you're running the command with, doesn't have the necessary permissions to write to /var/www/html/. Try changing the permissions or owner of that directory. Try:
sudo chown $USER /var/www/html

The $USER variable contains the logged in username (in your case ren), so it will make your user the owner of that directory. Then run the installation command:
laravel new blog

A: As a noob, it took me a few good painstakingly hours to figure this out. As far as my understanding goes, you'll need to initiate the new project with laravel new <project> in a 777 directory. So you'd go like:
 ### make directory and grant full permissions
 sudo mkdir /var/www/laravel
 sudo chmod -R 777 /var/www/laravel/
 cd /var/www/laravel/

 ### run laravel installer
 laravel new web-project

 ### move your project in www root
 sudo mv web-project /var/www/

The last bit where you move the directory is optional and you may leave it there or move it to anywhere your vhost might be set up.
Personal note: I was actually hoping setting up a new Laravel app to be easier than this. I'm confident however it will get easier with practice :)


text:
Q: How to integrate Google Analytics with jQuery Mobile application? I try to develop a jQuery Mobile application with multi-page template. I want to add Google Analytics into the application.
I reference this documents,Using Google Analytics with jQuery Mobile. It seems not work in my application.
The code in my app is below:
<script type="text/javascript">
    var _gaq = _gaq || [];

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();

    $('[data-role=page]').on('pageshow', function (event, ui) {
        try {
            _gaq.push(['_setAccount', 'UA-30119852-1']);
            hash = location.hash;

            if (hash) {
                _gaq.push(['_trackPageview', hash.substr(1)]);
            } else {
                _gaq.push(['_trackPageview']);
            }
        } catch(err) {
        }
    });
</script>

How can I integrate Google Analytics with jQuery Mobile application?

A: $(document).delegate('[data-role=page]', 'pageshow', function (event, ui) {
console.log('pageshow event handler called for ');
var url = location.href;
console.log('pageshow event url = '+url);

try
{
    //_gaq.push(['_trackPageview', url]);
    _gaq.push( ['_trackPageview', event.target.id] );
    console.log('done pushing page '+url);
}
catch(error) {
    // error catch
    console.log('got error '+error);
}
});


text:
Q: match word if not inside other word thecompletestring must match complete
thecompletelystring must not match complete
theuncompletestring must not match complete
theuncompletelystring must not match complete
I tried word boundaries, but they don't work in URLs.
I have a word list in an array, one word, one item.
How to match a word if it isn't inside an other word?

A: This cannot be done with regexp. To successfully distinguish between those cases, you need to write something that understands the English language. That will obviously not be easy to do properly.
To get pretty close, you could use a dictionary of words and see if the string can be split to words in that dictionary with the word you're looking for as one of the words. This will not account for typos or misunderstandings or two words accidentally being considered as one. You would need something that truly speaks a human language for that.


text:
Q: Root-finding algorithms for discrete function Assume that we have function f(x)
f(x) has 3 possible constant outputs
f(x)= a if x>b
f(x)= 0   if x =b
f(x)= -a if x<b
Is there an iteration method that can be used to generate initial guess then iterates to find b?

A: For initial guess
Take $u_1 = 0$ and $\epsilon = 1$ if $f(u_0) = -a$ / $\epsilon = -1$ if $f(u_0) = a$. Compute $u_n = u_0 + n \epsilon$ until $f(u_0)f(u_n) \lt 0$.
Then use Bisection method algorithm.

A: If you have $l$ and $r$ such that $f(l) = -a$ and $f(r) = a$ then the bisection method should converge to $x$.
That is, set $l_1 = l$ and $r_1 = r$. Then if $f\left(\frac{l_n + r_n}{2}\right) = 0$ we are done. Otherwise if it is $-a$, set $l_{n+1} = l_n$ and $r_{n+1} = \frac{l_n + r_n}{2}$ and finally if is $a$, set $l_{n+1} = \frac{l_n + r_n}{2}$ and $r_{n+1} = r_n$. $l_n$ and $r_n$ should both converge to $x$.
Now to find initial guesses, try $l = -2^n$ and $r = 2^n$ which will find initial guesses in the asymptotic order of binary digits of $b$.

A: If the domain were a compact interval such as $[a,b]$, you'd simply take the boundary points as initial guesses and proceed by binary bisection. Here, we can use a suitable function to map $\Bbb R$ to a bounded interval and extend it to its closure.
For example, $\arctan$ maps $\Bbb R$ to $(-\frac\pi2,\frac\pi2)$, so we might do the following

*

*Set $L\leftarrow-\frac \pi2$ and $R\leftarrow \frac\pi2$.

*If $L>-\frac\pi2$ and $R<\frac\pi2$, go to step 7

*Set $M\leftarrow \frac{L+R}2$ and compute $Y=f(\tan M)$

*If $Y=0$, terminate with result $\tan M$

*If $Y=a$, set $R\leftarrow M$ and go back to step 2

*Otherwise, set $L\leftarrow M$ and go back to step 2

*Set $L\leftarrow \tan L$, $R\leftarrow\tan R$

*Set $M\leftarrow \frac{L+R}2$ and compute $Y=f(M)$

*If $Y=0$, terminate with result $M$

*If $Y=a$, set $R\leftarrow M$ and go back to step 8

*Otherwise, set $L\leftarrow M$ and go back to step 8


text:
Q: Convert two vectors into a vector of tuples using stl and boost i have
vector<time> tt;
vector<space> xx;

i would like to get
vector<tuple<time,space>> trajectory;

this is what I have so far
  std::for_each(boost::make_zip_iterator(
        boost::make_tuple(tt.begin(),xx.begin(),
        boost::make_tuple(tt.end(),xx.end(),
        []() {
          trajectory.push_back(make_tuple(get<0>(),get<1>()));
        }
        );

i'm not sure how to proceed further. one way is i can make a functor as zip_func in http://www.boost.org/doc/libs/1_52_0/libs/iterator/doc/zip_iterator.html#examples but i don't want to write extra code and I want to use lambda.
any thoughts?

A: How about something like (untested code):
std::copy(
    boost::make_zip_iterator(boost::make_tuple(tt.begin(),xx.begin()),
    boost::make_zip_iterator(boost::make_tuple(tt.end  (),xx.end  ()),
    std::back_inserter(trajectory)
    );

No need for a lambda!
In your sample code you are unpacking a tuple only to create another tuple, so I was able to get rid of that.


text:
Q: How to reassemble file chunks sent via Dropzone.js in PHP? To handle large files' uploads, I have to send them to the server by breaking them down into chunks. I use Dropzone.js as a library. My problem is that I could not find guide how to reassamble chunked files on server side (PHP in my case)

A: How big are your files?
Have you tried to increase post-max-size and upload_max_filesize   ?


text:
Q: Meaning of 'mu' in 'uWSGI' Web-server gateway interface? What does 'mu' stand for in uWSGI? I see that uWSGI pronounced "mu wiz gee". And WSGI means web-server gateway interface. But what about the 'mu' part?

A: It refers to the letter mu, μ, which looks like u if you squint. Since mu is the letter for the SI prefix micro-, the idea is that uWSGI (or rather, μWSGI) would be a small WSGI.
However, the official documentation or repository for uWSGI don't use the letter mu, nor does the official logo, so I'd pronounce it "You Whiskey".


text:
Q: SQL Server Query Count Join Table I have 2 tables are call Suppliers and Products, which products have SupplierID as foreign key.
My question is how to make a query that can show this result
Supplier Name | Total Products
--------------+---------------
Unilever      | 20
Kalbe         | 50
Jhonson       | 70

My table structure

*

*Suppliers => ID, Name

*Products => ID, SupplierID, Brand, Price

This is what I tried:
SELECT COUNT(*) AS Total
FROM Products
GROUP BY SupplierID

A: select
    s.Name as 'Supplier Name', count(p.ID) as 'Total Products'
from
    Supliers as s
left outer join
    Producsts as p on (s.Id = p.SupplierID)
group by
    s.Name;

A: All you need in addition to your query is a sub-query to obtain the name:
SELECT COUNT(*) as Total
  , (select Name from Supplier where ID = SupplierID) as [Supplier Name]
FROM Products
GROUP BY SupplierID

A: you can use left join by SuplierID + subquery for Products group by SuplierID to avoid multi slow query.
select T1.Name as Supplier Name
 ,T2.cnt as Total Product
from Supliers T1
left join (
    select SuplierID,count(1) cnt
    from Products
    group by SuplierID
) T2 on T1.ID = T2.SuplierID


text:
Q: How to use Facebook Ads Insight API with app token? I am using Facebook Ads Insight API with a user token at the moment, but this user token expires (every hour for temporary token, and every 60 days for extended token) and I need to update it manually in my environment. Is there a way to use an app token to permanently allow access to the AdsInsight API? Otherwise, what's a programatic way to refresh the user token? (FYI, I use airflow to store the token in admin/connections)
For now my URL request is :
https://graph.facebook.com/v8.0/act_<SECRET_AD_ACCOUNT_ID>/insights?access_token=<SECRET_TOKEN>=ad_id,ad_name,clicks,unique_clicks,inline_link_clicks,unique_inline_link_clicks&time_range={'since':'2021-01-01','until':'2021-01-05'}&time_increment=1&level=ad

When the <SECRET_TOKEN> is

*

*a user token : Data is generated correctly

*an app token I get an error. (See bellow)

Error when using app token:
{
   "error": {
      "message": "Unsupported get request. Object with ID 'act_<SECRET_AD_ACCOUNT_ID>' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
      "type": "GraphMethodException",
      "code": 100,
      "error_subcode": 33,
      "fbtrace_id": "<SECRET>"
   }
}

A: The user tokens last 60 days, but there is a way to automatically update them through the API. Make a GET call to the following endpoint every < 60 days to refresh your user token.
oauth/access_token?grant_type=fb_exchange_token&client_id=<APP_CLIENT_ID>&client_secret=<APP_SECRET>&fb_exchange_token=<USER_TOKEN>


text:
Q: How do I reformat the output of a BASH script? I am trying to find specific files in a directory that contain a string.
Code I've written so far:
for x in $(find "$1" -type f -name "*."$2"") ;
do
     grep -Hrnw $x -e "$3"
done

The output I get:
./crop.py:2:import torch
./crop.py:3:import torch.backends.cudnn as cudnn

I am trying to get spaces on both sides of the colon like this:
./crop.py : 2 : import torch
./crop.py : 3 : import torch.backends.cudnn as cudnn

I am fairly new to programing in BASH. I've tried using sed command but had not luck with it.

A:
I am trying to get spaces on both sides of the colon

I've tried using sed command but had not luck with it.

sed 's/:/ : /g'

A: Why are you using a for-loop for browsing through the find results, while you can use a find ... -exec?
Like this:
find "$1" -type f -name "*."$2"" -exec grep -Hrnw {} -e "$3" \;

(I didn't test this, it might contain some bugs)

A: find "$1" -type f -name "*.$2" | xargs grep -Hrnw -e "$3"| sed 's/:/ : /g'

A: Suggesting to try one liner command:
grep -Hrnw "$3" $(find "$1" -type f -name "*.$2" -printf "\"%p\"\n") | sed 's/:/ : /g'


text:
Q: Prisma, How to query if string exist in another string I am writing a prisma query but I need to know if a string exist in another string.
In prisma we can do this
  where: {
    id: { in: [22, 91, 14, 2, 5] },
  },

for arrays. but I want to be able to check if the property value exist in a string. Some thing like this
  where: {
    comment: { in: "some random string containing the value in comment" },
  },

So if comment: 'the value' it should match the query above. I can not find a sample of this kind of operation in the prisma doc.
I am looking for inverse of the string_contains function. basically the equivalent of this SELECT * FROM table WHERE POSITION(comment IN "some random string containing the value in comment") > -1

A: I think what you are trying to do can be done by using prisma filtering and sorting function contains.
In your case, it should be looks like:
where: {
    comment: { contains: "the value" },
},

The above query will return you the records that contains the value on comment column.
You can have a look on this document Prisma Filtering and sorting and check out the part of Filter on relations

A: You should be able to use something like string_contains, which works like this:
const getUsers = await prisma.user.findMany({
  where: {
    pets: {
      path: ['favorites', 'catBreed'],
      string_contains: 'Van',
    },
  },
})


text:
Q: Assign values to new column based on conditions between two pandas DataFrames Lets say there are two data frames:
df1 contains 4 columns. The 'NAME' column contains the name of the cities (A, B, C). Each of the other columns represents a year (y0, y1, y2) containing the number of people living on that city.
np.random.seed(seed=34)
name = ['A','B','C']
y0 = np.random.random_integers(1,high=40, size=3)
y1 = np.random.random_integers(1,high=40, size=3)
y2 = np.random.random_integers(1,high=40, size=3)
df = pd.DataFrame(data={'NAME' : name, 'y0' : y0, 'y1' : y1, 'y2' : y2})
df

   NAME y0  y1  y2
0   A   34  36  15
1   B   22  6   30
2   C   5   12  19

df2 contains 3 columns. The column 'NAME' contains the name of the cities. The 'y' column contains the value of the year (y0, y1, y2) and the 'i' column contains the number of people who have internet access.
y = ['y0', 'y1', 'y2',  'y0', 'y1', 'y2',  'y0', 'y1', 'y2']
name2 = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
i = [15, 6, 12, 18, 4, 20, 3, 8, 2]
df2 = pd.DataFrame(data={'NAME':name2, 'y':y, 'i':i})
df2

   NAME y   i
0   A   y0  15
1   A   y1  6
2   A   y2  23
3   B   y0  18
4   B   y1  17
5   B   y2  20
6   C   y0  3
7   C   y1  24
8   C   y2  2

I need to create a column on df2 that contains the values of df1 with the condition that the value of df2['NAME'] is equal to df1['NAME'] and df2['y'] is equal to the df1 column , in order to get the following result:

   NAME y   i   v
0   A   y0  15  34
1   A   y1  6   36
2   A   y2  12  15
3   B   y0  18  22
4   B   y1  4   6
5   B   y2  20  30
6   C   y0  3   5
7   C   y1  8   12
8   C   y2  2   19

The number of times that the cities names appear on df is not constant.
Thank you in advance.

A: You can do this, since the values match:
df2['v'] = df.melt(col_level=0, id_vars='NAME').sort_values(by='NAME').reset_index(drop=True)['value']

output:
  NAME   y   i   v
0    A  y0  15  34
1    A  y1   6  36
2    A  y2  12  15
3    B  y0  18  22
4    B  y1   4   6
5    B  y2  20  30
6    C  y0   3   5
7    C  y1   8  12
8    C  y2   2  19

or with combinefirst
df3 = df.melt(col_level=0, id_vars='NAME').sort_values(by='NAME').reset_index(drop=True)
df3 = df3.rename(columns={'variable':'y'})
df3 = df2.combine_first(df3)
df3['value'] = df3['value'].astype(int)

  NAME   i  value   y
0    A  15     34  y0
1    A   6     36  y1
2    A  12     15  y2
3    B  18     22  y0
4    B   4      6  y1
5    B  20     30  y2
6    C   3      5  y0
7    C   8     12  y1
8    C   2     19  y2

A: a merge would be better imo,
df = pd.melt(df,id_vars='NAME',var_name='y',value_name='v')

df_new = pd.merge(df,df2,on=['NAME','y'].sort_values('NAME')
print(df_new)
  NAME   y   i   v
0    A  y0  15  34
3    A  y1   6  36
6    A  y2  12  15
1    B  y0  18  22
4    B  y1   4   6
7    B  y2  20  30
2    C  y0   3   5
5    C  y1   8  12
8    C  y2   2  19


text:
Q: jqgrid TreeGrid with frozen columns is not working currently frozen columns can not be setup with TreeGrid .Here Is the Link
I tried the solution suggested at this site: https://github.com/tonytomov/jqGrid/pull/420
to freeze columns on treegrid. It freezes the column and expanding the nodes work fine for all levels of the tree. However, collapsing row is not working for me if the tree level is more than three. Is anyone successful in using frozen columns with TreeGrid?
I am using jqgrid version: 4.4.4
Thank you in advance for your help!
Best Regards


text:
Q: Cookies and Candies
In how many ways can I distribute $6$ identical cookies and $6$ identical candies to $4$ children, if each child must receive at least $1$ of each type of item?

I know how to distribute the things if they are a specific amount, but I'm struggling with the "at least" part.

A: Lets say $A,B,C,D$ are $4$ children and you need to distribute $6$ identical candies and $6$ identical cookies.
Now first each $A,B,C,D$ children will get $1$ candy and $1$ cookie.
So, now we have to distribute the remaining $2$ candies and $2$ cookies among $4$ children.
To distribute $2$ candies  use the formula $$^{n+r-1}C_{n-1}$$ where $n=4,r=2$
$$^{4+2-1}C_{4-1}=\ ^ 5C_3=\frac{5!}{2!\cdot3!}=10\ ways$$
Again to distribute $2$ cookies  use the formula $$^{n+r-1}C_{n-1}$$ where $n=4,r=2$
$$^{4+2-1}C_{4-1}=\ ^ 5C_3=\frac{5!}{2!\cdot3!}=10\ ways$$
So, total number of ways $=10\times 10=100$ ways.

A: One candy and one cookie can be given to one of the 4 children in 6*6 ways.i-e 36 ways.
Likewise second candy and second cookie can be given in 25 ways.
Similarly third and fourth candy and cookie can be given in 16 and 9 ways respectively.
Now 2 cookies and 2 candies remains. They can be distributed to any one of 4 children in 4 ways each i-e $4^4 ways$.
Hence the total number of ways of distributing 6 cookies and 6 candies to 4 children so that each one of them get at least one cookie and one candy are 36*25*16*9*$4^4$ ways.


text:
Q: Spring Boot ReactiveRedis custom annotation to subscribe the channel and get the data I am working on spring boot ReactiveRedis for the pub-sub mechanism following is my code and it is working fine, I am getting data in subscribe call back.
@Autowired
private ReactiveRedisOperations<String, Object> reactiveRedisTemplate;

@PostConstruct
    public void init(){
        System.out.println("*****SampleLoader***** initialized - SampleLoader");

        this.reactiveRedisTemplate.listenTo(ChannelTopic.of("some-topic")).subscribe(data -> {
                System.out.println(
                        "data.getChannel():-" + data.getChannel() + ":" + "data.getMessage():-" + data.getMessage());
        });
    }

But my question is how to create a custom annotation like
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@MessageMapping
@Documented
@Repeatable(RedisListeners.class)
public @interface RedisListener{
}

@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RedisListeners {

    RedisListener[] value();

}

  @RedisListener("some-topic")
        public void redisData(String channel, Object data){

        }

@RedisListener will subscribe to the topic and return the call-back data.

A: *

*Obtain all methods of adding annotation RedisListener through scanning

*Get the values of the annotation, and listen to these topics through the reactiveRedisTemplate

*Call the method through reflection in the callback method


text:
Q: Create RavenDB reference field without linking to Newtonsoft.Json I am storing an object in RavenDB that has a reference to another object.  I wish to indicate to the RavenDB serializer that it should be a reference, not an embedded object.  The way to do this is to decorate it with [JsonObject(IsReference = true)] attribute.  This is fine, however it means that I have to reference the Raven.Imports.Newtonsoft.Json assembly in my POCO assembly.
So the question is, is there another way to apply this attribute?  Perhaps using DefaultContractResolver somehow?
Many thanks for any help.

A: You can handle that using a contract resolver yes. You can customize the contract resolvers in the RavenDB Conventions.


text:
Q: Custom User model error on changing password form through admin interface Trying to set up custom user model on the start of django project, but i am facing a recurrent problem that i have only been able to patch, that now is affecting the changepassword of admin interface. On change password form submit, it crashes with error:
AttributeError at /admin/custom_users/customuser/7/password/

'NoneType' object has no attribute 'strip'

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/admin/custom_users/customuser/7/password/

Django Version: 2.2
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'cashflow.apps.CashflowConfig',
 'custom_users.apps.CustomUsersConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
  395.                                raw_as_string=raw_as_string)

During handling of the above exception (Column 'is_superuser' cannot be null), another exception occurred:

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
  168.             return method(query, args)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in execute
  266.                                          raw_as_string=self._raw_as_string)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
  398.                                              sqlstate=exc.sqlstate)

During handling of the above exception (1048 (23000): Column 'is_superuser' cannot be null), another exception occurred:

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
  99.             return super().execute(sql, params)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in execute
  218.         return self._execute_wrapper(self.cursor.execute, query, new_args)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
  174.                         utils.IntegrityError(err.msg), sys.exc_info()[2])

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/six.py" in reraise
  683.             raise value.with_traceback(tb)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
  168.             return method(query, args)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in execute
  266.                                          raw_as_string=self._raw_as_string)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
  398.                                              sqlstate=exc.sqlstate)

During handling of the above exception (Column 'is_superuser' cannot be null), another exception occurred:

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in statement
  606.             return self._executed.strip().decode('utf8')

During handling of the above exception ('NoneType' object has no attribute 'strip'), another exception occurred:

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
  142.                     response = view_func(request, *args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
  223.             return view(request, *args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper
  45.         return bound_method(*args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/auth/admin.py" in user_change_password
  141.                 form.save()

File "/home/mh/devel/dreamit_control/dcontrol/custom_users/forms.py" in save
  32.             self.user.save()

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/auth/base_user.py" in save
  66.         super().save(*args, **kwargs)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in save_base
  779.                 force_update, using, update_fields,

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in _save_table
  851.                                       forced_update)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in _do_update
  900.         return filtered._update(values) > 0

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/query.py" in _update
  760.         return query.get_compiler(self.db).execute_sql(CURSOR)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1426.         cursor = super().execute_sql(result_type)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1097.             cursor.execute(sql, params)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
  103.             sql = self.db.ops.last_executed_query(self.cursor, sql, params)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/operations.py" in last_executed_query
  127.         return force_text(cursor.statement, errors='replace')

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in __getattr__
  230.         return getattr(self.cursor, attr)

File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in statement
  608.             return self._executed.strip()

Exception Type: AttributeError at /admin/custom_users/customuser/7/password/
Exception Value: 'NoneType' object has no attribute 'strip'

on stack trace, i can see that the problem is that is_staff=NULL and is_superuser=NULL on the attempted query.
I dont know why django passes this parameters as null on passwordchange since they are set to false on model and nowhere are they as fields on the CustomUserPassForm. Had this same issue on user change form, but after adding fieldsets to CustomUserAdmin(UserAdmin) class, i was able to edit a user. (as the is_superuser and is_staff input checkboxes appeared on form in html)
models.py
class CustomUserManager(BaseUserManager):
    def create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('correo es obligatorio')
        email = self.normalize_email(email)
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_staff', False)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('superuser must have is_staff=True')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('superuser musthave is_superuser=True')
        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractUser, PermissionsMixin):
    cargo = models.TextField(max_length=50, null=True)
    rut = models.IntegerField(null=True)
    DIGITO_VERIFICADOR_CHOICES = (
        ('1','1'),
        ('2','2'),
        ('3','3'),
        ('4','4'),
        ('5','5'),
        ('6','6'),
        ('7','7'),
        ('8','8'),
        ('9','9'),
        ('0','0'),
        ('K','K')
    )
    digito_verificador = models.CharField(max_length=1, choices=DIGITO_VERIFICADOR_CHOICES, null=True)
    nombre = models.CharField(max_length=25, default="john")
    apellido = models.CharField(max_length=25, default="doe")
    email = models.EmailField(verbose_name='correo', max_length=255, unique=True)
    username = models.TextField(max_length=255, null=True)
    is_superuser = models.BooleanField(default=False, blank=True)
    is_staff = models.BooleanField(default=False, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

forms.py
class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
        model = get_user_model()
        fields = ['email', 'rut', 'digito_verificador',]

class CustomUserChangeForm(UserChangeForm):

    rut = forms.IntegerField(min_value=1000000)
    #is_superUser = forms.BooleanField()
    class Meta:
        model = get_user_model()
        fields =  ['rut', 'digito_verificador',]
        #['email', 'is_superuser','is_staff' ]

class CustomUserPassForm(AdminPasswordChangeForm):
#    is_staff = forms.BooleanField(initial=False)
 #   is_superuser = forms.BooleanField(initial=False)

    #fields = ['is_staff','is_superuser']
    def save(self, commit=True):
        password = self.cleaned_data["password1"]
        self.user.set_password(password)
        print(self.user)
        if commit:
            self.user.save()
        return self.user

admin.py
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    change_password_form = CustomUserPassForm
    model = get_user_model()
    list_display = ['email', ]
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('personal info',{'fields': ('nombre', 'apellido',('rut','digito_verificador'))}),
        ('permissions', {'fields':('is_superuser', 'is_staff')})
    )
    add_fieldsets = (
        (None, {
            'classes':('wide',),
            'fields':('email', 'password1', 'password2'),
        }
        ),
    )

admin.site.register(CustomUser, CustomUserAdmin)

Have been two days reading tutorials and documentation, including official django guide, all which leave out any information about implementation of change_password_form.

A: The problem was the save method of the CustomUserPassForm. For some reason (i havent done the complete followup) the user attribute had is_staff and is_superuser set to NULL. forcing these to false patched the problem.
class CustomUserPassForm(AdminPasswordChangeForm):

    def save(self, commit=True):
        password = self.cleaned_data["password1"]
        self.user.set_password(password)
        self.user.is_staff = False
        self.user.is_superuser = False

        if commit:
            self.user.save()

        return self.user

Now if anyone can shed some light as to why, i'd be appreciated (also, how to set the is_staff and is_superuser to the same value that is actually held in db.)


text:
Q: What do we call the covector associated to a vector? Let $V$ denote an inner product space. Write $V^*$ for either the algebraic dual, or else the continuous dual. In either case, for each vector $v \in V$, we get a covector $v^c \in V^*$ given by:
$$v^c = \langle v,-\rangle$$

Question. We call $v^c$ the [what] of $v$?

A: Echoing @Lærne, $v^c$ is the dual of $v$.  If you want a reference, how about Halmos's "Finite-Dimensional Vector Spaces"?  In the second edition, sections 13, 14, and 15 along with sections 67, 68, and 69 may be what you're looking for.

A: $\renewcommand{ket}[1]{|#1\rangle}$
$\renewcommand{bra}[1]{\langle#1|}$
There are several common terminologies:

*

*As you might guess based on the fact that $V^*$ is called the "dual" of $V$, in mathematics and mathematical physics the covector of a vector $v$ is called the "dual" of $v$.

*In physics, vectors are often denoted e.g. $\ket{v}$.
The $v$ is a label which names the vector.
In other words, $\ket{v}$ is like $\vec{v}$.
The associated covector is denoted $\bra{v}$.
The notation is justified by the fact that if you line up the covector and the vector you get
$$ \bra{v}v\rangle$$
which is the usual symbol for an inner product.
The symbol $\ket{\cdot}$ is called a "ket" and the $\bra{\cdot}$ is called a "bra" so that when you line them up to make an inner product you get "braket".
In this system, the association between the vector and associated covector is expressed by using the same label, $v$, in either the ket or the bra symbol.
In speech we just call $\bra{v}$ "bra $v$", as opposed to "ket $v$".
I think many people would still say "$\bra{v}$ is the dual of $\ket{v}$".

*You mentioned inner product spaces.
In fact, the inner product function $\bra \cdot \cdot \rangle$ can be thought of as a rank-2 tensor: when you feed it two vectors it spits out a scalar.
This tensor can be denoted in index notation as $g^{\alpha \beta}$.
The inner product of two vectors $U_\alpha$ and $V_\beta$ is written
$$\bra{U}V\rangle = g^{\alpha\beta} U_\alpha V_\beta \tag{1}$$
where matching indices indicates contraction.
The upper indices are called "covector" indices because they indicate the need to consume a vector in order to produce a scalar.$^{[a]}$
So, if we have something like this
$$U^\alpha \, ,$$
that thing must be a covector because it contracts with a single vector to yield a scalar.
Therefore, upper indices indicate covector parts of the tensor and lower indices indicate vector parts.
Now, if we contract $g$ with only one vector
$$ g^{\alpha \beta}V_\beta$$
we're left with a free upper index, i.e. a covector.
This thing is usually denoted $V^\alpha$ and is precisely the covector associated to $V_\beta$, a.k.a the dual of $V_\beta$.
In this system you might also call $V^\alpha$ the "covariant version of $V_\beta$" or say that $V^\alpha$ is "$V_\beta$ with its index raised".
The point of this answer is to list the various common ways that the covector versions of vectors are called, and provide some motivation for the terminology.
$[a]$: It's also common to call upper indices "covariant" and lower indices "contravariant". This has to do with how the components of representations of vectors and covectors, expressed in a given basis, transform under coordinate transformations.


text:
Q: Highcharts, export/copy image to clipboard I need to copy highchart to clipboard as image, how i can do that?
Ther's export function build-in but it shows window prompt to open/download but i want to right click on chart (or use 'export' button in right upper corner) and next choose 'copy image to clipboard'.
Need your help once again boys!

A: To my best knowledge, I don't think you can do it. At least not across browsers, but I think IE allows copying contents to clipboard. In fact, IE9 even allows right clicking the highChart's chart and gives option of "copy" which copies it to the clipboard. IE9 basically allows this on any SVG object. Firefox and Chrome don't allow copying contents to clipboard, not through JS, there are various flash options, but I would suggest staying away unless you absolutely must


text:
Q: Need to add DISTINCT to Join I am trying to use DISTINCT in my query, but I am not able to get the syntax correct to get the result that i am expecting.  I made a couple different stack overflow posts, and I think I finally understand how to include all of the information i need to get help.
I built a shared space on DB Fiddle with all of the information already loaded here:
https://www.db-fiddle.com/f/b2o3Wy31hLmwSZLAfpuaVr/0#&togetherjs=IrGzVdtmMh
CREATE TABLE hosts (
  hostid INT NOT NULL,
  name VARCHAR(30) NOT NULL,
  PRIMARY KEY (hostid),
  UNIQUE (name)
);
INSERT INTO hosts
    (hostid, name)
VALUES
    (10761,"CUCM1"),
    (10762,"CUCM2"),
    (10763,"CUCM3");

CREATE TABLE items (
  hostid INT NOT NULL,
  itemid INT NOT NULL,
  name VARCHAR(60) NOT NULL,
  valuemapid INT NOT NULL
);
INSERT INTO items
    (hostid,itemid,name,valuemapid)
VALUES
(10761,304827,"Phone 33 44 55 66 77 88:Model of the Phone",68),
--phone1
(10761,304827,"Phone 33 44 55 66 77 88:Model of the Phone",68),
--phone1
(10761,304827,"Phone 33 44 55 66 77 88:Model of the Phone",68),
--phone1
(10761,304828,"Phone 33 44 55 66 88 88:Model of the Phone",68),
--phone2
(10761,304828,"Phone 33 44 55 66 88 88:Model of the Phone",68),
--phone2
(10761,304828,"Phone 33 44 55 66 88 88:Model of the Phone",68),
--phone2
(10761,304829,"Phone 33 44 55 77 77 88:Model of the Phone",68),
--phone3
(10761,304829,"Phone 33 44 55 77 77 88:Model of the Phone",68),
--phone3
(10761,304820,"Phone 33 44 44 66 77 88:Model of the Phone",72),
--phone4
(10761,304820,"Phone 33 44 44 66 77 88:Model of the Phone",72);
--phone4

CREATE TABLE history_uint (
  itemid INT NOT NULL,
  value INT NOT NULL
);

INSERT INTO history_uint
    (itemid,value)
VALUES
(304827,109),
(304828,109),
(304829,109),
(304820,110);

CREATE TABLE mappings (
  valuemapid INT NOT NULL,
  value INT NOT NULL,
  newvalue VARCHAR (30) NOT NULL,
  PRIMARY KEY (valuemapid)
);

INSERT INTO mappings
    (valuemapid,value,newvalue)
VALUES
(68,109,"Cisco 7841"),
(72,110,"Cisco 7940");

And here is my Query that i have been able to piece together
SELECT map.newvalue as 'Model of Phone', Count(*) as 'Number of Phones'
FROM hosts h
    LEFT JOIN items i
        ON h.hostid=i.hostid
    LEFT JOIN history_uint huint
        ON i.itemid=huint.itemid
    LEFT JOIN mappings map
        ON i.valuemapid=map.valuemapid
WHERE huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;

Right now the query returns
Model of Phone  Number of Phones
Cisco 7841      8
Cisco 7940      2

But i am hoping to use DISTINCT on the items table colomn itemid so we only get back
Model of Phone  Number of Phones
Cisco 7841      3
Cisco 7940      1

Thank you for your help!

A: What happen if you DISTINCT the COUNT?
SELECT map.newvalue as 'Model of Phone'
    , Count(DISTINCT i.name) as 'Number of Phones'
FROM hosts h
JOIN items i ON h.hostid = i.hostid
JOIN history_uint huint ON i.itemid = huint.itemid
JOIN mappings map ON i.valuemapid = map.valuemapid AND huint.value=map.value
WHERE i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;

A: Since you specifically want distinct records from the items table which will give you the phone type, your query should probably look like the following:
SELECT map.newvalue as 'Model of Phone', Count(distinct i.itemid) as
'Number of Phones'
FROM hosts h
LEFT JOIN items i
    ON h.hostid=i.hostid
LEFT JOIN history_uint huint
    ON i.itemid=huint.itemid
LEFT JOIN mappings map
    ON i.valuemapid=map.valuemapid
WHERE huint.value=map.value AND i.name LIKE '%Model of the Phone'
GROUP BY map.newvalue;

When you did a count(*) the reason why it returned 8 rows as the count was because each row renders distinct when you add the itemid (from history_uint) to the select fields. So collectively, the fields were not distinct thus returning all 8 rows.


text:
Q: How to compile C without a main function using CL? I'm trying to create a PE binary (or lib) using CL so I can explore the produced assembly language? The code I have is simple:
test.c
void f() { return; };

And that's it. I compile like so:
cl /Od test.c

And I get the error LINK : fatal error LNK1561: entry point must be defined. I kinda knew this would happen because I know the compiler expects an entry point.
But how can I compile the code without any entry points to inspect the assembly?

A: The solution is to assemble the code only and to not invoke the linker as per the MS Docs:
cl /Od /c test.c


text:
Q: Mysql - Fetch 5 rows above and under user (ranking) I have a table:
r_user  | r_points |
--------------------
user1   | 12       |
user2   | 124      |
user3   | 34       |
user4   | 35       |
user5   | 57       |
user6   | 3        |
user7   | 452      |
user8   | 8        |
user9   | 12       |
user-c  | 0        |
user-b  | 0        |
user-a  | 0        |

Lets say I want to fetch the ranking for user6. I want 5 users above and below his entry ordered by r_points and next r_user ASC, so that users with equal points ( user-c, user-b, user-a ) are sorted ASC like ( user-a, user-b... ).
If there aren't 5 users above or underneath, the difference should be put to the opposite. So if user6 is 4 from bottom, I want 6 users fetched above. Always a count of 10 users.
That is my result, I would like to have:
r_user  | r_points |
--------------------
user5   | 57       |
user4   | 35       |
user3   | 34       |
user9   | 12       |
user1   | 12       | -> In this direction ORDER is other way round
user8   | 8        |
user6   | 3        | --> THATS THE USER BY ID <--
user-a  | 0        |
user-b  | 0        |
user-c  | 0        |

I have no idea, how to do that, since my table has r_user as PK and no AI-ID.
Thank you
EDIT:
That's my version of it. However that version is not fetching more users above/below if the user is on 3rd from bottom. That only works if there are 5 rows underneath and above. That's not what I want.
(
SELECT r_user, r_points
FROM ranking
WHERE r_points >= ( SELECT r_points FROM ranking WHERE r_user = 'user6' )
ORDER BY r_points ASC LIMIT 5
)
UNION DISTINCT
(
SELECT r_user, r_points
FROM ranking
WHERE r_points <= ( SELECT r_points FROM ranking WHERE r_user = 'user6' )
ORDER BY r_points DESC LIMIT 6
)
ORDER BY r_points DESC, r_user ASC

A: You wrote that you have no unique id, so in my fiddle the user is hard coded by this line IF(t.r_user = 'user2'. To change user you have to change that value.
Hope this will be helpful to you:
http://sqlfiddle.com/#!9/d2329/31
SELECT *
FROM (
  SELECT
    t.*,
    IF(@idx IS NULL, @idx:=1, @idx:=@idx+1) idx,
    IF(t.r_user = 'user2',@median:=r_points, IF(@start IS NULL, @start:=@idx, IF(@after IS NULL, @start:=@idx, null))),
    IF(@median IS NULL, IF(@before IS NULL,@before:=1, @before:=@before+1) ,
    IF(@after IS NULL ,@after:=0, @after:=@after+1))

  FROM (
    SELECT *
    FROM table1
    ORDER BY r_points DESC
    ) t
  ) t2
 WHERE IF(1+@before+@after<=10, true,
          IF(@before<=5, t2.idx >= 0 AND t2.idx <= @start+5+(5-@before),
             IF(@after<=4, t2.idx >= @start-4-(4-@after),
                t2.idx >= @start-4 AND t2.idx <= @start+5
             )
          )
        );


text:
Q: WCF Streamed Response is buffered after moving Config to code i have client server app using net.tcp bindings with streamedResponse service, all WCF config has been defined in the app.config and all works fine with no problem, i had to remove the config from the client app and define them in code, nothing changed on the server, but the client seems to get the response as buffered instead of streamed with this transition, here is how i build the service in client code :
public static BuildChannelFactory()
{
channelFactorty = new ChannelFactory<IMyService>(GetStreamBinding(),
                   Address);

            channelFactorty .Endpoint.Address = new EndpointAddress(
                 new Uri(Address), EndpointIdentity.CreateDnsIdentity(
                 "MyServer"));

            channelFactorty.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.LocalMachine, StoreName.Root,
                X509FindType.FindBySubjectName,
               "MySubject");

            channelFactorty.Credentials.ServiceCertificate.
Authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.Custom;

channelFactortyCredentials.ServiceCertificate.Authentication.
CustomCertificateValidator = MyCertificateValidator;
}

private static NetTcpBinding GetStreamBinding()
    {

          NetTcpBinding streamBinding = new NetTcpBinding
            {
                Name = "streamBinding",
                ReceiveTimeout = new TimeSpan(2, 0, 0),
                SendTimeout = new TimeSpan(0, 2, 0),
                MaxBufferSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                TransferMode = TransferMode.StreamedResponse,

                ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas
                {
                    MaxArrayLength = int.MaxValue,
                    MaxStringContentLength = int.MaxValue
                }

            };

            streamBinding .Security.Mode = SecurityMode.Transport;
            streamBinding .Security.Transport.ClientCredentialType =
            TcpClientCredentialType.Certificate;
        }

        return streamBinding;
    }

A: ok no problem in code, the problem was from the response, it was a custom stream that holds an List property, this is not supported and it will be switched to buffered automatically. so moved the List to be returned with message header and all worked fine.


text:
Q: Why does my VHDL simulation fail after one input for this device? EDIT: Found a solution. See the bottom of the post
I am wondering why my simulation of the following entity fails to run for more than one input. When I change the inputs, the system crashes, and I don't understand why.
I have the following entity:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity subtraction is
    port (
        signal clk : in std_logic;
        signal minuend : in std_logic_vector(15 downto 0);
        signal subtrahend : in std_logic_vector(15 downto 0);
        signal difference : out std_logic_vector(15 downto 0)
    );
end subtraction;

architecture datapath of subtraction is

type ROM_ARRAY is array (0 to 9) of std_logic_vector(3 downto 0);
constant ROM: ROM_ARRAY :=
    (
    x"0",
    x"1",
    x"2",
    x"3",
    x"4",
    x"5",
    x"6",
    x"7",
    x"8",
    x"9"
    );

constant thousand : unsigned(11 downto 0) := x"3E8";
constant hundred : unsigned(7 downto 0) := x"64";
constant ten : unsigned(3 downto 0) := x"A";

signal m, s, d: unsigned(14 downto 0);
signal d0, d1, d2, d3 : unsigned(14 downto 0);

begin

m <=    resize(unsigned(minuend(15 downto 12)) * thousand, m'length) +
        resize(unsigned(minuend(11 downto 8)) * hundred, m'length) +
        resize(unsigned(minuend(7 downto 4)) * ten, m'length) +
        resize(unsigned(minuend(3 downto 0)), m'length);

s <=    resize(unsigned(subtrahend(15 downto 12)) * thousand, s'length) +
        resize(unsigned(subtrahend(11 downto 8)) * hundred, s'length) +
        resize(unsigned(subtrahend(7 downto 4)) * ten, s'length) +
        resize(unsigned(subtrahend(3 downto 0)), s'length);

--d <=  m - s;

d0 <= ((m-s) mod 10); -- (m-s) can be replaced with d if uncommented above
d1 <= ((((m-s) mod 100) - ((m-s) mod 10)) / 10);
d2 <= ((((m-s) mod 1000) - ((m-s) mod 100) - ((m-s) mod 10)) / 100);
d3 <= ((((m-s) mod 10000) - ((m-s) mod 1000) - ((m-s) mod 100) - ((m-s) mod 10)) / 1000);

--difference <= ROM(to_integer(d3))&ROM(to_integer(d2))&ROM(to_integer(d1))&ROM(to_integer(d0));

process(clk)
begin
    difference <= ROM(to_integer(d3))&ROM(to_integer(d2))&ROM(to_integer(d1))&ROM(to_integer(d0));
end process;

end datapath;

The code might look a bit complicated, but it's actually quite simple. I'm just taking a Binary Coded Decimal input (of up to 4 digits) and subtracting another BCD input of the same size from it, and then outputting the difference in BCD (which is what the vector array is for).
Some of this is just to practice using certain things I'm learning about VHDL. So please forgive my inelegance.
At any rate, the code works perfectly for one input. But then fails the moment I change the inputs. This is true whether I use a process to handle assignment of a the final value to difference, or if I use the purely combinational logic approach (which is currently commented out).
The testbed is simple, and shows that I'm just looking at the output for three sample inputs. Removing the difference assignment and the d0 through d3 assignments allows the code to continue through the testbed (and this is verifiable if you add internal testing-only signal to the testbench, or otherwise expose the values in m, s, and (optionally) d).
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity subtraction_tb is
--  Port ( );
end subtraction_tb;

architecture Behavioral of subtraction_tb is

signal clktb : std_logic;
signal mtb, stb, dtb : std_logic_vector(15 downto 0);
signal moutb, soutb,doutb : std_logic_vector(14 downto 0);
--signal m0tb, m1tb, m2tb, m3tb : std_logic_vector(14 downto 0);

begin

uut : entity work.subtraction
    port map (
    clk => clktb,
    minuend => mtb,
    subtrahend => stb,
    difference => dtb
    );

clock : process
begin
    clktb <= '1';
    wait for 5 ns;
    clktb <= '0';
    wait for 5 ns;
end process;

testing : process
begin
    mtb <= x"1430";
    stb <= x"0430";
    wait for 10 ns;
    mtb <= x"9450";
    stb <= x"9320";
    wait for 10 ns;
    mtb <= x"9000";
    stb <= x"8111";
    wait for 10 ns;
wait;
end process;

end Behavioral;

I am frankly confused why the "d" assignments create this mischief in my entity. In purely combinational terms, and in comparison to other projects I've done, everything looks above aboard.
Any insight would be greatly appreciated.
EDIT TO ADD ERROR DETAILS:
As a few people have asked for simulator and error details. The simulator is Xilinx Vivado, there is no error. Rather, the simulation runs, and displays output for the first entry. But it shows only the output for that entry. It's as if the testbed had only up to the first wait for 10 ns statement, and then stops, displaying nothing at all after 10 ns.
It does automatically go from the waveform back to the code, and an arrow appears pointing at the line where I assign the difference, however, that arrow, the console, and elaborate.log contain no message indicating what might be happening. It simply does this thing I've described.
If this isn't clear enough, I will find time to post the waveform later, to demonstrate what I mean.
Here are the waveforms:

More Additions:
I have been trying to account for the possibility that the simulator does not like the addition I'm doing, which could result in a value larger than the vector size I've tried. To that end, here is one example of an attempted solution which results in utter nonsense at the output.
Code:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity bdc_subtraction is
    port (
        --Internal Testing Signals
        signal mout, sout: out std_logic_vector(18 downto 0);
        signal dout : out std_logic_vector(18 downto 0);
        --signal m0t, m1t, m2t, m3t, s0t, s1t, s2t, s3t : out std_logic_vector(14 downto 0);
        signal m0t : out std_logic_vector(15 downto 0);
        signal m1t : out std_logic_vector(15 downto 0);
        signal m2t : out std_logic_vector(15 downto 0);
        signal m3t : out std_logic_vector(15 downto 0);
        signal s0t : out std_logic_vector(15 downto 0);
        signal s1t : out std_logic_vector(15 downto 0);
        signal s2t : out std_logic_vector(15 downto 0);
        signal s3t : out std_logic_vector(15 downto 0);
        --Inputs and outputs
        signal clk : in std_logic;
        signal minuend : in std_logic_vector(15 downto 0);
        signal subtrahend : in std_logic_vector(15 downto 0);
        signal difference : out std_logic_vector(15 downto 0)
    );
end bdc_subtraction;

architecture datapath of bdc_subtraction is

type ROM_ARRAY is array (0 to 9) of std_logic_vector(3 downto 0);
constant ROM: ROM_ARRAY :=
    (
    x"0",
    x"1",
    x"2",
    x"3",
    x"4",
    x"5",
    x"6",
    x"7",
    x"8",
    x"9"
    );

constant thousand : unsigned(11 downto 0) := x"3E8";
constant hundred : unsigned(7 downto 0) := x"64";
constant ten : unsigned(3 downto 0) := x"A";

signal m, s: unsigned(18 downto 0);

signal m0 : unsigned(15 downto 0);
signal m1 : unsigned(15 downto 0);
signal m2 : unsigned(15 downto 0);
signal m3 : unsigned(15 downto 0);

signal s0 : unsigned(15 downto 0);
signal s1 : unsigned(15 downto 0);
signal s2 : unsigned(15 downto 0);
signal s3 : unsigned(15 downto 0);

signal d0, d1, d2, d3 : unsigned(14 downto 0);
signal d : unsigned(18 downto 0) := (others => '0');

begin
--Testing Signals
mout <= std_logic_vector(m);
sout <= std_logic_vector(s);
dout <= std_logic_vector(d);
m0t <= std_logic_vector(m0);
m1t <= std_logic_vector(m1);
m2t <= std_logic_vector(m2);
m3t <= std_logic_vector(m3);
s0t <= std_logic_vector(s0);
s1t <= std_logic_vector(s1);
s2t <= std_logic_vector(s2);
s3t <= std_logic_vector(s3);

-- COMBINATIONAL LOGIC

m3 <=   resize(unsigned(minuend(15 downto 12)) * 1000, m3'length);
m2 <=   resize(unsigned(minuend(11 downto 8)) * 100, m2'length);
m1 <=   resize(unsigned(minuend(7 downto 4)) * 10, m1'length);
m0 <=   resize(unsigned(minuend(3 downto 0)), m0'length);

s3 <=   resize(unsigned(subtrahend(15 downto 12)) * 1000, s3'length);
s2 <=   resize(unsigned(subtrahend(11 downto 8)) * 100, s2'length);
s1 <=   resize(unsigned(subtrahend(7 downto 4)) * 10, s1'length);
s0 <=   resize(unsigned(subtrahend(3 downto 0)), s0'length);

m <=    resize(m3+m2+m1+m0, m'length);
s <=    resize(s3+s2+s1+s0, s'length);

d <=    (m-s);

--d0 <= (d mod 10);
--d1 <= (((d mod 100) - (d mod 10)) / 10);
--d2 <= (((d mod 1000) - (d mod 100) - (d mod 10)) / 100);
--d3 <= (((d mod 10000) - (d mod 1000) - (d mod 100) - (d mod 10)) / 1000);

--difference <= ROM(to_integer(d3))&ROM(to_integer(d2))&ROM(to_integer(d1))&ROM(to_integer(d0));

end datapath;

And here is the slightly modified testbench:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity bcd_subtraction_tb is
--  Port ( );
end bcd_subtraction_tb;

architecture Behavioral of bcd_subtraction_tb is

signal clktb : std_logic;
signal mtb, stb, dtb : std_logic_vector(15 downto 0);
signal moutb, soutb : std_logic_vector(18 downto 0);
signal doutb : std_logic_vector(18 downto 0);
signal m0tb : std_logic_vector(15 downto 0);
signal m1tb : std_logic_vector(15 downto 0);
signal m2tb : std_logic_vector(15 downto 0);
signal m3tb : std_logic_vector(15 downto 0);
signal s0tb : std_logic_vector(15 downto 0);
signal s1tb : std_logic_vector(15 downto 0);
signal s2tb : std_logic_vector(15 downto 0);
signal s3tb : std_logic_vector(15 downto 0);

begin

uut: entity work.bdc_subtraction
    port map (
    --Internal Testings
    mout => moutb,
    sout => soutb,
    dout => doutb,
    m0t => m0tb,
    m1t => m1tb,
    m2t => m2tb,
    m3t => m3tb,
    s0t => s0tb,
    s1t => s1tb,
    s2t => s2tb,
    s3t => s3tb,
    --Standards
    clk => clktb,
    minuend => mtb,
    subtrahend => stb,
    difference => dtb
    );

clock : process
begin
    clktb <= '1';
    wait for 5 ns;
    clktb <= '0';
    wait for 5 ns;
end process;

testing : process
begin
    mtb <= x"1430";
    stb <= x"0430";
    wait for 10 ns;
    mtb <= x"9450";
    stb <= x"9320";
    wait for 10 ns;
    mtb <= x"9000";
    stb <= x"8111";
    wait for 10 ns;
    --std.env.stop(0);
wait;
end process;

end Behavioral;

Whereas the earlier version gave the correct output for a single input, this version doesn't give the correct anything as an output, and instead provides rather interesting values for m2, m3, and s2 and s3. I'm not sure why, yet.

I also want to add, I've tried doing this as well (and modifying the other signals accordingly):
signal m0t : out std_logic_vector(3 downto 0);
signal m1t : out std_logic_vector(7 downto 0);
signal m2t : out std_logic_vector(11 downto 0);
signal m3t : out std_logic_vector(15 downto 0);
signal s0t : out std_logic_vector(3 downto 0);
signal s1t : out std_logic_vector(7 downto 0);
signal s2t : out std_logic_vector(11 downto 0);
signal s3t : out std_logic_vector(15 downto 0);

This is based on the idea that for two vectors, of n and m bits respectively, the product will be no greater in length than n+m bits. The results are exactly identify to using all 16-bit vectors, as in the code immediately above this segment.
I'm wondering if resize() behaves a bit differently than expected, or if the addition of vectors of varying sizes is causing some kind of overflow error somewhere. For instance, if X is greater than Y in bit length, X+Y could be greater than X, so perhaps a little concatonation might work as a fix.
I will try that, but any other thoughts remain welcome.
SOLUTION
There were two issues with this code. First, the addition used to assign values to "m" and "s" caused problems because vivado couldn't be sure of the vector sizes, since it had no way to know I had limited input to prevent illegal situations. After fixing that, I got rather bizarre outputs. To fix that, I simply had to use the constant thousand, hundred, and ten vectors which I had not previously been using. For some reason, it seems like Vivado was interpreting the lines like this one:
s3 <=   resize(unsigned(subtrahend(15 downto 12)) * 1000, s3'length);

as an unsigned vector times a vector, and not a natural number. So this was getting translated as  * 8 rather than  * 1000. On the other hand, the following works fine:
constant thousand : unsigned(11 downto 0) := x"3E8";
[...]
s3 <=   resize(unsigned(subtrahend(15 downto 12)) * thousand, s3'length);

I don't know why it does this, since 1000 was not in quotes to indicate a binary value or in hex. Numeric_std supports {unsigned * natural}, so my best guess is that the resize function is doing something unexpected. But I don't know for certain, because I haven't dug up the code for resize. If I have time to look into it, I'll see if I can nail this behavior down, and I will update this post.

A: Per the advice of some people here, I have reported the misinterpreting of 1000 as 8
SOLUTION (posting here so I can mark this problem as 'solved' tomorrow)
There were two issues with this code. First, the addition used to assign values to "m" and "s" caused problems because vivado couldn't be sure of the vector sizes, since it had no way to know I had limited input to prevent illegal situations. After fixing that, I got rather bizarre outputs. To fix that, I simply had to use the constant thousand, hundred, and ten vectors which I had not previously been using. For some reason, it seems like Vivado was interpreting the lines like this one:
s3 <=   resize(unsigned(subtrahend(15 downto 12)) * 1000, s3'length);

as an unsigned vector times a vector, and not a natural number. So this was getting translated as  * 8 rather than  * 1000. On the other hand, the following works fine:
constant thousand : unsigned(11 downto 0) := x"3E8";
[...]
s3 <=   resize(unsigned(subtrahend(15 downto 12)) * thousand, s3'length);

I don't know why it does this, since 1000 was not in quotes to indicate a binary value or in hex. Numeric_std supports {unsigned * natural}, so my best guess is that the resize function is doing something unexpected. But I don't know for certain, because I haven't dug up the code for resize. If I have time to look into it, I'll see if I can nail this behavior down, and I will update this post.


text:
Q: How to dockerized java microservices efficiently While a java application server will extend a unique JVM to run several (micro)services, a dockerized java microservices architecture will run a JVM for each dockerized microservice.
Considering 20+ java microservices and a limited number of host it seems that the amount of resources consumed by the JVMs on each host is huge.
Is there an efficient way to manage this problem ? Is it possible to tune each JVM to limit resources consumption ?
The aim is to limit the overhead of using docker in a java microservices architecture.

A: Each Docker and JVM copy running uses memory. Normally having multiple JVMs on a single node would use shared memory, but this isn't an option with docker.
What you can do is reduce the maximum heap size of each JVM.  However, I would allow at least 1 GB per docker image as overhead plus your heap size for each JVM. While that sounds like a lot of memory it doesn't cost so much these days.
Say you give each JVM a 2 GB heap and add 1 GB for docker+JVM, you are looking needing a 64 GB server to run 20 JVMs/dockers.


text:
Q: Shopify question: Possible to modify contents of page for when path is /app/? I was wondering if it's possible to target /app/ pages using liquid flow controls?
I'm trying to exclude a particular element from showing up on one of our app pages. The app page uses our layout/theme.liquid file when it loads. Wondering if there's a way I can set a condition to look for app based pages like we do for other template/page conditions like {% if template == 'something' %}

A: A call to any Proxy is going to result in data being returned. So if you have a link in your Liquid to a Proxy, Shopify could possibly navigate there eg: /app/fizzbuzz and render what your Proxy returns as Liquid. In that case, you'd know you're on /app/fizzbuzz after the page is loaded, so a quick inspection of the URL would let you run JS.
A call from a link results in Shopify rendering the content_for_layout, if your element is in there don't include that element.
Would be helpful to know how you are using the Proxy to give you more details. Most people use it as an Ajax call for JSON and then render the returned data. I assume you are not doing that.


text:
Q: Parse a file with internal json twitter4j data to plain text I have a file containing the data ( as obtained from Twitter4J methods like twitter.showUser()) and each of the line looks like
UserJSONImpl{
id=182857317,
name='Inria',
screenName='Inria',
location='France',
description='Institutderechercheensciencesdu#numérique,
ducôtédesinventeurs#informatique#mathématiques#innovation[
    compteofficiel
]',
isContributorsEnabled=false,
profileImageUrl='',
profileImageUrlHttps='',
url='',
isProtected=false,
followersCount=10171,
status=StatusJSONImpl{
    createdAt=MonOct2118: 56: 17CEST2013,
    id=392333528358088704,
    text='RT@upmc: Y'a-t-ilunpilotedansl'avion?Colloquiumd'#informatiquedemainsoirà18havecGillesDowek@Inria',
    source='<ahref=""rel="nofollow">TweetDeck</a>',
    isTruncated=false,
    inReplyToStatusId=-1,
    inReplyToUserId=-1,
    isFavorited=false,
    inReplyToScreenName='null',
    geoLocation=null,
    place=null,
    retweetCount=3,
    isPossiblySensitive=false,
    contributorsIDs=[
        J@3cbd7173,
        retweetedStatus=null,
        userMentionEntities=[
            UserMentionEntityJSONImpl{
                name='UPMC-Paris',
                screenName='upmc',
                id=19063270
            },
            UserMentionEntityJSONImpl{
                name='Inria',
                screenName='Inria',
                id=182857317
            }
        ],
        urlEntities=[
            URLEntityJSONImpl{
                url='',
                expandedURL='',
                displayURL=''
            }
        ],
        hashtagEntities=[
            HashtagEntityJSONImpl{
                text='informatique'
            }
        ],
        mediaEntities=[

        ],
        currentUserRetweetId=-1,
        user=null
    },
    profileBackgroundColor='FFFFFF',
    profileTextColor='343434',
    profileLinkColor='AAAAAA',
    profileSidebarFillColor='BDBDBD',
    profileSidebarBorderColor='FFFFFF',
    profileUseBackgroundImage=true,
    showAllInlineMedia=false,
    friendsCount=1209,
    createdAt=WedAug2517: 30: 06CEST2010,
    favouritesCount=927,
    utcOffset=7200,
    timeZone='Paris',
    profileBackgroundImageUrl='',
    profileBackgroundImageUrlHttps='',
    profileBackgroundTiled=false,
    lang='fr',
    statusesCount=2783,
    isGeoEnabled=false,
    isVerified=false,
    translator=false,
    listedCount=544,
    isFollowRequestSent=false
}

I would like to convert this data format to a plain text format with all the fields.
Thank you for the help

A: There are several APIs around for JSON - processing.
The new JSR-353 (part of JEE 7) could be useful to you , you could try http://www.jdom.org/
just to mention two.
Both mainly iterate over the complete JSON - Object which can be constructed from a JSON - String.
So how to want to format your text? If you just want to put everything into a text - file you could append to a String member of your Main - class, if you want to produce a csv -text -file
you are translating between two different views of a data model and should build a proper data model for the csv - file before creating the view of it, the actual csv - file.


text:
Q: Saving the content of data into csv - AngularJS Hi I'm trying to save the content of data which came from my webserver into csv file.
I'm trying this code which came from various question here in stackoverflow.
.success(function(data, status, headers, config) {
    console.log(data);
    if (data.success) {
        console.log(data);
        var saving = document.createElement('a');

        saving.href = 'data:attachment/csv,' + encodeURIComponent(data);
        saving.download = 'Summary.csv';
        saving.click();
    }
})
.error(function(data, status, headers, config) {
    console.log('error in downloading!');

});

But the content of data doesn't save into my summary.csv and gave me this
[object object]. Can someone help me with this?

A: The first problem is that encodeURIComponent() requires a string, and you are giving it an object, so it calls .toString() on it, which is why you get [object Object].
Instead, you need to convert your data array into a CSV string yourself. If you are using D3.js you can use d3.csv.format(rows), which is very nice. Or you can find another JS CSV library. Or you can use the following very simplistic implementation I just wrote for you:
function csv(arr) {
    var ret = [];
    ret.push('"' + Object.keys(arr[0]).join('","') + '"');
    for (var i = 0, len = arr.length; i < len; i++) {
        var line = [];
        for (var key in arr[i]) {
            if (arr[i].hasOwnProperty(key)) {
                line.push('"' + arr[i][key] + '"');
            }
        }
        ret.push(line.join(','));
    }
    return ret.join('\n');
}

NB: This function assumes you pass it a valid array with at least one element, and all the elements are objects with exactly the same keys. If none of these assumptions are true for you, either extend my function or use a more robust third party library.

So, putting this all together, your final code would be:
.success(function(data, status, headers, config) {
    console.log(data);
    if (data.success) {
        console.log(data);
        var saving = document.createElement('a');

        saving.href = 'data:attachment/csv,' + encodeURIComponent(csv(data.results));
        saving.download = 'Summary.csv';
        saving.click();
    }
})
.error(function(data, status, headers, config) {
    console.log('error in downloading!');
});

Note that I needed to access data.results to get the actual array of results. And I am assuming you will use my csv() function or another similar one to convert the array into a CSV string.

A: add append the saving to work in firefox!!
... // as is written
saving.download = 'Summary.csv';
document.body.appendChild(saving);
saving.click();

A: Use ng-csv
<button type="button" ng-csv="ExportCsv()" filename="ExportCsv.csv" csv-header="['a','b']" charset="utf-8">CSV</button>
$scope.ExportCsv= async function(){
  const msg = await getdata();
  return msg;
}
var getdata =  function abc(a,b) {
  return new Promise(resolve => {
    $http.get(// use backend)
          .success(function (data, status, headers, config) {
             $scope.datacsv =[];angular.forEach($scope.dt, function (value,key) {
             $scope.datacsv.push({"a":value.a,"b":value.b});

          });

      })
    setTimeout(() => {
                    resolve($scope.datacsv);
    }, 2000);
  });
}


text:
Q: Alter all table with prefixe I'm looking for a SQL code allowing to alter all table with a prefixe word :
I got many table names XXXX_users and i would like to add a column to each. Is it possible to do it with just one row with something like :

ALTER TABLE %_users

I use PHPMyAdmin for the database management.
Thanks in advance

A: For 'dynamic MySQL' ('dynamic SQL'), auto generate the ALTER statements with this:
   SELECT CONCAT('RENAME TABLE ', table_name, ' TO XXXX_', table_name, ';' ) alter_table_stmt
     FROM INFORMATION_SCHEMA.tables t
    WHERE TABLE_SCHEMA IN ('<DB SCHEMA NAME>');

then execute the generated statements as a batch.


text:
Q: how can i fetch my local json file in angular 13.2 and display data with html its literally my third day trying to do that.thats what i achieved ,it displays nothing
,what i really want to do is to fetch data from lacal json so that every json element will be displayed in a html block
Service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) {
    this.getJSON().subscribe(matches => console.log(matches))};
        public getJSON(): Observable<any> {
      return this.http.get("./matches.json");
  }
  }

component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
  selector: 'app-matches',
  templateUrl: './matches.component.html',
  styleUrls: ['./matches.component.css']
})
export class MatchesComponent implements OnInit {

  constructor(private ApiService : ApiService) { }

  ngOnInit(): void {

    this.ApiService.getJSON().subscribe(data => {
      console.log(data);
    });
  }

}

matches.json
[{"id":"1","homeTeam":"Es Tunis","awayTeam":"Tatawin","dateM":"2022-04-21","stade":"Rades","NBtickets":"20000"},
{"id":"2","homeTeam":"Rejiche","awayTeam":"Etoile du sahel","dateM":"2022-04-11","stade":"Mahdia","NBtickets":"15000"},
{"id":"3","homeTeam":"Cs Cheba","awayTeam":"Solimane","dateM":"2022-04-11","stade":"Cheba","NBtickets":"5000"},
{"id":"4","homeTeam":"Zarzis","awayTeam":"Club Africain","dateM":"2022-04-11","stade":"Jlidi","NBtickets":"10000"},
{"id":"5","homeTeam":"Olympique Beja","awayTeam":"Monastir","dateM":"2022-04-11","stade":"Boujemaa Kmiti","NBtickets":"15500"},
{"id":"6","homeTeam":"Ca Bizert","awayTeam":"Cs Sfaxien","dateM":"2022-04-11","stade":"Tayeb mhiri","NBtickets":"10000"},
{"id":"7","homeTeam":"Hammam-sousse","awayTeam":"Ben Gerdane","dateM":"2022-04-11","stade":"Bouaali hwar","NBtickets":"12000"},
{"id":"8","homeTeam":"hammam-Lif","awayTeam":"Metlaoui","dateM":"2022-04-11","stade":"Stade municipale","NBtickets":"10000"}]

why wont my code display anything?
ps:i tried many things such as importing file.json but nothing worked(im beginner)


text:
Q: affine patch and geodesics " the complement of a codimension-one projective subspace of RP3(real projective space) is identifiable in a geodesic-structure manner with an affine 3-space so that the group of projective transformations acting on it is identical with the group of affine transformations of the affine 3-space.we call this set an ' affine patch ' .conversely , a natural completion of an affine 3-space is identified with RP3 in a geodesic preserving manner ".
what does 'geodesic preserving manner' mean?
I know it means that we can embed affine 3-space in RP3 by a map which preserves geodesics , but how does this map do this?

A: The way I read this statement is the following: you can take projective 3-space, denote any plane as "the plane at infinity", and the remainder (i.e. projective space minus that one plane) will behave as an affine space. Any projective transformation which preserves the plane at infinity will then correspond to an affine transformation.
All of the above can be readily seen when you consider coordinates. Using a simple transformation of your coordinate system, you can take the plane at infinite (your codimension-one subspace) to be $w=0$. Then any point $(x,y,z,w)^T$ in the complement will have $w\neq0$. So you can dehomogenize to $(x/w, y/w, z/w)^T$ and use that as affine coordinates.

what does 'geodesic preserving manner' mean?

The fact that they refer to geodesics instead of collinearity seems a bit strange to me, but I guess the message is the same: (projective) lines will map to (affine) lines. Which again is straight-forward given the dehomogenization interpretation above.
For the converse case, this "natural completion" refers to the union of the original affine space with elements at infinity. Expressed in coordinates, this is the step where you introduce homogenous coordinates, some of which may have $w=0$. Lines still remain lines.


text:
Q: An internal error occurred in the Places API library I'm working with GoogleMaps an GooglePlaces API but I always obtain de same error.
"The operation couldn't be completed. An internal error occurred in the Places API library. If you believe this error represents a bug, please file a report using the instructions on our community and support page (https://developers.google.com/places/support)"
I've tried to run pod try GoogleMaps and when I launch de project any map is loaded, only a tableView with different options.
This is my code, I only want to obtain the user position:
-(IBAction)getCurrentPlace:(UIButton *)sender {
[placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *placeLikelihoodList, NSError *error){
    if (error != nil) {
        NSLog(@"Pick Place error %@", [error localizedDescription]);
        return;
    }

    self.nameLabel.text = @"No current place";
    self.addressLabel.text = @"";

    if (placeLikelihoodList != nil) {
        GMSPlace *place = [[[placeLikelihoodList likelihoods] firstObject] place];
        if (place != nil) {
            self.nameLabel.text = place.name;
            self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:@", "]
                                      componentsJoinedByString:@"\n"];
        }
    }
}];
}

I have imported mi APIKEY in didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[GMSServices provideAPIKey:@"MY_APIKEY"];

return YES;
}

And this is my Podfile
platform :ios, '7.0'
source 'https://github.com/CocoaPods/Specs.git'

target 'googlePlace' do

   pod 'GoogleMaps'
   pod 'GooglePlaces'

end

Finally, my apikey is configured to iOS application in Google Console.
What's the problem??

A: This looks like your API key is either invalid or out of quota.
Can you check that you are passing the correct API key to GMSPlacesClient.provideAPIKey(_:).
If you are sure that you are passing the correct API key check the Google API Console (https://console.developers.google.com/) to ensure you have not run over your daily quota limit.
This issue can be tracked here: https://issuetracker.google.com/issues/35830792

A: Answer my own question
https://developers.google.com/places/migrate-to-v2?hl=es-419
This fixed the problem
Migrating to Google Places API for iOS, version 2
With the version 2 release of the Google Maps SDK for iOS, the Google Places API for iOS has been split from the Google Maps SDK for iOS and is now distributed as a seperate CocoaPod.
Take the following steps to update your existing apps:
Update your Podfile to reference the GooglePlaces CocoaPod in addition to the GoogleMaps CocoaPod. If you are not using the Google Maps SDK for iOS, you can remove GoogleMaps.
If you are using the place picker, update your Podfile to reference the GooglePlacePicker CocoaPod in addition to GooglePlaces.
Rename GoogleMaps to GooglePlaces in all imports where you are using the Places API.
Specify your API key using GMSPlacesClient.provideAPIKey(:) instead of GMSServices.provideAPIKey(:).
Get the required open source license text using GMSPlacesClient.openSourceLicenseInfo() as well as GMSServices.openSourceLicenseInfo() if you are using the Google Maps SDK for iOS or the Place Picker.

A: After doing 8 to 12 hours R&D Found below solution. I am sure it will work.
Just add the key in AppDelegate.swift file, not any other class. It will solve your problem.
   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
         GMSPlacesClient.provideAPIKey("KEY")
         GMSServices.provideAPIKey("KEY")

    }

Note: It is compulsory to initialize GMSPlacesClient in AppDelegate Because it will take some time for initialization.

A: 2018 answer, well in my new job, we're having a hard time about this. My own Places key works but not my new company's Places key. After a few hours, I remember the time when I was setting my own keys, I HAD TO REFRESH or REGENERATE NEW KEYS for the Places API before I got it to work. Now back to my current situation, I told this to my colleagues and boom, we just had to refresh the key, and it worked! :)