text:
Q: Issues with overloading Order I am pretty new to Mathematica(about 90 minutes) and I have encountered a problem. I have searched the web pretty comprehensively and came up with nothing.
For a computing problem that I am solving, I needed to use this package
http://www.theophys.kth.se/~phl/Mathematica/
I specifically need to use the CompressedTransferMatrix1F method.
However, when I try the example as mentioned in the package documentation, this is what happens, and the matrix is not as I expect it to be.

I am guessing this has something to do with the fact that Order method is overloaded is the package. It takes a single argument of type graph and returns the number of vertices in a graph. And the default order method in Mathematica takes 2 arguments. Help to resolve this issue is really appreciated.

(* Order::usage *) If[!StringMatchQ[Order::usage, "Order[g]"],
    Order::usage = Order::usage <>  "\n Order[g] returns the number of
  vertices in a graph g."

If post language is not clear, feel free to edit. Thank you.


text:
Q: Like counting on a post using cakephp I have two model User(id,username,password),Post(id,user_id,body,created,liked,disliked),if any user like or dislike a post, i want to show total number of like or dislike. i implementet it using  this answer it did not worked for me, please somebody tell me how can i do it ?
this is my Post controller:
function voteUp($id = null) {
    if ($this->RequestHandler->isAjax()) {
        $this->Post->id = $id;
        if ($this->Post->saveField('liked', $this->Post->field('liked') + 1)) {

        }
    }
    $newValue = $this->Post->findById($id);
    return $newValue['post']['liked'];
}

function voteDown($id = null) {
    if ($this->RequestHandler->isAjax()) {
        $this->Post->id = $id;
        if ($this->Post->saveField('disliked', $this->Post->field('disliked') + 1)) {

        }
    }
    $newValue = $this->Post->findById($id);
    return $newValue['Post']['disliked'];
}

This is my posts/view file :

        <?php echo $post['Post']['id']; ?>

        <?php echo $post['Post']['liked']; ?>

        <?php echo $post['Post']['id']; ?>

        <?php echo $post['Post']['disliked']; ?>

this is my js like file:

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to run tomcat as service and not use root user I copy catalina.sh to /etc/init.d/tomcat and sudo chkconfig --add tomcat
it started as root user,I want use another user,how?

A: If you do want to create your own start up script for whatever reason. Then to run tomcat under another user use su -c "$TOMCAT_HOME/bin/tomcat.sh start" nobody when starting tomcat. (nobody is the user in this case that tomcat will start under)
http://www.jguru.com/faq/view.jsp?EID=455567

A: You should not copy catalina.sh to /etc/init.d/tomcat. Ubuntu provides (in its tomcat6 package) a /etc/init.d/tomcat6 startup script that will invoke catalina.sh as the correct user.
Also, using chkconfig on Ubuntu is not supported; it's a script for Red Hat-based systems. Don't use it.


text:
Q: How to decode base64 string to file without store it I want to decode base64 string to file object to show it in my application without store it in disk.
the following code convert my string to file object but store it in local disk, How to avoid that?
FileOutputStream fos = null;
try {
    if (base64ImageData != null) {
       fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE);
       byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
       fos.write(decodedString);
       fos.flush();
       fos.close();
    }

} catch (Exception e) {

} finally {
    if (fos != null) {
        fos = null;
    }
}

A: get rid of fos.write. Display decodedString using a method of your choosing.


text:
Q: ZPL II Extended Characters I'm trying to print extended code page 850 characters using ZPL II to a Zebra S4M.  Whenever one of the extended characters I.E. ASCII value > 127 is used I get a box of varying shades of grey instead of the actual value.
I'm trying to print ± and ° (ALT+0177 and ALT+0176).  I suspect its the RawPrinterHelper I am trying to use (as downloaded from MS, and another from CodeProject) however I cant see where the character codes are going wrong.
Weirdly, printing direct from Notepad renders the correct characters, which leads me to believe it is a problem with the raw printer helper class.
I am not tied to using the Raw Printer Helper class so if there is a better way of doing it, I am more than happy to see them.
SAMPLE ZPLII
Without escaped chars
^XA
^FO30,200^AD^FH,18,10^FD35 ± 2 ° ^FS
^FS
^XZ

With escaped chars (tried both upper and lower case)
^XA
^FO30,200^AD^FH,18,10^FD35 _b0 2 _b1 ^FS
^FS
^XZ

Raw Printer Helper
[StructLayout(LayoutKind.Sequential)]
public struct DOCINFO
{
    [MarshalAs(UnmanagedType.LPWStr)]
    public string printerDocumentName;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pOutputFile;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string printerDocumentDataType;
}

public class RawPrinter
{
    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long OpenPrinter(string pPrinterName, ref IntPtr phPrinter, int pDefault);

    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long StartDocPrinter(IntPtr hPrinter, int Level, ref DOCINFO pDocInfo);

    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long StartPagePrinter(IntPtr hPrinter);

    [
        DllImport("winspool.drv", CharSet = CharSet.Ansi, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long WritePrinter(IntPtr hPrinter, string data, int buf, ref int pcWritten);

    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long EndPagePrinter(IntPtr hPrinter);

    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long EndDocPrinter(IntPtr hPrinter);

    [
        DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true,
            CallingConvention = CallingConvention.StdCall)]
    public static extern long ClosePrinter(IntPtr hPrinter);

    public static void SendToPrinter(string printerJobName, string rawStringToSendToThePrinter,
                                     string printerNameAsDescribedByPrintManager)
    {
        IntPtr handleForTheOpenPrinter = new IntPtr();
        DOCINFO documentInformation = new DOCINFO();
        int printerBytesWritten = 0;
        documentInformation.printerDocumentName = printerJobName;
        documentInformation.printerDocumentDataType = "RAW";
        OpenPrinter(printerNameAsDescribedByPrintManager, ref handleForTheOpenPrinter, 0);
        StartDocPrinter(handleForTheOpenPrinter, 1, ref documentInformation);
        StartPagePrinter(handleForTheOpenPrinter);
        WritePrinter(handleForTheOpenPrinter, rawStringToSendToThePrinter, rawStringToSendToThePrinter.Length,
                     ref printerBytesWritten);
        EndPagePrinter(handleForTheOpenPrinter);
        EndDocPrinter(handleForTheOpenPrinter);
        ClosePrinter(handleForTheOpenPrinter);
    }
}

Actual Fix from the Accepted Answer set the Character Internationalisation ( Code ^CI27 ) to Code Page 1252.
^XA
^FO30,200^AD^CI27^FH,18,10^FD35 _b0 2 _b1 ^FS
^FS
^XZ

A: Yes, the shaded boxes have those byte codes, in code page 1252.  Which no doubt is the default code page for the printer, 1252 is the Windows code page for Western Europe and the Americas.
You'll have to send a command to switch the code page to 850.  Judging from the manual, that requires ^CI to select character set 13.
Keeping the code page at 1252 and changing your character codes instead would be wise.  The glyph tables are in the back of the manual.


text:
Q: Hash string into RGB color Is there a best practice on how to hash an arbitrary string into a RGB color value? Or to be more general: to 3 bytes.
You're asking: When will I ever need this? It doesn't matter to me, but imagine those tube graphs on any GitHub network page. There you can see something like this:

Where every colored line means a distinct git branch. The low tech approach to color these branches would be a CLUT (color lookup table). The more sophisticated version would be:
$branchColor = hashStringToColor(concat($username,$branchname));

Because you want a static color every time you see the branches representation. And for bonus points: How do you ensure an even color distribution of that hash function?
So the answer to my question boils down to the implementation of hashStringToColor().

A: A good hash function will provide a near uniform distribution over the key space.  This reduces the question to how do I convert a random 32 bit number to a 3 byte RGB space.  I see nothing wrong with just taking the low 3 bytes.
int hash = string.getHashCode();
int r = (hash & 0xFF0000) >> 16;
int g = (hash & 0x00FF00) >> 8;
int b = hash & 0x0000FF;

A: For any Javascript users out there, I combined the accepted answer from @jeff-foster with the djb2 hash function from erlycoder.
The result per the question:
function djb2(str){
  var hash = 5381;
  for (var i = 0; i < str.length; i++) {
    hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
  }
  return hash;
}

function hashStringToColor(str) {
  var hash = djb2(str);
  var r = (hash & 0xFF0000) >> 16;
  var g = (hash & 0x00FF00) >> 8;
  var b = hash & 0x0000FF;
  return "#" + ("0" + r.toString(16)).substr(-2) + ("0" + g.toString(16)).substr(-2) + ("0" + b.toString(16)).substr(-2);
}

UPDATE: Fixed the return string to always return a #000000 format hex string based on an edit by @alexc (thanks!).

A: As an example, this is how Java calculates the hashcode of a string (line 1494 and following). It returns an int. You can then calculate the modulo of that int with 16,777,216 (2^24 = 3 bytes) to get an "RGB-compatible" number.
It is a deterministic calculation so the same word(s) will always have the same colour. The likelihood of hash collision (2 strings having the same colour) is small. Not sure about the colour distribution, but probably fairly random.

A: I just build a JavaScript library named color-hash, which can generate color based on the given string (using HSL color space and BKDRHash).
Repo: https://github.com/zenozeng/color-hash
Demo: https://zenozeng.github.io/color-hash/demo/

A: I tried all the solutions others provided but found that similar strings (string1 vs string2) produce colors that are too similar for my liking. Therefore, I built my own influenced by the input and ideas of others.
This one will compute the MD5 checksum of the string, and take the first 6 hex digits to define the RGB 24-bit code.
The MD5 functionality is an open-source JQuery plug in.
The JS function goes as follows:
function getRGB(str) {
    return '#' + $.md5(str).substring(0, 6);
}

A link to this working example is on jsFiddle. Just input a string into the input field and press enter, and do so over and over again to compare your findings.

A: If you are using C# and want HSL colors
Here is a class I wrote based on the library written by Zeno Zeng and mentioned in this answer .
The HSLColor class was written by Rich Newman, it is defined here

    public class ColorHash
    {

        // you can pass in a string hashing function of you choice
        public ColorHash(Func<string, int> hashFunction)
        {
            this.hashFunction = hashFunction;
        }

        // or use the default string.GetHashCode()
        public ColorHash()
        {
            this.hashFunction = (string s) => { return s.GetHashCode(); };
        }

        Func<string, int> hashFunction = null;

        static float[] defaultValues = new float[] { 0.35F, 0.5F, 0.65F };

        // HSLColor class is defined at https://richnewman.wordpress.com/about/code-listings-and-diagrams/hslcolor-class/
        public HSLColor HSL(string s) {
            return HSL(s, defaultValues, defaultValues);
        }

        // HSL function ported from https://github.com/zenozeng/color-hash/
        public HSLColor HSL(string s, float[] saturationValues, float[] lightnessValues)
        {

            double hue;
            double saturation;
            double luminosity;

            int hash = Math.Abs(this.hashFunction(s));

            hue = hash % 359;

            hash = (int)Math.Ceiling((double)hash / 360);
            saturation = saturationValues[hash % saturationValues.Length];

            hash = (int)Math.Ceiling((double)hash / saturationValues.Length);
            luminosity = lightnessValues[hash % lightnessValues.Length];

            return new HSLColor(hue, saturation, luminosity);
        }

    }

A: Interstingly enough a common representation of hashing functions like sha256 or md5 is as a hex string. Here is a fiddle that uses the 10 6 byte segemnts to create a coloful representaion of and sha256 hash. It uses the last 4 byte segment to determine the angle of the colors.
https://jsfiddle.net/ypx4mtnr/4/
async function sha256(message) ... see fiddle ...

   async function sha256(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
   }
   function sha256tohtml(x,b){
var y=chunkSubstr(x,6);
return '<div style="'+
    'display: inline-block;'+
    'margin:2em;'+
    'width:128px;'+
    'height:128px;'+
    'border-radius: 512px;'+
    'background: conic-gradient('+
    '   from '+((360/65536)*parseInt(y[10],16))+'deg at 50% 50%,'+
    '   #'+y[0]+' '+(0+b)+'%,'+
    '   #'+y[0]+' 10%,'+
    '   #'+y[1]+' '+(10+b)+'%,'+
    '   #'+y[1]+' 20%,'+
    '   #'+y[2]+' '+(20+b)+'%,'+
    '   #'+y[2]+' 30%,'+
    '   #'+y[3]+' '+(30+b)+'%,'+
    '   #'+y[3]+' 40%,'+
    '   #'+y[4]+' '+(40+b)+'%,'+
    '   #'+y[4]+' 50%,'+
    '   #'+y[5]+' '+(50+b)+'%,'+
    '   #'+y[5]+' 60%,'+
    '   #'+y[6]+' '+(60+b)+'%,'+
    '   #'+y[6]+' 70%,'+
    '   #'+y[7]+' '+(70+b)+'%,'+
    '   #'+y[7]+' 80%,'+
    '   #'+y[8]+' '+(80+b)+'%,'+
    '   #'+y[8]+' 90%,'+
    '   #'+y[9]+' '+(90+b)+'%,'+
    '   #'+y[9]+' 100%);">
';
  }
   function chunkSubstr(str, size) {
  const numChunks = Math.ceil(str.length / size)
  const chunks = new Array(numChunks)

  for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
    chunks[i] = str.substr(o, size)
  }

  return chunks
}
   function draw(x){
    sha256(x).then((x)=>{
        var html=sha256tohtml(x,0);
            document.getElementById('addhere').innerHTML=html;
        });
   }
   window.onload=function(){
    document.getElementById('sha256string').oninput=function(){draw(this.value);}
        draw(document.getElementById('sha256string').value)
}

<input id="sha256string" value="Hello World">


text:
Q: Why can't files introduced by require.context() be dynamically updated in Vue? I am building an static markdown blog website using Vue3,and I am using require.context() to load markdown files.
This is the project structure,and I load files from static/posts.
├── dist
│   ├── assets
│   │   └── static
│   │       └── posts
│   │           ├── dev-first-vue3-todolist.md
│   │           ├── dev-fix-missing-xcrun.md
├── package.json
├── src
│   ├── App.vue
│   ├── main.js
├── static
│   └── posts
│       ├── dev-first-vue3-todolist.md
│       ├── dev-fix-missing-xcrun.md
└── vue.config.js

Here's  how I load these markdown files.
let context = require.context("../static/posts", true, /\.md$/, "sync");
let keys = context.keys();

// the markdown file list
const postRawList = [];

keys.forEach((key) => {
  const raw = context(key).default;
  postRawList.push(raw);
});

It worked well. I can read postRawList  from static/posts and render them by markdown parser.
The point is, I want my blog website static, so when I build this Vue app I use copy-webpack-plugin to copy these markdown files from static/posts to dist/assets/static/posts and it worked well.
    config.plugins.push(
      new CopyWebpackPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "static/posts"),
            to: path.resolve(__dirname, "dist/assets/static/posts"),
          },
        ],
      })
    );

I want to manage my markdown posts only by adding or deleting markdown files in dist/assets/static/posts.
But after I changing the markdown files in dist/assets/static/posts(like delete dev-first-vue3-todolist.md) ,the  markdown object list(postRawList) doesn't be updated.
The markdown list is the same as the markdown list in static/posts , and no matter how I change files in this 2 posts folder,it does't be updated.
I guess it is caused by "require cache", and I had tried to delete cache after changing the files, but it did't work.
delete require.cache[context.id];

So I want to know why the file objects not be updated after I built the app and  change the files in markdown directory(loaded by require.context()).
This is my first time asking questions on stackoverflow,and I feel sorry if I didn't make it clear.


text:
Q: Copy all contents (recursive) of a folder from one s3 bucket to another I am trying to copy all files from one S3 Folder to another in different buckets. I was able to come to a solution where one could list all objects and copy them to different bucket path. Is there any other better solution to this problem?
P.S: I have to do this using AWS SDK (Javascript)

A: If you have a working solution by listing objects in the source bucket and then copying each object to the destination bucket, then that's great!
Some other options:

*

*Use the AWS Command-Line Interface (CLI) aws s3 cp or aws s3 sync commands, which effectively is the same as your solution but somebody has written the code

*Use Cross-Region Replication - Amazon Simple Storage Service, but the buckets must be in different regions

*Configure an Amazon S3 Event to trigger an AWS Lambda function whenever a new file is created. Program the Lambda function to copy the file immediately. The result is near-instant copying of files rather than having to copy them in batches at regular intervals.


text:
Q: The makeup of the Imperial fists pre M 42 In the book 'I am Slaughter', the author Dan Abnett describes the naming convention of companies and battle brothers inside of the Imperial Fists.
Apparently the companies are named after the walls of the Imperial Palace.
The battle brothers are named after something they are good at.
I was wondering if this is a relic of the past that doesn't get used in M42 or if they still name their companies this way in the present?
They are after all a "codex" chapter.

A: @Edlothiad and @Cherubel:
Supporting quotes:
•Pre-War of the Beast (but post-Iron Cage) IF is set up with 50 Companies, or Walls: Note that the "wall-brothers" are the Company Champions of each Wall/Company, charged to stand guard atop each Company's namesake wall at the Imperial Palace.
 I am Slaughter, ch.15

'It would be the worst loss imaginable,' agreed Zarathustra. 'For the Imperial Fists, the Old Seventh, greatest of all the Adeptus Astartes, and the most loyal of all defenders of Terra, to be reduced to… to nothing, to nothing but the last fifty wall-brothers stationed at the Palace. To lose all but five per cent, to be diminished to a twentieth… How would we ever recover from that?'

• That thing which happened in Book 10:
 The Last Son of Dorn, ch18

 The prime-ork had known exactly what had to be destroyed. To eliminate the one thing its rival could not afford to lose.
'I think… I think that…'
'No!' said Bohemond. 'No, I will not accept it. The line of Dorn must live on.'

They had lost. The last son of Dorn was dead.

•Refounding:
 Shadow of Ullanor, ch3

 'We all know how it wounded Dorn to break his Legion. The grief of it never left him. Imagine how he would have felt to see this day come to pass. Imagine what he would do now, if he could have attended this Feast. What he would tell us. Of course, the loss of the Imperial Fists will be remembered – will be honoured by all the Chapters here present. But all of the Chapters here were Imperial Fists once… and could be again.'

 'Let every Successor give back a little of what it took to build their honoured Chapters – in vessels, weapons, battle-brothers and plate. And for Dorn's sake, let that plate be painted yellow.'

'For Dorn's sake?' Issachar said. 'For Dorn's sake, let the best of us – victorious in the Feast and brother to all of us – take his rightful place as Master of the Imperial Fists. Let his name be carved into the bones of Rogal Dorn, and let no son of Dorn speak beyond our brotherhood of this again.'

•Abandoning the tradition of wall-names:
 The Beheading, ch4

'My third, and final decree,' said Thane. 'I will be a crusading lord. The Imperial Fists shall no longer stand upon a wall and look out on our enemies and defy them to come to us. We shall be a mobile fortress, moving ever forward to crush those who would spurn the will of the Emperor, whether they be known or unknown. Dangers cannot be waited upon, but must be rooted out and destroyed ere they pose a risk. Never again shall an enemy of the Imperium enter the orbit of Holy Terra. This we swear! For what use is a wall if all the lands about it are laid waste and occupied by the hateful foe? No longer will we stand in one place. No longer will we take wall-names, but we shall become a wall for the whole Imperium. Phalanx will leave before the end of the week, and I will be taking the Imperial Fists with me.'

Admittedly I could not find any direct quote that the IF organization was changed from 50 Walls x 20 Marines to the standard 10 companies x 100 Marines, but this timeframe seems plausible to me, as

Thane was previously CM of the Fists Exemplar - the hardcore Codex-compliant chapter among the IF's Second Founding successors, and he folded its remnants into the new IF.

A: Edit: I posted the supporting quotes from the books below.
Massive spoilers for Books 10 to 12 of The Beast Arises below; beware!

The Imperial Fists chapter, in the form it was established by Dorn after the Heresy and the breaking of the old VIIth, died with its very last member in the 10th book. However it was refounded in secret by its Successors, with the Chapter Master of the Codex-compliant successor (Fists Exemplar) becoming the new CM and leading the Imperium's forces to victory over The Beast. Part of his reforms after the victory was the abandonment of the IF's peculiar traditions and it becoming fully Codex-compliant.


text:
Q: Overflow position of child element being applied to window on refresh I have a search results page in a React app where the user can select filters, which in turn updates the query params of the URL and causes a re-mount in React. One issue I'm running into, across multiple browsers, is that if any my filters are within overflow-y containers, then the position of the child overflow is applied to the window on re-mount. Here's an example:

*

*Scroll within a child div that contains a checkbox (let's say 70% of the way down the div)

*Click on a checkbox filter

*Component will re-mount

*Regardless of where the main window scroll location was set previously, the main window is now scrolled down 70% the way.

I've tried setting restoration to manual, but that doesn't do anything. I've also tried to grab the scroll position manually, with window.scrollY and similar functions, and restore it to that position, but it returns the scroll position of the child element.

A: Using window.history.pushState allows query params to be updated without forcing a re-render.


text:
Q: Restrict document types for only PDF and Word documents I'm using the UIDocumentMenuViewController to pick and choose documents. I want to restrict users to pick only .pdf and .docx files.
I know I can allow only PDFs like this.
UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)

But how do I include .docx types as well?


text:
Q: Django Python Social Auth, Authentication Canceled by Facebook app I am trying to implement website login using Facebook credentials. I see different responses when I press Cancel on Facebook widget or Okay. When I press Cancel I see the following

    Environment:

    Request Method: GET
    Request URL: http://wakevent.com/complete/facebook/?redirect_state=cvZGNl42bKvgcDDDezBy14VJ1Eit5OmT&error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=cvZGNl42bKvgcDDDezBy14VJ1Eit5OmT

    Django Version: 1.8.2
    Python Version: 2.7.6
    Installed Applications:
    ('django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'mainapp',
     'social.apps.django_app.default')
    Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
     'social.apps.django_app.middleware.SocialAuthExceptionMiddleware')

    Traceback:
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
      57.         response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
      58.         return view_func(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/utils.py" in wrapper
      51.             return func(request, backend, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/views.py" in complete
      28.                        redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/actions.py" in do_complete
      43.         user = backend.complete(user=user, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py" in complete
      41.         return self.auth_complete(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/utils.py" in wrapper
      229.             return func(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/backends/facebook.py" in auth_complete
      68.         self.process_error(self.data)
    File "/usr/local/lib/python2.7/dist-packages/social/backends/facebook.py" in process_error
      60.         super(FacebookOAuth2, self).process_error(data)
    File "/usr/local/lib/python2.7/dist-packages/social/backends/oauth.py" in process_error
      363.                 raise AuthCanceled(self, data.get('error_description', ''))

    Exception Type: AuthCanceled at /complete/facebook/
    Exception Value: Authentication process canceled

Which is predicatble. But when I press Okay I see another error.

    Environment:

    Request Method: GET
    Request URL: http://wakevent.com/complete/facebook/?redirect_state=cvZGNl42bKvgcDDDezBy14VJ1Eit5OmT&code=AQBe5WWQYk9BJE2fvNIt0RWVYxLaddhXT6t3UQwtF3aJcvbbLrVwsMlxsKEgwulVAtV4WHlYG5lG1HbEHk_cjFhMfWEHy9B8dedrOZagw0AWyGVyvaFtRqOn8_3G8nQb2nEe-DZMdG13V7Jgzrebtu6QXxGuyNzZPVXRnbPiKGUz8jW2p-r_wWB7QAuW-6rdZuII8_1ePBBoGgzmLlKLvMLfZoCqI62h0slF5t2IoAraHahRtnkWeIeH6AVf5u4vzZ8qXatz9fuun8ZK-8rqv5p5HDWZOdydNGm7ZtNh0g1OSpZU4TFAGxAqWbo0LpgiCRs&state=cvZGNl42bKvgcDDDezBy14VJ1Eit5OmT

    Django Version: 1.8.2
    Python Version: 2.7.6
    Installed Applications:
    ('django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'mainapp',
     'social.apps.django_app.default')
    Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
     'social.apps.django_app.middleware.SocialAuthExceptionMiddleware')

    Traceback:
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
      57.         response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
      58.         return view_func(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/utils.py" in wrapper
      51.             return func(request, backend, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/views.py" in complete
      28.                        redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/actions.py" in do_complete
      43.         user = backend.complete(user=user, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py" in complete
      41.         return self.auth_complete(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/social/utils.py" in wrapper
      232.                 raise AuthCanceled(args[0])

    Exception Type: AuthCanceled at /complete/facebook/
    Exception Value: Authentication process canceled

I am running the website locally on Ubuntu 14.04 apache web server with 80 port. I suspect wrong Facebook app setup but do not know what to debug.
Also, I can mention that Twitter login is working on the same setup.
Please advise!

A: I did wrong Facebook app setup. In the Security / Server IP Whitelist I put 127.0.0.1 address. The problem was gone after removing this address (blank space is okey).

A: Check the redirect URL. I had wrongly specified redirect URL along with client ID while making post request. For Facebook redirect URI is optional. Try removing that and it will work fine.


text:
Q: Two queries on triangles, the sides of which have rational lengths Let us define a "rational triangle" as one in the Euclidean plane, with lengths of all sides rational.
We are aware that a positive integer is called "congruent" only if it is the area of a right triangle with rational length sides; so not every rational number is the area of some right rational triangle. However,

*

*is every positive rational number the area of some (not necessarily right) rational triangle?

*for two given rational numbers $A$ and $P$, among the infinitely many general triangles with area $A$ and perimeter $P$ (there are infinitely many such triangles if $A$ and $P$ are within a suitable range), is there a guarantee that there are any (or infinitely many) rational triangles?

A: If for the equation derived by Chris Wuthrich, we introduce the new variables $p = 2P$, $q = x - P/2$, $r = y-P/2$, we obtain the more symmetric relation $$
pqr(p+q+r) = A^2.
$$
Now I knew I recognized this equation from somewhere, and after a little searching I hit upon some slides by Noam Elkies where your Question 1 is resolved completely. (Elkies further credits Franz Lemmermeyer with bringing this problem under his attention.)
It seems that the credit for this goes to Euler. The surface described by the equation above has a K3 surface with maximal Picard rank
($\rho=20$) as its smooth model. Euler presumably used the elliptic fibrations and the presence of many rational curves on the surface to produce a $1$-parameter family of solutions (as suggested by Will Sawin).

A: On the second question: There is the inequality $12\sqrt{3}A\leq P^2$ that needs to be satisfied first of all to get a triangle.
Using Heron's formula for a triangle with sides $x$ and $y$, you are asking for the rational solutions to $(x+y-P/2)(P/2-x)(P/2-y)=2A^2/P$. The projective closure of this curve is an elliptic curve with $O=(1:-1:0)$ and two other rational $3$-torsion points at infinity.
Now for instance the curve for $A=1$ and $P=5$ is isomorphic to the curve with Cremona label 9650m1. This curve has $E(\mathbb{Q})=\mathbb{Z}/3\mathbb{Z}$ and hence there is no triangle with rational side of perimeter $1$ and area $5$. So the answer to this question is no in general.
For other values the rank is positive and you get solutions. For instance $P=6$ and $A=1$, we get $x=5/3$ and $y=3/2$ corresponding to the generator of the Mordell-Weil group. There are infinitely many solutions which correspond to $x>0$ and $y>0$ and $6-x-y>0$.
For $P=8$ and $A=3$, the curve has $6$ rational points, so one only gets finitely many (3) triangles in this case. $x=y=5/2$ is one.
The first question can now be viewed as trying to find a solution in $x$, $y$ and $P$ for a fixed given $A$. This is a non-isotrivial elliptic surface defined over $\mathbb{Q}$. I would expect that the rational point on it are Zariski dense, but I don't know if this can be shown. If so, the answer to the first question would be positive.

A: Here is a back of an envelope calculation which suggest that there will be many such triangles. Choose two positive rationals $r$ and $t$ to be the perimeter and twice the area respectively. We can assume that the triangle has vertices $(0,0), (c,0), (p,q)$ with $c$ a positive rational.  We set $q=\frac t c$.  $p$ is then determined as a solution of the quadratic equation:
$$p^2+\dfrac{t^2}{q^2}=
\dfrac{(c^2-2 p c -(c-r)^2)^2}{4 (c-r)^2}.
$$
If this $p$ is rational, then we have a triangle with the required form. Given that we can choose $r,c,t$ arbitrarily, it seems reasonable that there will be a plethora of such cases but I haven't checked the details. Since the above quadratic equation was obtained by the usual squaring procedures, there is also some sign checking to be done.


text:
Q: How can I search a specific word in between two sign to notepad++? I'm new on Notepad++ and I want to know search a specific word in between two sign ?
I couldn't find the answer on the internet. I need your help.

A: Open the Mark dialog ( Ctrl + M )
SEARCH (?s-i)(?<=WORD).+?(?=WORD)
Tick the two options Purge for each search and Wrap around
Un-tick all other box options
Select the Regular expression search mode
Click on the Mark All button


text:
Q: Are all electromagnetic waves transverse in free space? I understand that in vacuum, monochromatic plane waves are transverse. I suppose that a non-monochromatic plane wave would also have this property, as it can be decomposed using the Fourier transform and each of its components would be transverse.
However, what happens if the waves are not plane? Are they still transverse? The only demonstrations I've found are used for plane waves, so I don't know if this is a necessary condition or is just done for simplicity but can be generalized.

A: As discussed in the comments, the plane wave approximation is mostly irrelevant. The only important ingredient is the fact that the homogeneous vacuum Maxwell equations read
$$
\nabla\cdot\boldsymbol E=\nabla\cdot\boldsymbol B= 0
$$
and therefore, after a Fourier transform $\boldsymbol x\to\boldsymbol k$ we get
$$
\boldsymbol k\cdot\boldsymbol E=\boldsymbol k\cdot\boldsymbol B= 0
$$
which means that the fields are transverse.
In practice, the most simple treatment of electromagnetic waves is through the vector potential. The equations are simplest in the Lorenz gauge
$$
\partial_\mu A^\mu=0
$$
which, again, in Fourier space becomes $k\cdot A=0$, i.e., the vector potential is transverse. Other very useful gauge is the radiation gauge
$$
\nabla\cdot \boldsymbol A=0
$$
which, again, implies that $\boldsymbol A$ is transverse:
$$
\boldsymbol k\cdot\boldsymbol A=0
$$

A: It depends on what you mean by "EM waves are transverse". If you mean "the $\mathbf E$ and $\mathbf B$ fields are always orthogonal to the direction of propagation", where you're willing to take a case-by-case approach to the direction of propagation (or you want to use e.g. the time-averaged Poynting vector or some similar measure for the direction of propagation) then the assertion is false.
For most working physicists, however, that's a bit of a wonky understanding of what 'transverse' means, particularly for fields with a complex spatial dependence where you do not have a well-defined direction of propagation. In those cases, as AccidentalFourierTransform points out, the correct understanding of the phrase is purely in terms of the Maxwell scalar equations:
$$
\nabla\cdot\mathbf E = 0 = \nabla\cdot\mathbf B.
$$
This gives you your transversality constraint: it's phrased in a wonky differential-equation language, but at each point it essentially gives you a direction in which each field cannot point, based on its local coordinate dependence.
On the other hand, this can give some weird results if you want to stick to some more intuitive understanding of the "propagation direction" of the field. The clearest example of this is in a waveguide, which has a well-defined "direction" in the axis of the waveguide, but for which the electric or magnetic fields can have nonzero components in that direction. These components are typically small (and they vanish in the limit where the wavelength is much smaller than the waveguide width) but they are nonzero, and they can be important for applications. (For an example of these components in action (and/or shameless plug), see this paper.)
In essence, the way this works is that a confined waveguide mode, such as
$$
\mathbf E(\mathbf r,t) = E_0\hat{\mathbf e}_y \sin(x/L)\cos(kz-\omega t),
$$
is only confined because it is a standing wave in the $x$ direction, and this is best seen as the superposition of two travelling waves:
$$
\mathbf E(\mathbf r,t) = \mathrm{Re}\mathopen{}\left(
E_0\hat{\mathbf e}_y \frac{1}{2i}\left(e^{i(x/L+kz-\omega t)}-e^{i(-x/L+kz-\omega t)}\right)
\right)\mathclose{}.
$$
Here both waves are transverse, and (assuming $kL\ll 1$) they both have $\mathbf k$ vectors close to but not quite on the waveguide axis $\hat{\mathbf e}_z$. Thus, the electric and magnetic fields for each component are orthogonal to the propagation direction of each plane wave, but since there is more than one such propagation direction, the global field gets a bit confused about what that term actually means.
The specific example above is a transverse electric (TE) mode, with the electric field orthogonal to the waveguide axis, so it may sound a bit confusing, but with a bit of thought you can see that the corresponding magnetic field needs to point in the $y,z$ plane and therefore it's a bit more complicated. Finding this magnetic field is easy, since we can just plop in the corresponding field for each plane-wave component, but now you need to account for the fact that the two magnetic components are not parallel:
\begin{align}
\mathbf B(\mathbf r,t)& = \mathrm{Re}\mathopen{}\left(
B_0 \frac{1}{2i}\left(
\frac{-\hat{\mathbf e}_x-kL\hat{\mathbf e}_z}{\sqrt{1+k^2L^2}} e^{i(x/L+kz-\omega t)}
-\frac{-\hat{\mathbf e}_x+kL\hat{\mathbf e}_z}{\sqrt{1+k^2L^2}} e^{i(-x/L+kz-\omega t)}\right)
\right)\mathclose{}
\\& =
-\frac{B_0\hat{\mathbf e}_x}{\sqrt{1+k^2L^2}}\sin(x/L)\cos(kz-\omega t)
-B_0\frac{kL\hat{\mathbf e}_z}{\sqrt{1+k^2L^2}}\cos(x/L)\sin(kz-\omega t)
.
\end{align}
In particular, note that now you have a nonzero $\hat{\mathbf e}_z$ component (though again this is small when $kL\ll 1$). Does this make the magnetic field stop being "transverse"? That's up to what you want to make of the term, really.
While this is the simplest example, it should be clear that the situation is pretty generic any time that vector optics come into play. Thus, you have equivalent effects in a tight Gaussian focus (example), general waveguides (example), spherical waves (cf. Jackson 3rd ed. §9.7), and so on. These admit a similar explanation to the above in terms of a continuous superposition of plane waves (i.e. they can be decomposed as Fourier transforms of a bunch of transverse plane waves with $\mathbf k\cdot\mathbf E=0 = \mathbf k \cdot\mathbf B$), but anytime a point gets significant contributions from multiple different directions of $\mathbf k$ vectors then you will have some trouble establishing a unique 'direction of propagation'.


text:
Q: How to get variables between the curly brackets in django template in django views? I have django template file. Now i want to get all the variables list that are between curly brackets. I think it is possible with the regular expressions. And i read about regular expressions. But there is no function i found to be helpful.
template code snippet:

                Dear Candidate,

                Welcome to Creative Talent Management!

                We have created an account for you. Here are your details:

                Name:{{name}}

                Email:{{email}}

                Organization:{{organization}}

                Password:{{password}}

I want to get name,email,organization,password in my python function.
Right now i'm reading the template but getting empty list.
if created:
        temp_path = str(instance.html_template.path)

        html_file = open(instance.html_template.path, 'r', encoding='utf-8')
        file_data = html_file.read()
        render_param = re.findall("^{{ . }}$", file_data)
        print("html param ",render_param)

A: That's sort of back-to-front. You would normally pass all the variables which might be used from your view to the template rendering through the context. It doesn't matter if  one or more of the context variables are unused by the template. Of course, you should have a test which catches variable name spelling errors ({{usernmae}} will render as null string without error ).
For checking the template, you might simply grep '{{' some_template.html, or write something in Python to get (say) an alphabetically sorted list of variable names. But that's a program-development aid, not a part of the Django server code.
If you really wanted to, you could just open the template file and write similar Python code as part of your view. But, why??


text:
Q: MySQL Search X amount of rows for specific terms I have a database with a little over 300 rows.
For various reasons I only want to search 21 rows at a time for specific terms and at different starting index points.
I am querying for 'banned commercials' in a column called search_terms.
When I use the query below it searches all 300 rows 'banned commercials' instead of just 21 rows.
SELECT `rating_score`
FROM archived_videos
WHERE search_terms='banned commercials'
ORDER BY `rating_score` DESC
LIMIT 0,21

A: Try using this
SELECT rating_score FROM archived_videos WHERE search_terms='banned commercials' ORDER BY rating_score DESC LIMIT 21

Limiting it specifying 21 will limit the results to first 21

A: If you want to search the top 21 rated rows, you can do this with a subselect
SELECT t.`rating_score`
from (select *
      FROM archived_videos
      ORDER BY `rating_score` DESC
      LIMIT 0,21) t
WHERE t.search_terms='banned commercials'

A: I take it from your question that you want to search a block of 21 rows, not limit the result set to 21 rows. The LIMIT clause limits the results, not the set of records being searched. To limit records, you need to add something to your where clause. What this is depends on the contents of your table. If you had a sequence column that numbered the rows from 1 to 300, you could say "where sequence>= 1 and sequence < 21", and adjust the numbers as appropriate.
Another way to do it is to add a select clause:
select iif (search_terms="banned", 1, 0) as flag
into temp_table
from archived_videos
limit 21

select * from temp_table where flag = 1

You might be able to combine these two selects into one using a subselect.


text:
Q: My scripts doesn't work on Mozilla Firefox but does on Chrome I have a simple "Back to top" button coded in JS. When I scroll down 150px  it shows on the bottom-right part of the page and when I click on this button it takes me back to the top of the page.
This works correctly on Google Chrome, but on Mozilla Firefox it does not.
I have a similar problem with another script that generates a random number from a user input.
first script on codepen:
(function(){

  function createButton() {

    var button = document.createElement("button");

    button.classList.add("backToTop", "hiddenBack");
    button.textContent = "back";
    document.body.appendChild(button);

    return button;
  }
  var button = createButton();

  function animatedScroll(){
    if(window.pageYOffset > 0){
      window.scrollBy(0, -5);
      setTimeout(animatedScroll, 10);
    }

  };

  button.addEventListener("click", function(e) {
      e.stopPropagation();
      animatedScroll();

   },false);

  window.addEventListener("scroll", function(e){

    if( window.pageYOffset >= 150){
      button.classList.remove("hiddenBack");
    }else {
      button.classList.add("hiddenBack");
    }

  },false);

})();

second script on codepen:
var btn = document.querySelector("#getNumbers"),
    output = document.querySelector("#showNumbers");

function getRandom(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

function showRandomNumber(){

  var numbers = [];
  var random,
  from = document.querySelector("#from").value,
  to = document.querySelector("#to").value,
  how = document.querySelector("#how").value;

  for(var i = 0; i < how; i++){

    random = getRandom(from,to);

    while(numbers.indexOf(random) !== -1){
      random = getRandom(from,to);
    }

  numbers.push(random)
  }

  output.value = numbers.join(", ");

}

btn.onclick = showRandomNumber;

A: Use the window.pageYOffset instead of document.body.scrollTop:
if(window.pageYOffset >= 150)
More detail on the issue here : document.body.scrollTop Firefox returns 0 : ONLY JS


text:
Q: How to best get results from 3 different tables based on ID matches in Laravel. Trying to get products AND variants for a particular supplier.
I can get the products easy enough, but can't figure out how to best get to the variants with matching product_id and send it to the view.
Variants.product_id matches with Product.ID
This works (getting products for the supplier)
 public function suppliers($id) {

    $supplier = Supplier::orderby('company_name', 'ASC')->find($id);
    $products = Supplier::find($id)->products;

    $data = [];
    $data['supplier'] = $supplier;
    $data['products'] = $products;

    return view('admin.purchasing.supplier-details', $data);
}

I've tried this to get the variants also without luck.
Controller:
    public function suppliers($id) {

    $supplier = Supplier::orderby('company_name', 'ASC')->find($id);
    $products = Supplier::find($id)->products;
    $variants = array();
    foreach ($products as $product) {
        $product_id = $product->id;
        $variants[] = Variant::find($product_id);
    }
    $data = [];
    $data['supplier'] = $supplier;
    $data['products'] = $products;
    $data['variants'] = $variants;
    return view('admin.purchasing.supplier-details', $data);
}

View:
    @foreach($products as $product)

            {{ $product['title'] }}
            @foreach($variants as $variant)
                @if($variant->product_id == $product['id'])
                    ${{ $variant->price }}
                @else
                    not set
                @endif
            @endforeach

    @endforeach

Any tips much appreciated.

A: First of all , you should have relation set on your models to make this work
like this For exemple :
Supplier.php
public function products()
{
    return $this->hasMany('App\Product');
}

Product.php
 public function variants()
{
    return $this->hasMany('App\Variant');
}
public function Supplier()
{
    return $this->belongsToMany('App\Supplier'); //in case you have only one supplier for each product change this to belongsto
}

Variant.php
public function products()
    {
        return $this->belongsToMany('App\Product'); //not sure if this should be manytomany or one to many , it deppends on what you did
    }

anyway now you can do this
Controller
public function suppliers($id) {

    $Data = Supplier::where('id',$id)->orderby('company_name', 'ASC')->with('products.variants')->first(); //you will get the supplier with all products associated to him with variants foreach product

    return view('admin.purchasing.supplier-details')->with('Data',$Data); // now you just loop the $supplierwithproducts->products to get results (dd the variable to check output)

    }

View
{{ $Data->name }} // supplier name since Supplier model was the starting point
@foreach($Data->products as $product) //loop all products related to that supplier
  {{ $product->name }} //shows product name (depends on you database columns
    @foreach($product->variants as $variant) // loops all variants in the current product
      {{ $variant->name }} // shows variants
    @endforeach
@endforeach

If you copy and paste this code it might not work ,but this will give you an idea how you should handle relations in laravel (levrage eloquent relations)
Check this for more informations
Laravel Docs
Laracasts Defining Relationships With Eloquent
Laracasts Updating Records and Eager Loading


text:
Q: How can i call a JQuery function outside of a JQuery class? I have a class:
var BrandDrug = Class.extend({
    fun1: function() {
       $.MyFunc(); //This does not work.
    }
});

//Outside function
$.MyFunc = (function() {
   //Code
});

How can i call the $.MyFunc from the BrandDrug Class?

A: You have to define the "$.MyFunc" before the "BrandDrug" class and it will work.
edit: also note that you are not extending jQuery properly. See this tutorial (for example) on how to build proper jQuery plugins.


text:
Q: Using Bootstrap DatetimePicker with Sweet Alert 2 - Display calendar over alert I am using the SweetAlert2 dialog with a form inside. I want to use the Bootstrap DateTimePicker widget.
The calendar widget popup is displayed within the SweetAlert window instead of over top of it. This makes the alert expand and contract - and you must scroll inside the alert to see the calendar. The desired behavior is for the calendar to display as a child of the primary page and display over top of the alert.
https://jsfiddle.net/ghr2bwoc/13/
  swal({
    title: 'Date picker',
    html: '<input id="datepicker">',
    showConfirmButton: false,
    onOpen: function() {
        $('#datepicker').datetimepicker({});
    },

  }).then(function(result) {

  });

A: Create an additional class in your style sheet:
.swal2-overflow {
  overflow-x: visible;
  overflow-y: visible;
}

Add this new class to your sweet alert code using the customClass attribute.
swal({
  title: 'Date picker',
  html: '<input id="datepicker">',
  showConfirmButton: false,
  customClass: 'swal2-overflow',
  onOpen: function() {
      $('#datepicker').datetimepicker({});
  },

}).then(function(result) {

});

A: If your are like me and don't want the sweetalert's height to automatically resize when the datetime picker appears. Add a max height and max width (max-height: 550px !important;min-height:550px !important;) to @taekwondoalex's answer.
So still add the custom class to the sweetalert  like so;
swal({
  title: 'Date picker',
  html: '<input id="datepicker">',
  showConfirmButton: false,
  customClass: 'custom-swal-class',
  onOpen: function() {
      $('#datepicker').datetimepicker({});
  },

}).then(function(result) {

});

Then add to your css and change the pixel height to match the height you want for example 550px
.custom-swal-class {
    overflow-x: visible;
    overflow-y: visible;
    max-height: 550px !important;
    min-height: 550px !important;
}


text:
Q: How to use nested attributes in yii2? How can I define mongodb nested attributes in yii2? and display it in index GridView?
Sample collection :

This is my model :
public function attributes()
{
    return [
        '_id',
        ....
        'approved',
        'Userbanks', //How to define this nested attribute?
        'createdAt',
        'updatedAt',
    ];
}

public function rules()
{
    return [
        [[''createdAt', 'updatedAt', 'requestStatus', 'approved',
            'Userbanks'// here ?
         ], 'safe']
        ];
}

In my GridView :
[
            'format' => 'raw',
            'label' => 'Withdrawer',
            'attribute' => 'Userbanks{accountholdername}', //How to get accountholdername here
],

A: The same way as using relational databases:
You need create the all different models and next write the relations.
I recommend to you read the gii generator  from Yii2 and Mongo DB  i think it be usefull for you . Here
This is your  model :
/**
* @property Userbanks[] $userbanks
* @return \yii\db\ActiveQuery
*/
public function getUserbanks()
{
    return $this->hasMany(Userbanks::className(),['_id'=>'user_id']);// your relation ids
}


text:
Q: How to scrape ebay listing ID from attribute with BeautifulSoup? I'm trying to edit my code to scrape the ebay listing ID of several listings. Right now, it scrapes the listing title and price. I can't figure out how to scrape only the listing id number from the iid. Below is the ebay html:

I read that iid is an attribute so I tried:
listing_id = item.select_one('div[iid]')

That gave me the whole code of the div class as above.
Then, from searching I tried:
listing_id = [tag['iid'] for tag in item.select_one('div[iid]')]

But that gave the error, TypeError: string indices must be integers.
How do I go about only getting 234387305971? Thanks.

A: Try this:
from bs4 import BeautifulSoup

sample = """

"""

listing_id = [
    tag['iid'] for tag in
    BeautifulSoup(sample, "lxml").find_all("div", class_="lvpic pic img left")
]
print(listing_id)

Output:
['234387305971']

If you wan to print the ids use one of the following:
for id_ in listing_id:
    print(id_)

print(listing_id[0])


text:
Q: difference in space complexity on using recursive program I want to know difference(greater or lesser) between space complexity of a recursive and non recursive program with lowest space complexity.I know that recursion uses stack in its operations,but does recursion always increase space complexity.Can recursion be helpful in reducing space complexity?I will also appreciate any guidance for a good tutorial of stack use in recursion.Please also provide an short example for clarification if possible.

A: Recursion can increase space complexity, but never decreases.
Consider for example insert into binary search tree.
Nonrecursive implementation (using while cycle) uses O(1) memory.
Recursive implementation uses O(h) memory (where h is the depth of the tree).
In more formal way:
If there is a recursive algorithm with space complexity O(X), then there always is nonrecursive algorithm with space complexity O(X) (you can just simulate recursion by using stack). But it doesn't go the other way (see example above).

A: You can achieve exactly the same space complexity with tail recursion as loop iteration if your implementation language support TCO.
int acc=1;
(for int i=1; i<=n; i++) {
  acc*=i;
}
return acc;

Is the same as:
int fact (int i, int acc) {
  if( i == 1)
     return acc;
  return fact(i--, i*acc);
}
return fact(n);


text:
Q: What folders/files of a Firefox profile should you exclude from your commit? I'm trying to store a Firefox profile in git.  I've configured it to use a proxy and I want to be able to pull the profile back up when I check the code out again.
As far as I can tell from the documentation there's a Cache folder and an Offline Cache folder that probably shouldn't be included because they are just cached folders, and not any thing of significance to retaining the proxy settings to be used when the Firefox profile is loaded.
Is there anything else in the profile folder that isn't worth including in the commit, because it has nothing to do with:

*

*Preventing the profile from being loaded.

*Preventing the proxy settings from being loaded on the next checkout

I've tried adding the following:
# Ignore FF Cache
ProxyProfileFF/cache2/**
ProxyProfileFF/OfflineCache/**
ProxyProfileFF/jumpListCache/**
ProxyProfileFF/startupCache/**
ProxyProfileFF/saved-telemetry-pings/**

# Ignore vim temp files
*~

A: Here is my .gitignore file:
( that stored in the profile folder )
i.e.
/Users/me/Library/Application Support/Firefox/Profiles/9j5n99pf.default

here is a link to the gist as well
cookies.sqlite
cookies.sqlite-wal
favicons.sqlite-wal
logins.json
places.sqlite-wal
prefs.js
storage/
datareporting/
webappsstore.sqlite
webappsstore.sqlite-wal
weave/
addonStartup.json.lz4
favicons.sqlite
permissions.sqlite
places.sqlite
protections.sqlite
search.json.mozlz4
serviceworker.txt
sessionCheckpoints.json
SiteSecurityServiceState.txt
storage-sync.sqlite
storage.sqlite
bookmarkbackups
saved-telemetry-pings
sessionstore.jsonlz4
addons.json
AlternateServices.txt
content-prefs.sqlite
extensions.json
formhistory.sqlite
xulstore.json

A: I prefer the "better safe then sorry approach".
That is exclude everything and only add files really needed, based on https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data. Moreover I don't add files from which I know / think that they store login credentials / passwords (those are marked with NEVER STORE THEM UNENCRYPTED).
Here is the relevant part of my .gitignore,
# ## exclude everything and only allow specific files
*
!.gitignore

# ###################################
# ## FIREFOX
# ##  based on https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data
!profiles.ini
!installs.ini
#
# ## profiles
!Profiles/
!Profiles/*/
#
# ##  bookmarks, downloads & browsing history
!Profiles/*/places.sqlite
#!Profiles/*/favicons.sqlite
!Profiles/*/bookmarkbackups/
!Profiles/*/bookmarkbackups/*
#
# ##  site-specific preferences
!Profiles/*/permissions.sqlite
!Profiles/*/content-prefs.sqlite
#
# ##  search engins
#!Profiles/*/search.json.mozlz4
#
# ##  personal dictionary
!Profiles/*/persdict.dat
#
# ##  autocompelte history
#!Profiles/*/formhistory.sqlite
#
# ##  cookies & passwords
# ##   NEVER STORE THEM UNENCRYPTED
#!Profiles/*/key4.db
#!Profiles/*/logins.json
#!Profiles/*/cookies.sqlite
#
# ##  DOM storage
# ##   NEVER STORE THEM UNENCRYPTED?
#!Profiles/*/webappsstore.sqlite
#!Profiles/*/chromeappsstore.sqlite
#
# ##  Extensions
!Profiles/*/extension*
!Profiles/*/extensions/*
#
# ##  security certificate settings
#!Profiles/*/cert9.db
#
# ##  security device settings
#!Profiles/*/pkcs11.txt
#
# ##  download actions
#!Profiles/*/handlers.json
#
# ##  stored sessions
#!Profiles/*/sessionstore.jsonlz4
#
# ##  toolbar customization
#!Profiles/*/xulstore.json
#
# ##  user preferences
!Profiles/*/prefs.js
!Profiles/*/user.js
#
# ##  containers
!Profiles/*/containers.json


text:
Q: Postfix bad notify parameter syntax Please bear with me as I'm not an expert admin
I have a linux mail server that has been running for a couple of years and now all of a sudden a certain user is unable to send emails. They immediately get a response from "System Administrator" saying
501 5.5.4 error bad notify parameter syntax

This only happens for this user and only on their computer. It works fine in Thunderbird but not in Outlook 2013. Other users can use Outlook 2013 with no problem.
I watched the log and this is what it says when this user attempts to send email
replacing command "RCPT TO: <myemail@gmail.com> NOTIFY=SUCCESS,FAILURE,DELAY" with "RCPT TO: <myemail@gmail.com> NOTIFY=SUCCESS,FAILURE,DELAY NOTIFY=NEVER"

I've checked for any Outlook rules that could be adding headers, disabled email virus scanner, re-added account, etc.
I've been reading and it appears that NOTIFY=NEVER can not be mixed with any other NOTIFY commands
I have a smtpd_command_filter setup like this
/^(RCPT\s+TO:<.*>.*)\s+NOTIFY=\S+(.*)/ $1 NOTIFY=NEVER$2
/^(RCPT\s+TO:.*)/                    $1 NOTIFY=NEVER

I'm not good with regular expressions but I'm guessing it's not parsing the original command correctly and is adding NOTIFY=NEVER to the end instead of replacing it.
In the meantime I have commented that out, which sends a "your message has been sucessfully delivered" notice back to the sender. I silenced that by adding
smtpd_discard_ehlo_keywords = silent-discard, dsn
to main.cf
Are my new settings okay or do I need to fix the original problem, which I'm guessing is in the regular expression? Any ideas?

A:
I've been reading and it appears that NOTIFY=NEVER can not be mixed with any other NOTIFY commands

For reference, it defined in RFC 1891 Section 5.1

A RCPT command issued by a client may contain the optional esmtp-keyword "NOTIFY", to specify the conditions under which the SMTP server should generate DSNs for that recipient. If the NOTIFY esmtp-keyword is used, it MUST have an associated esmtp-value, formatted according to the following rules, using the ABNF of RFC 822:
notify-esmtp-value = "NEVER" / 1#notify-list-element

notify-list-element = "SUCCESS" / "FAILURE" / "DELAY"

Notes:
a. Multiple notify-list-elements, separated by commas, MAY appear in a NOTIFY parameter; however, the NEVER keyword MUST appear by itself.
b. Any of the keywords NEVER, SUCCESS, FAILURE, or DELAY may be spelled in any combination of upper and lower case letters.

This is your regex (looks like copied from this page)
/^(RCPT\s+TO:<.*>.*)\s+NOTIFY=\S+(.*)/ $1 NOTIFY=NEVER$2
/^(RCPT\s+TO:.*)/                    $1 NOTIFY=NEVER

This is RCPT command string from Outlook 2013
RCPT TO: <myemail@gmail.com> NOTIFY=SUCCESS,FAILURE,DELAY

Above string will match the second line. Why? Because between TO: and <myemail@gmail.com>, there whitespace.  Your first line of regex doesn't contain whitespace between TO: and '<`.
For space between ':' and '<' problem, here what RFC 5321 says

Since it has been a common source of errors, it is worth noting that spaces are not permitted on either side of the colon following FROM in the MAIL command or TO in the RCPT command.  The syntax is exactly as given above.

So, that's why the problem appear locally. Looks like outlook still adding space between after RCPT TO: thus violation RFC spec.
Regex Solution:
Modify the first line of regex, so it become this
/^(RCPT\s+TO:\s*<.*>.*)\s+NOTIFY=\S+(.*)/ $1 NOTIFY=NEVER$2

adding \s* will match string which have zero or more whitespace after RCPT TO:
For explanation how regex works, visit this page.


text:
Q: A function defined by $L^p$ integral is continuous on the boundary Suppose $f$ is a measurable function on $X$, $\mu$ is a positive measure on $X$, and
$$g(p)=\int_X|f|^p d\mu=||f||_p^p, (0<p<\infty)$$
Let $E=\{p|g(p)<\infty\}$. Assume $||f||_\infty >0$.
Prove $g$ is continuous on $E$.
I have proved $g$ is continuous on the interior of $E$. A hint is given that continuity of $g$ on $\partial E$ follows from monotonicity applying to $\chi_{|f|>1}f$ and $\chi_{|f|\le 1}f$.
Could you explain what does it mean and how to use it? I am a little confused about what my target is. I think I need to show if $r\in E$, but $\forall \epsilon>0, r-\epsilon \not\in E$, then $\lim_{p\to r^+}g(p)=g(r)$.

For a proof that $g$ is continuous on the interior of $E$, suppose $r<p<s,r,s\in E$, then $p=tr+(1-t)s$. By Holder's inequality, we know $p\in E$. Rewrite the relation, we have
$$g( tr+(1-t)s)\le g(r)^tg(s)^{(1-t)}$$
Since $x\to \log x$ is increasing, we have $$\log g( tr+(1-t)s)\le t \log(r) +(1-t)\log g(s),\forall t\in(0,1)$$ So $\log g$ is convex in $E^\circ$, so $\log g$ is continuous, hence $g$ is continuous  in $E^\circ$.

A: Let $r\in E$, but $r+\epsilon \not\in E$
Let $p_n \rightarrow r$ with each $p_n \leq r$ and $p_n\in E$.
Then we see that
$|f|^{p_n} $ goes $|f|^{r}$ pointwise a.e.
Using the hint
$$\lim_n \int |f|^{p_n} = \lim_n \int_{\{|f|<1\}} |f|^{p_n} + \lim_n \int_{\{|f|\geq 1\}} |f|^{p_n} $$
Try dominated convergence theorem on $\{|f|<1\}$, and try monotone convergence theorem on $\{|f|\geq 1\}$.


text:
Q: Use Cartan subalgebra in spinor representation to find weights of vector representation For $SO(2n)$ we can construct the lie algebra elements by using antisymmetric combinations of $\gamma_\mu$ which obey the Clifford algebra.
Up to some prefactor the elements $ S_{\mu \nu} = \alpha [\gamma_\mu , \gamma_\nu] $ can be used as generators. Then we can identify the cartan subalgebra with the elements $ H_i = S_{(2i-1)(2i)} $.
Now I would like to use this to find the weights for an element ($A_\mu)$ in the vector representation of $SO(2n)$. For this purpose I used the $\gamma_\mu$ basis and tried to find the weights for $A_\mu \gamma^\mu$.
The problem is that certain elements of the cartan algebra just commute with parts of the $A_\mu \gamma^\mu$ sum. For example:
$H_2 (A_1 \gamma^1) = (2 \alpha \gamma_3 \gamma_4) \cdot (A_1 \gamma^1)  = (2 \alpha ) \cdot (A_1 \gamma^1) \gamma_3 \gamma_4 $
since the commutation of the 2 $\gamma$ gives a factor of $(-1)^2$. Raising and lowering indices is without consequence since the metric for the Clifford algebra is euclidean ( $\delta ^{\mu \nu}$ ).
But this parts should rather go to zero to get a linear action from $H$ on the vector represention.
What is wrong with the approach above? or should it work? Is there a way to justify that the commutation corresponds to a zero element ( or zero weight if it commutes with the wohle $A_\mu \gamma^\mu$)?

A: The problem with this approach is that it mixes up different denotations.
The action of the Cartan subalgebra on the vector representation (or standard representation in math literature) is defined as given above:
\begin{equation}
H_{2}(A_{1}*e_1)
\end{equation}
by matrix multiplication on a vector. Where $e_1$ is a basis vector of the $R^{2n}$.
However, in the question above we do not act on the vector space $R^{2n}$ but rather on the vector space $R^{n \times n}$. The dimension of the matrix-vector space is reduced by the constraints of the Clifford algebra to have also dimension $2n$.
Nonetheless, we are acting with the Cartan Subalgebra not on the standard vector space but on the vector space of the $ n \times n $ matrices. The appropriate action on this vector space is given by the commutator:
\begin{equation}
[H_2, A_1 \gamma^1] = 0
\end{equation}
Then the weights can be read of in the correct way.


text:
Q: Replacement for JSON_ARRAYAGG and JSON_OBJECT from MySQL in v5.6 or PHP I've inherited an old project that runs on MySql 5.6 and Zend FW 2. I'm trying to run a query that will give the same results as JSON_OBJECT() but mysql 5.6 doesn't support that.
Basically I have 2 tables
Receipts -

receipt_id
phone
amount
status

1
7777777777
5682
Success

2
8888888888
4586
Success

3
5555555555
7589
Success

Receipt_Item -

receipt_id
item_id
quantity
price

1
1
23
5682

1
2
30
5682

2
1
10
7589

3
1
23
4355

3
2
41
3665

And need to get this output
[
    {
        "receipt_id": 1,
        "phone": "7777777777",
        "amount": "5682",
        "status": "Success",
        "receipt_item" : [
            {
              "receipt_id" : 1,
              "item_id" : 1,
              "quantity" : 23,
              "price" : 5682
            },
            {
              "receipt_id" : 1,
              "item_id" : 2,
              "quantity" : 30,
              "price" : 5682
            }

        ]
    },
    {
        "receipt_id": 2,
        "phone": "8888888888",
        "amount": "4586",
        "status": "Success",
        "receipt_item" : [
            {
              "receipt_id" : 2,
              "item_id" : 1,
              "quantity" : 10,
              "price" : 7589
            }
        ]
    },
    {
        "receipt_id": 3,
        "phone": "5555555555",
        "amount": "7589",
        "status": "Success",
        "receipt_item" : [
            {
              "receipt_id" : 3,
              "item_id" : 1,
              "quantity" : 23,
              "price" : 4355
            },
            {
              "receipt_id" : 3,
              "item_id" : 2,
              "quantity" : 41,
              "price" : 3665
            }

        ]
    }
]

Due to the version I cannot use JSON_OBJECT(). Is there any other way in sql to get this result.
If not can I post-process this in PHP to combine multiple objects with the same receipt_id and creating an inner array with combined receipt items?
Essentially turning this:
[
    [
        "receipt_id"    => 1,
        "phone"     => "7777777777",
        "amount"    => "5682",
        "status"    => "Success",
        "item_id"     => 1,
        "quantity"      => 23,
        "price"     => 5682
    ],
    [
        "receipt_id"    => 1,
        "phone"     => "7777777777",
        "amount"    => "5682",
        "status"    => "Success",
        "item_id"     => 1,
        "quantity"      => 23,
        "price"     => 5682
    ],
]

into this
[
    [
        "receipt_id"    => 1,
        "phone"    => "7777777777",
        "amount"    => "5682",
        "status"    => "Success",
        "receipt_item"     => [
            [
              "item_id"     => 1,
              "quantity"     => 23,
              "price"     => 5682
            ],
            [
              "item_id"     => 2,
              "quantity"     => 30,
              "price"     => 5682
            ]

        ]
    ],
]

In PHP I can use array_unique() and array_column(), and then loop through the original array to get the result. But is there an in-built way to get there?
Thanks.

A: You can aggregate data on PHP side using array_reduce:
$output = array_reduce(
    $input,
    function($acc, $r) {
        if (!isset($acc[$r["receipt_id"]])) {
            $acc[$r["receipt_id"]] =  [
                "receipt_id"    => $r["receipt_id"],
                "phone"         => $r["phone"],
                "amount"        => $r["amount"],
                "status"        => $r["status"],
                "receipt_item"  => []
            ];
        }

        $acc[$r["receipt_id"]]["receipt_item"][] = [
            "item_id"  => $r["item_id"],
            "quantity" => $r["quantity"],
            "price"    => $r["price"]
        ];
        return $acc;
    },
    []
);

run PHP online


text:
Q: Magento 2 - Wysiwyg Images Not Showing in Custom Product Attributes Using Text Area I have created a website that uses several custom product attributes which are text areas. The content pulls through just fine with the exception of the images which were placed in the text areas using the Wysiwyg Editor.
I have found a number of solutions online, non of which have had an effect and I am fairly sure the issue is likely to me not calling the attributes correctly.
The code I am using the the phtml file is:
<?php
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_product = $block->getProduct();
$_code = $block->getAtCode();
$_className = $block->getCssClass();
$_attributeLabel = $block->getAtLabel();
$_attributeType = $block->getAtType();
$_attributeAddAttribute = $block->getAddAttribute();
if ($_attributeLabel && $_attributeLabel == 'default') {
  $_attributeLabel = $_product->getResource()->getAttribute($_code)->getFrontendLabel();
}
$_attributeValue =$_product->getResource()->getAttribute($_code)->getFrontend()->getValue($_product);
?>

<?php if ($_attributeValue): ?>

        <?php if ($_attributeLabel != 'none'): ?><?php echo $_attributeLabel?><?php endif; ?>
        <div class="value" <?php echo $_attributeAddAttribute;?>><?php echo $_attributeValue; ?>

<?php endif; ?>

<?php

$dimensions = $_product->getResource()->getAttribute('dimensions')->getFrontend()->getValue($_product);
$features_benefits = $_product->getResource()->getAttribute('features_benefits')->getFrontend()->getValue($_product);
$flooring_specification = $_product->getResource()->getAttribute('flooring_specification')->getFrontend()->getValue($_product);
$timber_grades = $_product->getResource()->getAttribute('timber_grades')->getFrontend()->getValue($_product);
$profiles_available = $_product->getResource()->getAttribute('profiles_available')->getFrontend()->getValue($_product);
$specification = $_product->getResource()->getAttribute('specification')->getFrontend()->getValue($_product);

if (!empty($dimensions) || !empty($features_benefits) || !empty($flooring_specification) || !empty($timber_grades) || !empty($profiles_available) || !empty($specification)) {
    ?>
    <?php
    if (!empty($dimensions)) {
        ?>

Dimensions

        <?php echo $dimensions; ?>
        <?php
    }
    if (!empty($features_benefits)) {
        ?>

Features & Benefits

        <?php echo $features_benefits; ?>
        <?php
    }
    if (!empty($flooring_specification)) {
        ?>

Specification

        <?php echo $flooring_specification; ?>
        <?php
    }
    if (!empty($timber_grades)) {
        ?>

Timber Grades

        <?php echo $timber_grades; ?>
        <?php
    }
    if (!empty($profiles_available)) {
        ?>

Profiles

        <?php echo $profiles_available; ?>
        <?php
    }
    if (!empty($specification)) {
        ?>

Specification

        <?php echo $specification; ?>
        <?php
    }
    ?>
    <?php
}
?>

The issue can be seen on this page:
https://www.blueprintdoorsandfloors.co.uk/solid-oak-3-ledged-braced-cottage-door
When inspecting the code the issue can be seen as the image path not being generated correctly:

Has anyone else encountered this issue, or one similar, and found a solution.
Any assistance or advice would be appreciated as this has been baffling me for a few days now on and off.
The site is running Magento 2.2.5 Community Edition
Thanks
Kev


text:
Q: Should I upgrade from Symfony 1.2.9 to 1.4 I am a few weeks from hopefully launching my site (Yes, I know like I may be tempting fate, even merely asking this question).
I am developing using SF 1.2.9 (using Propel ORM), but I am increasingly being tempted to upgrade to 1.4, least of all, I feel it will be less of an effort to migrate a life system from 1.4 to 2.0 later on, than from 1.2 to 1.4. Also, IIRC, active support for 1.2 is being phased out next year, whereas 1.4 is to be supported till 2012 (IIRC).
So, shall I bite the bullet and upgrade, or shall I take the (on the face of it - safer) option and stay put with 1.2.9?

A: If you want to use some of the new features, you should upgrade of course. As the symfony development is test driven, I assume the new versions are stable and reliable.
But: Do not upgrade to 1.4 but to version 1.3. The later has an extra compatibility layer to ensure that projects based on 1.2 still work. There are some internal changes in 1.4 that forces you to really refactor some parts of your project to keep it working. With 1.3 you can make this changes step by step.
The only differences between 1.3 and 1.4 is this compatibility layer. For specific instructions, read this upgrade guide.
As for support, 1.3 is supported until the end of next year which gives you plenty of time to upgrade to 1.4 step by step.
And in general I belief also that upgrading from 1.4 to 2.0 will be easier than from 1.2.
Edit:
You can find the changes here and the deprecated stuff here.
I don't know if 'internal changes' was the right word. There is some stuff you have to consider if you change to 1.4 but the deprecated stuff in 1.4 still works in 1.3.
I will try to upgrade one of my projects to 1.3 this weekend and I can give you feedback somehow if you want to.

A: Are their any compelling reasons for the upgrade? Does version 1.4 have more bug fixes, or additonal features that your appliation must have? Are their any breaking changes between 1.2.9 and 1.4? Is there any refactoring to do after you've upgraded to 1.4 from 1.2.9?
I'm looking at this from a .net framework perspective;
.net 1.1 to 2.0 - there were many changes here. many of them were breaking changes, but the benefits of the upgrade were great.
.net 2.0 to 3.0 or 3.5 - a lot of upgrades were introduced here, but not very many if any breaking changes since the last two upgrades were based on the same basic framework. You can live with the 2.0 version without upgrading to any of the other two.
So if the Symfony upgrade is similiar, I would wait for a little while. You've got your application built, tested and ready to go. See what it takes for the upgrade and then see about integrating the new features in during the next iteration of your development.
Good luck with your site, and hope this helps some.


text:
Q: Writing Bengali in latex I'm new comer in this community. When i'm going to compile this,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% !TEX TS-program = XeLaTeX

\documentclass[10pt]{article}
\usepackage{polyglossia}
\setmainlanguage[numerals=Devanagari]{bengali}
\setotherlanguage{english}
\newfontfamily\englishfont[Scale=MatchLowercase]{Linux Biolinum O}
\newfontfamily\bengalifont[Script=Bengali]{Akaash}
\begin{document}
\tableofcontents

\section{ভূমিকা}
এটি একটি ইংরেজি লেখা ছোট অধ্যায় যে বাঙ্গালী এ \textenglish{Google Translate} দ্বারা অনুবাদ করা হয়েছে. এটা খুব স্পষ্ট নয় যদি সঠিক অনুবাদ বা না কিন্তু ক্রিয়াটি ফন্ট দেখাতে যথেষ্ট হওয়া উচিত.
\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Following message is showing. Few months ago that did not happen.
This is XeTeX, Version 3.14159265-2.6-0.99996 (MiKTeX 2.9)
entering extended mode
(D:/Latex/ben.tex
LaTeX2e <2016/03/31> patch level 3
Babel <3.9r> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files (x86)\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files (x86)\MiKTeX 2.9\tex\latex\base\size10.clo"))
("C:\Program Files (x86)\MiKTeX 2.9\tex\latex\polyglossia\polyglossia.sty"
(D:/Latex\etoolbox.sty) (D:/Latex\makecmds.sty)
("C:\Program Files (x86)\MiKTeX 2.9\tex\latex\xkeyval\xkeyval.sty"
("C:\Program Files (x86)\MiKTeX 2.9\tex\generic\xkeyval\xkeyval.tex"
("C:\Program Files (x86)\MiKTeX 2.9\tex\generic\xkeyval\xkvutils.tex"
("C:\Program Files (x86)\MiKTeX 2.9\tex\generic\xkeyval\keyval.tex"))))
("C:\Program Files (x86)\MiKTeX 2.9\tex\latex\fontspec\fontspec.sty"
(D:/Latex\expl3.sty
(C:\Users\kausani\AppData\Roaming\MiKTeX\2.9\tex\latex\l3kernel\l3names.sty
*****************************************************************
**
** Package l3names is obsolete and has been removed!
**
** Its functionality is now only provided as part of the expl3 package.
**
** After showing you an error message you can hit <return> we will continue
** for now by loading expl3 for you. However, the old packages will be
** removed entirely at the end of 2017.
**
** Therefore, please replace '\usepackage{l3names}'
** with '\usepackage{expl3}' in your documents as soon as possible.
**
*******************************************************************

! Package l3names Error: This package is obsolete --- use 'expl3' instead.

See the l3names package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.45   \@ehc

?

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

What have I to do?

A: "C:\Program Files (x86)\MiKTeX 2.9\tex\latex\fontspec\fontspec.sty"
(D:/Latex\expl3.sty

You are pulling most of your packages from the standard miktex place but you have an old local copy of expl3 in D:/Latex\expl3.sty you want to remove (or move) that copy and let latex find the current copy of expl3 from the standard miktex input  tree.
(You are also getting etoolbox and some other packages from d:\latex which would be better if they came from the standard input path so that you get the current versions)


text:
Q: how to put text on image bitmap at bottom? What I Want: I want to add text at bottom of a image which I have chose from either gallery or camera.
Original Image

I added blue color strip to image at bottom

In that strip, I want to add some text exactly in middle.
What's the Problem:

*

*I'm unable to position text exactly in middle of blue color strip.

*For different images, text size changes. Some time it is very small, some time it is very big.

What I Tried: My code is like below.
MainActivity.java
    public class MainActivity extends AppCompatActivity {

    private ImageView mImageView;

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

        mImageView = findViewById(R.id.imageView);
    }

    public void openGallery(View view) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 100);
    }

    public void openCamera(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 101);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null && resultCode == Activity.RESULT_OK) {

            if (requestCode == 100) {

                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media
                            .getBitmap(getApplicationContext().getContentResolver(), data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                addStampToImage(bitmap);

            } else if (requestCode == 101) {

                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                addStampToImage(bitmap);
            }
        }
    }

    private void addStampToImage(Bitmap originalBitmap) {

        int extraHeight = (int) (originalBitmap.getHeight() * 0.15);

        Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
                originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.BLUE);
        canvas.drawBitmap(originalBitmap, 0, 0, null);

        Resources resources = getResources();
        float scale = resources.getDisplayMetrics().density;

        Paint pText = new Paint();
        pText.setColor(Color.WHITE);
        pText.setTextSize((int) (20 * scale));

        String text = "Maulik";

        /*Rect r = new Rect();
        canvas.getClipBounds(r);
        int cHeight = r.height();
        int cWidth = r.width();
        pText.setTextAlign(Paint.Align.LEFT);
        pText.getTextBounds(text, 0, text.length(), r);
        float x = -r.left;
        float y = cHeight / 2f + r.height() / 2f - r.bottom;

        int minusSpace = (int) (canvas.getClipBounds().bottom * 0.07);

        canvas.drawText(text, 0, canvas.getClipBounds().bottom - minusSpace, pText);*/

        Rect bounds = new Rect();
        pText.getTextBounds(text, 0, text.length(), bounds);
        int x = (newBitmap.getWidth() - bounds.width())/6;
        int y = (newBitmap.getHeight() + bounds.height())/5;

        canvas.drawText(text, x * scale, y * scale, pText);

        mImageView.setImageBitmap(newBitmap);
    }
}

Any help will be appreciated!
Updated: 1st Aug 2018
Changes in addStampToImage method.
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);

Rect textHeightWidth = new Rect();
pText.getTextBounds(fromWhichMode, 0, fromWhichMode.length(), textHeightWidth);

canvas.drawText(textToStamp, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
                originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
                pText);

Above changes giving me text in middle of blue strip. But core ISSUE remains same. i.e Text size changes with respect to different image sizes.

A: Check the  below code:-
private void addStampToImage(Bitmap originalBitmap) {

    int extraHeight = (int) (originalBitmap.getHeight() * 0.15);

    Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
            originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(newBitmap);
    canvas.drawColor(Color.BLUE);
    canvas.drawBitmap(originalBitmap, 0, 0, null);

    Resources resources = getResources();
    float scale = resources.getDisplayMetrics().density;

    String text = "Maulik";
    Paint pText = new Paint();
    pText.setColor(Color.WHITE);

    setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);

    Rect bounds = new Rect();
    pText.getTextBounds(text, 0, text.length(), bounds);

    int x=  ((newBitmap.getWidth()-(int)pText.measureText(text))/2);
    int h=(extraHeight+bounds.height())/2;
    int y=(originalBitmap.getHeight()+h);

    canvas.drawText(text, x, y, pText);

    imageView.setImageBitmap(newBitmap);
}

private void setTextSizeForWidth(Paint paint, float desiredHeight,
                                        String text) {

    // Pick a reasonably large value for the test. Larger values produce
    // more accurate results, but may cause problems with hardware
    // acceleration. But there are workarounds for that, too; refer to
    // http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
    final float testTextSize = 48f;

    // Get the bounds of the text, using our testTextSize.
    paint.setTextSize(testTextSize);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    // Calculate the desired size as a proportion of our testTextSize.
    float desiredTextSize = testTextSize * desiredHeight / bounds.height();

    // Set the paint for that size.
    paint.setTextSize(desiredTextSize);
}

Edit:-
Instead of above addStampToImage method you can also use your updated addStampToImage method like below:-
private void addStampToImage(Bitmap originalBitmap) {

    int extraHeight = (int) (originalBitmap.getHeight() * 0.15);

    Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
            originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(newBitmap);
    canvas.drawColor(Color.BLUE);
    canvas.drawBitmap(originalBitmap, 0, 0, null);

    Resources resources = getResources();
    float scale = resources.getDisplayMetrics().density;

    String text = "Maulik";
    Paint pText = new Paint();
    pText.setColor(Color.WHITE);

    setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);

    Rect bounds = new Rect();
    pText.getTextBounds(text, 0, text.length(), bounds);

    Rect textHeightWidth = new Rect();
    pText.getTextBounds(text, 0, text.length(), textHeightWidth);

    canvas.drawText(text, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
            originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
            pText);

    imageView.setImageBitmap(newBitmap);
}

A: try this one i think help to you
/**
     * FOR WATER-MARK
     */
public static Bitmap waterMark(Bitmap src, String watermark, Point location, int color, int alpha, int size, boolean underline) {
            int[] pixels = new int[100];

            //get source image width and height
            int widthSreen = src.getWidth();   // 1080L // 1920
            int heightScreen = src.getHeight();  // 1343L  // 2387

            Bitmap result = Bitmap.createBitmap(widthSreen, heightScreen, src.getConfig());
            //create canvas object
            Canvas canvas = new Canvas(result);
            //draw bitmap on canvas
            canvas.drawBitmap(src, 0, 0, null);
            //create paint object
            Paint paint = new Paint();
    //        //apply color
    //        paint.setColor(color);
    //        //set transparency
    //        paint.setAlpha(alpha);
    //        //set text size
            size = ((widthSreen * 5) / 100);
            paint.setTextSize(size);
    //        paint.setAntiAlias(true);
    //        //set should be underlined or not
    //        paint.setUnderlineText(underline);
    //
    //        //draw text on given location
    //        //canvas.drawText(watermark, w / 4, h / 2, paint);

            Paint.FontMetrics fm = new Paint.FontMetrics();
            paint.setColor(Color.WHITE);
    //        paint.setTextSize(18.0f);
            paint.getFontMetrics(fm);
            int margin = 5;
            canvas.drawRect(50 - margin, 50 + fm.top - margin,
                    50 + paint.measureText(watermark) + margin, 50 + fm.bottom
                            + margin, paint);

            paint.setColor(Color.RED);
            canvas.drawText(watermark, 50, 50, paint);
            return result;
        }

call this method on your onActivityResult
 Bitmap bitmapp = waterMark(bitmap, your_string, p, Color.RED, 90, 90, true);


text:
Q: Android - Activate the appbar scrolling on a per viewpager recyclerview basis I have a ViewPager with 2 tabs containing a Recyclerview.
I am using support libraries 22.2.0 (AppCompat, Recycler view...).
My viewpager xml is initially :
<android.support.v4.view.ViewPager
   android:id="@+id/viewPager"
   app:layout_behavior="@string/appbar_scrolling_view_behavior"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

I would like to activate/desactivate the appbar scrolling on a per tab/recyclerview basis instead of on whole viewpager basis, that is,
one tab/recyclerview will make the appbar scrolling and the other tab/recyclerview won't.
This issue is that when i remove
app:layout_behavior="@string/appbar_scrolling_view_behavior"

from  viewpager   a default layout_behavior is applied to viewpager which still activates appbar scroll on both tab/recyclerview.
My strategy is to desactivate the appbar scrolling in viewpager, maybe something like this :
   <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            app:layout_behavior="@string/appbar_desactivated_behavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

And activate it on my first tab/recyclerview  only. Like this :
<android.support.v7.widget.RecyclerView
    ...
    android:id="@+id/playlist1_rv"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
</android.support.v7.widget.RecyclerView>

But I need a class for "@string/appbar_desactivated_behavior".
Does it exist? Is not, how to write it? Or do you think about another strategy?
Thanks in advance.

A: If you are using a ViewPager, the appbar_scrolling_view_behavior needs to be set on the ViewPager for proper layout.
All you have to do is turn off nested scrolling in the RecyclerView that you don't want to scroll the app bar:
        recyclerview.setNestedScrollingEnabled(false);

Note that you may have issues with positioning and you may have to put an appbar-sized margin at the bottom of the recyclerview.  And if your user scrolls the appbar up with the other recyclerview then swipes to this recyclerview, there will be a space at the bottom of the page.


text:
Q: Positioning links next to logo on navigation bar Basically what I am doing is trying to get the navigation links to be centered in the middle of the navigation bar. I read up a little that float: left; may affect positioning of divs that are right next to it. So my question is there any solutions to get the navigation links in the middle of the navigation bar?

@import url(http://fonts.googleapis.com/css?family=Oswald);
 * {
  margin: 0;
  padding: 0;
}
/* Navigation Styles */

.nav {
  height: 80px;
  background-color: #ffffff;
  border-bottom: 1px solid #aeaeae;
  position: fixed;
  width: 100%;
}
.logo h2 {
  float: left;
  padding-left: 70px;
}
.logo a {
  text-decoration: none;
  color: #9595a2;
  font-size: 50px;
  font-family: 'Oswald', sans-serif;
  -webkit-transition-property: color, text;
  -webkit-transition-duration: .1s, .1s;
  -webkit-transition-timing-function: linear, ease-in;
  -moz-transition-property: color, text;
  -moz-transition-duration: 1s;
  -moz-transition-timing-function: linear, ease-in;
  -o-transition-property: color, text;
  -o-transition-duration: 1s;
  -o-transition-timing-function: linear, ease-in;
}
.nav .logo a:hover {
  color: red;
}
.nav-links {
  float: right;
}
.nav-links ul {} .nav-links li {
  display: inline;
  list-style-type: none;
}
.nav-links a {
  padding-top: 30px;
  padding-right: 40px;
  text-decoration: none;
  font-family: 'Oswald', sans-serif;
  color: #9595a2;
  font-size: 20px;
}
/* About Styles */

.about {
  height: 880px;
  background-color: #dddddd;
  -moz-box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
  -webkit-box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
  box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
}
.about h2 {
  font-size: 50px;
  padding-top: 105px;
  text-align: center;
  color: red;
  font-family: 'Oswald', sans-serif;
}

  <title>Moises Cortez | Graphic Designer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/style.css" />

Moises

About

Portfolio

Skills

Contact

About

A: Anchor tag in HTML are inline elements. To be able to give them margin or padding. You must display block or inline-block to make anchors a block level element.
CSS
.nav-links a{
  display: inline-block;
}

Add that CSS line to your existing selector.

A: Given the requirements, you can use display:table; and display:table-cell to the children elements in the menu. Then add vertical-align:middle to each table-cell element. This approach will avoid you any calculation on margin and padding and it will be easy to vertical align each element.

*

*I suggest you to create another wrapper inside .nav, called
.nav-wrapper.

*Set .nav-wrapper as display:table; with height and width at 100%.

*Set .nav-link and .logo as display:table-cell; vertical-align:middle; so to vertical-align both.

*Remove padding top from the links and display each link as display:inline-block;
CHECK DEMO

@import url(http://fonts.googleapis.com/css?family=Oswald);
 * {
  margin: 0;
  padding: 0;
}
/* Navigation Styles */

.nav {
  height: 80px;
  background-color: #ffffff;
  border-bottom: 1px solid #aeaeae;
  position: fixed;
  width: 100%;
}
.nav-wrapper{
  display:table;
  height:100%;
  width:100%;
}
.logo{
  display:table-cell;
  vertical-align:middle;
}

.logo h2 {
  float: left;
  padding-left: 70px;
}
.logo a {
  text-decoration: none;
  color: #9595a2;
  font-size: 50px;
  font-family: 'Oswald', sans-serif;
  -webkit-transition-property: color, text;
  -webkit-transition-duration: .1s, .1s;
  -webkit-transition-timing-function: linear, ease-in;
  -moz-transition-property: color, text;
  -moz-transition-duration: 1s;
  -moz-transition-timing-function: linear, ease-in;
  -o-transition-property: color, text;
  -o-transition-duration: 1s;
  -o-transition-timing-function: linear, ease-in;
}
.nav .logo a:hover {
  color: red;
}
.nav-links {
  display:table-cell;
  vertical-align:middle;
  text-align:right;
}
.nav-links li {
  display: inline-block;
  list-style-type: none;
}
.nav-links a {
  padding-right: 40px;
  text-decoration: none;
  font-family: 'Oswald', sans-serif;
  color: #9595a2;
  font-size: 20px;
}
/* About Styles */

.about {
  height: 880px;
  background-color: #dddddd;
  -moz-box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
  -webkit-box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
  box-shadow: inset 0 8px 8px -8px #193047, inset 0 -8px 8px -8px #193047;
}
.about h2 {
  font-size: 50px;
  padding-top: 105px;
  text-align: center;
  color: red;
  font-family: 'Oswald', sans-serif;
}

  <title>Moises Cortez | Graphic Designer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/style.css" />

Moises

About

Portfolio

Skills

Contact

About