text:
Q: Print a matrix without row and column indices
If I print a matrix, it is shown with row and column indices in the console. E.g.
> print(diag(3))
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

How can I suppress the column and row indices? I.e. something like this:
> print(diag(3), indices=FALSE)
1    0    0
0    1    0
0    0    1

I can see that the cwhmisc package should contain a printM function to do this according to the documentation but it is not there when I load cwhmisc. Also, this seems like something you should be able to to in base R.

A: The function prmatrix in the base package could work for this, it can take the arguments collab and rowlab:
prmatrix(diag(3), rowlab=rep("",3), collab=rep("",3))

 1 0 0
 0 1 0
 0 0 1

A: Another solution with function write.table
write.table(diag(3), row.names=F, col.names=F)

You can make it prettier by separating the columns with a tabulation
write.table(matrix(sample(1000,9),3,3), row.names=F, col.names=F, sep="\t")


text:
Q: Typescript can't see declared class on a compile stage but can at the end Typescript can see my class that I declared in .d.ts file, but not when it's doing a compile
I declared a class in .d.ts
declare class Handlebars {
static compile(s: string): (a: object) => string;
}

And added that file to configurations, so main file can see the class
{
"compilerOptions": {
  "allowJs": false
},
"files": [
    ".d.ts",
    "index.ts"
]
}

A: Try this. You don't import Handlebars so it can't use it.
.d.ts
declare class Handlebars {
    static compile(s: string): (a: object) => string;
}

export { Handlebars };

index.ts
import { Handlebars } from "./.d";

let template = Handlebars.compile("text");
console.log(template({ doesWhat: "rocks" }));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Electron wavelength vs. light(s) wavelengths I am doing some research into wave and waveform. I am looking at different types of microscopy for potential purchase.  However, I came across Max Knoll a minute ago and I am curious as to how electron wavelengths are shorter than light waves?  Aren't electrons [themselves] "light waves" as pertains to physics?  Anyway, my inquiry specific pertains to a Max Knoll quote:

Using electrons, which have a far shorter wavelength than light, it was possible to resolve individual objects at a far greater magnification. Four years later, Max Knoll discovered a means to sweep an electron beam over the surface of a sample, creating the first scanning electron microscope (SEM) images.

Additionally, I am trying to find differences in wavelength between light from the sun vs. light from thunderbolts.
Any help is much appreciated.

A: Electrons are not "light waves as pertains to physics". You maybe thinking about the interaction between charged particles (like electrons) and photons in the context of quantum electrodynamics.
But since electrons are quantum mechanical objects, they will have wavelike properties. Their wavelengths can be computed from their momentum using the De Broglie relation $$\lambda=\frac{h}{p}$$ and the electron De Broglie wavelengths in SEMs are $\approx 1$ Angstrom or $10^{-10}$m typically.
Visible light however has wavelengths in the range $380-700$nm which are about $5000$ times larger than these electron wavelengths.
So by accelerating a beam of electrons so that they have high enough momentum/energy, their wavelengths will become  smaller (as can be seen from the equation above) than the wavelengths of visible light.
This will then allow the SEM to resolve objects smaller than what visible light would do.

A: Visible light ranges in wavelength from a bit less than 400 nanometers to somewhere around 700 nanometers or a bit more (it's not possible to be more precise, because the word "visible" is already a bit vague).  Ultraviolet light ranges in wavelength from 400 nanometers down to somewhere between 10 and 100 nanometers (depending on whose definitions you prefer).  The wavelength of an electron is about 1/10 of a nanometer.

A: We must remember that the electrons were first postulated as particles from experiments on cathode rays in the end of the $19^{th}$ century. They were the so called beta rays. The fact that those rays have mass and charge, and the first modelling of atoms lead us to the intuition of small particles.
But the beta rays had optical properties similar to x-rays, penetrating human tissues and allowing to photograph inner portions of matter. It is not so surprising that they have a wave length as x-rays have. The difference is that they are massive and charged radiation.

A: This is a long comment on aspects not touched by the other answers.

Aren't electrons [themselves] "light waves" as pertains to physics?

No, they are not. In this answer of mine I show the experiments that demonstrate clearly that elementary particles as the photon and electron , do not show individually a wave property. At the particle level, what is showing a sinusoidal distribution is the accumulation of ensembles of particles, the probability of appearing in an interaction, dependent on their quantum mechanical wavefunction.
Electrons are elementary particles obeying  quantum mechanical equations and their ensemble behavior shows wave properties with the frequencies discussed in the other answers. These wave properties are used for electron microscopy.
"Light waves" are huge ensembles of photons that build up the classical Maxwell electromagnetic wave.
So ensembles of electrons, electron beams, have wave properties, but electron beams are not "light waves".

Additionally, I am trying to find differences in wavelength between light from the sun vs. light from thunderbolts.

The wavelength/frequency of light identifies it uniquely. There is no difference due to the source of light.


text:
Q: how to convert kannada to romanised english ? is there a tool to do that how  to  convert Kannada script or romanised English (Kannada) into English . can someone guide me with this
here is an example
ಸುಸ್ವಾಗತ
in roamnised english :
suswagatha
After transliteration:
welcome
There are so many online tools are there to do the conversion from romanised English to Kannada . is there any tool to do the opposite ?
converting Kannada to romanised English text

A: You can use google translator for it https://translate.google.com/

A: I found a website where you can convert kannada script to english . here you have multiple ways to convert . You can use rest api calls to the webapp or you can go through browser .
Bramhinet from IITB
Here You have to select

*

*input language : Kannada

*output language : English

*Script conversion

*input kannada Script text

*press convert

A: What you called "romanization" is actually "transliteration". Here's Kannada to Latin script using ICU4J library in Groovy:
@Grab(group='com.ibm.icu', module='icu4j', version='58.2')
import com.ibm.icu.text.Transliterator;

String anything = "ಸುಸ್ವಾಗತ";
String id = "Kannada-Latin";

println Transliterator.getInstance(id).transform(anything);

Outputs:
susvāgata


text:
Q: Как мне вывести canvas на задний фон Использовал библиотеку канваса particles.js, все подключил, канвас идеально отображается. Вот только канвас занял всю страницу, закрыв доступ к заветным кнопкам на сайте.

 particlesJS("particles-js", {
    particles: {
      number: { value: 101, density: { enable: true, value_area: 850 } },
      color: { value: "#ffffff" },
      shape: {
        type: "circle",
        stroke: { width: 0, color: "#000000" },
        polygon: { nb_sides: 3 },
        image: { src: "img/github.svg", width: 100, height: 100 }
      },
      opacity: {
        value: 1,
        random: false,
        anim: { enable: false, speed: 1, opacity_min: 0.1, sync: false }
      },
      size: {
        value: 1.5,
        random: true,
        anim: { enable: false, speed: 40, size_min: 0.1, sync: false }
      },
      line_linked: {
        enable: true,
        distance: 150,
        color: "#ffffff",
        opacity: 0.4,
        width: 1
      },
      move: {
        enable: true,
        speed: 6,
        direction: "none",
        random: false,
        straight: false,
        out_mode: "out",
        bounce: false,
        attract: { enable: false, rotateX: 600, rotateY: 1200 }
      }
    },
    interactivity: {
      detect_on: "canvas",
      events: {
        onhover: { enable: true, mode: "repulse" },
        onclick: { enable: false, mode: "push" },
        resize: true
      },
      modes: {
        grab: { distance: 400, line_linked: { opacity: 1 } },
        bubble: { distance: 400, size: 40, duration: 2, opacity: 8, speed: 3 },
        repulse: { distance: 70, duration: 0.4 },
        push: { particles_nb: 4 },
        remove: { particles_nb: 2 }
      }
    },
    retina_detect: true
  });
body {
  margin: 0;
  font: normal 75% Arial, Helvetica, sans-serif;
}
canvas {
  display: block;
  vertical-align: bottom;
} /* ---- particles.js container ---- */
#particles-js {
  position: fixed;
  width: 100%;
  height: 100%;
  background: transparent;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
}

 ##В коде страницы отображается так:

<canvas class="particles-js-canvas-el" style="width: 100%; height: 100%;" width="1349" height="424"></canvas>

  ##

Откуда появился новый class="particles-js-canvas-el" и как его поставить на фон

A: Попробуйте указать валидный селектор particlesJS("#particles-js", {}), скорее всего библиотека не находит элемент и создает свой в конце страницы
Либо через css с указанием z-index

A: Если particles.js, отработал и canvas отображается, и проблема просто в стилях.
То решить проблему перекрытия, наверняка, можно с помощью CSS.
Попробуйте поиграться со свойством z-index для элементов на странице. Оно как раз отвечает за порядок наложения элементов. Следует заметить что оно влияет только на элементы со свойством position установленным например в absolute, fixed или relative..
К сожалению я не вижу всей верстки. И трудно дать точный ответ.
Но возможно подойдет такая конструкция: #particles-js { z-index: -1; ...}.
Что касается элемента <canvas class="particles-js-canvas-el" ...>/canvas> то этот элемент создается библиотекой particles.js, и лучше не привязывать стили или скрипты к нему, можно считать его - закрытой внутренней реализацией данной библиотеки.


text:
Q: How to create interface of object with predefined keys? I have object with data:

const data = [
      {
        type: 'soccer',
        price: '$10'
      },
      {
        type: 'running',
        price: '$5'
      },
      {
        type: 'hockey',
        price: '$15'
      }
    ]

I want to convert it to object where key will be item.type:

const parsedData = {
  soccer: {
    type: 'soccer',
    price: '$10'
  },
  running: {
    type: 'running',
    price: '$5'
  },
  hockey: {
    type: 'hockey',
    price: '$15'
  }
}

I've defined enum with types: enum GameTypes { 'soccer', 'running', 'hockey' }. And when I trying to use enum as key of object I'm getting error:
Element implicitly has an 'any' type because expression of type 'GameTypes' can't be used to index type 'GameProducts'.
  Property '[GameTypes.lottery]' does not exist on type 'GameProducts'.ts(7053)
Full code:

enum GameTypes { 'soccer', 'running', 'hockey' }

type Game = {
  type: GameTypes
  price: string
}

type GameProducts = { [key in GameTypes]?: Game } | {}

const data: Array<Game> = [
  {
    type: 'soccer',
    price: '$10'
  },
  {
    type: 'running',
    price: '$5'
  },
  {
    type: 'hockey',
    price: '$15'
  }
]

// trying to format games in object
const formatGames: GameProducts = data.reduce((acc | {}, item) => {
    if (!acc[item.type]) {  // <-- error here
      acc[item.type] = []
    }
    acc[item.type].push(item)

    return acc
  }, {})

What I'm doing wrong? Any other ways to do it?

A: There's a few issues to resolve:

*

*GameProduct is not defined, which should probably be replaced by Game

*GameProducts is map to an array and not a simple object

*for the reducer to understand the code, and lint it appropriately, it's easier to use immutable code like below

*Use need to use the mapping GameTypes['some_value'] for the transpiler to acknowledge your code.

enum GameTypes { 'soccer', 'running', 'hockey' }

type Game = {
  type: GameTypes
  price: string
}

type GameProducts = { [key in GameTypes]?: Game[] };

const data: Array<Game> = [
  {
    type: GameTypes['soccer'],
    price: '$10'
  },
  {
    type: GameTypes['running'],
    price: '$5'
  },
  {
    type: GameTypes['hockey'],
    price: '$15'
  }
]

// formatting games object
const formatGames: GameProducts = data.reduce((acc: GameProducts, item) => {
    if (!acc[item.type]) {
        acc[item.type] = [];
    }

    acc[item.type] = [
        ...(acc[item.type] || []),
        item
    ];

    return acc
}, {});

console.log(formatGames);

You can also alternatively use:
enum GameTypes { Soccer = 'soccer', Running = 'running', Hockey = 'hockey' }

const data: Array<Game> = [
  {
    type: GameTypes.Soccer,
    price: '$10'
  }
]

Or a simpler solution:
type GameTypes = 'soccer' | 'running' | 'hockey';

const data: Array<Game> = [
  {
    type: 'soccer',
    price: '$10'
  }
]

Which would work just as fine.


text:
Q: How to properly quit Excel I am trying to print a receipt from Excel but unable to do so. I have tried release in reverse but I seems can't find what is missing. Kindly help! Thank you!
This is what i have done so far :
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

#Region "dim"
    Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
    Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "SampleReceipt.xls")
    Dim app As Excel.Application = Nothing
    Dim books As Excel.Workbooks = Nothing
    Dim book As Excel.Workbook = Nothing
    Dim sheets As Excel.Sheets = Nothing
    Dim sheet As Excel.Worksheet = Nothing
    Dim cell As Excel.Range = Nothing
#End Region

    Private Sub NAR(ByVal o As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
        Catch ex As Exception
            o = Nothing
        Finally

        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            app = New Excel.Application()
            books = app.Workbooks
            book = books.Open(xlPath)
            sheets = book.Sheets
            sheet = book.Sheets(1)
            cell = sheet.Range("A1")
            cell.Value = "Lorem Ipsum"
            book.SaveAs("C:\Temp\ExcelBook.xls")
            book.Close()
            app.Quit()
        Finally
            NAR(cell)
            NAR(sheet)
            NAR(sheets)
            NAR(book)
            NAR(books)
            NAR(app)
        End Try
    End Sub
End Class

A: This is a bit of a guess, but I don't think your NAR method is doing the job perfectly well.
You have this:
Private Sub NAR(ByVal o As Object)
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
    Catch ex As Exception
        o = Nothing
    Finally

    End Try
End Sub

Now, if you have an Exception raised by ReleaseComObject then you're just swallowing it - I would think that you want to see what the exception is. You really should only handle exceptions that you can recover from. Handling the top-level Exception really is an anti-pattern. So if ReleaseComObject is raising an exception then find out what it is and deal with that specifically.
Next, if you do have an exception you are then trying to set the reference to Nothing, but you're only setting a copy of the reference to Nothing. You're passing in o using ByVal. The original reference is untouched. You want to pass it in ByRef. Try that.
Also, It might be required that you set the reference to Nothing after releasing the component - so move it out of the Catch.
And finally, the help docs on ReleaseComObject says this:

If you want to call this method to ensure that a COM component is released at a determined time, consider using the FinalReleaseComObject method instead. FinalReleaseComObject will release the underlying COM component regardless of how many times it has re-entered the CLR. The internal reference count of the RCW is incremented by one every time the COM component re-enters the CLR. Therefore, you could call the ReleaseComObject method in a loop until the value returned is zero. This achieves the same result as the FinalReleaseComObject method.

I'd try those three things.
Try this code:
Private Sub NAR(ByRef o As Object)
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o)
    o = Nothing
End Sub

And, only put in exception handling if you have a specific exception to handle, but keep the o = Nothing out of the handling code.


text:
Q: Modifying attributes in XML file with Python I am very, very new to Python so please be kind!
I have created a test file in XML which has a list of fake customers and their associated telephone numbers. This was manually produced and took a fair while! I'm hoping to create an automated solution in Python to replace the first digit of the customer_ID (stored as an attribute within the XML) and generate a new XML.
After a few hours reading and developing here is my code;
# Python code for test data generation

import re
import xml.etree.ElementTree as ET
tree = ET.parse('Junk\\Test_File.xml')

root = tree.getroot()

for child in tree.iter():
Cust_ID = re.findall('([0-9]{10})', child.text)
A = [Cust_ID.replace(Cust_ID[0],'1') for Cust_ID in Cust_IDs]

print(A)

tree.write('Junk\\New.xml')

So far I can isolate the list of Customer IDs as Cust_ID and replace the first digit as required. My issue is writing these new values in my output.
Given how junior I am to this code I'm not 100% I'm on the right path so any pointers to a more complete solution (if there is one) would also be appreciated.
Many thanks

A: These day most people use libraries you have a number of choices.
2 I've used

*

*LXml

*CElementTree
import xml.etree.cElementTree as ET

root = ET.Element("root")
file = ET.SubElement(root, "file")

ET.SubElement(file, "fieldone", name="1").text = "something1"
ET.SubElement(file, "field2two", name="2").text = "something2"

tree = ET.ElementTree(root)
tree.write("file.xml")

Here are some useful documentation links
http://lxml.de/tutorial.html
http://effbot.org/zone/element-index.htm
https://docs.python.org/3/library/xml.etree.elementtree.html
Be aware xml.etree.ElementTree isn't secure


text:
Q: Dropdown in Nav bar not working with Bootstrap and Angular I am learning Angular and Bootstrap.  I have some code generated by Yeoman and I have a situation where normal links in my Nav bar are working fine.  However, drop down items are not working (the drop down appears in the nav bar but does not expand when clicked).  As you can see, I have put my navbar code into the view itself.
The interesting part is that the nav bar code will actually work when it is in the container (e.g. index.html).
The question I have is why isn't my navbar code working as expected in the view where it works fine in the container?
Here is my navbar code within the view with Nav bar drop down not working (important to note that the other nav bar items seem to be working fine):

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>
        Brand

Home

Profile

                Messages

Inbox

Drafts

Sent Items

Trash

                 Admin

Log out

Another action

Settings

'Allo, 'Allo

    Always a pleasure scaffolding your apps.

Splendid!

HTML5 Boilerplate

    HTML5 Boilerplate is a professional front-end template for building fast, robust, and adaptable web apps or sites.

Angular

    AngularJS is a toolset for building the framework most suited to your application development.

Karma

Spectacular Test Runner for JavaScript.

 from the Yeoman team

This is the code for my container (index.html) as generated by Yoeman. The nav bar code should be the same as above.
<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />

    <link rel="stylesheet" href="styles/main.css">

To test, I am using Chrome and I don't see any errors coming through the console.  I am using Bootstrap 3.
Thanks for your help.
Regards,
Gaj

A: You might try tightening up the relationship between dropdown-toggle and dropdown-menu. I think jQuery first looks for data-parent, then href to act. Add an id to menu and point to it from toggle
Messages

I would just use href (because as they say every anchor should always have an href)


text:
Q: can i deploy my GWT/MGWT application with phoneGap for IOS without MAC I have my GWT/Mgwt application
-I created my Android Setup Project
-Compiled my GWT project , Placed compiled GWT output into www folder of my Android Setup project with cordova , And Everything's fine , I can see my GWT project on my Android mobile.

Now I want to deploy my same GWT project on my Iphone .
The setps i see they require a MAC
http://docs.phonegap.com/en/1.7.0/guide_getting-started_ios_index.md.html#Getting%20Started%20with%20iOS
But I'm also reading somewhere by different people that with PhoneGap You don't need to have Mac , one can deploy phoneGap Application on Iphone without MAC.
Please confirm is this Valid for GWT phoneGap Applications ?
Is there anyway I can change my GWT Web application to Iphone APP without having MAC machine.
I really need to get it confirmed before going to purchase MAC Machine
thanks

A: @junaidp,

*

*I don't know much about GWT, but it appears to be yet another construction framework

*You don't need a Mac to create a iOS App, you can use PG Build (Phonegap Build) instead of using a Mac.

*but you will need an iOS device for testing. I recommend using an iPodTouch, they are about $200

*You will need to Apple $100/year to be a developer. I have found no way around this.

*After you pay Apple then you can get your Apple Certificates for your iOS devices. You can only get the certificates from Apple.

*You will need the certificate, whether you used the CLI (Command Line Interface) or PG Build.

*You cannot deploy (test) on an iOS device with an App that does not
have a certificate.

These articles should help
Explanation of PhoneGap/Cordova for the Layman
https://iphonedevlog.wordpress.com/2014/06/24/using-cordova-3-5-cli-on-mac-os-x-mavericks-to-build-ios-apps/
Using Cordova 5.0 CLI on Mac OS X Mavericks to build iOS apps (5/2015)
https://iphonedevlog.wordpress.com/2014/06/24/using-cordova-3-5-cli-on-mac-os-x-mavericks-to-build-ios-apps/


text:
Q: If I want to develop php app in linux , which version of linux is best? If I want to develop php app in linux , which version of linux is best?

A: For the most part, PHP will perform identically no matter what flavour of Operating System you are using (there are, of course, minor caveats when dealing with Windows, specifically with regards to file locations, etc.)
Whether you are using Ubuntu, or Fedora, or any other version of Linux, you should not find any major effects on your ability to create PHP applications.
As Justin Ethier says - use whatever Linux version is the fastest and easiest for you to install.


text:
Q: Sendgrid connection refused I am developing a Ruby on Rails 3.2 application on Heroku. I added the sendgrid addon with
heroku addons:add sendgrid:starter

and then restarted with
heroku restart

However, if I try to send a password email in my application (I am using the devise login gem), I get this in the logs
2013-01-24T17:35:37+00:00 app[web.1]: Started POST "/users/password" for xxx.xxx.xxx.xx at 2013-01-24 17:35:37 +0000
2013-01-24T17:35:37+00:00 app[web.1]: Processing by Devise::PasswordsController#create as HTML
2013-01-24T17:35:37+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=", "user"=>{"email"=>"xxxxxxxx.xxxxxx@gmail.com"}, "commit"=>"Send me reset password instructions"}
2013-01-24T17:35:38+00:00 app[web.1]:   Rendered vendor/bundle/ruby/1.9.1/gems/devise-2.2.2/app/views/devise/mailer/reset_password_instructions.html.erb (1.0ms)
2013-01-24T17:35:41+00:00 app[web.1]:
2013-01-24T17:35:41+00:00 app[web.1]: Sent mail to xxx.xxxxx@gmail.com (3080ms)
2013-01-24T17:35:41+00:00 app[web.1]: Completed 500 Internal Server Error in 3311ms
2013-01-24T17:35:41+00:00 app[web.1]:
2013-01-24T17:35:41+00:00 app[web.1]: Errno::ECONNREFUSED (Connection refused - connect(2)):
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:546:in `initialize'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:546:in `open'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:546:in `tcp_socket'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:555:in `block in do_start'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/timeout.rb:58:in `timeout'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/timeout.rb:89:in `timeout'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:555:in `do_start'
2013-01-24T17:35:41+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/net/smtp.rb:525:in `start'
2013-01-24T17:35:41+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/mail-2.4.4/lib/mail/network/delivery_methods/smtp.rb:144:in `deliver!'
2013-01-24T17:35:41+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/mail-2.4.4/lib/mail/message.rb:2034:in `do_delivery'

A: You need to configure ActiveMailer with something like
ActionMailer::Base.smtp_settings = {
  :address        => "smtp.sendgrid.net",
  :port           => "25",
  :authentication => :plain,
  :user_name      => ENV['SENDGRID_USERNAME'],
  :password       => ENV['SENDGRID_PASSWORD'],
  :domain         => ENV['SENDGRID_DOMAIN']
}

and make sure your application has the SENGRID configuration variables in the environment - you can check with heroku config.


text:
Q: Calculate module of "Just int" in Haskell I'm trying to calculate the module of an index of a list.
list=[5,6,7,8]
a = elemIndex 7 list
b = mod a 2

Ideally, this would give me b = 0 since a = 2 (technically).
But I'm getting error messages since a is not 2 but Just 2.

A: You can do this with fmap :: Functor f => (a -> b) -> f a -> f b or its operator variant (<$>) :: Functor f => (a -> b) -> f a -> f b to apply a function to the item wrapped in the Just … data constructor:
b = (`mod` 2) <$> a
this will then return Just 0 when a is Just 2, and Nothing if the elemIndex returned a Nothing. This thus means that if elemIndex fails (because the index is out of range), b will be Nothing.

A: You can just use pattern matching with let to get to the inner part of the Maybe value when it is guaranteed to be Just _:
list = [5,6,7,8]
a = elemIndex 7 list
b = mod a 2

foo list = [b | n <- [5,6,7,8]
              , let a = elemIndex n [5,6,7,8]
              , let Just i = a
              , let b = mod i 2]
         = [b | n <- list
              , let Just i = elemIndex n list
              , let b = mod i 2]
         = [b | (_, i) <- zip list [0..]
              , let b = mod a 2]
         = ls where ls = [0,1] ++ ls

bar list = [(n,b) | n <- list
                  , let Just i = elemIndex n list
                  , let b = mod i 2]
         = [(n,b) | (n, i) <- zip list [0..]
                  , let b = mod i 2]
         = zip list ls where ls = cycle [0,1]

Normally this kind of pattern matching is frowned upon since it is partial, i.e. can cause error if the value is actually Nothing, but here it is correct by construction.
But then really, why put it into a Just -- just use it as it is. And we did.


text:
Q: Setting restify default JSON response I am trying to pipe a file's content using a readStream that writes to restify's response. But I am not able to set the global response Content-Type header
Here is what my code looks like
let restify = require('restify');
let router = require('./routes');

let server = restify.createServer({
    formatters: null,
    log: null,
    spdy: null,
    version: '0.0.1',
    handleUpgrades: false
});

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

//I think this is suppose to set the response header across the app but it is not
restify.defaultResponseHeaders = function(data) {
    this.header('Content-Type', 'application/json');
};

server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.CORS());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.requestLogger());
//server.use(restify.throttle());
server.use(restify.conditionalRequest());
server.use(restify.fullResponse());
server.use(restify.bodyParser());

//router
router(server);

My route action looks like this
let fs = require('fs');

module.exports = function ecmaRoutes(server) {

    let PATH = '/sample/';
    server.get(function sampleV1(req, resp) {

    let path = 'sample.json';

    let rStream = fs.createReadStream(path);
    rStream.pipe(resp);

});

};

For whatever reason my response is not setting the content-type to application/json. I can do it in the route action itself manually using
resp.header('Content-type', 'application/json');

but that would be cumbersome if I had to do it for every route.
Is there something fundamentally wrong with my route action?

A: You don't need to do it for every route. Just add this after listen function:
Try something like that:
server.use(function(req,res,next){
  res.setHeader('content-type','application/json')
 //   OR
  res.setHeaders({'content-type'}:'application/json'})

 next()
})


text:
Q: AngularJS: Can I use one-time binding in ng-pluralize? I tried this, but it does not work: This is now implemented in Angular 1.3.4.
<!doctype html>

    <input type="number" ng-model="foo" ng-init="foo=1">

    Normal binding: <ng-pluralize count="foo" when="{'0': 'zero', '1': 'one', 'other': 'many'}"></ng-pluralize>

    One-time binding: <ng-pluralize count="::foo" when="{'0': 'zero', '1': 'one', 'other': 'many'}"></ng-pluralize>

Is there another way using ng-pluralize?
Plnkr: http://plnkr.co/edit/iaFI3p?p=preview

A: Blackhole's suggestion works (thank you!)
// Blackhole's suggestion, try here: http://plnkr.co/edit/roxHzV?p=preview
<ng-pluralize count="{{ ::foo }}" when="{'0': 'zero', '1': 'one', 'other': 'many'}"></ng-pluralize>

I was expecting count="::foo" to work so I opened an issue on GitHub. Caitp from the Angular team agreed and it's currently planned for Angular 1.3.4.


text:
Q: Finding periodic points of diffeomorphism of the circle I want to find all the periodic points of the following diffeomorphism of the circle:
$f(x) = x + \frac{1}{4} + \frac{1}{10} \sin(8 \pi x) \mod 1$
Where a periodic point is $p$ such that $f^n(p) = p$ for some $n \in \mathbb{N}$. I have shown the rotation number $\rho (f) = \frac{1}{4}$ (I think) so I know that periodic points exist (as the rotation number is rational) but that none are fixed points, i.e. no such $p$ for $n = 1$ (as rotation number is not zero).
I tried working from the definition but I get a horrible nest of sine functions. In general finding periodic points of functions like this doesn't appear to be well documented in my course notes, the recommended book or indeed the internet (from what I can find) so any help at all would be appreciated. I'm looking for a general method, not just the solution for this specific diffeomorphism, but really any help is great.
This isn't homework if anyone was wondering, it's revision and I'm more interested in the mathematics behind the general method for a solution than getting the specific solution of this question. Hints definitely welcome.
EDIT: Forgot to add, as for a lift $F$ of $f$ we have $deg(f) = F(x + 1) - F(x) = 1$, we know the diffeomorphism is orientation preserving.

A: Since you know what is the rotation number, there is simple way. Recall that the rotation number is $p/q$ with $p$ and $q$ coprime if and only if $f$ has a periodic point of period $q$. So you should concentrate on finding a point of period $4$, and a simple inspection shows $0$ has period $4$.
Other than that, the only question remaining is whether there are other orbits with period $4$ (for sure there are no orbits with other periods!). Indeed there are three other such orbits, that of $1/8$ and two others.


text:
Q: How to avoid rounding off in NSNumberFormatter I am trying to have a number string with maximum 2 decimals precision, while rest decimals just trimmed off instead of rounding them up. For example:
I have: 123456.9964
I want: 123456.99 -> Just want to trim rest of the decimal places
What I have tried is:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat: 123456.9964]];
 NSLog(@"%@", numberAsString);

There is nothing to set rounding mode as "none". What else can I do to maintain Decimal style formatting along with trimmed decimal digits? Any help will be appreciated. Thanks.

A: The following works for me:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
// optional - [numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
NSNumber *num = @(123456.9964);
NSString *numberAsString = [numberFormatter stringFromNumber:num];
NSLog(@"%@", numberAsString);

The output is: 123,456.99
Part of your problem is the use of numberWithFloat: instead of numberWithDouble:. Your number has too many digits for float.

A: you can use this
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble: 123456.9964]];
NSLog(@"%@", numberAsString);

A: [numberFormatter setRoundingMode: NSNumberFormatterRoundDown];

Use this code.

A: you can also just use round() and then convert it into a string afterward
var y = round(100 * 123456.8864) / 100

var x:String = String(format:"%.2f", y)
println("x: \(x)")

would print x: 123456.89, rounding the 8 to a 9.


text:
Q: Access properties of a virtual class in partial class public partial class IICustomer : IEntity
{
    public int CreatedByEmployeeId { get; set; }

    public virtual IItem IItem { get; set; }
}

public partial class IItem : IEntity
{
    public string ItemName { get; set; }
}

I want to access ItemName through the object of IICustomer.
public void SaveIICustomers(int itemId, [FromBody] IEnumerable<CustomerDto> customers)
{
    IICustomer items = new IICustomer();

    items.IItem.ItemName="Sam"; // exception is thrown here
}

But the above code is throwing a NullReferenceException

Object reference not set to instance of object.

A: It happens because your object items.IItem is not yet created, it's null. Only object items is create.
If you want to create also the IItem object when your item object is created I recommend you to add an constructor into the class IICustomer like that:
public partial class IICustomer : IEntity
{
    public IICustomer(){
        IItem= new IItem();
    }
    public int CreatedByEmployeeId { get; set; }
    public virtual IItem IItem { get; set; }
}

In this way each time when you'll create an object IICustomer you will create also it's property IItem.


text:
Q: Is possible dequeue/remove style from wp_footer() hook and add on wp_head() hook? I need unregister this enqueue style of wp_footer() hook and add it to the top of site with hook wp_head(), this is possible?
I'm optimizing my theme to validate in W3C, and one of the requirements of W3C is that all styles are within the tag <head></head>... I am using an specific plugin called Crayon Syntax Highlighter, and this plugin are inserting a style at the bottom of the page (probably using wp_footer() hook).
The name/id of script is crayon:

I've tryed all this functions but no success:
wp_deregister_style( 'crayon' );
wp_dequeue_style( 'crayon' );
remove_action( 'wp_enqueue_style' , 'crayon' , 10 );

wp_deregister_style( 'crayon-css' );
wp_dequeue_style( 'crayon-css' );
remove_action( 'wp_enqueue_style' , 'crayon-css' , 10 );

A: If you look at the source code, you can see that wp_enqueue_style( 'crayon' ) is called in Crayon::enqueue_resources() which itself is called either from either Crayon::the_content() or Crayon::wp_head(). The code in Crayon::wp_head is:
if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) {
  CrayonLog::debug('head: force enqueue');
  // Efficient enqueuing disabled, always load despite enqueuing or not in the_post
  self::enqueue_resources();
}

Which will enqueue the style only when certain settings are enabled. Otherwise, the style will only be enqueued from the_content filter which fires after wp_head has already been output.
So your two options are:

*

*Have the CSS enqueued on all pages in the header

*Have the CSS enqueued only on necessary pages but in the footer

A: Hmmmm.. the question is not very clear to me, if you could provide a little more info about your issue (like the specific files and scripts you need to modify) would be great. From what i understood, i'll try to help you. First, avoid plugins unless you really really need them. Now, you might be trying to move render-blocking JavaScript and CSS out of the  tag, that's because when you start loading a page through your browser, the first scripts you download are those between the  tag, by moving those scripts to your footer (footer.php or /public_html/wp-content/themes/yourtheme/footer.php) the Web page will start rendering all the data that needs to be visualized first, beginning from the top of the page and at last those scripts in the footer.php file. I bet
Crayon Syntax Highlighter is causing the issue, just try to put this <!-- W3TC-include-js-head --> before the closing </body> tag.
If you want to use wp_enqueue_scripts look at this example
function themeslug_enqueue_style() {
    wp_enqueue_style( 'core', 'style.css', false );
}

function themeslug_enqueue_script() {
    wp_enqueue_script( 'my-js', 'filename.js', false );
}

add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );

I hope this helps, good luck dude. :)


text:
Q: SignalR 2 Not working on azurewebsites I have a simple SignalR based timer on the server which updates my dashboard panel. Everything works fine on VS2012, however when I deploy to azure or IIS7.5 it can't stablish a connection. Here are the errors from console.
This is my hub:
public class BroadCastHub : Hub
{

    // Is set via the constructor on each creation
    //private readonly Broadcaster _broadcaster;
    private readonly TimeSpan BroadcastInterval = TimeSpan.FromMilliseconds(AppConfig.Instance.Tracing.RefreshRate * 1000);

    public BroadCastHub()  {
        if (AppConfig.Instance.Tracing.EnableServerAutoUpdates)
        {
            // Start the broadcast loop
            var _broadcastLoop = new Timer(
                UpdatePanel,
                null,
                BroadcastInterval,
                BroadcastInterval);
        }
    }

    public void UpdatePanel()
    {
        UpdatePanel(null);
    }

    public void UpdatePanel(object o)
    {

        var appService = DependencyResolver.Current.GetService<IApplicationService>();
        var applications = appService.GetSummaryCollection();
        var model = applications.Select(c => new ApplicationState
        {
            id = c.id,
            lastRunTime = c.lastRunTime.GetValueOrDefault(),
            totalTraces = c.totalTraces,
            status = appService.GetStatus(c.lastRunTime, c.lastTraceType, c.traceInterval)
        }.InjectFrom(c)).Cast<ApplicationState>().AsQueryable();

        Clients.All.updatePanel(model);

    }

}

This is my JS code (Angular):
   function init() {

        var broadCastHub = $.connection.broadCastHub;
        broadCastHub.client.updatePanel = function(apps) {
            console.log('Broadcasting');
        };

        $.connection.hub.start()
        .done(function () {
            console.log('Now connected, connection ID=' + $.connection.hub.id);
        })
        .fail(function () { console.log('Could not Connect!'); });

        //listenBroadcast();
    }

EDIT:
Curiously, I saw a similar article and implemented like this:
public class Broadcaster
{
    private readonly IApplicationService _applicationService;
    private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(() => new Broadcaster());
    // We're going to broadcast to all clients a maximum of 25 times per second
    private readonly TimeSpan BroadcastInterval = TimeSpan.FromMilliseconds(AppConfig.Instance.Tracing.RefreshRate * 1000);
    private readonly IHubContext _hubContext;
    private Timer _broadcastLoop;

    public Broadcaster()
    {
        _applicationService = DependencyResolver.Current.GetService<IApplicationService>();
        // Save our hub context so we can easily use it
        // to send to its connected clients
        _hubContext = GlobalHost.ConnectionManager.GetHubContext<BroadCastHub>();

        if (AppConfig.Instance.Tracing.EnableServerAutoUpdates) {
            // Start the broadcast loop
            _broadcastLoop = new Timer(
                UpdatePanel,
                null,
                BroadcastInterval,
                BroadcastInterval);
        }

    }

    public void UpdatePanel(object state)
    {
        var applications = _applicationService.GetSummaryCollection();
        var model = applications.Select(c => new ApplicationState
        {
            id = c.id,
            lastRunTime = c.lastRunTime.GetValueOrDefault(),
            totalTraces = c.totalTraces,
            status = _applicationService.GetStatus(c.lastRunTime, c.lastTraceType, c.traceInterval)
        }.InjectFrom(c)).Cast<ApplicationState>().AsQueryable();

        _hubContext.Clients.All.updatePanel(model);

    }

    public static Broadcaster Instance
    {
        get
        {
            return _instance.Value;
        }
    }
}

My hub:
public class BroadCastHub : Hub
{

    // Is set via the constructor on each creation
    private readonly Broadcaster _broadcaster;

    public BroadCastHub()
        : this(Broadcaster.Instance)
    {
    }

    public BroadCastHub(Broadcaster broadcaster)
    {
        _broadcaster = broadcaster;
    }

    public void UpdatePanel()
    {
        _broadcaster.UpdatePanel(null);
    }

}
Thanks for the article, I'll take a deeper look.


text:
Q: How to find the similar numeric column from one table with the column in another table Currently i am working on a project in which the use case is for example:
there are two data frames one from the db and the other from the user uploaded file.The user uploaded file will be having unnamed columns
DB DATA FRAME
|customer_id | name | age | days_as_customer | revenue | payment |
|------------|------|-----|------------------|---------|---------|
| 00001      | x1   | 25  | 40               | 2000    |monthly  |
| 00002      | x2   | 51  | 200              | 10000   | yearly  |

USER UPLOADED FILE
|customer_id | C1   | C2  | C3               | C4      | c5        |
|------------|------|-----|------------------|---------|-----------|
| 00011      | x5   | 45  | 1                | 8000    |quarterly   |
| 00022      | x6   | 33  | 20               | 1000    |half-yearly|

What i need is that i have to match the columns from the user uploaded file to the db columns ie:
output
{
age : C2,
days_as_customer : C3,
revenue : C4
}

Previously i tried using ks-test, qunatiles, skewness, central tendencies but the results are not as expected because most of time the uploaded file has central tendencies which is completely different from the db data frame
Can anyone suggest me any techniques to solve this ?


text:
Q: How do I open more than 64 child processes on windows using IPC::Open3 in perl? I get the following error when I try to open the 65th child process in windows:
open3: IO::Pipe: Can't spawn-NOWAIT: Resource temporarily unavailable
How do I open more than 64 child processes on windows using IPC::Open3 in perl?
The following code works fine in linux but fails with the above error on windows:
use POSIX qw[ :sys_wait_h ];;
use IPC::Open3;
use Carp;
use FileHandle;

my $i = 0;

while ($i < 300){
    my($IN)  = new FileHandle;
    my($OUT) = new FileHandle;
    my($ERR) = new FileHandle;

    $IN->autoflush(1);
    $ERR->autoflush(1);

    my($childpid) = IPC::Open3::open3($IN, $OUT, $_ERR, "<xyz process>")  or
                    Carp::confess("/n=====$i=======/nCould not open pipe");

    waitpid( $childpid, &WNOHANG);

    $ASPELL_IN->close();
    $ASPELL_OUT->close();
    kill(0,$childpid);
}


text:
Q: pre-populate ApplePay with address in Swift I'm looking to populate PKPaymentRequest.billingAddress / shippingAddress with an address I have on file as mentioned here:
https://developer.apple.com/library/ios/documentation/PassKit/Reference/PKPaymentRequest_Ref/#//apple_ref/occ/instp/PKPaymentRequest/billingAddress
This requires me to create an ABRecordRef from scratch. Below is my best attempt, but my app is crashing without a helpful error message:
var request = PKPaymentRequest();

var person: ABRecordRef = ABPersonCreate().takeRetainedValue()
ABRecordSetValue(person, kABPersonFirstNameProperty, "John", nil)
ABRecordSetValue(person, kABPersonLastNameProperty, "Doe", nil)

var multiValue : ABMutableMultiValue = ABMultiValueCreateMutable(ABPropertyType(kABPersonAddressProperty)).takeRetainedValue()
ABMultiValueAddValueAndLabel(multiValue, "123 Test Street", kABPersonAddressStreetKey, nil)
ABMultiValueAddValueAndLabel(multiValue, "Mountain View", kABPersonAddressCityKey, nil)
ABMultiValueAddValueAndLabel(multiValue, "CA", kABPersonAddressStateKey, nil)
ABMultiValueAddValueAndLabel(multiValue, "94040", kABPersonAddressZIPKey, nil)

ABRecordSetValue(person, kABPersonAddressProperty, multiValue, nil)

request.shippingAddress = person
request.billingAddress = person

A: I was able to figure this out after a few more hours of dedication, see below:
//Initialize new PassKit Payment Request
var request = PKPaymentRequest();

//Initialize ABRecord to pre-populate AP payment sheet
var record: ABRecordRef = ABPersonCreate().takeRetainedValue()

//Pre-populate first & last name
ABRecordSetValue(record, kABPersonFirstNameProperty, "John", nil)
ABRecordSetValue(record, kABPersonLastNameProperty, "Doe", nil)

//Pre-populate phone
var phone: ABMultiValueRef = ABMultiValueCreateMutable(ABPropertyType(kABMultiStringPropertyType)).takeRetainedValue()
ABMultiValueAddValueAndLabel(phone, "(555)123-4567", kABHomeLabel, nil)
ABRecordSetValue(record, kABPersonPhoneProperty, phone, nil)

//Pre-populate email
var email: ABMultiValueRef = ABMultiValueCreateMutable(ABPropertyType(kABMultiStringPropertyType)).takeRetainedValue()
ABMultiValueAddValueAndLabel(email, "john.doe@test.com", kABHomeLabel, nil)
ABRecordSetValue(record, kABPersonEmailProperty, email, nil)

//Pre-populate address
var address: ABMultiValueRef = ABMultiValueCreateMutable(ABPropertyType(kABMultiDictionaryPropertyType)).takeRetainedValue()
var addressDictionary : [String:String] = [kABPersonAddressStreetKey as String: "123 Test Street", kABPersonAddressCityKey as String: "Palo Alto", kABPersonAddressStateKey as String: "CA", kABPersonAddressZIPKey as String: "94301", kABPersonAddressCountryKey as String: "United States"]
ABMultiValueAddValueAndLabel(address, addressDictionary, kABOtherLabel, nil)
ABRecordSetValue(record, kABPersonAddressProperty, address, nil)

//Assign ABRecord to PKPaymentRequest
request.shippingAddress = record
request.billingAddress = record


text:
Q: How can I get only elements with odd ids from a D3 selection? How can I get only elements with odd indices using D3 selection?
var theData = [ 1, 2, 3, 4 ]

var p = d3.select("body").selectAll("p")
  .data(theData)
  .enter()
  .append("p")
  .text("hello");

In this case (I know that this code does not make a lot of sense), I would like to get the elements with indices 1 and 3.
An example fiddle is here:
https://jsfiddle.net/8tvdbfxs/

A: I updated your fiddle with an example solution. I added
a selector to get all odd children from the body. D3 can use any css selector. This allows you to use pseudo-selectors like :nth-child. For my example I have just changed the color of the text.
d3.select("body").selectAll(':nth-child(odd)')
    .style('color', 'orange');


text:
Q: Measure server bandwidth I want to measure a bandwidth of my implemented in Python remailer server, which means I want to measure how many bytes my server is processing per second. So how I was planing to do that is: for a fixed period of time (for example 300sec), I'm measuring the number of received bytes and sent bytes. After this period of time I compute the ratio: bytes_received / bytes_sent. However, I'm not sure this is what I want, because it gives me a ratio (which usually is around 1-1.5), so this means that I process all or almost all messages which I received in some period of time, but I want to measure how many bytes I processed. I will be very grateful if someone can advice me how I can measure my bandwidth.

A: I think what you need is to do this :
bytes_received = bytes_received300s - bytes_received0s
bytes_sent = bytes_sent300s - bytes_sent0s
total_bytes_processed = bytes_received - bytes_sent
This would give you the total number of bytes processed during the 300s period.

A: You can use psutil.net_io_counters() to calculate the bandwidth over a period of time. You'll take a snapshot at 0 seconds and a snapshot at 300 seconds.
def get_bandwidth():
    # Get net in/out
    net1_out = psutil.net_io_counters().bytes_sent
    net1_in = psutil.net_io_counters().bytes_recv

    time.sleep(300) # Not best way to handle getting a value 300 seconds later

    # Get new net in/out
    net2_out = psutil.net_io_counters().bytes_sent
    net2_in = psutil.net_io_counters().bytes_recv

    # Compare and get current speed
    if net1_in > net2_in:
        current_in = 0
    else:
        current_in = net2_in - net1_in

    if net1_out > net2_out:
        current_out = 0
    else:
        current_out = net2_out - net1_out

    network = {"traffic_in": current_in, "traffic_out": current_out}

    # Return data in bytes
    return network


text:
Q: CGRectMake coordinates refers to which coordinates We use CGRectMake to set the width,height and x and y ordinates but x and y refers to which
 coordinates is of the root view and if yes then if I create an child view and then add this
 button to the child view then which coordinates it will refer to which coordinates?
UIButton *roundRectButton = [UIButton buttonWithType:

UIButtonTypeRoundedRect];

[roundRectButton setFrame:CGRectMake(60, 50, 200, 40)];

A: When you set the frame, it means you are positioning it with respect to its superview and when you use bounds, it means you are positioning it with the real (x,y) coordinates of device.
Here you are setting the frame of the view(i.e. UIButton) so you are positioning it with respect to its parentView.

A: A UIView coordinates system refers to its superview and has its orignin in the top-left corner of its superview.
As stated here

The default coordinate system in UIKit has its origin in the top-left corner and has axes that extend down and to the right from the origin point. Coordinate values are represented using floating-point numbers, which allow for precise layout and positioning of content regardless of the underlying screen resolution. Figure 1-4 shows this coordinate system relative to the screen. In addition to the screen coordinate system, windows and views define their own local coordinate systems that allow you to specify coordinates relative to the view or window origin instead of relative to the screen.

So your uibutton coordinate system will refer to its super UIView.


text:
Q: random hyperharmonic series The Harmonic Series is defined as:
$\sum_{n} \frac{1}{n}$ where $n=1,2,3,4....$.
This series is known to be divergent.
A generalization of this series can be made by raising each term to $p$:
$\sum_{n} \frac{1}{n^p}$  which is also known as the hyperharmonic series and is known to be convergent when  $p>1$.
On the other hand, for $p=1$, if the signs of the terms are alternating the sum:
$\sum_{n} \frac{(-1)^n}{n}$ is convergent and approaches $\ln{2}$.
A natural extension would be to introduce randomness in the sign of each terms.
$\sum_{n} \frac{\epsilon_{n}}{n}$ where $\epsilon_{n}$ is defined by the probability of its outcome: $P(\epsilon_{j} = 1)=P(\epsilon_{j} = -1)=1/2$. This is called the random harmonic series in Schmuland (http://www.stat.ualberta.ca/people/schmu/preprints/rhs.pdf).
My question is: What would happen if we generalize this to the case of the random HYPERharmonic series? What would be the distribution of the result of the summation?

A: The case $p=2$ is treated briefly in the final section of the cited
Schmuland paper, which gives a picture of the distribution.  The observations
in the paper's first few sections adapt to arbitrary $p>1$: the distribution
is not expected to have a simple formula, but the moment-generating function
has a product formula (exhibited below),
which we can use to compute each power moment ${\mathbb E}(X_p^{2k})$
of this random variable $X_p = \sum_n \epsilon_n/n^p$
as a polynomial in $\zeta(2p), \zeta(4p), \zeta(6p), \ldots, \zeta(2kp)$.
[The odd-order moments vanish by symmetry.]
This is because the distribution of $X_p$ is the convolution of
an infinite series of distributions, the $n$-th of which is supported on
$\pm 1 /n^p$ each with probability $1/2$; therefore
$$
{\mathbb E}(\exp(tX_p))
= \prod_{n=1}^\infty \left(\frac12 e^{t/n^p} + \frac12 e^{-t/n^p} \right)
= \prod_{n=1}^\infty \cosh(t/n^p).
$$
We can recover the power moments from the expansion of
${\mathbb E}(\exp(tX_p))$ in a Taylor series about $t=0$,
writing
$$
\begin{eqnarray}
\log {\mathbb E}(\exp(tX_p))
&=& \sum_{n=1}^\infty \log(\cosh(t/n^p)) \cr
&=& \sum_{n=1}^\infty
\frac12 \left(\frac{t}{n^p_{\phantom1}}\right)^2
- \frac1{12} \left(\frac{t}{n^p_{\phantom1}}\right)^4
+ \frac1{45} \left(\frac{t}{n^p_{\phantom1}}\right)^6
- \frac{17}{2520} \left(\frac{t}{n^p_{\phantom1}}\right)^8
+ - \cdots \cr
&=&
\frac{\zeta(2p)}{2} t^2
- \frac{\zeta(4p)}{12} t^4
+ \frac{\zeta(6p)}{45} t^6
- \frac{17\zeta(6p)}{2520} t^8
+ - \cdots
\end{eqnarray}
$$
and exponentiating.
While the random variables $X_p$ may be no more than objects of curiosity,
similar constructions arise naturally in analytic number theory, such as
the value at a fixed $s>1$ of the Dirichlet $L$-series associated to a random
real character $\chi$.  In this example, the terms $\chi(n)/n^s$ in the
Dirichlet series are correlated, but the Euler product
$L(s,\chi) = \prod_l (1 - \chi(l)/l^s)^{-1}$ has independent factors, so
$\log L(s,\chi)$ is an infinite convolution of the same kind.  Likewise
if the $\epsilon_n$ were random complex numbers of unit length:
the analogue could be $\log L(s,\chi)$ for a random Dirichlet charater $\chi$
that need not be real, or $\log \zeta(\sigma + it)$ for fixed $\sigma>1$
and random real $t$.  For these sums of complex-valued random variables,
the factors in the moment generating function get more complicated than
hyperbolic cosines, but are still tractable.


text:
Q: AngularJS infinite digest loop I'm passing an object to an AngularJS directive like so:
<context-selector
            is-buy="true"
            num-to-select="0"
            init-object="{ads: rule.ads_list, adContainer: rule.container_ad_id, campaign: rule.campaign_id}">
        </context-selector>

and it causes Angular infinite digest loop because of the init-object.
I guess that's because Angular compares the object by reference.
The directive definition is:
directive('contextSelector', function() {
        return {
            restrict: 'E',
            scope: {
                vertical: "@",
                levelsDepth: "@",
                isBuy: "@",
                shellsLeft: "=",
                numToSelect: "@",
                initObject: "=" // {ads: [1,2], adContainer: 4, campaign: 6}
            },

Is there a solution to this issue?

A: After I did some more searching on google, I came up with this post:
https://github.com/angular/angular.js/issues/4054
Apparently it's a known issue and was fixed in Angular >= 1.2.5


text:
Q: Darboux integral mistake in example? enter image description here
Shouldn't the first integral have (b-a) rather than 1 on the end? (i.e the width of the rectangle, the height always being 1). And why is there an inequality sign on the end? Why not just equal?
Thank you!


text:
Q: Use a JTable from a list in a for-each I use Java Spring MVC in my webapplication. I need to make a table in JTable from a list that belongs to a Java Object (locally called table in for-each loop, as you can see below).
So for each table, there's a table.listOfThings (a java.util.List object) I have to show inside JTable.
HTML:
c:forEach var="table" items="${listOfTables}">

            <fmt:message key="thisTitle" />:

And the JS:
$(document).ready(function() {
    readyTable();
)};

function readyTable(){
     $('#jTableContainer').jtable({
         title: 'List Title',
         actions: {
             listAction: ${table.listOfThings},
         },
         fields: {
             Field: {
                 key: true,
                 title: 'Field',
                 width: auto;
         }
     });

    $("#jTableContainer").jtable("load");
}

This way, JTable is always empty - it just display the title. How can I do it?

A: I know you can access response stuff in document ready, maybe try passing it to that function like readyTable(${table.listOfThings}); or maybe set a global variable which is given a value during ready(), have a play and use the debugger if you're using chrome, or console.log(${table.listOfThings}) in your ready() to see what's going on


text:
Q: Ble distance calculation using Time Is it possible to calculate distance between BLE-BLE or Beacon-BLE device using Time(T) taken on packet received on receiver device with measured power or RSSI value?
Is there any formula for that?

A: You can get a formula for estimating distance from time of flight measurements from this paper.
However, commercially available Bluetooth chipsets do not provide accurate timers capable of measuring time of flight.  Further, smartphones do not provide access to such time of flight data.  As a result, such a formula is if little practical value for most use cases.


text:
Q: Using the Perl split() command to parse the output from the `du' command I have a Perl script that has the following snippet in it:
@mylittlearray = split(/\/dir1\/dir2\//, `du --max-depth=1 \/dir1\/dir2\//`
print $mylittlearray[0];
print $mylittlearray[1];
print "\n";

The output is
24    ones
8

mylittlearray[0] and [1] should be returning only 24  and "ones", not "ones8".  If I pipe the du command to a file and turn on set list in VIM I see the following:
24^I./ones$
8^I./twos$

If I run the du command with a -0, I see this:
24      ./ones^@8       ./twos^@8       ./threes^@8     ./fours^@8      ./fives^@80     .^@

I'm trying to figure out how to split either format so that directory names are separated or split from the size for the next directory.  In other words I want mylittlearray[0] to equal 24, mylittlearray[1] to only contain "ones", mylittlearray[2] would contain "8" and so on.
Any ideas on how to accomplish this?

A: Your question doesn't quite make it clear, but if you're simply interested in gathering the data for each resulting entry from du, loop over the results like this:
#!/usr/bin/perl
use strict;
use warnings;

# Capture the output from du
my @array = `du --max-depth=1 /some/folder/`;

# Loop over the output
foreach (@array)
{
    chomp; # Strip new-line
    my ($size, $dir) = split; # Split on whitespace
    print "Dir: $dir, Size: $size\n";
}

A: Using map instead of split:
my $dir = "/dir1/dir2/";
my @mylittlearray = map { m!(\d+)\s+$dir(.*)! } `du --max-depth=1 '$dir'`;
print join(", ", @mylittlearray), "\n";


text:
Q: iPhone App: how to get app icon from app id? I am looking for a way to get the app icon from the app id. Do you know how to do it? Please share the way. Thanks.
e.g
Instagram, where the id I'm looking for is: id389801252
https://itunes.apple.com/jp/app/instagram/id389801252?mt=8
I want to get this image:

A: Just for reference, you can use the app's bundle id too:
http://itunes.apple.com/lookup?bundleId=com.burbn.instagram

A: (I composed this answer after 2 minutes of googling... It's just the matter of the correct keyword!)
This is possible using an undocumented documented API of the iTunes Store. It might change in the future, but it doesn't seem to have changed in the near past, so here you are...
NSString *idString = @"id389801252";

NSString *numericIDStr = [idString substringFromIndex:2]; // @"389801252"
NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@", numericIDStr];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *json = [NSData dataWithContentsOfURL:url];

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
NSArray *results = [dict objectForKey:@"results"];
NSDictionary *result = [results objectAtIndex:0];
NSString *imageUrlStr = [result objectForKey:@"artworkUrl100"]; // or 512, or 60

NSURL *artworkURL = [NSURL URLWithString:imageUrlStr];
NSData *imageData = [NSData dataWithContentsOfURL:artworkURL];
UIImage *artworkImage = [UIImage imageWithData:imageData];

Note that this performs two synchronous round-trips using the NSURL API, so you better wrap this in a backgorund thread for maximal user experience. Feed this program an ID string (idString in the code above) and in the end, artworkImage will contain a UIImage with the desired image.

A: Not sure if this is at all relevant anymore, but Apple provides an iTunes Link Maker tool. If you use this tool to find your app, you'll also see where it shows an App Icon section. Click embed and grab the img link from there. One thing to note, I did end up playing with the url a bit to find the right size and format I needed (for instance you can get a jpg render instead of png or select an arbitrary size like 128x128)


text:
Q: Simplify Boolean Expression: X + X'Y'Z I know that the following is equal:
X + X'Y'Z = X + Y'Z
How can simplify the left side to arrive the right side using basic Boolean identities?
Thanks in advance.

A: Expression                            Justification
---------------------------------     -------------------------
X + X'Y'Z                             initial expression
(XY'Z + X(Y'Z)') + X'Y'Z              r  = rs + rs'
(XY'Z + XY'Z + X(Y'Z)') + X'Y'Z       r = r + r
(XY'Z + X(Y'Z)' + XY'Z) + X'Y'Z       r + s = s + r
(XY'Z + X(Y'Z)') + (XY'Z + X'Y'Z)     (r + s) + t = r + (s + t)
X(Y'Z + (Y'Z)') + (Y'Z)(X + X')       rs + rt = r(s + t)
X(1) + (Y'Z)(1)                       r + r' = 1
X + Y'Z                               r(1) = r

A: The fastest way to prove this expression is to add a redundant term that will discard X'
X + X'Y'Z = X(1+Y'Z) + X'Y'Z
          = X + XY'Z + X'Y'Z
          = X + (X+X')Y'Z
          = X + Y'Z


text:
Q: Keyword - debugger | A practical example From MDN.

Invokes any available debugging functionality. If no debugging
  functionality is available, this statement has no effect.

I've debugged in IE, Safari, and FF and have found no need for this keyword.  Does it have a practical use?  Can someone provide a practical example?

A: Typing debugger; into your code triggers the same functionality as setting a breakpoint in the debugging utility.  I have had various debugging utilities not show the script because of using a script inside a cms or other unknown reasons.  However the scripts still halted and allowed me to check the state of variables where ever i used debugger;
This may be a stretch of a practical example but i have found a use for it.
Technically
debugger;

appears to be a manual or coding way to trigger a debug utility as opposed to setting a break point inside of a debug utility.  Hope this helps.


text:
Q: How can I make personal notes on the map? I'd like to be able to add my own notes and comments to locations in Skyrim - for example "There's a bandit leader here whom I couldn't kill yet - come back later to finish the job". How can I do that? Mods are an option.

A: There is a mod that allows it indeed, you can download it from here:
http://www.nexusmods.com/skyrim/mods/38731/
The features list:

*

*You can place your own markers with your own, self-written notes attached to them.

*Up to 60 custom markers (if you want more, it's easy to add more in Creation Kit).

*You can fast travel to your markers.

*You can edit and remove your markers.

*Works with SkyUi's Location Finder.

*First line of your note become a marker name (displayed on the map and in Location Finder).

*English and Polish localizations.

As you see, it is only available in English or Polish so this might conflict if your game is in a different language. However, you can instruct Steam to change the language of the game in the game's properties menu.


text:
Q: GM_setValue is not defined I'm trying to get a fairly simple script which persists a value and retrieves it in the successor to GreaseMonkey: Scriptish.
Browser: Firefox 9.0
Scriptish: 0.1.7
On Windows 7 Ultimate 64-bit
// ==UserScript==
// @id             testSerialization
// @name           Test Serialization
// @version        1.0
// @namespace      com.mobilvox.com
// @author
// @description
// @include        http://www.google.com/
// @run-at         document-end
// ==/UserScript==

GM_setValue("isCurrent", true);
GM_log("Is this script current? " + GM_getValue("isCurrent", false));

When I run it I get:
[10:29:59.074] GM_setValue is not defined
@Scratchpad:29
 @ Scratchpad:29

A: I have a complete working code with jQuery and GM_ codes. Try this:
// ==UserScript==
// @name           GM_ debug script
// @description    checking GM_setValue and GM_getValue with jQuery
// @namespace      eaposztrof
// @include        *
// @require     http://code.jquery.com/jquery-1.9.1.js
// @grant       GM_getValue // [grants][1]
// @grant       GM_setValue
// ==/UserScript==

function GM_getValueUTF8(key) { // UTF8 safe
    var value = GM_getValue(key);
    return (value && value.length) ? decodeURI(value) : '';
}

function GM_setValueUTF8(key, value) {
    GM_setValue(key, encodeURI(value));
}

    GM_setValueUTF8('asd','GM_setValue, GM_getValue working! press [Alt+X] to check with jQuery');
    alert(GM_getValueUTF8('asd'));

(function (){
    this.$ = this.jQuery = jQuery.noConflict(true);

    $(document).ready(function () {

        $ (document).keydown (function (e) {
            switch (e.keyCode) {
                case 88:    // "x"
                    if (e.altKey) {
                        setTimeout(function() { // [workaround][2]
                            GM_setValueUTF8('asd','GM_setValue, GM_getValue working inside jQuery');
                            alert(GM_getValueUTF8('asd'));
                        }, 0);
                    }
            }
        });
    });
}
//
) ();

A: This looks like a possible bug, see related bugs like "GM_setValue not working".
Possible actions:

*

*Firefox 9 is getting obsolete.  Upgrade to FF 12 or FF 13 and see if the problem persists.

*File a bug report for Scriptish.


text:
Q: websphere .net client login different user Hi I want to login different credentials to wepshere mq from my pc.The error message like that.
The call to initialize the User ID 'mypcuser' failed with CompCode 2 and Reason
2035. If an MQCSP block was used, the User ID in the MQCSP block was 'mydifferentuser' user'.
ACTION:
Correct the error and try again.

In error I see both user of my differentuser and mypcuserboth
My code and my setting properties like that ,How can I login wephshere mq with given username and password authentication
public Hashtable init(String connectionType, string hostName, string channel)
    {
        Hashtable connectionProperties = new Hashtable();

        // Add the connection type
        // connectionProperties.Add(MQC.TRANSPORT_PROPERTY, connectionType);

        connectionProperties.Add(MQC.USER_ID_PROPERTY, "mydifferentuser");
        connectionProperties.Add(MQC.PASSWORD_PROPERTY, "xxx");
        connectionProperties.Add(MQC.CONNECTION_NAME_PROPERTY, hostName);
        connectionProperties.Add(MQC.CHANNEL_PROPERTY,  channel);
        connectionProperties.Add(MQC.MQADPCTX_YES,1);
....
        MQQueueManager qMgr = new MQQueueManager(QueueManagerName, connectionProperties);

A: connectionProperties.Add(MQC.USER_ID_PROPERTY, "username");
connectionProperties.Add(MQC.PASSWORD_PROPERTY,"****");
connectionProperties.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);

these properties must set client .net code.
and in webpsheremq side username must be setto mca field.And user must have right in computer.


text:
Q: How to check which StorageVolume we have access to, and which we don't? Background
Google (sadly) plans to ruin storage permission so that apps won't be able to access the file system using the standard File API (and file-paths). Many are against it as it changes the way apps can access the storage and in many ways it's a restricted and limited API.
As a result, we will need to use SAF (storage access framework) entirely on some future Android version (on Android Q we can, at least temporarily, use a flag to use the normal storage permission), if we wish to deal with various storage volumes and reach all files there.
So, for example, suppose you want to make a file manager and show all the storage volumes of the device, to show what the user can grant access to, and if you already have access to each, you just enter it. Such a thing seems very legitimate, but as I can't find a way to do it.
The problem
Starting from API 24 (here), we finally have the ability to list all of the storage volumes, as such:
    val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageVolumes = storageManager.storageVolumes

And, for the first time ever, we can have an Intent to request access to a storageVolume (here). So if we want, for example, to request the user to grant access to the primary one (which will just start from there, actually, and not really ask anything), we could use this:
startActivityForResult(storageManager.primaryStorageVolume.createOpenDocumentTreeIntent(), REQUEST_CODE__DIRECTORTY_PERMISSION)

Instead of startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_CODE__DIRECTORTY_PERMISSION) , and hoping the user will choose the correct thing there.
And to finally get the access to what the user chose, we have this:
@TargetApi(Build.VERSION_CODES.KITKAT)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE__DIRECTORTY_PERMISSION && resultCode == Activity.RESULT_OK && data != null) {
        val treeUri = data.data ?: return
        contentResolver.takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        val pickedDir = DocumentFile.fromTreeUri(this, treeUri)
        ...

So far we can request for permission on the various storage volumes...
However, the problem arises if you want to know which you got permission to and which you haven't.
What I've found

*

*There is a video about "Scoped Directory Access" by Google (here), which they talk specifically about the StorageVolume class. They even give information about listening to mount-events of StorageVolume, but they don't tell anything about identifying those that we got access to.

*The only ID of StorageVolume class is uuid , but it's not even guaranteed to return anything. And indeed it returns null in various cases. For example the case of the primary storage.

*When using the createOpenDocumentTreeIntent function, I've noticed there is a Uri hidden inside, probably telling which to start with. It's inside the extras, in a key called "android.provider.extra.INITIAL_URI". When checking its value on the primary storage, for example, I got this:
content://com.android.externalstorage.documents/root/primary

*When I look at the Uri I get in return in the onActivityResult, I get something a bit similar to #2, but different for the treeUri variable I've shown :
content://com.android.externalstorage.documents/tree/primary%3A

*In order to get the list of what you have access to so far, you can use this:
val persistedUriPermissions = contentResolver.persistedUriPermissions
This returns you a list of UriPermission, each has a Uri. Sadly, when I use it, I get the same as on #3, which I can't really compare to what I get from StorageVolume :
content://com.android.externalstorage.documents/tree/primary%3A

So as you can see, I can't find any kind of mapping between the list of storage volumes and what the user grants.
I can't even know if the user has chosen a storage volume at all, because the function of createOpenDocumentTreeIntent only send the user to the StorageVolume, but it's still possible to select a folder instead.
The only thing that I do have, is a chunk of workaround functions I've found on other questions here, and I don't think they are reliable, especially now that we don't really have access to File API and file-path.
I've written them here, in case you think they are useful:
@TargetApi(VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    final int end = docId.indexOf(':');
    String result = end == -1 ? null : docId.substring(0, end);
    return result;
}

private static String getDocumentPathFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    //TODO avoid using spliting of a string (because it uses extra strings creation)
    final String[] split = docId.split(":");
    if ((split.length >= 2) && (split[1] != null))
        return split[1];
    else
        return File.separator;
}

public static String getFullPathOfDocumentFile(Context context, DocumentFile documentFile) {
    String volumePath = getVolumePath(context, getVolumeIdFromTreeUri(documentFile.getUri()));
    if (volumePath == null)
        return null;
    DocumentFile parent = documentFile.getParentFile();
    if (parent == null)
        return volumePath;
    final LinkedList<String> fileHierarchy = new LinkedList<>();
    while (true) {
        fileHierarchy.add(0, documentFile.getName());
        documentFile = parent;
        parent = documentFile.getParentFile();
        if (parent == null)
            break;
    }
    final StringBuilder sb = new StringBuilder(volumePath).append(File.separator);
    for (String fileName : fileHierarchy)
        sb.append(fileName).append(File.separator);
    return sb.toString();
}

/**
 * Get the full path of a document from its tree URI.
 *
 * @param treeUri The tree RI.
 * @return The path (without trailing file separator).
 */
public static String getFullPathFromTreeUri(Context context, final Uri treeUri) {
    if (treeUri == null)
        return null;
    String volumePath = getVolumePath(context, getVolumeIdFromTreeUri(treeUri));
    if (volumePath == null)
        return File.separator;
    if (volumePath.endsWith(File.separator))
        volumePath = volumePath.substring(0, volumePath.length() - 1);
    String documentPath = getDocumentPathFromTreeUri(treeUri);
    if (documentPath.endsWith(File.separator))
        documentPath = documentPath.substring(0, documentPath.length() - 1);
    if (documentPath.length() > 0)
        if (documentPath.startsWith(File.separator))
            return volumePath + documentPath;
        else return volumePath + File.separator + documentPath;
    return volumePath;
}

/**
 * Get the path of a certain volume.
 *
 * @param volumeId The volume id.
 * @return The path.
 */
private static String getVolumePath(Context context, final String volumeId) {
    if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP)
        return null;
    try {
        final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        if (VERSION.SDK_INT >= VERSION_CODES.N) {
            final Class<?> storageVolumeClazz = StorageVolume.class;
            final Method getPath = storageVolumeClazz.getMethod("getPath");
            final List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
            for (final StorageVolume storageVolume : storageVolumes) {
                final String uuid = storageVolume.getUuid();
                final boolean primary = storageVolume.isPrimary();
                // primary volume?
                if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                    return (String) getPath.invoke(storageVolume);
                }
                // other volumes?
                if (uuid != null && uuid.equals(volumeId))
                    return (String) getPath.invoke(storageVolume);
            }
            return null;
        }
        final Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        final Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
        final Method getUuid = storageVolumeClazz.getMethod("getUuid");
        //noinspection JavaReflectionMemberAccess
        final Method getPath = storageVolumeClazz.getMethod("getPath");
        final Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
        final Object result = getVolumeList.invoke(storageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            final Object storageVolumeElement = Array.get(result, i);
            final String uuid = (String) getUuid.invoke(storageVolumeElement);
            final Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);
            // primary volume?
            if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                return (String) getPath.invoke(storageVolumeElement);
            }
            // other volumes?
            if (uuid != null && uuid.equals(volumeId))
                return (String) getPath.invoke(storageVolumeElement);
        }
        // not found.
        return null;
    } catch (Exception ex) {
        return null;
    }
}

The question
How can I map between the list of StorageVolume and the list of granted UriPermission ?
In other words, given a list of StorageVolume, how can I know to which I have access to and which I don't , and if I do have access, to open it and see what's inside?

A: Here is an alternate way to get what you want. It is a work-around like you have posted without using reflection or file paths.
On an emulator, I see the following items for which I have permitted access.
persistedUriPermissions array contents (value of URI only):

0 uri = content://com.android.externalstorage.documents/tree/primary%3A
   1 uri = content://com.android.externalstorage.documents/tree/1D03-2E0E%3ADownload
   2 uri = content://com.android.externalstorage.documents/tree/1D03-2E0E%3A
   3 uri = content://com.android.externalstorage.documents/tree/primary%3ADCIM
   4 uri = content://com.android.externalstorage.documents/tree/primary%3AAlarms

"%3A" is a colon (":"). So, it appears that the URI is constructed as follows for a volume where "<volume>" is the UUID of the volume.

uri = "content://com.android.externalstorage.documents/tree/<volume>:"

If the uri is a directory directly under a volume, then the structure is:

uri = "content://com.android.externalstorage.documents/tree/<volume>:<directory>"

For directories deeper in the structure, the format is:

uri = "content://com.android.externalstorage.documents/tree/<volume>:<directory>/<directory>/<directory>..."

So, it is just a matter of extracting volumes from URIs in these formats. The volume extracted can be used as a key for StorageManager.storageVolumes. The following code does just this.
It seems to me that there should be an easier way to go about this. There must be a missing linkage in the API between storage volumes and URIs. I can't say that this technique covers all circumstances.
I also question the UUID that is returned by storageVolume.uuid which seems to be a 32-bit value. I thought that UUIDs are 128 bits in length. Is this an alternative format for a UUID or somehow derived from the UUID? Interesting, and it is all about to drop! :(
MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
        var storageVolumes = storageManager.storageVolumes
        val storageVolumePathsWeHaveAccessTo = HashSet<String>()

        checkAccessButton.setOnClickListener {
            checkAccessToStorageVolumes()
        }

        requestAccessButton.setOnClickListener {
            storageVolumes = storageManager.storageVolumes
            val primaryVolume = storageManager.primaryStorageVolume
            val intent = primaryVolume.createOpenDocumentTreeIntent()
            startActivityForResult(intent, 1)
        }
    }

    private fun checkAccessToStorageVolumes() {
        val storageVolumePathsWeHaveAccessTo = HashSet<String>()
        val persistedUriPermissions = contentResolver.persistedUriPermissions
        persistedUriPermissions.forEach {
            storageVolumePathsWeHaveAccessTo.add(it.uri.toString())
        }
        val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val storageVolumes = storageManager.storageVolumes

        for (storageVolume in storageVolumes) {
            val uuid = if (storageVolume.isPrimary) {
                // Primary storage doesn't get a UUID here.
                "primary"
            } else {
                storageVolume.uuid
            }
            val volumeUri = uuid?.let { buildVolumeUriFromUuid(it) }
            when {
                uuid == null ->
                    Log.d("AppLog", "UUID is null for ${storageVolume.getDescription(this)}!")
                storageVolumePathsWeHaveAccessTo.contains(volumeUri) ->
                    Log.d("AppLog", "Have access to $uuid")
                else -> Log.d("AppLog", "Don't have access to $uuid")
            }
        }
    }

    private fun buildVolumeUriFromUuid(uuid: String): String {
        return DocumentsContract.buildTreeDocumentUri(
            "com.android.externalstorage.documents",
            "$uuid:"
        ).toString()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("AppLog", "resultCode:$resultCode")
        val uri = data?.data ?: return
        val takeFlags =
            Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        contentResolver.takePersistableUriPermission(uri, takeFlags)
        Log.d("AppLog", "granted uri: ${uri.path}")
    }
}

A: EDIT: Found a workaround, but it might not work some day.
It uses reflection to get the real path of the StorageVolume instance, and it uses what I had before to get the path of persistedUriPermissions . If there are intersections between them, it means I have access to the storageVolume.
Seems to work on emulator, which finally has both internal storage and SD-card.
Hopefully we will get proper API and not need to use reflections.
If there is a better way to do it, without those kinds of tricks, please let me know.
So, here's an example:
MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val storageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val storageVolumes = storageManager.storageVolumes
        val primaryVolume = storageManager.primaryStorageVolume
        checkAccessButton.setOnClickListener {
            val persistedUriPermissions = contentResolver.persistedUriPermissions
            val storageVolumePathsWeHaveAccessTo = HashSet<String>()
            Log.d("AppLog", "got access to paths:")
            for (persistedUriPermission in persistedUriPermissions) {
                val path = FileUtilEx.getFullPathFromTreeUri(this, persistedUriPermission.uri)
                        ?: continue
                Log.d("AppLog", "path: $path")
                storageVolumePathsWeHaveAccessTo.add(path)
            }
            Log.d("AppLog", "storage volumes:")
            for (storageVolume in storageVolumes) {
                val volumePath = FileUtilEx.getVolumePath(storageVolume)
                if (volumePath == null) {
                    Log.d("AppLog", "storageVolume \"${storageVolume.getDescription(this)}\" - failed to get volumePath")
                } else {
                    val hasAccess = storageVolumePathsWeHaveAccessTo.contains(volumePath)
                    Log.d("AppLog", "storageVolume \"${storageVolume.getDescription(this)}\" - volumePath:$volumePath - gotAccess? $hasAccess")
                }
            }
        }
        requestAccessButton.setOnClickListener {
            val intent = primaryVolume.createOpenDocumentTreeIntent()
            startActivityForResult(intent, 1)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("AppLog", "resultCode:$resultCode")
        val uri = data?.data ?: return
        val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        contentResolver.takePersistableUriPermission(uri, takeFlags)
        val fullPathFromTreeUri = FileUtilEx.getFullPathFromTreeUri(this, uri)
        Log.d("AppLog", "granted uri:$uri $fullPathFromTreeUri")
    }
}

FileUtilEx.java
/**
 * Get the full path of a document from its tree URI.
 *
 * @param treeUri The tree RI.
 * @return The path (without trailing file separator).
 */
public static String getFullPathFromTreeUri(Context context, final Uri treeUri) {
    if (treeUri == null)
        return null;
    String volumePath = getVolumePath(context, getVolumeIdFromTreeUri(treeUri));
    if (volumePath == null)
        return File.separator;
    if (volumePath.endsWith(File.separator))
        volumePath = volumePath.substring(0, volumePath.length() - 1);
    String documentPath = getDocumentPathFromTreeUri(treeUri);
    if (documentPath.endsWith(File.separator))
        documentPath = documentPath.substring(0, documentPath.length() - 1);
    if (documentPath.length() > 0)
        if (documentPath.startsWith(File.separator))
            return volumePath + documentPath;
        else return volumePath + File.separator + documentPath;
    return volumePath;
}

public static String getVolumePath(StorageVolume storageVolume){
    if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP)
        return null;
    try{
        final Class<?> storageVolumeClazz = StorageVolume.class;
        final Method getPath = storageVolumeClazz.getMethod("getPath");
        return (String) getPath.invoke(storageVolume);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * Get the path of a certain volume.
 *
 * @param volumeId The volume id.
 * @return The path.
 */
@SuppressLint("ObsoleteSdkInt")
private static String getVolumePath(Context context, final String volumeId) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        return null;
    try {
        final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            final Class<?> storageVolumeClazz = StorageVolume.class;
            //noinspection JavaReflectionMemberAccess
            final Method getPath = storageVolumeClazz.getMethod("getPath");
            final List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
            for (final StorageVolume storageVolume : storageVolumes) {
                final String uuid = storageVolume.getUuid();
                final boolean primary = storageVolume.isPrimary();
                // primary volume?
                if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                    return (String) getPath.invoke(storageVolume);
                }
                // other volumes?
                if (uuid != null && uuid.equals(volumeId))
                    return (String) getPath.invoke(storageVolume);
            }
            return null;
        }
        final Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        final Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
        final Method getUuid = storageVolumeClazz.getMethod("getUuid");
        //noinspection JavaReflectionMemberAccess
        final Method getPath = storageVolumeClazz.getMethod("getPath");
        final Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
        final Object result = getVolumeList.invoke(storageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            final Object storageVolumeElement = Array.get(result, i);
            final String uuid = (String) getUuid.invoke(storageVolumeElement);
            final Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);
            // primary volume?
            if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) {
                return (String) getPath.invoke(storageVolumeElement);
            }
            // other volumes?
            if (uuid != null && uuid.equals(volumeId))
                return (String) getPath.invoke(storageVolumeElement);
        }
        // not found.
        return null;
    } catch (Exception ex) {
        return null;
    }
}

/**
 * Get the document path (relative to volume name) for a tree URI (LOLLIPOP).
 *
 * @param treeUri The tree URI.
 * @return the document path.
 */
@TargetApi(VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    //TODO avoid using spliting of a string (because it uses extra strings creation)
    final String[] split = docId.split(":");
    if ((split.length >= 2) && (split[1] != null))
        return split[1];
    else
        return File.separator;
}

/**
 * Get the volume ID from the tree URI.
 *
 * @param treeUri The tree URI.
 * @return The volume ID.
 */
@TargetApi(VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
    final String docId = DocumentsContract.getTreeDocumentId(treeUri);
    final int end = docId.indexOf(':');
    String result = end == -1 ? null : docId.substring(0, end);
    return result;
}

activity_main.xml
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"
  android:gravity="center" android:orientation="vertical" tools:context=".MainActivity">

  <Button
    android:id="@+id/checkAccessButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="checkAccess"/>

  <Button
    android:id="@+id/requestAccessButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="requestAccess"/>

</LinearLayout>

To put it in a simple function, here:
/** for each storageVolume, tells if we have access or not, via a HashMap (true for each iff we identified it has access*/
fun getStorageVolumesAccessState(context: Context): HashMap<StorageVolume, Boolean> {
    val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
    val storageVolumes = storageManager.storageVolumes
    val persistedUriPermissions = context.contentResolver.persistedUriPermissions
    val storageVolumePathsWeHaveAccessTo = HashSet<String>()
    //            Log.d("AppLog", "got access to paths:")
    for (persistedUriPermission in persistedUriPermissions) {
        val path = FileUtilEx.getFullPathFromTreeUri(context, persistedUriPermission.uri)
                ?: continue
        //                Log.d("AppLog", "path: $path")
        storageVolumePathsWeHaveAccessTo.add(path)
    }
    //            Log.d("AppLog", "storage volumes:")
    val result = HashMap<StorageVolume, Boolean>(storageVolumes.size)
    for (storageVolume in storageVolumes) {
        val volumePath = FileUtilEx.getVolumePath(storageVolume)
        val hasAccess = volumePath != null && storageVolumePathsWeHaveAccessTo.contains(volumePath)
        result[storageVolume] = hasAccess
    }
    return result
}

A: for API 30 (Android 11)
@TargetApi(30)
private fun getVolumePathApi30(context:Context, uuid: String): String{
    // /storage/emulated/0/Android/data/{packageName}/files
    // /storage/0222-9FE1/Android/data/{packageName}/files
    val list = ContextCompat.getExternalFilesDirs(context, null)
.map{ it.canonicalPath.replace(reAndroidDataFolder, "") }

    // /storage/emulated/0
    // /storage/0222-9FE1
    val path = if( uuid == "primary") {
        list.firstOrNull()
    }else {
        list.find { it.contains(uuid, ignoreCase = true) }
    }

    return path ?: error("can't find volume for uuid $uuid")
}

A: None of these solutions work at all on Samsungs running Android 11 (+?), since there's seemingly no way to get a volume name on these devices.
MediaStore.getExternalVolumeNames() doesn't work.
StorageManager.getStorageVolumes() doesn't work.
https://forum.developer.samsung.com/t/usb-massive-storage-not-recognized-in-galaxy-s20-android-11/9758/6
And yet, somehow, certain file explorer apps like X-Plore are able to get these volume names.


text:
Q: Vfill after a table does not work I have a table at the top and  would like to place the title at the page mid - or place it with vspace. But it doesn't work. Here is my code and my problem is on line 17 (the vfill do nothing).
\documentclass[a4paper, oneside]{memoir}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}

\begin{document}

\begin{table}[t]
   \begin{tabularx}{\textwidth}{|XX|} \hline
    \textbf{Received:}           & \textbf{Approved:}  \\
                              & \textbf{Date:}      \\
                              & \textbf{Signature:} \\
\textbf{(for the instructor)} &
    \\ \hline
  \end{tabularx}
\end{table}

\vfill %Why does this do nothing?

\begin{center}
\begin{minipage}{.6\textwidth}
\begin{center}
\Large{{\itshape Course}\\}
{\fontsize{40}{48} \textsc{\textbf{Title}}}\\
\rule{7.5cm}{0.1cm}\\
\vspace{0.25cm}
\begin{large}
\textsc{%
University\\
Institution\\
\today\\
}%
\vspace{0.25cm}
\rule{3.75cm}{0.1cm}
\end{large}
\end{center}
\end{minipage}
\end{center}

\vfill

Author \hfill E-mail

\end{document}

Kind regards and thank you very much in advance.

A: table creates a float. So in the main page, there is nothing at all before the \vfill so there is no need, LaTeX thinks, to fill it. (There is nothing to fill.) However, you presumably don't want a float here: you don't want the tabular to move. So don't put it in a table:
\documentclass[a4paper, oneside]{memoir}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}

\begin{document}

\noindent\begin{tabularx}{\textwidth}{|XX|} \hline
\textbf{Received:}           & \textbf{Approved:}  \\
                          & \textbf{Date:}      \\
                          & \textbf{Signature:} \\
\textbf{(for the instructor)} &
\\ \hline
\end{tabularx}

\vfill %Why does this do nothing?

\begin{center}
\begin{minipage}{.6\textwidth}
\centering
{\Large\itshape Course\\}
{\fontsize{40}{48} \textsc{\textbf{Title}}}\\
\rule{\linewidth}{0.1cm}\\
\vspace{0.25cm}
\large
\textsc{%
University\\
Institution\\
\today\\
}%
\vspace{0.25cm}
\rule{3.75cm}{0.1cm}
\end{minipage}
\end{center}

\vfill

Author \hfill E-mail

\end{document}


text:
Q: Python " : " precedence compared to other operators in array index I'm stumped on a line of code in Python that I'm supposed to translate. Most websites don't have a clearer example of my situation now.

output_qr_dim, and i are just integers

output_r[output_qr_dim * i:output_qr_dim * i + output_qr_dim, output_qr_dim * j:output_qr_dim * j + output_qr_dim] = ra

At first I thought it means you just complete the operations on either sides of the :, then only perform the slicing. But according to this website, http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html, the slicing takes precedence over the other operations, so I'm rather confused at the moment.
Any help would be appreciated


text:
Q: Получение комментариев facebook через post запрос Пробую получить комментарии в facebook
Запрос происходит по ссылке: https://www.facebook.com/ajax/ufi/comment_fetch.php?dpr=1
Скопировал полностью Request Headers, кроме
:authority:www.facebook.com
:method:POST
:path:/ajax/ufi/comment_fetch.php?dpr=1
:scheme:https

И попробовал выполнить post запрос
r = requests.post('https://www.facebook.com/ajax/ufi/comment_fetch.php?dpr=1', headers = headers)

На запрос получаю ошибку 408


text:
Q: Get terminal output (Python) Hello I've been tryng to get the terminal output of my program in python like so:
import os
print('test')
output = os.popen("python inter.py")
preprocessed = output.read()
print(preprocessed)

(file name is inter.py)
However, the program does nothing and just runs in an infinite loop.
Are there any obvious mistakes here?
(I've tried using subsystem.run() but this seemed simpler)
Thanks

A: use stdout variable to get the output
In the below code we are calling inter.py from pro.py:
pro.py
process = subprocess.run(['python3.10', 'inter.py'],
                         stdout=subprocess.PIPE,
                         universal_newlines=True)
print(process.stdout)

inter.py
print("Hello World")

Output:
$ python3.10 inter.py
Hello World