text:
Q: Audio source not appearing in pulseaudio but playing over headphone jack I use a headset with internal USB sound card running on Ubuntu 16.04 with KDE 5.5 and Firefox 56.0 (64-bit). Recently playing music using the Amazon Music web player stopped working.

*

*Using the same setup, music from other sources, like Youtube, works without problem.

*When I start a track in the Amazon Player, it starts and the progress bar is moving. However, no music is playing over the headphones.

*When I start pavucontrol, no new entry in the playback tab is created for the audio source and there is no movement in the output devices tab.

Now for the strange part:

*

*When I plug my earbuds headphones into the audio jack, I hear the music Amazon is playing.

*There is still no movement in the devices tab and no entry in the playback tab.

*When I mute the internal sound card (the one that is used for the earbuds), the sound stops.

I have tried
alsactl restore

and removing the pavu config files, but both did not solve this problem. Additionally I installed virtually all pulseaudio component and added the Phonon VLC backend. I tried disabling all devices but my external sound card, but nothing worked.
Does anyone have an idea, what is going on here?
Edit:
On chromium, the player works and the source shows up in pavucontrol, as long as I play music from my library (i.e. tracks I 'own' as opposed to tracks I added via Prime 'for free streaming'). The other tracks start, immediately stop and skip to the next track.

A: This seemed to be a problem with the flash player plugin being no longer supported for 16.04. Installing the chromium flash player plugin solved my problem:
$ sudo apt-get install browser-plugin-freshplayer-pepperflash

I found this solution in the following question which also links to additional information: Flash plugin for Firefox on Ubuntu 16.04


text:
Q: Increase ulimit in cygwin I am having a php loop script, For sudden it gives me error "core dump!", then it stops. people advice me to increase the ulimit, so i just wonder, how to increaste the ulimit?
am getting:
   mzapc@mzabox ~/test

   $ ulimit -n
   256

   mzapc@mzabox ~/test
   $ ulimit -Hn
   3200

I've tried to do $ ulimit -s 2046, with failed attempt. nothing comes out still same response. any advice?, thank you.

A: To debug a php script one way is to run
php -e <your-script>

http://linux.die.net/man/1/php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Isomorphism question about groups I know that the group $\mathbb{Z}/9\mathbb{Z}$ is not isomorphic to the group $\mathbb{Z}/3\mathbb{Z}\times\mathbb{Z}/3\mathbb{Z}$, but I just do not know how to prove this.

A: Hint: the group $\mathbb{Z}/9\mathbb{Z}$ is cyclic. Is $\mathbb{Z}/3\mathbb{Z}\times\mathbb{Z}/3\mathbb{Z}$ cyclic?

A: $$\mathbb Z_9=\{\bar{0},\bar{1},\bar{2},\bar{3},\bar{4},\bar{5},\bar{6},\bar{7},\bar{8},\bar{9}\}=\langle \bar{1} \rangle$$ and $$\mathbb Z_3\times\mathbb Z_3=\{(x,y)\mid x,y\in\mathbb Z_3\}$$ By checking, we find that the equation $3*x=0$ has $3$ solutions in $\mathbb Z_9$ while the same equation has $9$ solutions in the other group.

A: Suppose, seeking a contradiction, that $\varphi:\mathbb{Z}_9 \rightarrow \mathbb{Z}_3 \times \mathbb{Z}_3$ is an isomorphism.
Suppose $\varphi(1)=(a,b) \in \mathbb{Z}_3 \times \mathbb{Z}_3$.  Then
\begin{align*}
\varphi(3) &= \varphi(1+1+1) \\
&= \varphi(1)+\varphi(1)+\varphi(1) & \text{since } \varphi \text{ is an homomorphism} \\
&= (a,b)+(a,b)+(a,b) & \text{since } \varphi(1)=(a,b) \\
&= (a+a+a,b+b+b) \\
&= (0,0) & \text{since } a \in \mathbb{Z}_3 \text{ and } b \in \mathbb{Z}_3.
\end{align*}
Similarly, we can show $\varphi(-3)=(0,0)$, contradicting that $\varphi$ is a bijection.

A: Hint: $\mathbb{Z}_9$ has only one subgroup of order three, namely $\{0,3,6\}$.


text:
Q: Remove files, which provided by pipe I have this command chain:
find . -print | grep php | xargs grep 'eval' -sl | xargs wc -l | grep ' [1-2][0-9] '

This provide me this output:
 14 ./includes/js/calendar/lang/vgju.php
 18 ./includes/phpInputFilter/default.php
 14 ./includes/Archive/eula.php
 18 ./media/system/js/json.php

This files are infected php files and I would like to remove it with my chain.
How can I do it?

A: Although you can probably do this whole thing with find command only you can try appending |xargs rm -f to that command.
Here's what it would look like
find . -print | grep php | xargs grep 'eval' -sl | \
    xargs wc -l | grep ' [1-2][0-9] ' | \
    cut -f 2 -d ' ' | xargs rm -f

Note that the xargs rm command works here because you know there aren't any special characters in the file names. If there might be spaces in the file names, you can use xargs -d '\n' rm -f (Linux only).


text:
Q: Love2d "bad argument #2 to 'draw' (Quad expected, got nil)" I am currently trying to make a flappy bird copy and I am having trouble when attempting to spawn in pipes (when a pipe should spawn I get the following error: "bad argument #2 to 'draw' (Quad expected, got nil)").
The functions that are causing the problem are the following (they are located in three different classes):
Pipe = Class{}

local PIPE_IMAGE = love.graphics.newImage('FlappyBirdPipe.png')

PIPE_SCROLL = -60

PIPE_WIDTH = 20
PIPE_HEIGHT = 160

function Pipe:init(orientation, y)
    self.x = VIRTUAL_WIDTH
    self.y = y

    self.width = PIPE_IMAGE:getWidth()
    self.height = PIPE_HEIGHT

    self.orientation = orientation
end

function Pipe:render()
    love.graphics.draw(PIPE_IMAGE, self.x,
        (self.orientation == 'top' and self.y + PIPE_HEIGHT or self.y),
        0, 1, (self.orientation == 'top' and -1 or 1))
end

function PipePair:update(dt)
    if self.x > -PIPE_WIDTH then
        self.x = self.x - PIPE_SCROLL * dt
        self.pipes['lower'].x = self.X
        self.pipes['upper'].x = self.x
    else
        self.remove = true
    end
end

If anything is unclear or I have left out some vital information I am more than glad to give more information (I am new to Stack Overflow so I am not really sure how everything here works).
(I am using love2d version 11.3 in vscode)
Edit: I pinpointed the error to how I update the self.x in the Pipe class from the PipePair class' update function. Somehow this altering of self.x seems to make it nil.

A: I just figured it out!
function PipePair:update(dt)
    if self.x > -PIPE_WIDTH then
        self.x = self.x - PIPE_SCROLL * dt
        self.pipes['lower'].x = self.X
        self.pipes['upper'].x = self.x
    else
        self.remove = true
    end
end

There is a capital X on self.pipes['lower'].x = self.X. For so long I have been trying to figure it out and it was all due to an X. Wow, I feel so stupid.

A: the error is saying that a variable is nil, this might have been caused by a typo. and the problem is being caused because of a capital X in self.X
try:
function PipePair:update(dt)
    if self.x > -PIPE_WIDTH then
        self.x = self.x - PIPE_SCROLL * dt
        self.pipes['lower'].x = self.x -- typo was here
        self.pipes['upper'].x = self.x
    else
        self.remove = true
    end
end


text:
Q: Can not use eval in Matlab This is my code :
 collection = cubsfantony 848 visa/mastercard, money order/cashiers checks

 temp = regexprep(collection,' ',''',''')

%return
temp = cubsfantony','848','visa/mastercard,','money','order/cashiers','checks'  % why?

eval(['words = {''',temp,'''};']);

And Matlab return as follows:
 Error: Unexpected MATLAB expression.

Could anyone help me ?

A: There's no need to use eval at all... please don't use it.  It's considered bad practice.  However, it is my understanding that you want to split up all strings that are separated by spaces and place them into a separate cell array.  You can easily do that with strsplit and use the space character as the splitting delimiter character:
collection = 'cubsfantony 848 visa/mastercard, money order/cashiers checks';
out = strsplit(collection, ' ');

We get:
>> out = strsplit(collection, ' ')

out =

  Columns 1 through 4

    'cubsfantony'    '848'    'visa/mastercard,'    'money'

  Columns 5 through 6

    'order/cashiers'    'checks'


text:
Q: build object from another object that compares its keys to values in an array The following object is used as a starting point to populate options of a select box in the UI of an app:
const months = {
  "1": "Jan",
  "2": "Feb",
  "3": "Mar",
  "4": "Apr",
  "5": "May",
  "6": "Jun",
  "7": "Jul",
  "8": "Aug",
  "9": "Sep",
  "10": "Oct",
  "11": "Nov",
  "12": "Dec"
}

The options for the select box must be limited though based on the contents of another array.  Here is an example of that array:
const existingMonths = [
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  12
];

So in this example, the object of final options for the select box should be:
const availableMonths = {
  "9": "Sep",
  "10": "Oct",
  "11": "Nov"
}

I'm having difficulty figuring out how to build the availableMonths object.  This does not give the desired output:
const availableMonths = Object.entries(months).filter(k => !existingMonths.includes(k));

A: You need to take the key from the array of entries and check with the numerical value of the key against the value of the array. Finally create a new object from the entries.

const
    months = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" },
    existingMonths = [  1,  2,  3,  4,  5,  6,  7,  8,  12],
    availableMonths = Object.fromEntries(Object
        .entries(months)
        .filter(([k]) => !existingMonths.includes(+k))
    );

console.log(availableMonths);

A:

const months = {
  "1": "Jan",
  "2": "Feb",
  "3": "Mar",
  "4": "Apr",
  "5": "May",
  "6": "Jun",
  "7": "Jul",
  "8": "Aug",
  "9": "Sep",
  "10": "Oct",
  "11": "Nov",
  "12": "Dec"
}

const existingMonths = [1, 2, 3, 4, 5, 6, 7, 8, 12]

const availableMonths = Object.fromEntries(
   Object.entries(months).filter(([k, v]) => !existingMonths.includes(+k))
)

console.log(availableMonths)

A: Step 1: Shallow Copy months object
Step 2: Loop throught existingMonths
Step 3: Delete shallow copied properties by comparing with existingMonths
elements

let
months = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" },
existingMonths = [  1,  2,  3,  4,  5,  6,  7,  8,  12],availableMonths = {}

Object.assign(availableMonths,months);

existingMonths.forEach((monthNumber) =>{delete availableMonths[monthNumber]})

console.log(availableMonths);


text:
Q: Override JComponent.getBaselineResizeBehavior() but keep Java5 compatibility For my Swing project, I need to support both Java 5 and Java 6.
I have defined a custom JComponent (call it Picture) and, after embedding it in a JScrollPane, I put it in a JPanel that uses DesignGridLayout manager.
DesignGridLayout supports baseline alignment thanks to swing-layout open source library (implements baseline support for Java 5 and provides compatibility with the new Java 6 baseline support).
My Picture class overrides public int getBaseline(int width, int height) so that I can define a correct baseline for it. Note that "override" is not completely correct: it overrides the method on Java6 but defines it in Java5.
When I run my sample app on Java5, everything is fine: the Picture baseline I have defined is correctly used.
However, when I use Java6, my Picture#getBaseline() method does not get called! And of course the baseline alignment of my picture is terrible (centered).
After checking in Java6 source, I have seen that, in BasicScrollPaneUI, getBaseline() calls first getBaselineResizeBehavior() on the viewport component (my Picture instance).
And it will call getBaseline() only if getBaselineResizeBehavior() returns Component.BaselineResizeBehavior.CONSTANT_ASCENT.
Now my problem is that getBaselineResizeBehavior() is a Java6 method of JComponent that I cannot implement in Java5 because it returns an enum Component.BaselineResizeBehavior which does not exist in Java5.
So my question (finally) is: how can I implement (or simulate?) getBaselineResizeBehavior() so that my class can still compile and run in a Java5 environment?

A:
how can I implement (or simulate?)
  getBaselineResizeBehavior() so that my
  class can still compile and run in a
  Java5 environment?

You cannot compile this method declaration with the Java 5 library because the type Component.BaselineResizeBehaviour does not exist:
public Component.BaselineResizeBehavior getBaselineResizeBehavior()

You must compile using Java 6. Your classes can still run on Java 5 if you compile to a 1.5 target, but you must take care that they handle absent types/methods gracefully. Add tests for these cases as you encounter them. Ensure developers attempt to run their code on Java 5 prior to check-in.
For example, this class...
public class MyPanel extends javax.swing.JPanel {

    public java.awt.Component.BaselineResizeBehavior getBaselineResizeBehavior() {
        return java.awt.Component.BaselineResizeBehavior.OTHER;
    }

    public static void main(String[] args) {
        new MyPanel();
        System.out.println("OK");
    }

}

...can be compiled and run as follows using the javac JDK compiler:
X:\fallback>javac -version
javac 1.6.0_05

X:\fallback>javac -target 1.5 MyPanel.java

X:\fallback>"C:\Program Files\Java\jre1.5.0_10\bin\java.exe" -cp . MyPanel
OK

All the popular IDEs offer options for generating older class versions. You can use reflection to test for the existence of methods/types at runtime when you need to make decisions about code paths.
Failure to set the target will result in errors like this:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version n
umber in .class file
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)

A: I would make a subclass of Picture, perhaps called PictureJava6, which implemented the getBaselineResizeBehaviour(), and when creating instances of Picture, do:
public Component pictureFactory() {
    if(javaVersion > "1.6") {
        return new PictureJava6();
    } else {
        return new Picture();
    }
}

A: You can use reflection to try to get the CONSTANT_ASCENT return value by name.  If it can't be reflected, you are J5, otherwise J6.  This side-steps the explicit dependency and allows compilation to J5.
Foll. is an example of doing this for dialog modality:
try {
    Field  fld=Class.forName("java.awt.Dialog$ModalExclusionType").getField("TOOLKIT_EXCLUDE");
    Method mth=getClass().getMethod("setModalExclusionType",new Class[]{fld.getType()});
    mth.invoke(this,new Object[]{fld.get(null)});
    }
catch(Throwable thr) {
    log.errorln("Unable to configure window to be unaffected by modal dialogs - dialogs may need to be closed to operate help.");
    log.errorln("Use Java 6 or later to avoid modal dialogs conflicting with the help system.");
    log.errorln("Exception: "+thr);
    }

UPDATE: I originally posted code with the J5 code commented out; I've changed that because I realized it confuses the issue by implying that the J5 code would not work in J6 - it does.

A: I think that the return type is not treated as part of the a method signature in resolving virtual functions and overloads; it might be that you can define your "overriding" method to return Object, and reflect out the return Enum per my first answer.  Since you're compiling in J5 it won't be a compile time conflict, but the JVM should still choose your method to override... It might or it might throw a runtime exception.  Still, it's worth a try.
For example:
public Object getBaselineResizeBehavior() {
    Object ret;
    // reflect out the return value
    return ret;
    }

Any error handling can be System.out, purely for debugging, since this will not be invoked unless you are J6, so the reflection, correctly coded, should always work if invoked.
And I would, of course, comment this method to make it very clear what's going on.


text:
Q: How to debug a Visual Studio 2013 Extension Update page error? I'm trying to open Product Updates in Visual Studio 2013 / Extension and Updates / Updates / Product Updates however whenever I open it it shows an error message with the following message:
'=' is an unexpected token. The expected token is ';'. Line 124, position 93.
Is there a way I can investigate this error, is there an editable configuration file or how to go about?
Most likely irrelevant but in case related I'm trying to update following the recommendation to the following issue Visual Studio 2013: Database Project MSBuild error


text:
Q: How to make Mercurial on Windows use an SSH key for push/pull? How to tell TortoiseHg (or Mercurial in general) that I want to use a given SSH key when pushing/pulling to/from a remote repository?

A: On Windows, see Accessing SSH-controlled repositories from a Windows client: you need PuTTY, plink and a particular config setting.
To put that in a particular repository, put in .hg/hgrc
[ui]
ssh="C:\path to\plink.exe" -ssh -i "C:\your path to\private.key"

Also note that you don't need to specify the key path if you use pageant.

A: You need to use PuTTY, set up a profile in that for the connection to the remote repository.  and then in TortoiseHg you can then connect to ssh://profilename/
e.g. I set one up for bitbucket and called it bitb, so the connection is
ssh://bitb/url-to-repo.


text:
Q: Modify element text with loop in xml file using python I have been doing some modifications on an .xml file using python and lxml library and ElementTree. I have this result:
<component xmlns:xsi="http://www.w3.orgr">
  <memoryMaps>
    <memoryMap>
      <name>name</name>
      <description>description</description>
      <peripheral>
        <name>periph</name>
        <description>description</description>
        <baseAddress>0x0</baseAddress>
        <range>0x8</range>
        <width>32</width>
        <registers>
          <register>
            <name>reg1</name>
            <displayName>1</displayName>
            ....
          </register>
          <register>
            <name>reg2</name>
            <displayName>1</displayName>
              .................
           </register>
           <register>
            <name>reg3</name>
            <displayName>1</displayName>
             ..................
           </register>
       </registers>
      </peripheral>
    </memoryMap>
  </memoryMaps>
</component>

what I want now is in every 'register' to have 'name' and 'displayName' with same text (by copying the text of name in the displayName) like this:
<registers>
      <register>
        <name>reg1</name>
        <displayName>reg1</displayName>
        ....
      </register>
      <register>
        <name>reg2</name>
        <displayName>reg2</displayName>
          .................
       </register>
       <register>
        <name>reg3</name>
        <displayName>reg3</displayName>
         ..................
       </register>
   </registers>

I tried a code like this after parsing my file:
 for register in root.findall('.//register'):
    tempo = register.find('.//name').text
    for EL in root.iter('displayName'):
        EL.text = tempo

This seems to replace only in the last register correctly, and the rest of registers have wrong display name. I know I have a problem with my loop maybe?
Please advice
Thank you!

A: from lxml import etree

root = etree.parse(r'<your file.xml>')

for name in root.xpath('//name[./following-sibling::displayName]'):
    name.getnext().text = name.text

print( etree.tostring(root, pretty_print=True).decode('utf-8') )

Prints:
<component xmlns:xsi="http://www.w3.orgr">
  <memoryMaps>
    <memoryMap>
      <name>name</name>
      <description>description</description>
      <peripheral>
        <name>periph</name>
        <description>description</description>
        <baseAddress>0x0</baseAddress>
        <range>0x8</range>
        <width>32</width>
        <registers>
          <register>
            <name>reg1</name>
            <displayName>reg1</displayName>
            ....
          </register>
          <register>
            <name>reg2</name>
            <displayName>reg2</displayName>
              .................
           </register>
           <register>
            <name>reg3</name>
            <displayName>reg3</displayName>
             ..................
           </register>
       </registers>
      </peripheral>
    </memoryMap>
  </memoryMaps>
</component>

A: Recommend you a simple library.
from simplified_scrapy import SimplifiedDoc, utils
# xml = utils.getFileContent('your xml path')
xml = '''
        <registers>
          <register>
            <name>reg1</name>
            <displayName>1</displayName>
            ....
          </register>
          <register>
            <name>reg2</name>
            <displayName>1</displayName>
              .................
           </register>
           <register>
            <name>reg3</name>
            <displayName>1</displayName>
             ..................
           </register>
       </registers>
'''
doc = SimplifiedDoc(xml)  # create doc
registers = doc.selects('register')

for r in registers:
    r.displayName.setContent(r.name.html)

# Or
names = doc.selects('register>name')

for n in names:
    n.setContent(n.next.html)

    # Or
    # n.setContent(n.getNext('displayName').html)

print(doc.html)

Result:
    <registers>
      <register>
        <name>reg1</name>
        <displayName>reg1</displayName>
        ....
      </register>
      <register>
        <name>reg2</name>
        <displayName>reg2</displayName>
          .................
       </register>
       <register>
        <name>reg3</name>
        <displayName>reg3</displayName>
         ..................
       </register>
   </registers>

Here are more examples. This lib is easy to use.


text:
Q: Convert base-2 binary number string to int I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt()
255

Is there a way to do this in Python?

A: You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:
>>> int('11111111', 2)
255

Here is documentation for Python 2, and for Python 3.

A: Just type 0b11111111 in python interactive interface:
>>> 0b11111111
    255

A: If you wanna know what is happening behind the scene, then here you go.
class Binary():
    def __init__(self, binNumber):
        self._binNumber = binNumber
        self._binNumber = self._binNumber[::-1]
        self._binNumber = list(self._binNumber)
        self._x = [1]
        self._count = 1
        self._change = 2
        self._amount = 0
        print(self._ToNumber(self._binNumber))
    def _ToNumber(self, number):
        self._number = number
        for i in range (1, len (self._number)):
            self._total = self._count * self._change
            self._count = self._total
            self._x.append(self._count)
        self._deep = zip(self._number, self._x)
        for self._k, self._v in self._deep:
            if self._k == '1':
                self._amount += self._v
        return self._amount

mo = Binary('101111110')

A: Here's another concise way to do it not mentioned in any of the above answers:
>>> eval('0b' + '11111111')
255

Admittedly, it's probably not very fast, and it's a very very bad idea if the string is coming from something you don't have control over that could be malicious (such as user input), but for completeness' sake, it does work.

A: A recursive Python implementation:
def int2bin(n):
    return int2bin(n >> 1) + [n & 1] if n > 1 else [1]

A:
If you are using python3.6 or later you can use f-string to do the
  conversion:

Binary to decimal:
>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.
>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

A: For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot.  It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.
def BitsToIntAFast(bits):
  m,n = bits.shape
  a = 2**np.arange(n)[::-1]  # -1 reverses array of powers of 2 of same length as bits
  return bits @ a

A: Another way to do this is by using the bitstring module:
>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

Note that the unsigned integer (uint) is different from the signed integer (int):
>>> b.int
-1

Your question is really asking for the unsigned integer representation; this is an important distinction.
The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

A: For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'

int(bin(a), 2)
# 10
eval(bin(a))
# 10

A: Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])


text:
Q: Why can't I set the focus to an ASP.Net TextBox control in Javascript or from code behind? I'm trying to set the focus to a TextBox control (which is inside an UpdatePanel) in an ASP.Net application (C#). I've tried the following in the code behind:
tbxName.Focus();
Page.SetFocus(tbxName);
tsmManageTables.SetFocus(tbxName);

None of those worked, so then I went to Javascript. Here's my Javascript function:
function SetControlFocus(ctrlID) {
  var ctrl = document.getElementById(ctrlID);
  ctrl.focus();
}

Here's the method in code behind that's calling it:
private void SetControlFocus(Control ctrl)
{
  StringBuilder focus = new StringBuilder();
  focus.AppendLine("");
  ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false);
}

And the call:
SetControlFocus(tbxName);

I've also tried the Javascript:
(function($) {
  SetControlFocus = function(ctrlID) {
    var ctrl = $('<%= ' + ctrlID + ' %>');
    ctrl.focus();
  };
})(jQuery);

With either version of the Javascript function, I get the error

"Object ctl00_MainContent_tbxName has no method 'focus'"

What am I doing wrong?
UPDATE:
I tried Karl's suggestion of using a class selector instead of the ID selector with the ugly <%= =>, but it didn't work. Now I'm getting a different error:

Uncaught ReferenceError: className is not defined

with the Javascript:
(function($) {
  SetControlFocus = function(ctrlClass) {
    var ctrl = $('.' + ctrlClass);
    ctrl.focus();
  };
})(jQuery);

the markup:
<asp:TextBox ID="tbxName" runat="server" CssClass="className"></asp:TextBox>

the calling method:
private void SetControlFocus(Control ctrl)
{
  StringBuilder focus = new StringBuilder();
  focus.AppendLine("");
  ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false);
}

the call (C#):
SetControlFocus(tbxName);

and the generated HTML for the TextBox:
<input name="ctl00$MainContent$tbxName" type="text" id="ctl00_MainContent_tbxName" class="className" />

UPDATE 2:
I played around some more with this and made progress (I think). Now I'm not getting any error messages, but the focus still isn't going to the TextBox. Here's my current jQuery function:
(function($) {
  SetControlFocus = function(ctrl) {
    //give the control focus
    alert(ctrl);
    ctrl.focus();
  };
})(jQuery);

And here's the C# method where I call it:
private void SetControlFocus(TextBox ctrl)
{
  StringBuilder focus = new StringBuilder();
  focus.AppendLine("");
  ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false);
} //end method SetControlFocus

Notice that I'm passing the control's ClientID to the Javascript function. The weird thing is that the Javascript is taking the ClientID and actually "capturing" the control object, rather than a string containing the ClientID. The alert is working, it gives me [object HTMLInputElement] in the alert. Any tips?
UPDATE 3:
I've modified the Javascript function:
(function($) {
  SetControlFocus = function(ctrlSelector) {
    alert(ctrlSelector);
    $(ctrlSelector).focus();
  };
})(jQuery);

and the calling method:
private void SetControlFocus(TextBox ctrl)
{
  StringBuilder focus = new StringBuilder();
  focus.AppendLine("");
  ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false);
}

(notice the addition of single quotes around the argument - '{0}').
Now I'm getting the correct selector (the alert responds with #ctl00_MainContent_txtName), no errors, but the TextBox still isn't getting focus.

A: Your second javascript is missing the hash sign to denote the ID selection.
(function($) {
  SetControlFocus = function(ctrlID) {
    var ctrl = $('#<%= ' + ctrlID + ' %>');
    ctrl.focus();
  };
})(jQuery);

This should do the trick.

A: You are missing the # for an ID selector.
Either do this:
var ctrl = $('#<%= ' + ctrlID + ' %>');

Or use a class name in your ASP.NET TextBox control instead, like this:
<asp:TextBox id="TextBox1" runat="server" CssClass="TheTextBox" />

Now your selector becomes this:
var ctrl = $('.TheTextBox');

Note: Using class selectors versus ID selectors greatly simplifies the selector syntax and removes the gnarly embedded code block (<%= ... %>) syntax you were using. While it is not as fast as an ID selector, the gains of simpler and more maintainable code are definitely worth it in my mind.
UPDATE:
Wrap the entire selector value in single quotes, like this:
var ctrl = $("'." + ctrlClass + "'");

A: I finally figured out a way to make this work! I moved the jQuery SetControlFocus() call into another jQuery function that I'm calling from my code behind. The code behind method calls MessageDialog(), which now looks like this:
(function($) {
  MessageDialog = function(title, dialogText, focusID) {
    //add the dialog div to the page
    $('body').append(String.Format("

{1}

", title, dialogText));
    //create the dialog
    $('#messageDialog').dialog({
      modal: true,
      resizable: false,
      draggable: false,
      close: function(event, ui) { $('body').find('#messageDialog').remove(); },
      buttons:
        [{
          text: 'OK',
          click: function() {
          $(this).dialog('close');
          //Set focus to the control object in argument #3 (if provided)
            if (focusID.length > 0) {
              SetControlFocus(focusID);
            }
          }
        }]
      });
    };
})(jQuery);

SetControlFocus() remains:
(function($) {
  SetControlFocus = function(ctrlSelector) {
    $(ctrlSelector).focus();
  };
})(jQuery);

And my calling method in C# (which is an overload of a method I already had) is:
private void DisplayMessageDialog(string msgTitle, string msgText, string ctrlID)
{
  StringBuilder msg = new StringBuilder();
  msg.AppendLine("");
  ClientScript.RegisterStartupScript(this.GetType(), "messageDialog", msg.ToString(), false);
} //end method DisplayMessageDialog (overload #2 - specifies a control to get focus
  //after the dialog is dismissed)


text:
Q: Change the default behavior of Double.ToString() According to this link, Double.ToString() uses NumberFormatInfo.CurrentInfo to format doubles. But CurrentInfo has 2 decimals by default and is read-only so I cant change it. How can I change this default behaviour? (calling the overload of ToString() is not a solution)

A: You can change CurrentInfo for current thread by changing Threading.Thread.CurrentCulture.
Also, you're not right saying CurrentInfo has 2 decimals by default. CurrentInfo is set based on current system locale, which means you can get different results depending on machine configuration your program is running at.


text:
Q: python calling a def() inside of def() I'm making a package for my python assistant and have found a problem.
Im importing the following program into the main script.
import os

def load() :
    def tts(name) :
        os.system("""PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(' """ + name + " ');"

how do i call the function into my program
ive tried :
import loadfile
loadfile.load().tts("petar")

and it didn't work

A: You are never supposed to expose a sub-function outside of its scope, in this case, the tts method outside load. It's actually imposible to access tts without exposing its reference outside of your load() method.  I suggest you to rather use a class like this:
In loadfile.py:
import os

class LoadFile(object):
    def tts(self, name):
        os.system("""PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(' """ + name + " ');")

def load():
    return LoadFile()

On main code:

import loadfile
loadfile.load().tts("petar")

A: When you run loadfile.load().tts("petar"), it is equivalent to:
v = loadfile.load()
v.tts("petar")

Your method loadfile.load() does not return any value, so v is assigned None. Then you try to call tts() against None, which is an error.
Why are you trying to do this? Maybe you want to create a class?

A: you can follow this code to call def within def
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

Reference URL

A: You also can use the decorator "@classmethod" to create some funcion inside your class that doesn't need create an instance of your class.
In your "my_package.py" file you can do some like this:

class Loaders():

   @classmethod
   def load(self, parameter):
      return self.tts(parameter)

   def tts(self):
      os.system("""PowerShell...""")
      ...
      return self

In python files that will call this "my_package.py" you can code:

       filename        classname
          |                |
          V                V
from my_package import Loaders

# to use your method tts you can Instantiate your class and after call the method:
x = Loaders()
x.tts('petar')

# or you can call directly some classmethod
x = Loaders.load('petar')

If you need change the steps when initializing your class, ... you can edit the instantiation method init

class Loaders():

   def __init__(self, some_param):
      ...do something...

      return self

...
# so when you when you call
x = Loaders()

# " ... do something ..." will do and the class object (self) will return.


text:
Q: How to use a sprite inside a css notification box? (and not a single image) The Template I use has notication box like text-info, text-alert, text-tip classes, which are color boxes with an icon at the beginning.
I managed to add a lot of different icons, so in order to keep my website quick, I wish to replace the icons by a single sprite.
And so I did.
But... I can't find a way to neatly vertical-align the icon Inside the box...
I would have put a screen capture if only I could, but I'm a newbie here... so you will have to visit this page to see what I am talking about (please remove the spaces aroundd rouchenergies, and when you land on the page, go at the bottom of the article, look for 2 grey notification boxes looking very similar) :
http://www.rouchenergies.fr/qui-sommes-nous/qualifications/rge-qualibois.html
The above box is the template's css, with a single class called text-file-pdf.
HTML =

bla bla bla

The lower box is my css, which needs 2 different classes : 1 for box called "box-gris", 1 for icon called "file-pdf"
HTML =

bla bla bla

Let's have a look to the css :
CSS OF THE TEMPLATE:

.text-file-pdf {
 border-top: 2px solid #e5e5e5;
 border-bottom: 2px solid #e5e5e5;
 background: #f2f2f2 url(../../../images/small-n-flat-master/file-pdf.png) no-repeat;
}
.text-file-pdf {
 background-position: left center;
 padding: 0.8em 0.8em 0.8em 5em;
 min-height: 20px;
}

CSS OF MY OWN:

.box-gris {
 border-top: 2px solid #e5e5e5;
 border-bottom: 2px solid #e5e5e5;
 background-color: #f2f2f2;
}

.box-gris {
 padding: 0.8em 0.8em 0.8em 5em;
 min-height: 20px;
}

.file-pdf {
 display: inline-block;
 background-image: url(../../../images/small-n-flat-master/sprite-small-n-flat.png);
 background-repeat: no-repeat;
 width: 60px;
 height: 24px;
 float: left;
 margin-left: -5em;
 vertical-align: middle;
}
.file-pdf {
 background-position: 0 -1080px;
}

I Wonder why the vertical-align: middle; does not work... and/or what I should be doing instead of this?
Any help welcome;)


text:
Q: Memory leak in weakValue map reference for synchronized method I am creating an interface for executing methods concurrently, while abstracting away the synchronization details (To swap for a distributed implementation when needed). I've created a single jvm implementation that allows Strings to be used as the mutex by storing them in a map to ensure one reference is used, even if Strings of different references are passed in. The concurrency seems to work fine, however I was surprised to see that the test was showing the reference count is never decreasing. I assumed using WeakValues() would be enough to prevent memory leaks, but it seems that is not the case. Can anyone point out what could be causing this leak?
public class SynchronousMethodExecutorSynchronizedImpl implements ISynchronousMethodExecutor {

// mutex map to provide string references
final Map<String, String> mutexMap = new MapMaker()
    .weakValues()
    .makeComputingMap(
        new Function<String, String>() {
        @Override
        public String apply(String id) {
            return id;
        }
    });

@Override
public Object doSynchronousMethod(String domain, String id, ISynchronousMethod synchronousMethod) {
    synchronized(mutexMap.get(domain + "." + id))
    {
        return synchronousMethod.execute();
    }
}

}
Here is the test that is failing at the very last assertion:
public class SynchronousMethodExecutorSynchronizedImplTest extends TestCase {
int counter;
SynchronousMethodExecutorSynchronizedImpl methodExecutor;

@Override
public void before() throws Exception {
    super.before();

    methodExecutor = new SynchronousMethodExecutorSynchronizedImpl();
}

@Test
public void concurrentExecute() throws InterruptedException {
    assertEquals(0, counter);

    for(int i=0; i<1000; i++)
        getConcurrentExecutorThread().start();

    // wait for threads to complete
    Thread.sleep(1000);

    assertEquals(1, methodExecutor.mutexMap.size());

    try
    {
        final List<long[]> infiniteList = new LinkedList<long[]>();

       for(long i = Long.MIN_VALUE; i < Long.MAX_VALUE; i++)
            infiniteList.add(new long[102400]);

        fail("An OutOfMemoryError should be thrown");
    }
    catch(OutOfMemoryError e)
    {

    }

    assertEquals(2000, counter);
    assertEquals(0, methodExecutor.mutexMap.size());
}

// synchronous method
private ISynchronousMethod method = new ISynchronousMethod() {
    @Override
    public Object execute() {
        counter++;
        return null;
    }
};

/**
 * Executes a line of code.
 *
 * @return Thread
 */
private Thread getConcurrentExecutorThread() {
    return new Thread() {
        @Override
        public void run() {
            methodExecutor.doSynchronousMethod("TEST", "1", method);
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {

            }
            methodExecutor.doSynchronousMethod("TEST", new String("1"), method);
        }

    };
}

}
This last assertion is what breaks the test:
assertEquals(0, methodExecutor.mutexMap.size());

A: You're storing the exact same String object as both the key and the value. The key is a strong reference to the object, and as long as a strong reference to it exists, the weak reference to it is meaningless. The definition of weakly reachable (here) states that:

An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference.

By the way, even with this corrected I don't think you can assume that the map will always be empty at the end. It will probably be close to empty, but I think that's all that can be said about it.

A: Weak references will only be collected when the JVM absolutely needs more memory.


text:
Q: Doubt regarding second quantization In Schwartz it is stated that second quantization can be viewed as modes having energy given by the relation $E=\hbar\omega$ and then considering each mode as simple harmonic oscillator. So my doubt is the energy corresponding to $n\hbar\omega$ can be viewed in following two ways. We operate creation operator on vacuum $n$ times for the state of $\omega$ frequency or we operated just once with the creation operator corresponding to $n\omega$ frequency. So the way to differentiate between these two state is only by measuring the corresponding frequency or wavelength whichever is more convenient. Or is there something more subtle about it? Or my whole thought process is wrong because of some misconception?

A: Acting once with a creation operator of frequency $n \omega$ introduces a single particle of energy $n \omega \hbar$.
Acting $n$ times with a creation operator of frequency $\omega$ introduces $n$ particles of energy $\omega \hbar$ each.
Those are two different, orthogonal quantum states. Actually, Fock space of free QFTs decomposes into $n$-particle subspaces for  each positive integer $n$.
But both states are eigenstates of the energy operator (Hamiltonian) with equal eigenvalues.

A: A system with $n$ excitations with energy $\hbar\omega$ each (with total energy $n\hbar\omega$) is different from a system with one excitation with energy $\hbar\omega'$, with $\omega'=n\omega$.
This is clear when looking at the two corresponding Hamiltonian, $\hat H = \frac{\hat p^2}{2m}+\frac{m\omega}{2}\hat x^2$ and $\hat H' = \frac{\hat p^2}{2m}+\frac{m\omega'}{2}\hat x^2$. This is also true for the wave-function corresponding to these two states.


text:
Q: virtual model and form_for (or formtastic) Sometimes we need form without model creation - for example search field or email, where should be send some instructions. What is the best way to create this forms? Can i create virtual model or something like this? I'd like to use formtastic, but not form_tag.

A: Firstly, Formtastic doesn't need a model in all cases, although it certainly works best and requires less code with a model.
Just like Rails' own built-in form_for, you can pass in a symbol instead of an object as the first argument, and Formtastic will build the form and post the params based on the symbol.  Eg:
<% semantic_form_for(:session) do |f| %>
  ...
<% end %>

This will make the form values available to your controller as params[:session].
Secondly, a model doesn't mean an ActiveRecord model.  What I mean is, Formtastic will work with any instance of a class that quacks like an ActiveRecord model.
A classic example of this that many people are using Authlogic for authentication with Formtastic.  Part of Authlogic is the idea of a UserSession model, which works fine:
Controller:
def index
  @user_session = UserSession.new
end

Form:
<% semantic_form_for(@user_session) do |f| %>
  <%= f.input :login %>
  <%= f.input :password %>
<% end %>

This will make your form data available in your controller as params[:user_session].
It's really not that hard to create a model instance to wrap up the concerns of your model.  Just keep implementing the methods Formtastic is expecting until you get it working!

A: default_language.rb

class DefaultLanguage
  attr_accessor :language_id
end

foo_controller.rb

  def index
    @default_language = params[:default_language] || Language.find_by_name("English")
  end

index.erb

<% semantic_form_for @default_language do |form| %>
  <% form.inputs :id => 'default_language' do %>
      <%= form.input :id,
       :as => :select,
       :collection => @languages,
       :required => false,
       :label => "Primary Language:",
       :include_blank => false %>
    <% end %>
  <% end %>

I used AJAX to post the form when the value changed.

A: Or you simply create a form with form_for and leave the model reference blank.
for example
    <% form_for "", :url=>some_url do |f| %>
<%= f.text_field "some_attribute" %>
<%= submit_tag "submit" %>
You can fetch the values by simply saying params[:some_attribute] in your controller.


text:
Q: Selenium not finding all the elements Selenium can't find all the  tags in a webpage. It finds only one, but there are two, and I need those two to make my script work. This is the link. I tried using WebDriverWait, but it still returned me only one of the  tags. I tried searching for different divs, but I kept returning me only one. I think it has to do with some of the classes that the second div has, and the first one doesn't, but I am really stuck.
Here's the HTML code.
full_image_link = driver.find_element_by_class_name('sc-1qpw8k9-3')
full_image_link.click()

full_image_link_ = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located(
        (By.CLASS_NAME, 'sc-1qpw8k9-3')
    )
)

A: You can use the api to retrieve the image links, no need to scrape:
import requests

r = requests.get('https://www.pixiv.net/ajax/illust/93333481/pages?lang=en').json()
image_links = [i['urls']['original'] for i in r['body']]

Result:
['https://i.pximg.net/img-original/img/2021/10/10/23/35/09/93333481_p0.jpg',
 'https://i.pximg.net/img-original/img/2021/10/10/23/35/09/93333481_p1.jpg']


text:
Q: Chargebee Portal Session API includes a redirect_url for when user logs out. From their UI I can't see how the user can logout? Implementing Chargebee Portal Session integrating it into my app.
If the users subscription is inactive, Im redirecting them to the portal to update their subscription.
The API provides:
redirect_url
URL to redirect when the user logs out from the portal.

My (ruby) code is like this, matches the example in the API:
result = ChargeBee::PortalSession.create({
      :customer => {
        :redirect_url => current_lessons_url,
        :id => chargebee_customer_token
        }
      })

I get the portal loading just fine.. but how does the user logout.. and trigger the return to my app?  I can't see it.
Here's how it looks for me. How does the user logout and initate a return to my app?

A: Assuming that you are using SSO via API portal auth setup,
In order to handle the Logout scenario, you can call Chargebee's Logout a portal session API endpoint and pass the respective portal session ID from which the user is trying to log out. So on logout call, the redirect URL passed in the create function is used and the end-user is redirected to the specified URL destination/app.
Reference - https://apidocs.chargebee.com/docs/api/portal_sessions?lang=ruby#logout_a_portal_session


text:
Q: Percolation Textbook Recommendation I was wondering if someone could recommend a Percolation textbook for undergraduates.  I have looked at Percolation by Grimmett and it seems quite dense.  I was looking for a book that I could self-study from with a decent amount of explanation.  As far as background, I have taken a graduate course in measure theory and the undergraduate analysis sequence. Thanks.

A: I think for your background, the notes of Hugo Duminil-Copin would be great. They are just 30 pages long but it is a decent amount of exposition and it has many exercises that can help you develop by yourself. Some proofs are a bit short, but I think they use a nice amount of intuition for those who are starting in the area.

A: From what I remember, Bollobas and Riordan book is much more accessible than Grimmett. Hopefully it will suit your needs (or those of the MSE readers who arrived here).


text:
Q: Where does Android studio store git passwords? When pushing some changes using Android studio (on Windows if that's relevant) I accidentally clicked the save password option.
Where are these credentials stored and how do I remove them?

A: Vonc linked me in a comment to Signed Into Wrong Git Account in Android Studio
I tried firing up "git bash" and checking for credential.helper, it was not set but I don't know whether that was because it really isn't set or because git bash and andriod studio use different settings. So I deemed this inconclusive.
I then tried another link in that answer which suggested going to file->settings->system-settings->passwords, this told me that keepass was being used and gave me an option to clear the database. Unfortunately there did not seem to be a way to view a list of what passwords were in the database.
I cleared the keepass database and it now prompts me for a password, so presumablly my password was stored there. I would have liked more positive confirmation though.


text:
Q: Verify my answer: show a bijection from (0,1) into [0,1] Could someone verify my answer? Am i correct?
Question: Show a bijection from  $[0,1]$ (closed) into $(0,1)$ (open)
Answer:
Define a sequence $X = \{x_{n}\}_{x\in\mathbb{N}}$ by $ x_{n} = \frac{1}{(2n-1)}$ such that $X \subset [0,1]$ and a sequence $ Y = \{y_{n}\}_{y\in\mathbb{N}}$ by $ y_{n} = \frac{1}{2} - \frac{1}{2^n}$ such that $ Y \subset [0,1] $. Then we have $ X = \{1, \frac{1}{3}, \frac{1}{5}, ... \} $ and $ Y = \{ 0, \frac{1}{4}, \frac{3}{8}, ...\} $. We see $ X \cap Y = \emptyset $. Define a function $ f: X \rightarrow (0,1)$ such that $ f(x_{n}) = x_{n+1}$ and a function $ g: Y \rightarrow (0,1)$ such that $ g(y_{n}) = y_{n+1} $.
Now we can construct a function $ h: [0,1] \rightarrow (0,1) $ such that:
$$ h(z) = \begin{cases}
 f(z), \text{if} \quad z \in X \\
 g(z), \text{if} \quad z \in Y \\
 z, \text{if} \quad z \in [0,1] \setminus (X \cup Y )
\end{cases} $$
That function is bijective.

A: This is close.  You want $y_0=0$ but your expression does not give that.  As you say, that is now fixed.


text:
Q: How to test json format with specific url use RSpec Rails 4.0? I need to test url like "/users.json?search=" + "[params]":
it "renders a successful response" do
 get :show, params: "/users.json?search=c"
 expect(response).to have_http_status(200)
 expect(response).to be_successful
end

My controller like
def index
  @users = User.search(params[:search]).limit(10)

  respond_to do |f|
    f.json { render json: @users }
  end
end

When I run test I have this error:
Failure/Error: before { get :show, params: "/users.json?search=unk" }

NoMethodError:
undefined method `symbolize_keys' for "/users.json?search=unk":String
```

A: In Rails 4, you pass the params without defining the params key:
get :show, format: :json, search: c

As of Rails 5, you pass the params with the params key:
get :show, format: :json, params: { search: c }


text:
Q: Send error message with .htaccess if invalid user I'm setting up .htaccess and .htpasswd files in a subdirectory of a website and I was wondering if its possible to set up a custom error message. Typically you get the following;
Authorization Required
This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.
However, I'd like to change this message. In addition, I'd like to limit the number of attempts to login. I've read that it used to be 3, but its unlimited the way I've set it up. I currently have the following in my .htaccess file.
AuthUserFile c:\wamp\.htpasswd
AuthName "localhost"
AuthType Basic
require valid-user

I've been trying to read through the apache tutorials about .htaccess but it seems like a maze, if someone could point me in the right direction I'd appreciate it.

A: If authorisation fails, you usually get a 401 error.
You can choose what to display when a 401 occurs by adding a line to your .htaccess
ErrorDocument 401 /var/www/error/401.html

Ideally this should be a static html page (not php or anything that might also error) and make sure that unauthenticated users can access the error page.
Then you can put what you like in it.


text:
Q: Using enum values in model stored in a database I don't seem to figure it out how to use enum values in an ASP.NET MVC 3 model (using code first approach) so that they are stored in a database and are preserved.
My model code looks like:
public class TestNews
{
    public int Id { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    //[EnumDataType(typeof(TestNewsType))]?
    public TestNewsType Type { get; set; }

    [Required]
    public string Title { get; set; }
}

public enum TestNewsType : short
{
    Draft = 0,
    PublishedPublicly = 1,
    PublishedInternally = 2,
    Removed = 3
}

After the database gets recreated it contains the table TestNews, but it contains only the columns:

*

*Id

*Date

*Title

How to make it also store the Type in the database? And also should the EnumDataType annotation be used?
I would later like to use it in a controller action like:
    public ActionResult Latest(int count=5)
    {
        var model = db.TestNews
            .Where(n => n.Type == TestNewsType.PublishedPublicly)
            .OrderByDescending(n => n.Date)
            .Take(count)
            .ToList();
        return PartialView(model);
    }

A: The June CTP of Entity Framework introduced Enum support.
As an alternative to using the CTP, at the MSDN blogs is an article on how to fake enums with Entity Framework.


text:
Q: .sort in protocol extension is not working I have a protocol as well as a protocol extension and I'd like to implement a function in the protocol extension to sort an array defined by the protocol with custom objects, but it's not working.
protocol MyProtocol {
    var myArray: [MyObject] { get set }
}

extension MyProtocol {
    func sortArrayByCreationTime() {
        myArray.sort {
            $0.created > $1.created
        }
    }
}

Xcode is telling me that 'sort' has been renamed to 'sorted(by:)', but if im using this a new array gets created, but I need the old array to be sorted, not a new one.
What am I doing wrong?

A: It's a misleading error – the problem is that you need to mark your sortArrayByCreationTime() method as mutating in order to tell the compiler that it's mutating a property (as protocols can be adopted by both value and reference types):
extension MyProtocol {
    mutating func sortArrayByCreationTime() {
        myArray.sort {
            $0.created > $1.created
        }
    }
}

A: I created a Minimal, Complete, and Verifiable example (MCVE) out of the original code, and I made it work in a Swift 3 playground
import UIKit
import XCTest

extension Date
{
    init?(year: Int, month: Int, day: Int) {
        var dateComponents = DateComponents()
        dateComponents.day = day
        dateComponents.month = month
        dateComponents.year = year
        guard let date = Calendar.current.date(from: dateComponents)
        else { return nil }
        self = date
    }
}

struct MyObject {
    var created: Date
}

protocol MyProtocol {
    var myArray: [MyObject] { get set }
}

extension MyProtocol {
    mutating func sortArrayByCreationTime() {
        myArray.sort {
            $0.created > $1.created
        }
    }
}

struct ArrayContainer: MyProtocol {
    var myArray: [MyObject]
}

let objects = [
    MyObject(created: Date(year: 2016, month: 9, day: 1)!),
    MyObject(created: Date(year: 2016, month: 11, day: 1)!),
    MyObject(created: Date(year: 2016, month: 4, day: 1)!),
    MyObject(created: Date(year: 2016, month: 8, day: 1)!),
]
var container = ArrayContainer(myArray: objects)

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMdd"

XCTAssertEqual(["0901", "1101", "0401", "0801"],
               container.myArray.map { dateFormatter.string(from: $0.created) })
container.sortArrayByCreationTime()
XCTAssertEqual(["1101", "0901", "0801", "0401"],
               container.myArray.map { dateFormatter.string(from: $0.created) })

Let me give two options:
Option 1: Improved
In Option 1, extend the Array struct, so that you can create mutating method sortByCreationDate. There is a trick that needs to be pulled out of a hat in order to extend [MyObject] (an array of MyObject)
protocol MyObjectProtocol { var created: Date { get set } }
extension MyObject: MyObjectProtocol { }
extension Array where Element: MyObjectProtocol {
    mutating func sortByCreationTime() {
        self.sort {
            $0.created > $1.created
        }
    }
}

var container2 = ArrayContainer(myArray: objects)
XCTAssertEqual(["0901", "1101", "0401", "0801"],
               container2.myArray.map { dateFormatter.string(from: $0.created) })
container2.myArray.sortByCreationTime()
XCTAssertEqual(["1101", "0901", "0801", "0401"],
               container2.myArray.map { dateFormatter.string(from: $0.created) })

Option 2: Better
In Option 2, extend Sequence. A sequence will allow you to sort objects that are Arrays, and other types, e.g., Dictionaries. Better yet, it does not create a mutating method. But honestly MyProtocol is a confusing API. With this method, MyProtocol is no longer necessary.
extension Sequence where Iterator.Element == MyObject {
    func sortedByCreationTime() -> [Iterator.Element] {
        return self.sorted {
            $0.created > $1.created
        }
    }
}
var container3 = ArrayContainer(myArray: objects)
XCTAssertEqual(["0901", "1101", "0401", "0801"],
               container3.myArray.map { dateFormatter.string(from: $0.created) })
XCTAssertEqual(["1101", "0901", "0801", "0401"],
               container3.myArray.sortedByCreationTime().map { dateFormatter.string(from: $0.created) })


text:
Q: Determine rasters particular area's within ranges using python My directions:
Create a script that determines what areas meet the following
conditions:

*

*Moderate slope — between 5 and 20 degrees

*Southerly aspect — between 150 and 270 degrees

*Forested — land cover types of 41, 42, or 43

Be sure to use the map algebra expressions of the arcpy.sa module.
I'm getting a final raster image with 3 colors on it when it should only be two...either you are in range of the above constraints or not.
#import arcpy
import arcpy
#set env
from arcpy import env
#set workspace
env.workspace = "D:/UW/Winter_2016/501/w5_more_arcpy8_9_10/ex9/"
from arcpy.sa import *

try:

    if arcpy.CheckExtension("spatial")== "Available":
        arcpy.CheckOutExtension("spatial")
#set elevation raster
        elevraster = arcpy.Raster("elevation")

        sloper = Slope(elevraster)
#Moderate slope — between 5 and 20 degrees
        idealslope = sloper < 20
        idealslope_lower = sloper > 5

        slopeFinal = idealslope - idealslope_lower

        slopeFinal.save("slopeFinal")

#Southerly aspect — between 150 and 270 degrees
        sAspect = Aspect(elevraster)
        s = sAspect > 150
        n = sAspect < 270

        sAspectFinal = n - s

        sAspectFinal.save("sAspectFinal")
#Forested — land cover types of 41, 42, or 43
#forestCover = arcpy.Raster("landcover.tif")

        forestCover = RemapValue([[41,1], [42,2], [43,3]])
        outreclass = Reclassify("D:/UW/Winter_2016/501/w5_more_arcpy8_9_10/ex9/landcover.tif", "VALUE", forestCover, "NODATA")
        outreclass.save("forestReclass")

        properArea = (outreclass & sAspectFinal & slopeFinal)
        properArea.save("properArea")

        arcpy.CheckInExtension("spatial")

finally:
    print "I'm done"

Suggestions? I'm sure there is a much better way to do this but I'm so new just trying to do it step by step, so I can understand the larger thinking process in writing python.

A: just a quick answer, but I see that you combine your aspect conditions using minus, which mean that you will end up with 3 values (-1, 0 and 1). You should instead multiply those results if you want to find layers that satisfy both conditions. Note that you can also use "and" operator in this case.
sAspectFinal = n * s
slopeFinal = idealslope * idealslope_lower

sAspectFinal = (sAspect > 150) and (sAspect < 270)

also you remap with 3 different values, if I understand well what you need you should set the same value.
forestCover = RemapValue([[41,1], [42,1], [43,1]])

or
outreclass = (forestRaster > 40) and (forestRaster < 44)

final notice, & is a bitwise operator. It is safer to use "and" (works with 0/1 rasters)

A: So this is what I came up with for an answer based on feedback above and google..
#import arcpy
import arcpy
#set env
from arcpy import env
#set workspace
env.workspace = "D:/UW/Winter_2016/501/w5_more_arcpy8_9_10/ex9/"
from arcpy.sa import *

try:

    if arcpy.CheckExtension("spatial")== "Available":
        arcpy.CheckOutExtension("spatial")
#set elevation  and forest cover raster files
        elevraster = arcpy.Raster("elevation")
        forestCoverTif = arcpy.Raster("D:/UW/Winter_2016/501/w5_more_arcpy8_9_10/ex9/landcover.tif")

        sloper = Slope(elevraster)
#Moderate slope — between 5 and 20 degrees
        idealslope = sloper < 20
        idealslope_lower = sloper > 5

        slopeFinal = idealslope * idealslope_lower

#Southerly aspect — between 150 and 270 degrees
        sAspect = Aspect(elevraster)
        s = sAspect > 150
        n = sAspect < 270

        sAspectFinal = n * s

#Forested — land cover types of 41, 42, or 43
#forestCover = arcpy.Raster("landcover.tif")

        outlandCover = ((forestCoverTif == 41) | (forestCoverTif == 42) | (forestCoverTif == 43))

#need to make one forest cover class for these three values

        properArea = (outlandCover & sAspectFinal & slopeFinal)
        properArea.save("properArea")

        arcpy.CheckInExtension("spatial")

finally:
    print "I'm done running the script."

A: import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "C:/EsriPress/Python/Data/Exercise09"
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
elev = arcpy.Raster("elevation")
lc = arcpy.Raster("landcover.tif")
slope = Slope(elev)
aspect = Aspect(elev)
goodslope = ((slope > 5) & (slope < 20))
goodaspect = ((aspect > 150) & (aspect < 270))
goodland = ((lc == 41) | (lc == 42) | (lc ==43))
outraster = (goodslope & goodaspect & goodland)
outraster.save("C:/EsriPress/Python/Data/Exercise09/Results/final")
arcpy.CheckInExtension("Spatial")


text:
Q: How to get window (modal/nonmodal) such is "Find and replace" Can't find how to get new window (form) which will behave like "Find and replace" window in VB IDE 2008, where window is allways on top and I can work on it but I can also work with underlayed code bit find and replace don't hide when I set focus to code window.
The best solution will be if I would be oopen more than one such window.
This is how I try but opened window is modal!
Dim fl As New myWindow
With fl
    .StartPosition = FormStartPosition.Manual
    .aCallerLocation = Me.Location
End With

Dim ret As Integer = fl.ShowDialog(Me)
fl.Close()
fl = Nothing

A: Showing the form as a dialog form, is not necessary to make the form stay in front of the primary form.  Using the ShowDialog method causes the form to be modal.  What makes it stay in front is the fact that you are passing Me for the owner parameter.  You can still pass an owner form, even if you are just calling the non-modal Show method:
Dim fl As New myWindow()
' ...
fl.Show(Me)

That way, the new form will stay in front of the primary form, but it will not be modal.  Therefore, both forms will be usable and you can show as many of those non-modal child forms in front of the primary form as you like.


text:
Q: Fractal tree in modern OpenGL (OpenGL 3.3 and above) I need an approach to draw a 3D fractal tree with modern OpenGL. Any suggestions?
I don't necessarily require full source code, just an idea how to do it.
What I'm trying to do is to make a 3D tree. In fixed-function OpenGL it's not so difficult to draw a good looking realistic tree, but I don't know how to do it in modern Opengl.
I thought it would be a good idea to use a cylinder model for every branch and use glm to transform it in the right place and size because in this case I could use the texture coordinates and normals of the model, but I got stuck and I don't know how to do it.
Here is fractal 2D tree made in fixed function OpenGL with recursion. If anyone interested I can send the entire source code.
void drawTree(int currentDepth, int maxDepth)
{
    if (currentDepth > maxDepth)
        return;

    if (currentDepth <= maxDepth - 2)
    {
        glColor3d(0.45, 0.2, 0.05);
        glLineWidth(10 * static_cast<GLfloat>(pow(TREE_FACTOR, currentDepth)));
    }
    else
    {
        glColor3d(0, 0.5, 0);
        glLineWidth(30 * static_cast<GLfloat>(pow(TREE_FACTOR, currentDepth)));
    }

    double lineLen = TREE_LINE_BASE_LEN * pow(TREE_FACTOR, currentDepth);
    glBegin(GL_LINES);
    glVertex2d(0, 0);
    glVertex2d(0, lineLen);
    glEnd();

    int angle1 = 10 + rand() % 40;
    int angle2 = 10 + rand() % 40;

    glTranslated(0, lineLen, 0);
    glRotated(-angle1, 0, 0, 1);
    drawTree(currentDepth + 1, maxDepth);
    glRotated(angle1 + angle2, 0, 0, 1);
    drawTree(currentDepth + 1, maxDepth);
    glRotated(-angle2, 0, 0, 1);
    glTranslated(0, -lineLen, 0);
}

How can I make something like this in modern OpenGL with VAOs and VBOs and shaders?

A: Quick idea.
void SudoCreateChild(const mat4x4& m2w_noscale, const int depth)
{
    if(depth>=MAX_DEPTH){
        return;
    }
    /// Creates the M2W matrix
    mat4x4 m2w=m2w_noscale * mat4x4::identity*(1/depth);
    /// Draw the branch
    DrawCylinder(m2w);
    /// Create the children branches
    for(int i=0; i<CHILDREN_NUMBER; ++i){
        float angle=(2.0f*PI/CHILDREN_NUMBER)*i;
        /// Initial rotation of PI/4 plus equal rotation between siblins
        mat4x4 rotation=mat4x4::rotate(angle, vector3(0,1,0))*mat4x4::rotate(PI*0.25, vector3(1,0,0))
        /// Size of the branch is 1/depth
        mat4x4 translation=mat4x4::translate(vector3(vector3(0,1,0)*(1/(depth+1))));
        /// Recursively create the branches
        SudoCreateChild(m2w_noscale*translation*rotation, depth+1);
    }
}

int main(void)
{
    SudoCreateChild(mat4x4::identity, 1);
    return 0;
}


text:
Q: Dual Boot - Booting Ubuntu brings me to Grub Command Line - New User Greetings AskUbuntu community !
I have a ASUS X55 (Intel(R) Core i5-5200 CPU @ 2.20GHz with 8GB RAM) I currently have Windows 10 , Version 1607.
Last week I had Ubuntu running on my computer however it was slightly buggy so I decided to remove it and try to re install it. I removed it, however I am having extreme difficulty trying to put it back on. I've watched countless YouTube installation videos , tried RUFUS , UUI and I still cant get it to work. I've spent 2-3 hours trying to solve this. I am new to Ubuntu so im hoping the community can help me with this one so I can pay it forward further down the line.
I also checked the hashes for my Ubuntu 16.04.1 iso and those are fine
When I write the iso to a USB and then attempt to boot from USB using
(settings >Update and security > recovery > advanced startup) I am brought to a grub prompt grub>.
What the heck can I do to fix this ? This is beginning to really irritate me because I have no idea what I can google to remedy this problem.
Any help would be appreciated !
I have also tried booting into BIOS and changing the boot order so ubuntu is #1 but this brings the same problem I outlined above.
Thanks - KG

A: You say you have windows 10 On your computer If I understand you,you also want to install ubuntu 16.04 on a partition and had it on once.
In windows 10 open the control panel click on Administrative tools on that window click computer management once in there click disc management. If you don't see it,click arrow infront of storage,once you see it  click disk management.Wait for your drive to show Part C: should be your windows 10 the partition you want Ubuntu to go should be re formated as to make it clean for installing your Ubuntu. If thats not right let us know.If you have installed Ubuntu 16.04 to a second drive reformat it then try a clean reinstall.

A: Are you booting into grub rescue? Try running  grub> set pager=1 Then grub> ls find where /boot/grub is located and make sure it is located in the proper place. Grub must be located on the boot sector of your HDD and not on a partition such as /dev/sda1.


text:
Q: proguard build nosuchmethoderror I'm building with proguard. I've explicitly told proguard to keep all classes that implement a certain interface.
-keep public class * implements com.me.app.views.Fooable

The interface has one method to implement: doSomething. But my app crashes when I build with proguard:
But I still get this error.
 java.lang.NoSuchMethodException: doSomething

How can I fix this so proguard wont ruin the build?

A: You should keep the interface and its method:
-keep interface com.me.app.views.Fooable {
  void doSomething();
}

Otherwise, the method may be renamed or even removed.


text:
Q: Is Anychart capable of font label resizing. How can I make the fonts scalable? I have several Anychart charts and maps that will be resized from full sized monitors to smart phones. The shapes resize fine, but the fonts do not. I haven't been able to find any documentation on this on the Anychart site.
Here is the basic script I'm currently using for formatting:

var firstSeries = usMap.choropleth(firstDataSetForSeries);
    firstSeries.geoIdField("code_hasc").overlapMode("allow-overlap");
    firstSeries.color("#e89498").hatchFill("percent05", "#866163", 1, 9).hovered({fill:"#f0b2b5"}).selected({fill:"#e89498"});
    firstSeries.labels().enabled(true).fontSize(13).fontColor('#000').fontWeight('bold').format(function(){
return this.value;
  });

A: To have the font size adjust to a size of the window, you could use a function provided below
// change font size on load
let font = 11;
let width = 720;
function getFontsByScreenWidth(actualFontSize, maxScreenWidth){
  return (actualFontSize / maxScreenWidth) * window.innerWidth;
};

// enable and customize the series labels
series
    .labels()
    .fontSize(getFontsByScreenWidth(font, width));

and in this sample: https://playground.anychart.com/j4yjf9TV/1


text:
Q: Syntax Highlighting not working with Prismjs I am running ghost as a blog software and I have a blog post that has markdown code snippets that I would like to have syntax highlighted.
I have followed the instructions to include the necessary header and footer tags and the specific tag for the language Im trying to highlight but still no syntax highlighting is taking place.
Here is a link to the page Im trying to get syntax highlight working on:
https://screaming-cactus.com/learning-to-love-result/
Any thoughts?

A: Not sure if the original poster is still in need of this, but if anyone is looking to syntax highlight their code blocks in Ghost and stumble upon this page, I've created a tutorial that shows you how: https://ghost.org/tutorials/code-snippets-in-ghost/


text:
Q: apt-get not getting latest version on some servers I've got Percona DB 5.6 on several Ubuntu 12.04 servers.  On a few of them, I've been able to successfully upgrade to the latest version (5.6.17) using
apt-get update
apt-get upgrade

On several others, apt-get update + upgrade tells me there's nothing to do, although the version installed there is only 5.6.15.  Why isn't it finding the most recent version?
Up-to-date version from servers that did update: "Server version: 5.6.17-65.0-587.precise-log (Ubuntu)"
Version from servers that are not updating: "Server version: 5.6.15-63.0-log Percona Server (GPL), Release 63.0"
I have confirmed that the following lines are in /etc/apt/sources.list on all servers:
deb http://repo.percona.com/apt precise main
deb-src http://repo.percona.com/apt precise main

(and it had to work at some point, because they were all installed originally using apt-get)
EDIT: From estibordo's suggestion, I'm adding in the output of
apt-cache policy percona-server-server-5.6

(percona-server-common-5.6 & percona-server-client-5.6 are identical to this too)
From the servers that are not upgrading:

percona-server-server-5.6:
  Installed: 1:5.6.15-rel63.0-519.precise
  Candidate: 1:5.6.15-rel63.0-519.precise
  Version table:
 *** 1:5.6.15-rel63.0-519.precise 0
        100 /var/lib/dpkg/status
     5.6.17-65.0-587.precise 0
        500 http://repo.percona.com/apt/ precise/main amd64 Packages

On my servers that did upgrade, this is the output:

percona-server-server-5.6:
  Installed: 5.6.17-65.0-587.precise
  Candidate: 5.6.17-65.0-587.precise
  Version table:
 *** 5.6.17-65.0-587.precise 0
        500 http://repo.percona.com/apt/ precise/main amd64 Packages
        100 /var/lib/dpkg/status

Why the difference, or more importantly, how do I fix the ones that are stuck on 5.6.15?
Thanks.

A: I think that
apt-cache policy percona-server-server

is what you need. It will provide the information about the installed version and if there are other candidates to install. It will also tell you from which repositories the packages came from.
You might use the same command with a wildcard, like:
apt-cache policy percona*

A: Having the same problem currently with some Ubuntu PPAs: Look closely at the version number of the installed package. It has a leading 1: at the beginning (the "epoch" - see https://askubuntu.com/questions/441879/why-do-some-packages-have-extra-numbers-on-the-front-of-their-version-string), which leads Apt to think that it's a higher version than the actual higher version from the repo. Did the old installation come from a PPA, or did they perchance change the version numbers?
Anyway, since the output does not state where the currently installed package comes from, the repository might have been removed from your configuration in the meantime.
I think it would be best to remove (not purge; removing should leave all your configuration intact; nonetheless, be sure to backup the corresponding folder in /etc) the current package, then (just to be safe) do an apt-get update && apt-get clean again, then install the package again normally with apt-get install. It should then have forgotten about the version with the 1: prefix and install the most recent from the repository.


text:
Q: Laravel Passport sends an "Unauthenticated" only when verifying emails I am working on my project and I have an issue with the API. The registering and login system work very well. I have a details route where I am able to retrieve informations about the current user. It means that the application is able to see that an user is authenticated and act in the right way.
I started working on the email verification (and honestly, it was pretty hard to make everything work properly). The email sends properly, but I have an issue with the link. When I click on it in the email, I get a error saying the the route doesn't exist (which is normal since I am on the api). However, when I add the header "Accept" for application/json and the Authorization header, I receive the message "Unauthenticated" even if the user is authenticated properly.
Routes :
Auth::routes(['verify' => true]);

Route::post('login', 'UserController@login');
Route::post('register', 'UserController@register');

Route::group(['middleware' => 'auth:api'], function() {
    Route::post('details', 'UserController@details');
});

User model :
<?php

namespace App;

use App\Notifications\VerifyEmail;
use Laravel\Passport\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'lastname', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyEmail);
    }

Register controller :
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class UserController extends Controller
{
    public $successStatus = 200;

    public function login() {
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $user = Auth::user();
            $success['token'] = $user->createToken('MyApp')->accessToken;
            return response()->json(['success' => $success], $this->successStatus);
        }
        else {
            return response()->json(['error' => 'Unauthorised'], 401);
        }
    }

    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required',
            'c_password' => 'required|same:password'
        ]);

        if($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;
        $user->sendEmailVerificationNotification();
        return response()->json(['success' => $success], $this->successStatus);
    }

    public function details()
    {
        $user = Auth::user();
        return response()->json(['success' => $user], $this->successStatus);
    }
}

Verification controller :
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}

Email Verification Notification :
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class VerifyEmail extends \Illuminate\Auth\Notifications\VerifyEmail
{
    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $verificationUrl = $this->verificationUrl($notifiable);

        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
        }

        return (new MailMessage)
            ->subject(('Vérification de l\'addresse email'))
            ->line(('Veuillez cliquer sur le bouton ci-dessous pour vérifier votre addresse email.'))
            ->action(('Vérifier mon addresse email'), $verificationUrl)
            ->line(('Si vous n\'avez pas créé de compte, vous n\'avez rien à faire de plus.'));
    }

}

A: You can see at the constructor of the VerificationController, there is $this->middleware('auth');. You should changed it to auth:api.
But, verification is something that browser loads. It shoudn't use api guard, it should be web (the default behaviour). You need to login first using normal login method (not via API), since that's not how API works.
The correct use case, just placed Auth::routes(['verify' => true]); in routes/web.php.


text:
Q: Invalid Thread Access even with XstartOnFirstThread in vm args I have an embryonic Java Web Start application with a single class. It runs on Windows and Linux but gets the dreaded Invalid Thread Access error on Mac OS X. I realise that this has been dealt with elsewhere. I have spent two full days scouring the Internet and have implemented all the solutions, but the problem persists.
My understanding is that calls to SWT must be made from the main thread which is the case here. Correct me if I am wrong in that.
I will post 3 snippets below, the source code of the application, the relevant part of the jnlp file and the error message on the Mac. The question is at the end.

JAVA SOURCE CODE
package client;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class AccountWindow {
 public static void main(String[] args) {
  Display display = new Display(); **// error occurs here**
  Shell shell = new Shell(display); shell.open();
  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }
  display.dispose();
 }
}

JNLP SNIPPET
<resources os="Mac\ OS\ X" arch="x86_64">
    <j2se version="1.5+" java-vm-args="-XstartOnFirstThread" />
    <nativelib href="swt-4.2-cocoa-macosx-x86_64.jar" />
</resources>

ERROR MESSAGE
org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.widgets.Display.error(Unknown Source)
    at org.eclipse.swt.widgets.Display.createDisplay(Unknown Source)
    at org.eclipse.swt.widgets.Display.create(Unknown Source)
    at org.eclipse.swt.graphics.Device.<init>(Unknown Source)
    at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
    at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
    at client.AccountWindow.main(AccountWindow.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.javaws.Launcher.executeApplication(Launcher.java:1550)
    at com.sun.javaws.Launcher.executeMainClass(Launcher.java:1488)
    at com.sun.javaws.Launcher.doLaunchApp(Launcher.java:1299)
    at com.sun.javaws.Launcher.run(Launcher.java:114)
    at java.lang.Thread.run(Thread.java:637)

PLEASE NOTE
- The display.syncExec solution posted at http://www.eclipse.org/swt/faq.php#javawebstart is not applicable because before you can invoke it you need a display. The error here happens when I try to create the display.
- I have used JaNeLa to validate the jnlp file and there are no red errors.
- <resources os="Mac\ OS\ X" arch="i386"> is being correctly interpreted because the correct swt library is being loaded.
- You can reproduce the error at http://thelinkjuicer.com/gannonline/client.jnlp

AND NOW THE QUESTION
Can anyone see anything in the source code or the jnlp snippet that would cause the error?
Secondary question: how can you tell if the -XstartOnFirstThread argument is actually being read by the VM?

A: Clearly, your main method is not being executed on the main thread. You can see in the stack trace that the launcher is actually started in another thread, and then the Launcher only indirectly calls main. This is unfortunately just the diagnostic, I am not sure about the solution. I have done a similar thing (SWT app through Java Web Start), but I can't remember how we solved this, if at all.
After checking the com.sun.javaws.Launcher source code, it is quite unclear how this could be made to work. The Launcher.launch method starts a new thread within which your main method is executed. You can follow the code to recreate the exact stacktrace you are getting.
The main entry point of Java Web Start shows that the main thread dies soon after starting.
Update
I dug something out: in this Eclipse bug report it is suggested that the problem could be related to this:
<resources>
  <j2se version="1.4+" />
  <jar href="client.jar" />
</resources>

The parser takes the j2se spec from here and ignores the later, more specific ones. Try removing the <j2se... line.
Update 2
Now I dug this up from here:
com.apple.concurrent.Dispatch.getInstance().getNonBlockingMainQueueExecutor().execute(
  new Runnable() { public void run() {
      final Display display = Display.getDefault();
      while (!display.isDisposed()) {
        if (!display.readAndDispatch())
          display.sleep();
      }
});

This actually sounds like something workable. It does exactly what I described in my comment below: patches into the main thread through a mechanism specifically put in place for this purpose. Try to adapt this to your need. You may not even need -XstartOnFirstThread with this.
Update 3
I finally found my old SWT-JWS project. It's got this in it:
<resources os="Mac OS X" arch="x86_64">
  <j2se version="1.6+" java-vm-args="-XstartOnFirstThread"/>
  <jar href="swt-cocoa-macosx-x86-64-3.6.2.jar" />
</resources>

and it works. It has no default j2se element, this element appears only in the OSX-specific entry.

A: This is an answer to the secondary question, "How can you tell if the -XstartOnFirstThread argument is actually being read by the VM?" (or the related question, "how can you detect if -XstartOnFirstThread was passed to the VM?")  I looked at java.lang.management.RuntimeMXBean.getInputArguments(), but -XstartOnFirstThread is not included in the returned List.  After some research, I was able to figure out something, so I hope this helps someone else who was in my shoes.
According to this link, there are several environment variables set by the launcher.  Among them are:
JAVA_MAIN_CLASS_pid
JAVA_STARTED_ON_FIRST_THREAD_pid
Use System.getenv() to obtain a Map of the environment variables.  From there, you can iterate through the entrySet() until you find an Entry with a getKey() whose return value starts with "JAVA_MAIN_CLASS_" . If the discovered Entry's getValue() contains the name of your main class, you can use the rest of the key to determine the pid.
Once you have the pid, look up the string "JAVA_STARTED_ON_FIRST_THREAD_pid" in the environment Map.  If it exists and has the value "1", the process was started with -XstartOnFirstThread.  Otherwise, the process was started without the flag.
This probably won't work in an unsigned WebStart application, since the System.getenv() method is prohibited by default.  But in a signed webstart application, or in a regular Java application, this does work.
Hope that helps,


text:
Q: How to reject string and double inputs? Why doesn't the following code reject string and double inputs?
How can I change it so it does?
int option;

do {
    System.out.printf("Welcome %s, select an option\n", theUser.getFirstName());
    System.out.println("1: Show previous transactions");
    System.out.println("2: Withdraw");
    System.out.println("3: Deposit");
    System.out.println("4: Transfer");
    System.out.println("5: Exit");
    System.out.print("\nEnter Option: ");
    option = input.nextInt();

    if (option != 1 && option != 2  && option != 3 && option != 4 && option != 5){
        System.out.println("\nError. Please choose a valid number");
    }
} while(option !=  1 && option  != 2  && option  != 3 && option  != 4 && option  != 5);

A: You could make a method to get an integer and checking that it really is one like this
private int getOption() {
    int option;
    try {
      option = scanner.nextInt();
    }
    catch (InputMismatchException e) {
      System.out.println("This was not valid input... " + scanner.next());
      return getOption();
    }
    return option;
}

You could also shrink your if block by using
if(option < 0 || option > 5)

A: Other than triggering an Exception, you can also use a bit of regular expression to check input is only 1 to 5:
Scanner scn = new Scanner(System.in);
String input;
do{
    System.out.print("Enter option (1-5): ");
    input = scn.nextLine();
    if(!input.matches("[1-5]+"))
        System.out.println("Invalid input, please enter only 1 - 5");
}while(!input.matches("[1-5]+"));

//int option = Integer.parseInt(input);  //if you need option to be an integer

SAMPLE OUTPUT:
Enter option (1-5): 3.3
Invalid input, please enter only 1 - 5
Enter option (1-5): 6
Invalid input, please enter only 1 - 5
Enter option (1-5): abc def
Invalid input, please enter only 1 - 5
Enter option (1-5):
Invalid input, please enter only 1 - 5
Enter option (1-5): 77
Invalid input, please enter only 1 - 5
Enter option (1-5): 3

Process completed.

Since I am only strictly matching values from 1 to 5, it blocks off any other inputs such as

*

*Strings

*Empty inputs

*Decimal values

*Numbers outside the range (<1 and >5).


text:
Q: Server error! Error 500 when using .htaccess file RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA, L]

I use this .htaccess file and when I access http://localhost/sites/MVC/help it does not return to index.php but gives:

Server error!
The server encountered an internal error and was unable to complete
  your request. Either the server is overloaded or there was an error in
  a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
localhost Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.19

A: Enable your rewrite module. That will solve your error.


text:
Q: How to implement a custom module in Android I am having some confusion trying to best design my application. In Android Studio when I add a new module it basically seems to just create an entirely new application. I am confused on what the benefit of this could actually be. When would someone want add a module like this to their project and not simply just create a new application? Also, is it a good idea to use this feature on Android? Should I instead merely use packages and reuse my code that way? Doing an internet search has gotten me nowhere as it appears all different types of languages treat modularization and packages as somewhat different. I have always just imported classes to reuse my code, and I am afraid that I seem to be missing some fundamental OO principle by not using modules. If someone could please fill me in on what this great mystery is, or some good reading material I will be greatly appreciative.

A: You should have one project for every application you develop.
If you want to use reusable modules in more than one project (which is an incredibly good software quality), you should pack a module or more in a library of reusable classes, and use those libraries in your project.
Libraries/modules should be developed in a way that they are independent, and they should be divided by functionality.
For example, you could have a module that lets you easily parse XML objects.  That would be regarded as an XML library/module.


text:
Q: How to set Kubeflow to use preemptible VMs? I'm trying to set up a new Kubeflow deployment to use preemptible VMs. Referring to this doc, I see that there is some YAML to specify preemptible nodes but I am not sure where to put it in the myriad of YAML files generated by kfctl.sh. Meanwhile, going through the console, I see Preemptible nodes = disabled, but there is no way to change it.
How do I set the Kubeflow node pools to be preemptible?

A: There's no way to change a node-pool from non-preemptible to preemptible.
What you can do is create a new preemptible node-pool and migrate the workloads from the non-preemptible node-pool to the new one.
By the other hand, you can go ahead and recreate the GKE cluster with a preemprible node-pool.
Hope this helps!

A: The kfp.gcp extension module has gcp.use_preemptible_nodepool().
Check the preemptible sample.


text:
Q: Display one version of image at multiple places in Magento? If you go this page, you'll notice I'm displaying the same version of image at 2 different places: one for the cloud zoom, and one at the middle of the page without zooming.
I'm currently using 2 different lines of code to generate the image and then return the URL of it, which essentially does the same thing:
<?php /* for cloud zoom */ echo $this->helper('catalog/image')->init($_product, 'image')->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->setWatermarkImageOpacity(0)->resize(600, null);?>

<?php /* for middle page */ echo $this->helper('catalog/image')->init($_product, 'image')->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->setWatermarkImageOpacity(0)->resize(600, null);?>

This is undoubtedly a lame solution because: 1) it occupies more disk storage as there are 2 distinct image files which are essentially the same image; 2) it significantly slows the page load as the user has to download both images.
So my question is how can I use the same version of image at multiple places in Magento? Is there any way to get the resize() method to return the URL of the image?
Thanks!

A: Mage_Catalog_Helper_Image has a __toString() method that does exactly that:
$imageUrl = $this->helper('catalog/image')->init($_product, 'image')->__toString();

HTH


text:
Q: Print unicode glyph together with its codepoint Is it possible to define a macro, call it charwithcodepoint, such that
\charwithcodepoint{A}

emits an equivalent of
\texttt{A} (U+0041)

And similar for other codepoints as well. If not, can I do the opposite, codepointwithchar so
\codepointwithchar{U+0041}

emits an equivalent to
\texttt{A} (U+0041)

I would like to do so in order to document a parser. Is there a package that support this?
The engine pdftex and the input file is UTF-8.

A: New version that takes a single UTF-8 character or a single ASCII letter command sequence such as \#

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\DeclareUnicodeCharacter{1D400}{\textbf{\textrm{A}}}% for demo only

% code mostly from the 2015/10/01 latex release inputenc)

\makeatletter
\def\charwithcodepointb#1{%
\texttt{#1}
(%
U+%
\expandafter\UTFviii@hexnumber\expandafter{%
                     \the\numexpr\expandafter\decode@UTFviii\detokenize{#1}\relax})%
}

\gdef\decode@UTFviii#1\relax{%
  \expandafter\UTFviii@cleanup
    \the\numexpr\dec@de@UTFviii#1\relax)))))\@empty}
\gdef\UTFviii@cleanup#1)#2\@empty{#1}
\def\d@c@de@UTFviii#1{%
\dec@de@UTFviii{#1}}
\gdef\dec@de@UTFviii#1{%
\ifx\relax#1%
\else
  \ifnum`#1>"EF
    ((((`#1-"F0)%
  \else
    \ifnum`#1>"DF
      (((`#1-"E0)%
    \else
      \ifnum`#1>"BF
        ((`#1-"C0)%
      \else
        \ifnum`#1>"7F
        )*64+(`#1-"80)%
        \else
        +`#1 %
        \fi
      \fi
    \fi
  \fi
  \expandafter\dec@de@UTFviii
\fi}
\gdef\UTFviii@hexnumber#1{%
\ifnum#1<"10 0\fi
\ifnum#1<"100 0\fi
\ifnum#1<"1000 0\fi
\UTFviii@hexnumb@r{#1}}
\gdef\UTFviii@hexnumb@r#1{%
\ifnum#1>15 %
\expandafter\UTFviii@hexnumb@r\expandafter{\the\numexpr(#1-8)/16\relax}%
\fi
\UTFviii@hexdigit{\numexpr#1\ifnum#1>0-((#1-8)/16)*16\fi\relax}%
}
\gdef\UTFviii@hexdigit#1{\ifcase\numexpr#1\relax
  0\or1\or2\or3\or4\or5\or6\or7\or8\or9\or
  A\or B\or C\or D\or E\or F\fi}

\def\charwithcodepoint#1{%
\ifcat\relax\noexpand#1%
\expandafter\expandafter\expandafter\charwithcodepointb\expandafter\@gobble\string#1
\else
\charwithcodepointb{#1}%
\fi}

\makeatother

\begin{document}

\charwithcodepoint{A}

\charwithcodepoint{Á}

\charwithcodepoint{}

\charwithcodepoint{\A}

\charwithcodepoint{\\}

\charwithcodepoint{\#}

\end{document}