text:
Q: sending mail from phpmailer is working but cakephp mail is not working with saim cradienial Hii i am using phpmailer to send mail its working fine but in cake php it's not working .
please have a look the Configuration
For PhpMailer :
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->SMTPSecure = false;
$mail->SMTPAuth = false;
$mail->Host = "localhost";
$mail->Port = 25;
$mail->IsHTML(true);
$mail->Username = "order@domain.in";
$mail->Password = "password";

For CakePhp :
public $smtp = array(
    'transport' => 'Smtp',
    'from' => array('order@domain.in' => 'My domain'),
    'host' => 'localhost',
    'port' => 25,
    'timeout' => 30,
    'username' => 'order@domain.in',
    'password' => 'password',
    //'client' => null,
    //'log' => false,
);

I find out  following thing is doing the job for Phpmailer .
$mail->SMTPSecure = false;
$mail->SMTPAuth = false;

please any one assist me what is alternative of SMTPSecure and SMTPAuth in cakephp

A: Try to pass SSL parameter in context as an array.
 public $SendMail = array(
  'host' => 'smtp.host.com',
  'port' => 587,
  'username' => 'username@domain.com',
  'password' => 'password',
  'transport' => 'Smtp',
  'SMTPSecure' => 'tls',
  'tls' => true,
  'context'=>array('ssl' => array(
      'verify_peer' => false,
      'verify_peer_name' => false,
      'allow_self_signed' => true
    )),
 );


text:
Q: codeigniter email->attach errors I'm wondering how I might catch email class errors prior to codeigniter actually sending.
For example, if the function cannot find the attachment, it would seem that there isn't an error that gets thrown within the framework (at least that I can determine).
$this->email->attach('/path/to/file.ext');

I've tried:
if( !$this->email->attach('/path/to/file.ext') ){
  echo $this->email->print_debugger();
}

and no error is thrown.
I only notice that the attachment isn't attached after the send command is issued $this->email->send();
In fact, the email is sent, but obviously without the attachment, but also without the $this->email->message() content -- just an empty email body.
It would seem that the print_debugger() function really doesn't get populated until the send() function is called. If I intentionally point to a file that doesn't exist, the print_debugger() function will throw this error (only after the send() function is called):
Unable to locate the following email attachment: /path/to/file.ext
Your message
has been successfully sent using the following protocol: sendmail

User-Agent: CodeIgniter
Date: Thu, 23 May 2013 09:27:49 -0400
<snip>

When I call the print_debugger() function prior to the send() function, the result is only an empty array (I'm guessing, as the output from that call is just

).
I'm hoping to catch this error prior to the send() function being called from within the framework.
I do understand that I can use PHP natively to check for file_exists, but it'd be nice, IMHO, for codeigniter to throw some error earlier than it does.
if( file_exists('/path/to/file.ext') ):
    $this->email->attach('/path/to/file.ext');
else:
    echo 'ERROR';
endif;

Thoughts/Suggestions/Comments?

A: This isn't CodeIgniter specifc per-se. I think you are looking for PHP Exceptions. Example:
try {
    $this->email->attach('/path/to/file.ext');
} catch (Exception $e) {
     echo 'Caught exception: ',  $e->getMessage();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeScript interface for object with language labels On my ReactJS app I used to use labels.js objects to switch between languages:

export const labelsENG = {
  navSeries: 'shows',
  navHome: 'home',
  navVideo: 'video',
  navGames: 'games',
  navCurrent: 'current',
  navCatchUp: 'shame pile',
  navCommingSoon: 'comming soon',
  navFinished: 'finished',
  formModalHeader: 'Add new Poster',
  modalNoWiki: 'No wiki for ',
  modalCloseButton: 'CLOSE MODAL',
  modalReleased: 'Relased ',
  modalSeenAt: 'You seen it ',
  itemPart: 'Part ',
  itemSeason: 'Season ',
  footerCopyRights: '© 2022 Listownik by Kuba',
  footerHere: 'Footer here',
  error404: 'Error 404 Page Not Happy',
  errorDescribtion: `It's working anyway`,
  posterText: 'Some text',
  shelfSeen: 'Seen'
};

Now I'm trying to convert that code to TypeScript.
Is there any more efficient or elegant way to declare a type for that object than create an interface with strings for each parameter separately?

export interface LabelsInterface {
  navSeries: string;
  navHome: string;
  navVideo: string;
  navGames: string;
  navCurrent: string;
  navCatchUp: string;
  navCommingSoon: string;
  navFinished: string;
  modalNoWiki: string;
  modalCloseButton: string;
  modalReleased: string;
  modalSeenAt: string;
  itemPart: string;
  itemSeason: string;
  footerCopyRights: string;
  footerHere: string;
  error404: string;
  errorDescribtion: string;
  posterText: string;
  shelfSeen: string;
}

Edit
Problem appears when I'm trying to declare type for context labels in next component:

  const { labels }: LabelsInterface = useContext(LanguageContext);

labels contain labelsENG or labels[someOtherLang]

type Language = {
  lang: string;
  setLang: Dispatch<SetStateAction<Language>>;
};

const initialState: Language = {
  lang: languageLabel.eng,
  setLang: (): void => {}
};

const labelInitialState: {} = {
  labels: {},
  setLang: (): void => {}
};

export const LanguageContext = createContext(labelInitialState);

const DataProvider = () => {
 const [lang, setLang] = useState<Language>(initialState);
 const isLanguageEng: boolean = (lang as any) === 'ENG';
 const labels = isLanguageEng ? labelsENG : labelsPL;

 return (
      <LanguageContext.Provider value={{ labels, setLang }}>
        <RouteProvider />
      </LanguageContext.Provider>
    );
  };

Errors:

TS2740: Type '{}' is missing the following properties from type '{ navSeries: string; navHome: string; navVideo: string; navGames: string; navCurrent: string; navCatchUp: string; navCommingSoon: string; navFinished: string; formModalHeader: string; modalNoWiki: string; ... 10 more ...; shelfSeen: string; }': navSeries, navHome, navVideo, navGames, and 17 more.

TS2339: Property 'labels' does not exist on type '{ navSeries: string; navHome: string; navVideo: string; navGames: string; navCurrent: string; navCatchUp: string; navCommingSoon: string; navFinished: string; formModalHeader: string; modalNoWiki: string; ... 10 more ...; shelfSeen: string; }'.

A: After declaring the constant like you did, just create a new type off of that constant, like this: type LabelTypes = typeof labelsEng
Edit
No const as pointed out by Titian in the comments, only type. Use export if you wish to reuse it.


text:
Q: Why is the movement of a Chess King aperiodic? Imagine we have a king by itself on a chess board, making random moves around the board. Although it is apparently aperiodic, wouldn't the corresponding Markov chain to the King's movements be periodic since the King could only return to a square i on the board at moves 2,4,6 ... etc. (great common denominator of 2) after initially being at the square?
By definition, aperiodic chains have return times to i with a g.c.d. of 1.

A: Your mathematics is correct but your understanding of the rules of chess is not.  A king on any square that is not on the edge of the board can move to any of eight squares: the four that share a common edge with the one he's on and the four that share only a common vertex.


text:
Q: Remove unwanted nested elements with xslt In my document I have some unwanted nested <bo> tags. What would be the easiest way to xslt them away?
Source example:

    <bo>
        <bo>some text</bo>
        <bo>
            <bo>some other text</bo>
        </bo>
        <bo>more text</bo>
    </bo>

    <bo>
        <fig/>
    <bo/>

Result example:

some text

some other text

more text

        <fig/>

Thanx in advance!

A: Take the following as an approach to build on:
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="bo[.//bo]">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="boo[not(boo)]">

    <xsl:apply-templates/>

</xsl:template>

If that does not suffice then you need to explain in more detail which input variants you can have and how you want them to be transformed.
A full stylesheet using above templates is
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="bo[.//bo]">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="boo[not(boo)]">

    <xsl:apply-templates/>

</xsl:template>

</xsl:stylesheet>

and transforms

    <bo>
            <bo>some text</bo>
            <bo>
                <bo>some other text</bo>
            </bo>
            <bo>more text</bo>
    </bo>
    <bo>
        <fig/>
    </bo>

into

   <bo>some text</bo>
   <bo>some other text</bo>
   <bo>more text</bo>
   <bo>
      <fig/>
   </bo>

A: A general solution to omit identical tags nested directly inside each other:

In English: "Copy each node through, unless its name is the same as its parent's; in that case, just copy the children"


text:
Q: Connecting to my laptops localhost from my USB connected android device I have coded a C# MVC Internet Application with Visual Studio 2013 Express for Web on my laptop. I can compile and connect to this application with the following web address in my laptops browser: localhost:22101/
I am wishing to connect to this address in an Android application that I have coded, but am having some trouble connecting to the localhost on my laptop. My laptop is connected with a USB cable.
I have tried the following:

*

*Tried to connect to my laptops IPv4 address from ipconfig
(10.1.1.3)... no connection found.

*Tried to connect to 10.0.2.2... no connection found

My laptop and cell phone are both connected to the same wireless router.
Is this possible? Can I please have some help with this?
Thanks in advance

A: The local development server doesn't respond to external requests.
You will need to run it on a full blown iis I'm afraid.


text:
Q: Rainbows and Clouds What is the intensity of sunlight required to form a rainbow. I read in the love of physics by Walter Lewin than

""For you to see a rainbow, three conditions need to be met. First, the Sun needs to be behind you. Second, there must be raindrops in the sky in front of you—this could be miles or just a few hundred yards away. Third, the sunlight must be able to reach the raindrops without any obstruction, such as clouds."

I did not understand the third point.

A: The formation of the rainbow results from geometric optics, so the incoming photons need to have the same direction to make a bright rainbow appear. Thus you need direct sunlight. In case of clouds you get diffuse illumination (photons hitting the water droplets under different angles).

A: The answer from Charles is right and to see why the photons need to come from the same direction for a clear rainbow...

A: One can always use a garden hose to make a small, but very own rainbow.
This way, it is possible to try and check all of these conditions.

*

*The Sun must be behind you. In theory, higher-order rainbows (created by multiple reflections inside the droplets) can exist in the Sun direction, but they are at least as faint as the first-order one and the Sun is much brighter, so one needs pretty unusual conditions to see them.

*You need water droplets to send the properly colored light in your direction, or no rainbow for you.

*These droplets must receive direct sunlight. If they are in a shadow, no rainbow either.
p.s. the rainbow is a profoundly distorted image of the Sun. Water droplets are simply not a good mirror.


text:
Q: Postfix setting to enable emails to usernames I am trying to get postfix set up to send mail to a user with out specifying the domain. I believe the issue is that the email domain and the server domain are different.
The company email addresses are username@company.com and the server is built with  the domain cmpny.com.
I have tried adding company.com to the mydestinations but line in the main.cf but it is not helping.
Any advice would be great!
Thanks,
Joe

A: If you put company.com in mydestination, then you're telling postfix that he's the hosting mailserver for company.com. If that's what you want then do the following:

*

*Create an user: useradd -m -s /bin/bash testuser

*Then do (you may need mailutils package): echo "Hi there" | mail -s Testing testuser

*Then switch to user: su testuser

*And check for mail: mail
You should have your mail listed.
The same will work if you put testuser@company.com at #2


text:
Q: What's the meaning of "easy" here? From an American sitcom Friends S06E23, Transcript Here

[Scene: Joey and Rachel's, continued from earlier. Chandler is showing
  Rachel the ring.]
Chandler: Check out the ring.
Rachel: (gasps) Nice! One and a half carat easy.

What's the meaning of "easy" here?

A: In informal US English "easy" can be its own adverb, where you would formally use "easily". So the sentence means that the diamond is comfortably at least that much in weight.


text:
Q: Generating a list of delimited numbers Is there a function in Excel which is able to generate a list of numbers like this:
1|2|3|4|5

as shown in the image below:

I would like to be able to provide the start and end, something like =NUMBERSRANGE(1,50). There is no need to take the input from two other cells.
I did some research and here is my first Excel function:
Function RANGENUMBERS(D7, E7)
For i = D7 To E7
    RANGENUMBERS = i & "|"
Next
End Function

How would I go and concatenate number from For loop in order to get desired result?

A: This requires the TEXTJOIN() function:

Array enter (Ctrl+Shift+Enter) the following formula (don't forget to remove the { and }):
{=TEXTJOIN("|",TRUE,ROW(INDEX(C:C,1):INDEX(C:C,5)))}

While this works as is, it is preferable to replace C:C with the column that the formula is entered in. That way the formula won't break if column C is deleted.
Note that TEXTJOIN() is only available in Excel 2016. In earlier versions of Excel, a poly-fill UDF is required. (See this post for a basic one.)
Also note that this is a better solution than the ubiquitous alternative that uses the INDIRECT() function,
{=TEXTJOIN("|",TRUE,ROW(INDIRECT("1:5")))}

as INDIRECT() is volatile and causes the worksheet to calculate slower.
It is also easier to modify the INDEX version so the endpoints are references instead of hard-coded values.

A: Similar to telephone number and zip+4 masking, if the number will always be 5 digits, then how about using a custom number format like: #|#|#|#|#


text:
Q: How do I get Bash completion to *stop* working with aliases? This is kind of the opposite of this question.
I used to use ag to search for text in my projects, but then I found the hyperlinked grep from kitty. So I ripped out that script from kitty, dropped it in my user's bin, and aliased ag in my shell to run the script.
But now I've noticed that, because my alias is ag, Bash is loading the shell completion code for the real /usr/bin/ag and using it to try and complete commands that start with my ag alias. But the shell completion code actually executes ag on every completion attempt, and expects whatever ag points to in the shell to support a --list-file-types option, which the real /usr/bin/ag does, but which the script I use (which eventually delegates to rg AKA ripgrep) doesn't support. So when I type a, g, <TAB>, I get this printed:
ag error: Found argument '--list-file-types' which wasn't expected, or isn't valid in this context

USAGE:

    rg [OPTIONS] PATTERN [PATH ...]
    rg [OPTIONS] [-e PATTERN ...] [-f PATTERNFILE ...] [PATH ...]
    rg [OPTIONS] --files [PATH ...]
    rg [OPTIONS] --type-list
    command | rg [OPTIONS] PATTERN

For more information try --help

If I do complete -p | grep ag I see that it has loaded a completion function for ag:
complete -F _ag ag

If I complete -r ag I can unload the rule. But then if I do a, g, <TAB> again, the machinery responsible for dynamically loading completion rules sees that there's completion rules available for ag at /usr/share/bash-completion/completions/ag, and that no completion for ag is crrently set, so it re-loads them.
How do I stop my shell from using the available completion rules at /usr/share/bash-completion/completions/ag on my alias ag that does not actually correspond to those rules?
I really would like a method that 1. doesn't require uninstalling ag or its rules at the system level (so it can work for a non-superuser), and 2. doesn't require loading a fake completion rule to take the place of the system-provided one (although if that's the only way to do it I would like to know how to do that). I would also still like autocompletion to work for the ag command, using the default autocompletion behavior for commands and executables that don't have any special rules defined (which seems to be to just suggest filenames).
I noticed that /usr/share/bash-completion/bash_completion (which seems to be version 2.10 of https://github.com/scop/bash-completion on my system) has an internal _blacklist_glob; is there some way to control that as a user to ban a certain completion rule?


text:
Q: Program to check if the scoping is lexical or dynamic I found that the program to check if the scoping is lexical or dynamic is the one given below (source: http://inst.eecs.berkeley.edu/~cs61a/su10/resources/sp11-Jordy/scope/)
(define test
  (let ((scope 'lexical))
    (lambda () scope)))

(let ((scope 'dynamic))
  (test))

But how can this work? This should always print 'lexical (irrespective of whether the scope is lexical or dynamic) right? since in the local scope of the body of the first 'let' , scope is always defined to be 'lexical.. Please correct me if i am wrong

A: The value of test is not
(let ((scope 'lexical))
    (lambda () scope))

it is just
(lambda () scope)

When you call it, (test), the function body is evaluated, and it consists only of
scope

With lexical scope, this would be the value in the binding that was in effect when the definition was evaluated, i.e the lexically enclosing let-binding.
With dynamic scope, the binding of scope isn't looked up until the function is called.
At that time, the binding to 'lexical is long gone — it only exists during the definition of test.
When you
(let ((scope 'dynamic))
  (test))

a new binding is introduced in the environment, and this is the binding that is found when looking up scope.
The similar function
(define test
    (lambda ()
        (let ((scope 'whatever))
            scope)))

would work the way you suggest — always returning 'whatever — as the binding to 'whatever is in effect during the evaluation of scope even in a dynamic setting.

A: Scheme uses lexical scoping, so of course that code always returns lexical. However, in a Lisp system that uses dynamic scoping, scope would indeed be dynamic inside that (let ((scope 'dynamic)) ...) expression….
In order to understand that, you have to understand how dynamic scoping is implemented. Think of each variable as having a stack of values.† So, when the lambda expression was being evaluated, the value lexical has been pushed to scope's value stack (via the let). When the let block is exited, the value is popped off. Later, the second let block pushes the value dynamic to scope's value stack, which is what your function then sees.
† I highly appreciate the explanation from the Emacs Lisp manual about how dynamic bindings work in terms of a stack. It's helped me really understand the concept in concrete terms.


text:
Q: How to connect from Ubuntu VM on Azure to another without uploading the private key My Topology
Two Ubuntu servers, the edge which is exposed to the internet, and the core which is only connected locally. Both are on the same subnet and the core only accepts SSH from the edge server. SSH Private keys are stored on my local computer I'm connecting from. I'm using a custom ssh port and MFA on both servers
What I want to achieve is to connect from my computer to the edge server via SSH and from there connect to the core server using the private SSH key stored locally.
I'm sure it is quite simple but I have no clue how to achieve that.

A: What you are trying to do is "creating bastion host".
And it can be done by using ssh-agent.


text:
Q: Setting up a 2nd web application on another port I have a Web application on SharePoint 2010 setup on Port 80.
I would like to set up another Web Application for My Sites on Port 81. I have followed all of the steps to do this and can successfully access a users My Site
Is there any way to remove :81 from the URL that is created. I know this would not appear if I created it on the original web application on port 80 but I need to create MySites in a separate web application as per Microsoft best recommendation.
So my questions are:

*

*Can I create a second web app on port 80 and how would I
configure this? e.g. host header

*Is it OK to do this or does the 2nd web app need to be on a different
port?

Any advice would be greatly appreciated

A: If you have the proper DNS then its really easy.
Couple of options:
Host headers:
You can specify a host header when creating the web application which allows for multiple listeners on port 80
http://onlinecoder.blogspot.com/2012/10/setup-multiple-sharepoint-web.html
http://wwolfe.blogspot.com/2009/04/multiple-web-applications-on-port-80.html
VIA ForeFront UAG
deploy SharePoint web applications via Forefront Unified Access Gateway (UAG) in a topology in which the server running SharePoint Products and Technologies publishes multiple web applications on a single port.
Publishing multiple SharePoint applications on a single port
You dont need to create the web application on 2nd port. If you have host header you will be fine.


text:
Q: Matrix cannot be saved in MATLAB I want to save two strings into one matrix but I receive the following error:

Error using save Cannot create 'LayersProperties.mat' because 'Layers
  Properties' does not exist.
Error in Layers (line 29) save('Layers
  Properties\LayersProperties.mat', 'LayersList', 'TabList')

Here is my code:
 clear all
clc

% CREATE THE LIST OF DIFFERENT LAYERS
LayersList = {
    'Name'                  'k [W/m/K]'     'D [mm]'        'e [-]'        'Color R'   'Color G'  'Color B'

    'Glass 3.0'             1.00            3.000           0.92           0.6          0.8         1
    'EVA DuPont Elvax'      0.23            0.2500           0.00           0.8          1           1
    'Solar Cell'            180.00          0.180           0.00           0            0.45        0.74
    'Bcksht DuPont 0.10'    0.36            0.100           0.90           1            1           1

    'Bcksht DuPont 0.20'    0.36            0.200           0.90           1            1           1
    'Bcksht DuPont 0.30'    0.36            0.300           0.90           1            1           1
    'Bcksht DuPont 0.40'    0.36            0.400           0.90           1            1           1
    'Bcksht DuPont 0.50'    0.36            0.500           0.90           1            1           1
    'Bcksht DuPont 0.60'    0.36            0.600           0.90           1            1           1

    'PVB Saflex PA41'       0.19            0.760           0.00           0.8          1           1
    'Si rub. ELASTOSIL'     1.30            0.450           0.00           0.8          1           1
    'POE-based ENGAGE'      0.29            0.450           0.00           0.8          1           1

    };

TabList = {
    'Name'         'rho_tab [Ohm m]'  'T_R_coeff [1/�C]'  'k [W/m/K]'
    'Copper'       1.53E-08            3.90E-03            50
    };
save('Layers Properties\LayersProperties.mat', 'LayersList', 'TabList')

A: When encountering such a problem try checking if Matlab sees that the folder actually exists:
isfolder('Layers Properties')

I'm guessing it will return false. Then, for safety, prefer to use absolute paths and have you script ensure Matlab is running in the proper location:
disp(cd()) % shows your current directory

cd(fileparts(mfilename(fullpath))) % goes to the folder where the running script is located

fullfile(cd(), 'Layers Properties') % builds the absolute path to the Layers Properties folder.

Probably this would solve your problem:
save(fullfile(cd(), 'Layers Properties', 'LayersProperties.mat'), 'LayersList', 'TabList')

EDIT: If, as the new image shows, you already are on the Layers Properties folder, then you can simply do:
save('LayersProperties.mat', 'LayersList', 'TabList')


text:
Q: Add/Override behavior on Jaxb generated classes by extending them I have a web server responding with xml data and a client consuming it.
Both share the same domain code. One of the domain objects looks like this:
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement(name = "image")
public class Image {

    private String filename;
    private ImageTypeEnum type;

    @XmlElement(name = "imageUri")
    public String getAbsoluteUri() {
        // some complex computation
        return uri;
    }
}

When I try to unmarshal the response from the server into this object, since there's no setter for absoluteUri, I don't have the imageUri in the class. So I extend it like this:
public class FEImage extends Image{
private String imageUri;
    public String getAbsoluteUri() {
        return imageUri;
    }
    public void setAbsoluteUri(String imageUri) {
        this.imageUri = imageUri;
    }
}

My ObjectFactory
@XmlRegistry
public class ObjectFactory {
    public Image createImage(){
        return new FEImage();
    }
}

My code to unmarshal is here:
JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory",new ObjectFactory());
((JAXBElement)unmarshaller.unmarshal((InputStream) response.getEntity())).getValue();

However, the setAbsoluteUri doesn't seem to be getting called in FEImage while unmarshalling. When I add a dummy setAbsoluteUri in Image.java, everything works as expected.
Can someone tell me how can I cleanly extend from Image.java?

A: Note:  I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

A JAXB implementation is not required to use the ObjectFactory class when instantiating an object.  You can configure instantiation to be done via a factory class using the @XmlType annotation:
@XmlType(factoryClass=ObjectFactory.class, factoryMethod="createImage")
public class Image {

    private String filename;
    private ImageTypeEnum type;

    @XmlElement(name = "imageUri")
    public String getAbsoluteUri() {
        // some complex computation
        return uri;
    }
}

*

*http://blog.bdoughan.com/2011/06/jaxb-and-factory-methods.html
If you do the above, then your JAXB implementation will still use the Image class to derive the metadata so it will not solve your problem.  An alternate approach would be to use an XmlAdapter for this use case:

*

*http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html
Better still, when a property on your domain object does not have a setter, you can tell your
JAXB implementation (EclipseLink MOXy, Metro, Apache JaxMe, etc) to use field (instance variable) access instead using @XmlAccessorType(XmlAccessType.FIELD):
@XmlAccessorType(XmlAccessType.FIELD)
public class Image {
}

*

*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

UPDATE #1
If you are not able to modify the domain objects, then you may be interested in MOXy's externalized metadata.  This extension provides a means via XML to provide JAXB metadata for classes where you cannot modify the source.
For More Information

*

*http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html

*http://wiki.eclipse.org/EclipseLink/UserGuide/MOXy/Runtime/XML_Bindings

UPDATE #2 - Based on results of chat
Image
Below is the implementation of the Image class that I will use for this example.  For the complex computation of getAbsoluteUri() I simply add the prefix "CDN" to the filename:
package forum7552310;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement(name = "image")
public class Image {

    private String filename;
    private ImageTypeEnum type;

    @XmlElement(name = "imageUri")
    public String getAbsoluteUri() {
        return "CDN" + filename;
    }

}

binding.xml
Below is the MOXy binding document I put together.  In this file I do a few things:

*

*Set XmlAccessorType to FIELD

*Mark the absoluteURI property to be XmlTransient since we will be mapping the filename field instead.

*Specify that an XmlAdapter will be used with the filename field.  This is to apply the logic that is done in the getAbsoluteUri() method.

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum7552310">
    <java-types>
        <java-type name="Image" xml-accessor-type="FIELD">
            <java-attributes>
                <xml-element java-attribute="filename" name="imageUri">
                    <xml-java-type-adapter value="forum7552310.FileNameAdapter"/>
                </xml-element>
                <xml-transient java-attribute="absoluteUri"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

FileNameAdapter
Below is the implementation of the XmlAdapter that applies the same name algorithm as the getAbsoluteUri() method:
package forum7552310;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class FileNameAdapter extends XmlAdapter<String, String> {

    @Override
    public String marshal(String string) throws Exception {
        return "CDN" + string;
    }

    @Override
    public String unmarshal(String adaptedString) throws Exception {
        return adaptedString.substring(3);
    }

}

Demo
Below is the demo code demonstrating how to apply the binding file when creating the JAXBContext:
package forum7552310;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum7552310/binding.xml");
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Image.class}, properties);

        File xml = new File("src/forum7552310/input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Image image = (Image) unmarshaller.unmarshal(xml);

        System.out.println(image.getAbsoluteUri());

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(image, System.out);
    }
}

jaxb.properties
You need to include a file named jaxb.properties with the following contents in the same package as your Image class:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

input.xml
Here is the XML input I used:
<?xml version="1.0" encoding="UTF-8"?>
<image>
    <imageUri>CDNURI</imageUri>
</image>

Output
And here is the output from running the demo code:
CDNURI
<?xml version="1.0" encoding="UTF-8"?>
<image>
   <imageUri>CDNURI</imageUri>
</image>


text:
Q: Basic scene breaks transitioning from three.js v87 to v88 or v89 Does anyone know why the following breaks as three.min.js is updated from r87 to r88 or r89?  This is just using fundamentals from three.js-related training webistes.  With r87 or earlier, a cube is displayed.  With r88 or r89, there's just a black canvas.  I have tried this with Chrome, Firefox, & IE.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="three.min.js"></script>
<script>
    var renderer = null, scene = null, camera = null;

    function render() {
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    }

    $(document).ready(function() {
        var canvas = document.getElementById("webglcanvas");

        scene = new THREE.Scene();

        renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
        renderer.setSize(canvas.width, canvas.height);

        camera = new THREE.PerspectiveCamera(60, canvas.width / canvas.height, 0.1, 400);
        camera.position.set(60, 100, 100);
        scene.add(camera);

        camera.lookAt({"x": 50.0, "y": 50.0, "z": 50.0});

        var light = new THREE.PointLight(0xffff00);
        light.position.set(50, 50, 50);
        scene.add(light);

        var geometry = new THREE.BoxGeometry(50, 50, 50);
        var material = new THREE.MeshNormalMaterial();
        var cube = new THREE.Mesh(geometry, material);
        scene.add(cube);

        render();
    });
</script>
</head>
<body>
   <canvas id="webglcanvas" width="480" height="300"></canvas>
</body>
</html>

A: The following is not valid three.js code, and never has been valid three.js code:
camera.lookAt( { "x": 50.0, "y": 50.0, "z": 50.0 } );

Use
camera.lookAt( 50, 50, 50 );

or
camera.lookAt( myVector3 );

three.js r.90


text:
Q: Selenium global CacheLookup with WebElement exclusions I understand the basics of the Selenium [CacheLookup] tag, and that it can be applied to Web Elements to allow them to resolve more quickly on subsequent requests.  Since most elements are candidates for this, I am seeking a way to apply a single "Global" [CacheLookup] to all Web Elements within a Page Object at once, and then for the rare elements that are too dynamic for this, have something like an [ExcludeFromCacheLookup] tag applied to those few elements, on an element by element basis.  Does anyone know if this is possible?  Better yet, is it possible to apply this format to an entire "Page Object" assembly (.Net project in my case)?
I've scoured the internet, but haven't found anything that states if it is or is not possible.  This would be very useful in general, but being that I am retroactively applying this tag to existing elements, for which there are hundreds of them scattered among dozens upon dozens of Page Objects, it will be a huge time saver.
Thank you for any tips!


text:
Q: C++ code compiled using Homebrew's Clang on macOS Apple Silicon runs significantly slower with OpenMP than without I am trying to compile OpenMP-enabled C++ code on macOS Monterey (12.5.1) on Apple Silicon (Apple M1 Max) to get the respective speed-ups.
The code is compute-heavy, well understood and uses OpenMP since years (e.g. on x64 Ubuntu) without problems; the computations are more or less embarrassing parallel, so the speed-ups from running the computation via OpenMP in multi-threaded manner are significant.
When I compile the code on macOS with Apple Clang everything works, except that of course the code runs single-threaded since AppleClang does not support OpenMP.
That's why I have compiled now everything with Homebrew's Clang to enable OpenMP. Unfortunately, the results are different than expected. The code compiles and uses OpenMP; I see that since I had to fix a few minor issues on firstprivate clauses where Clang is more strict than GCC and I see the execution using multiple threads.
However, the runtime with OpenMP is significantly slower than without OpenMP. For instance, the computation without OpenMP takes ~15 seconds, with OpenMP it takes ~90 seconds, and even in the worse scaling case, I'd expect a speed-up of 2x-4x. Otherwise the results of the computation are correct, it just seems to affect the speed.
I have tried to compile the software with both llvm 14 (stable 14.0.6 (bottled)) and llvm 13 (stable 13.0.1 (bottled), tried due to a suspected regression) but without success so far.
The project is using CMake and the configuration looks as follows (this one is with LLVM 13, but I had tried with the default llvm beforehand):
export PATH="/opt/homebrew/opt/llvm@13/bin:$PATH"
...
cmake ../../ -DCMAKE_BUILD_TYPE=Release  \
  -DCMAKE_PREFIX_PATH=/opt/homebrew/opt/llvm@13   \
  -DCMAKE_CXX_COMPILER=/opt/homebrew/opt/llvm@13/bin/clang++   \
  -DCMAKE_C_COMPILER=/opt/homebrew/opt/llvm@13/bin/clang   \
  -DLDFLAGS="-L/opt/homebrew/opt/llvm@13/lib"   \
  -DCPPFLAGS="-I/opt/homebrew/opt/llvm@13/include"

I would be glad for any advice on how to resolve this issue. Thanks in advance!
--
Update 1:
When OMP_DISPLAY_ENV is enabled, the following is shown:
OPENMP DISPLAY ENVIRONMENT BEGIN
   _OPENMP='201611'
  [host] OMP_AFFINITY_FORMAT='OMP: pid %P tid %i thread %n bound to OS proc set {%A}'
  [host] OMP_ALLOCATOR='omp_default_mem_alloc'
  [host] OMP_CANCELLATION='FALSE'
  [host] OMP_DEFAULT_DEVICE='0'
  [host] OMP_DISPLAY_AFFINITY='FALSE'
  [host] OMP_DISPLAY_ENV='TRUE'
  [host] OMP_DYNAMIC='FALSE'
  [host] OMP_MAX_ACTIVE_LEVELS='1'
  [host] OMP_MAX_TASK_PRIORITY='0'
  [host] OMP_NESTED: deprecated; max-active-levels-var=1
  [host] OMP_NUM_TEAMS='0'
  [host] OMP_NUM_THREADS: value is not defined
  [host] OMP_PROC_BIND='false'
  [host] OMP_SCHEDULE='static'
  [host] OMP_STACKSIZE='8176k'
  [host] OMP_TARGET_OFFLOAD=DEFAULT
  [host] OMP_TEAMS_THREAD_LIMIT='0'
  [host] OMP_THREAD_LIMIT='2147483647'
  [host] OMP_TOOL='enabled'
  [host] OMP_TOOL_LIBRARIES: value is not defined
  [host] OMP_TOOL_VERBOSE_INIT: value is not defined
  [host] OMP_WAIT_POLICY='PASSIVE'
OPENMP DISPLAY ENVIRONMENT END

Once I set OMP_NUM_THREADS to a specific number, my test case yields the following runtimes (time via Boost's cpu_timer). One can clearly see that the code is fastest when running on a single thread (set via OMP_NUM_THREADS=1), even though it has been compiled with OpenMP support.

*

*OMP_NUM_THREADS=1:  15.85s wall, 30.97s user + 0.56s system = 31.53s CPU (198.9%)

*OMP_NUM_THREADS=2:  28.91s wall, 69.93s user + 0.71s system = 70.64s CPU (244.3%)

*OMP_NUM_THREADS=4:  36.63s wall, 134.07s user + 1.47s system = 135.54s CPU (370.0%)

*OMP_NUM_THREADS=8:  52.18s wall, 267.80s user + 12.35s system = 280.15s CPU (536.9%)

*OMP_NUM_THREADS=10: 52.29s wall, 285.78s user + 10.57s system = 296.35s CPU (566.8%)
Update 2:
System load from asitop (https://github.com/tlkh/asitop):

OMP_NUM_THREADS=1
OMP_NUM_THREADS=8


text:
Q: Put with macro variable as format I have a dataset with a variable called pt with observations 8.1,8.2,8.3 etc and a variable called mean with values like 8.24 8.1 8.234 etc. Which are paired with each other.
I want to be able to set my put informat to the formats from the variable num.
I get the errors "Expecting an arithmetic expression"
"the symbol is not recognized and will be ignored" and "syntax error" from my code. (underlining the &fmt. part)

if pt=&type;

call symput("fmt",pt);

fmt_mean = putn(mean,&fmt.);

Thanks in advance for your help.

A: The macro processor's work is done before SAS compiles and runs the data step.  So trying to place the value into a macro variable and then use it immediately to generate and execute SAS code will not work.
But since you are using the PUTN() function it can use the value of an actual variable, so there is no need to put the format into a macro variable.
fmt_mean = putn(mean,pt);

A: Please, post your data set and data step. Your description is hard to understand.
However the solution seems to be simple: do not use macro variables! You don't need them here. Unlike put() function which expect format know at compile time (that is when you can use macro variables) its analog putn() expects second argument to be variable. Of course, it works a little slower due to that permittance. So your code can look like that:
data ...;
    set ...(keep=mean pt);
    fmt_mean = putn(mean, pt);
run;

where pt variable maybe numeric, i.e. 8.2, or character, i.e. '8.2'.
If you want to understand how SAS macro works and what call symput does look here:
https://stackoverflow.com/a/69979074/7864377


text:
Q: How can i used the multi future in FutureBuilder? Begins an asynchronous calls the function and multiple.
However, the response to the second call is always null.
I want to update it to the screen when I get all the results.
sometimes invoked Error msg like this :
type 'List' is not a subtype of type 'Map<dynamic, dynamic>'
class _HomePageState extends State<Home> {
  final _formKey = GlobalKey<FormState>();
  final _formKey2 = GlobalKey<FormState>();
  aboutRes about; // delete

  var _callStack = [Gateway.Instance.about(), Wifi.Instance.ssidInfo(0)];

   @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body : Padding(
        padding: const EdgeInsets.all(15.0),
        child: Column(children: [
          Expanded(
            child: FutureBuilder(
              future : Future.wait(_callStack),
              key : _formKey,
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Text('Invoked Error is ${snapshot.error}');

                } else if (snapshot.hasData) {
                  return ListView (
                    padding: const EdgeInsets.all(0.8),
                    children: [
                      Container(
                        child : Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            InformationItem(about: snapshot.data[0]),
                            WirelessItem(ssid: snapshot.data[1]),
                          ],
                        ),
                      )
                    ]
                  );
                } else {
                  return CircularProgressIndicator();
                }
              }
            )
          ),
        ]),
      )
    );
  }
}

  Future<aboutRes> about() async {
    aboutRes res;

    ApiResponse response = await get(GATEWAY_ABOUT);
    // for jsonSerialization
    Map resMap = jsonDecode(response.body);
    res = aboutRes.fromJson(resMap);
    return res;
  }


text:
Q: Remote connection to host machine from remote machine, what happens? Just out of curiosity.  What would happen if I connect remotely to a Windows pc, and then from that remote pc remotely connect back to the original machine?  Is this how black holes are formed, or would I just get an error that I can't connect?

A: Depends on the software.  If you are talking about Remote Desktop, you will just get dropped from your original session.
I.e. you are on PC-A connecting to PC-B.  From your session in B you try to connect back to A.  Once you do this and enter your credentials, your session on A will be overridden by the new remote session from B and you will get dropped.


text:
Q: how to winactive WMP in Now Playing mode The below script opens Windows Media Player or activates when it has not been closed clicking the "Minimize" bottom at the "Now Playing" screen. How can I always Winactivate WMP?
    #c::   ;opens WMP
       sc=Windows Media Player  ;- window title
  IfWinExist,%sc%
      {
           IfWinNotActive ,%SC%,
           {
           WinActivate,%SC%
           WinWaitActive,%SC%
           }
           Return
      }
      gosub Launch ; Launch WMP
      Return
        Launch:
        ReLaunch:
        Run, C:\Program Files\Windows Media Player\wmplayer.exe /Task NowPlaying, , , PID
        Winwait, ahk_pid %PID%,,.25
        WinActivate, ahk_pid %PID%
        IfWinNotExist ahk_class WMP Skin Host
            gosub ReLaunch
      Return


text:
Q: Firebase Crashlytics auto starts apple watch application After installing firebase crashlytics on watch application, the app is being started every 10 minutes or so. Is this a normal behavior?

A: Started discussion on github:
https://github.com/firebase/firebase-ios-sdk/discussions/9194


text:
Q: Webview is not responding some times "Attempt to remove local handle scope entry from IRT, ignoring" Attempt to remove local handle scope entry from IRT, ignoring

01-18 20:30:48.725  30673-30673/com.packname.debug W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
  01-18 20:30:48.725  30673-30673/com.packname.debug W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
  01-18 20:30:48.735  30673-15614/com.packname.debug D/startTraficSt :﹕ 2525554070
  01-18 20:30:48.845  30673-15614/com.packname.debug D/oneByteTimeMillis :﹕ 106
  01-18 20:30:48.975  30673-30673/com.packname.debug W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 30673
  01-18 20:30:49.205   30673-5751/com.packname.debug E/chromium﹕ [ERROR:raw_channel.cc(341)] Invalid number of platform handles received
  01-18 20:30:49.205   30673-5751/com.packname.debug E/chromium﹕ [ERROR:channel.cc(307)] RawChannel read error (received bad message)
  01-18 20:30:49.205   30673-5735/com.packname.debug W/chromium﹕ [WARNING:proxy_message_pipe_endpoint.cc(50)] Failed to write enqueue message to channel
  01-18 20:30:49.205   30673-5735/com.packname.debug W/chromium﹕ [WARNING:proxy_message_pipe_endpoint.cc(50)] Failed to write enqueue message to channel
  01-18 20:30:49.205   30673-5735/com.packname.debug W/chromium﹕ [WARNING:channel.cc(315)] RawChannel write error


text:
Q: Is there a way to overlay an application over a full-screened program? I am looking to develop an application which is essentially a timer window which is always shown on the screen in front of any other application and never falls to the background when focusing other windows. An example is when I play a full-screen game I would like this timer to be overlaying the game and when I click the timer buttons on the window it does not close the game.
Any ideas how I can achieve this in C#/java/C++?
Thanks

A: C#: try setting the AlwaysOnTop property of the window (form)
java: call the setAlwaysOnTop(true) on the frame or dialog

A: I think that what you want to achieve can be achieved with the property  TopMost of the form in C#, and setAlwaysOnTop on a Java Window ...
In C++ on Windows you have to call the SetWindowPos function and passing as argument : HWND_TOPMOST attribue.
UPDATE
Since you have an application in fullscreen mode try setting your application in foreground with the Win32 API function : SetForegroundWindow .
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

SetForegroundWindow(this.Handle);

Otherwise you can try to avoid using the Win32 SetForegroundWindow function with something like this :
this.TopMost = true;
this.Activate();


text:
Q: Resizing/resampling geotiff file with Imagemagick breaks hill shading Using: QGIS 3.24.0 Tisler, ImageMagick 7.2.0-29, both Windows 64 bit on Windows 10.  The computer has 96GB of RAM and all the software is 64 bit builds, so I don't think it's a shortage of memory.
I have some ALOS 30m heightmap data in GEOTiff format that I am trying to get a softer hillshade of it to use as the background for a map.
When I load the original file (copied from the ALOS original ALPSMLC30_N032E010_DSM.tif), it will hillshade fine and display the hillshading if you select Raster->Analysis->Hillshade from the menu.
The range of values in the original comes out at 23-642 (see below)

In order to do this, I am resampling the file using Imagemagick to interpolate from 30m to a 3m pseudo-scale.
magick convert Tataouine30m.tif -filter Spline -resize 1000% Tataouine3m.tif
magick Tataouine3m.tif -crop 7200x7200+12000+0 Tataouine3m_cropped.tif

If I load the resulting image, I get this range of values and the hillshading no longer produces sensible results.  Also, the values of the Band 1 (gray) range are now different.

Two things have happened.  The coordinate system has been lost and the range of values in band1 has changed.  Hillshading doesn't work properly, and if I export the layer as a TIFF and open it in Photoshop it is just a uniform black or dark grey.  Frigging the levels doesn't do anything.
The question is twofold:
How can I resize and crop a geotiff (using ImageMagick or some other means) and retain the coordinates and height range so that I can generate a hillshade off it?
My google-fu is failing me.  Am I barking up the wrong tree here?

A: You can clip rasters in QGIS: Clipping raster with vector boundaries using QGIS
You can resample rasters in QGIS: Resampling GeoTIFF images to same resolution using QGIS
non-GIS graphic tools may or may not know about spatial referencing so you can lose the coordinate system and resolution information. Recent versions of GIMP might maintain the spatial reference information in a GeoTIFF but I'd still do this work in QGIS.


text:
Q: Is it good style to use lambda functions to define very small helper functions? As a silly example, let's say I have a function int f(vector<int> v), and for some reason, I need to do a couple of operations on v several times in f. Instead of putting a helper function elsewhere (which could increase clutter and hurt readability), what are the advantages and disadvantages to doing something like this (efficiency, readability, maintainability, etc.):
int f(vector<int> v)
{
    auto make_unique  = [](vector<int> &v)
    {
        sort(begin(v), end(v));
        auto unique_end = unique(begin(v), end(v));
        v.erase(unique_end, end(v));
    };
    auto print_vector = [](vector<int> const &v)
    {
        copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
        cout << endl;
    };

   make_unique (v);
   print_vector(v);
   // And then the function uses these helpers a few more times to justify making
   // functions...
}

Or is there some preferred alternative?

A: The advantage of such locally scoped functions is that they don't pollute the surrounding code with "helper" definitions—all of the behaviour can be restricted to a single scope. And since they have access to the lexical scope of the surrounding function, they can be used to factor behaviour without passing many parameters.
You can also use them to create small DSLs for abstracting the mechanical details of a function, allowing you to change them later. You define constants for repeated values; why not do the same for code?
For a tiny example, a state machine:
vector<int> results;
int current;
enum { NORMAL, SPECIAL } state = NORMAL;

auto input   = [&]{ return stream >> current; }
auto output  = [&](int i) { results.push_back(i); };
auto normal  = [&]{ state = NORMAL; };
auto special = [&]{ state = SPECIAL; };

while (input()) {
    switch (state) {
    case NORMAL:
        if (is_special(current))
          special();
        else output(current);
        break;
    case SPECIAL:
        if (is_normal(current))
            normal();
        break;
    }
}

return results;

A disadvantage is that you may be unnecessarily hiding and specialising a generic function that could be useful to other definitions. A uniquify or print_vector function deserves to be floated out and reused.

A: Efficiency:
This is basically functions versus functors which is what a lambda is under the hood. functors can actually be faster, this is because they are easier to inline, not all compilers will not inline function pointers (though it is possible). The reason for this is that when you pass a function pointer the compiler only knows the type of the function whereas the functor has the whole function because the type is unique.
Readability:
This part is more or less opinion based. Function pointers IMO are pretty annoying, they have ugly types and are not as versatile as functors. For example functors can easily be passed around at runtime. On the other hand writing out a full function is more readable than a big lambda.
The last point I would like to make is that a lambda like a functor can have a state (unlike a function, unless you count static vars), with a lambda you can capture a variable. Because of the compiler inlining limitations it is probably better not to pass around function pointers.
So I would say for small functions passed to stdlib it's better to use lambdas, and for larger ones implement a functor, function pointers are really no longer idiomatic in c++11.
Unfortunately it seems to me the way you are using them is not good. The compiler would have no problem inlining those as a normal function. And a function called print_vector or make_unique is better suited to it's own real function as it could be used in many other places.
Maintainability:
In this case I would say lambda's have a low maintainability, as they cannot be reused  outside the function and they look messy since they crowd the function they are in. So it would be better to define them outside.

A: C++ isn't meant to support laziness. Using lambdas instead of normal functions is no exception here.
This
int f(vector<int> v)
{
    sort(begin(v), end(v));
    v.erase(unique(begin(v), end(v)), end(v));
    copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
    cout << endl;
    /* And then the function uses these helpers a few more times to justify making functions... */
}

is much more succinct, standard, and readable than this
int f(vector<int> v)
{
    auto make_unique  = [](vector<int> &v)
    {
        sort(begin(v), end(v));
        auto unique_end = unique(begin(v), end(v));
        v.erase(unique_end, end(v));
    };
    auto print_vector = [](vector<int> const &v)
    {
        copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
        cout << endl;
    };

   make_unique (v);
   print_vector(v);
   /* And then the function uses these helpers a few more times to justify making functions... */
}

As a general rule of thumb, when your code itself isn't obscure (erase and sort and copy aren't obscure, they're standard C++ algorithms), adding more code only makes it worse.
Furthermore: there is no reason to restrict the type of v to vector<int> in so many places.
  Use type inference wherever the type doesn't matter.
If you feel it should be a separate function, then make it a separate function entirely.
Don't use lambdas as a crutch for being lazy.


text:
Q: Starting values for elo Recently made a tournament bracket where players can sign up and participate in a chance to get the winning spot. As you can see, here is a picture of it:

Once the tournament bracket is finished, I plan to convert these winnings into rankings. So, as a result, "Achilles" would be ranked #1 since he did the best in the tournament, then #2 would be "rjg 2", and so on. The reason why the tournament bracket would be converted into rankings is because now I want to give players the opportunity of creating matches against other players. This is significant because even though a tournament bracket works, it does not contain the outcome of every possible match between the players. That's fine, the tournament bracket is just there to give others a basic representation of who is the best/worst. However, once the tournament bracket is converted to rankings, new users also have the opportunity to sign up, allowing for more players to compete against each other. Now, before I begin the rankings part, I want to attempt to use Elo ranking in the matches. My problem is, I need to assign these players in the tournaments points. This is tricky because If i'm not careful my K value can mess with the order of things. Here is my table:
#1 Achilles
#2 rjg 2
#3 gg
#4 beta 1
#5 dfgsdf
#6 test2
#7 rjgtest
#8 rocket

I need to assign each player "points" to reflect the rankings. This means #1 Achilles would have the most points while #2 would be rjg2 and so on... However, with the way Elo works, I'm unaware on how much points to assign. If I do it too ranged, the players won't ever have any chance to move up in the rankings, but if I do it too small, the ranks will be constantly altering.
For example, if I set my table up like so:
1  1000
2  900
3  800
4  700
5  600
6  500
7  400
8  300
9  200
10 100

Where #1 would have 1,000 points, #2 would have 900 points, and so on. If rank #10 beats rank #1, it's obviously VERY unlikely. So, when I do the math with elo, here is what happens:
So if I go about it this way (based off of the way it is explained here ), lets say I have rank #10 facing rank #1. According to the website above, my formula is:
R' = R + K * (S - E)

and the rating of #10 only has 100 points where #1 has 1,000.
So after doing the math rank #10's expected value of beating #1 is:
1 / [ 1 + 10 ^ ( [1000 - 100] / 400) ]
= 0.0055%

0.55% is very low and makes sense, Rank #10 almost has no chance of beating someone as good as Rank #1. However, if he was to beat him, here is the result:
 100 + 32 * (1 - 0.0055)
 = 131.824

He would only gain 31 points when beating a player ranked as #1. This obviously won't work but I can either decrease the range in points or increase my K factor.
Does anyone have any suggestions to make this work? Or maybe suggest I rank my players a different way?

A: I'm afraid I don't know much about Elo ratings, but I understand that choosing an appropriate K value can be problematic.
I know that often the K value is altered depending on how many games a player has played. A player who has played many games is given a lower K value, so their rating does not change too much (because we are more certain about their rating, we want it to remain fairly constant). Similarly a player who has not played many games would get a higher K value (we are less certain about their rating, so we don't mind if it moves about more).
One alternative approach is to use ratings systems which try to incorporate a measure of our uncertainty about a player's rating. For example, the Glicko rating system or Microsoft's TrueSkill algorithm. These systems build up their own estimates of the variability in (or uncertainty about) a player's skill level, so you don't need to set a K value.
There is a very good Python implementation of TrueSkill at http://trueskill.org, written by Heungsub Lee, with plenty of examples of how to use the library. A player's rating comprises a mean (representing their estimated skill) and a standard deviation (representing our uncertainty about their skill).
TrueSkill is used by Microsoft for matchmaking on many Xbox games, so should be a good fit for your intention of matching players of similar ability.


text:
Q: Change of Variables in a Function I was reading the answer to this question and noted the following step in the derivation:
$$\text{Erf}(x) = 2\Phi(x\sqrt{2}) - 1$$
$$\implies \Phi(x) = \frac{1 + \text{Erf}(x/\sqrt{2})}{2}.$$
Where  $\Phi(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x e^{-z^2/2} \mathrm{d}z.$ is the CDF of the standard normal and $\text{Erf}(x) = \frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2} \mathrm{d}t$ is the error function.
This step made me wonder, in general, if $f(ax+b) = g(x)$ does this imply that $f(x) = g((x-b)/a)$ for any function? If we let $y = ax+b$, then we can substitute and get $f(y) = g((y-b)/a)$ and then simply swap out the $y$ for $x$ for notational consistency, but this seems a bit loose to constitute a "proof" in my mind.


text:
Q: How do I know if my long sms is sent properly? I've heard of concatenated SMS whereby SMSes longer than 160 alphanumerals are broken down, sent separately, and then recombined on the receiver's phone.
How do we know whether our long SMS is sent (and received) properly?
What happens if the receiving phone does not support concatenated SMS?


text:
Q: Have the "Bayreuther Mathematische Schriften" ever been digitalized? See update below.
This is borderline off-topic (certainly not a research question), but the rather successful story of a similar question gives me hope.
The Bayreuther Mathematische Schriften were a periodical published by the University of Bayreuth from 1979 till 2011, and included research papers, lecture notes and theses. Its 80 volumes include a surprisingly large amount of (Rota-style) combinatorics (which otherwise is a rare topic in German mathematics), including papers by Dress, Thévenaz, Kohnert, Strehl and Sturmfels as well as a long set of lecture notes on Polya enumeration and representations of symmetric groups. Both German- and English-language works appear in the periodical.
By now, the volumes are neither being sold nor seem to be available on the internet, and only a few papers and some amount of theses (quite possibly in a non-final form) can be found on the internet. Hence I am wondering:

Have the Schriften ever been digitalized?
If yes: What is preventing their open publication? Who has the copyrights?
If no: Are good sources for digitalization available? Is this something that a library could do with a bit of crowdfunding?

About the last question: I am currently near a full archive and have made a bunch of scans of the parts relating to algebraic combinatorics for myself. However, the binding of the volumes often limits the quality of my scans, as it prevents fully opening the journals. I am also having the impression that the volumes here are not quite the originals; a number of pages are missing due to incorrect printing, and quality is suboptimal in many places.
My impression is that someone, somewhere should still be having the originals for most of the content (LaTeX for the later volumes, probably microfiche for the earlier ones). Does anyone know where to look?
UPDATE: According to inside sources, there is a license problem: The authors have not granted the Bayreuth University any digital distribution rights (probably the copyright agreement did not include such language). Thus, authors can post their own papers online (if you are an author, please do so!), but the university cannot unless it gets green light from the authors. This seems to be a general problem in Germany (or the EU?), where distribution rights are not understood to include digital media by default. This brings me to the next question:

How did other German/European publishers (Springer, e.g.) handle this issue? I'm pretty sure that copyright agreements in the 1970s did not include any language on digital distribution, yet Springer distributes its full back catalogue.

A: Q1: Yes, the Bayreuther mathematische Schriften have been digitized by the Hathi Trust Digital Library.
Q2: The Hathi Trust Library states that "This item is not available online (Limited - search only) due to copyright restrictions." Since the publisher is Universität Bayreuth it is most likely that they hold the copyright.
Q3: No library will digitize and provide access to a publication that has copyright protection, but you can find a list of libraries that hold the volumes by following the links in the Hathi Trust database.
Incidentally, you mention that "the binding of the volumes often limits the quality of my scans, as it prevents fully opening the journals." Are you using a book scanner? I am a happy user of the CZUR book scanner, which corrects for the curved pages by postprocessing the image.

--- UPDATE ---
A brief addendum in response to the updated question:
In the United States copyright has been broadly defined to include reproduction by "any method now known or later developed" (see footnote 7 in Revising Copyright Law for the Information Age). I would be surprised if the definition would be more restrictive in Europe, and that is presumably why publishers just adapt their content to new reproduction methods, without having to once again secure permission from the original author.


text:
Q: SSO with OAuth for Communities Is it possible in Salesforce to provide a link on VF in the Customer portal so that once the portal user logged in and clicks on that link they should be redirected to the Community Home Page?

A: Yes, its entirely possible and well documented. Here are several links you may find useful. Getting Started With Communities (See Security & Authentication), Best Practices for Implementing Single Sign-On and Single Sign-On for Customer Portal Users.


text:
Q: Can we see the interference pattern in the double slit experiment if the walls of the slits are made of transparent glass? There are other questions on this site about when we put one of the slits in glass, or cover one of the slits with glass. I am not asking about that, and none of those question answer my specific question.
I have read this question:

Replacing the opaque walls with (flawless) glass might cause distortion in a similar band pattern (again, due to the time it takes the photons to get through the glass), but I doubt it'd be that noticeable by the naked eye.

Probability wave speed of dispersion and interference
As far as I understand, the double slit experiment can be done using visible wavelength light, and corresponding energy photons. Now my specific question is about what happens if we make the walls of the slits out of glass.
In this case, the photons can go through the slits or, they can refract through the glass. If I understand correctly, for a photon to move through the glass, it takes more time to reach the screen (relative to when it moves through the slits, which is filled with air). Since photons move faster in air then in glass, the photons could reach the screen faster through the slits, and slower through the glass. The other effect is about the angle when the photons enter and exit the glass. As far as I understand, the photons entering and exiting the glass will propagate at a changed angle, and they could cover the areas that would normally be dark, and make the interference pattern disappear.
There are no detectors on any slits, nor anything interfering with the photons. We cannot know which way (which slit) information either.
Just to clarify, I am not putting any glass on any slits, not covering any slit with anything, and there are no detectors on any slits or anything that would interfere with the photons that move through the slits.
The only difference to a normal double slit experiment is that in this case the photons have the ability (since they correspond to visible wavelength light) to propagate through the walls, since those are made of glass.
Now the answer says that there could be an interference pattern, but it could be distorted, and the reason it gives is about the fact that it takes a photon more time to propagate through glass. But that is not what I am asking, but I am asking about the angle the photons take when they enter and exit the glass, and could be covering the areas that would normally be dark, making the interference pattern disappear.

My initial thought was that the photons refracting through the glass will enter the glass at a changed angle and exit the glass at changed angle again (this angle is different relative to the photons that pass through the slits), and this different angle is what makes the pattern disappear. My reasoning was that the photons passing through the slits do not undergo such change in the angle, thus the photons refracting through the glass could cover the areas that would otherwise be dark.
So there are a few things that come to mind:

*

*the photons refracting through the glass take  longer time to reach the screen (relatively)

*the photons refracting through the glass exit at  changed angle

*all this might be nonsense, because photons are delocalized and do not travel along a definite path (or rather take all possible paths)

*when we see photons refracting through the glass and arriving (relatively) later, we know they did not go through the slits, and this might be interpreted as which way information, and make the pattern disappear
My question is specifically whether we would see an interference pattern.
Question:

*

*Can we see the interference pattern in the double slit experiment if the walls of the slits are made of transparent glass?

A: Yes, there will be an interference pattern. A cheap way to see this is to buy a holographic diffraction grating and see for yourself that it works just as a ruled grating, though with lower efficiency. Granted, it has grooves rather than holes, but this doesn't change the principle of phase modulation: here hundreds of grooves, while in double slit there are just two holes/grooves.
If you are not convinced by the grooves, you can just take a thin sheet of transparent plastic (or transparent film for printers), carefully carve a close pair of holes, and shine a laser pointer through this device, looking at a wall where you direct the output.


text:
Q: scikit-learn GaussianProcessRegressor vs GaussianProcess? Why was GaussianProcess deprecated in version 0.18? I am trying to use kriging(gaussian process) regression with a constant term and generalized exponential correlation model. I was able to do this in older version with GaussianProcess function (version 0.17.1). When I use it, I get a warning saying

deprecationWarning: Class GaussianProcess is deprecated; GaussianProcess was deprecated in version 0.18 and will be removed in 0.20. Use the GaussianProcessRegressor instead.

However, I can't find similar options with GaussianProcessRegressor. I wonder if I can do the same with GaussianProcessRegressor or scikit-learn doesn't plan to support this functionality anymore.

A: GaussianProcess function (version 0.17.1) is based on DACE package and provides two options: trend term and correlation term.

*

*Trend term in Kriging can be set to constant or polynomials such as linear, quadratic. GaussianProcessRegressor assumes a constant trend term which is mean of the training data. It does not support Kriging with trend. However, this is not a major issue because literature suggests that having complicated trend term might not help much. See (Chen, 2016) for example.

*Correlation term in GaussianProcess is similar to correlation kernels in GaussianProcessRegressor, latter being more flexible. RBF kernel is similar to squared exponential kernel in a slightly different form. (Instead of exp(-theta * (distance)^2) is replaced by exp(-theta*(distance)^2/length^2).
Finally, process variance in GaussianProcess is obtained by an analytical expression whereas in GaussianProcessRegressor it is obtained by maximizing likelihood estimator.
References:
S. N. Lophaven, H. B. Nielsen, J. Sondergaard, DACE-A MATLAB Kriging toolbox,
version 2.0, Tech. Rep., 2002a.
H. Chen, J. L. Loeppky, J. Sacks, W. J. Welch, et al., Analysis Methods for Computer Experiments: How to Assess and What Counts?, Statistical Science 31 (1) (2016) 40-60.

A: Yes you can.
The GaussianProcessRegressor class can be used as a drop-in replacement. By default, it uses a RBF Kernel. Thus depending on your case, you can set the Kernel accordingly. See  Rasmussen. Indeed, the purpose of this new class is to implement GP according to this bible.


text:
Q: How to wait for a subscription to complete angular I have a auth service and I want to retrieve the users record from firebase using angularfire before it returns but the data is returned too late. I added ".filter(data => data !== undefined)" but it did not cause it to wait.
this.authState = this.afAuth.authState;
this.authState.subscribe(user => {
  if (user) {
    this.currentUser = user;
    this.userid = this.currentUser.uid;
    this.displayname = this.currentUser.displayName;
    this.path = '/AU/user/' + this.currentUser.uid + '/';
    this.exists = this.af.object(this.path);
      // this line of code returns data after the navbar
      // and user components have started which is too late.
      // The filter was added to try to get it wait for the data.
    this.exists.filter(data => data !== undefined).subscribe(x => {

      if (x && (x.$value !== null)) {
        this.mobile = x.mobile;
        this.userid = x.userid;
        this.name = x.name;
        this.email = x.email;
        this.confirm = x.confirm;
          // the fields below are undefined in the console log
        console.log( 'email', this.email, 'name', this.name)
      } else {
        this.currentUser = null;
      }
  });

While googling this problem I found that perhaps I needed to map the response but it made no difference. Below is the code I used
 this.exists.map(response => this.response$)
            .filter(data => data !== undefined)
            .subscribe(x => {

I tried comparing to both "undefined" and "null". I have run out of ideas, please help.

A: How about using flatMap(), like this?
import 'rxjs/add/operator/mergeMap`;

this.exists.flatMap(response => {
  this.response$
  .catch(error => {
    console.error(error);
    return Rx.Observable.empty();
  });
});

I imported mergeMap operator, despite the fact that we will use flatMap, because of flatMap missing after upgrading to RC 6 and RxJS Beta 11 and rxjs flatmap missing.
Read about map vs flatMap, if you like.

A:  this.exists.flatMap(response => this.response$)


text:
Q: Creating new AVD for the newly built android system image I have built android lollipop code and i have generated the system image. I would like to run this in a emulator on a different machine where android sdk latest version is installed. According to this link I tried creating a new avd. And i tried going to the path (i.e. /.android/avd/your_avd_name.avd) , but icould not find the system.img file to substitute. What solution can I possibly use. Please let me know.
Regards,
Sathya Prasad P


text:
Q: Csv reading with fs and events, problem in manipulating the data for the scope of the function. With nodejs and jest I need help with one thing:
I have a function that generates an array of objects, as follows:
const parse = require('csv-parse');
const fs = require('fs');

async function dadosCsv(arquivo){
  let csvData = []
  fs.createReadStream(arquivo)
  .pipe(
    parse({
        columns: true,
    })
  )
  .on('data', async(row) =>{
    csvData.push(row)
  })
  .on('end', async() =>{
    return csvData
  })
}

module.exports = dadosCsv;

Then I try to use this array in a separate test file using jest methods
const dadosCsv = require('../helper/dadosCsv')
// Log function
console.log(dadosCsv);

describe("Testando", () => {
    dadosCsv(__dirname + '/importar_notas_sp.csv')

    test('Cenario', async() =>{
        csvData.forEach(function(item) {
          // Trying to log data from within the array into the above function
          console.log(JSON.parse(item.msgRetorno))
        })
    })
})

Error obtained, obs: I can get the asynchronous function of the other file, but I can't use the array from within it:
Trying to log data from within the array into the above function
        ReferenceError: csvData is not defined
      21 |
      22 |     test('Cenario', async() =>{
    > 23 |         csvData.forEach(function(item) {
         |         ^
      24 |           console.log(JSON.parse(item.msgRetorno))
      25 |         })
      26 |     })

      at Object.<anonymous> (src/importar_notas_SP.test.js:23:9)

Log function:
  console.log src/importar_notas_SP.test.js:20
    [AsyncFunction: dadosCsv]

A: Wesley, it looks like you are a beginner in Nodejs, Nevermind but you are missing a few things in code. I am modifying the code a bit.I would also suggest you learn more about promises and async-await. You have to handle call  to dadosCsv(__dirname + '/importar_notas_sp.csv') function correctly and also you need to return promise from function dadosCsv
const parse = require('csv-parse');
const fs = require('fs');

function dadosCsv(arquivo) {
    let csvData = []
    return new Promise(function(resolve, reject) {
        fs.createReadStream(arquivo)
            .pipe(
                parse({
                    columns: true,
                })
            )
            .on('data', async (row) => {
                csvData.push(row)
            })
            .on('end', async () => {
                resolve(csvData)
            })
            .on('error', (err) => {
                reject(err)
            })
    })
}
module.exports = dadosCsv;

======================test file=======================
const dadosCsv = require('../helper/dadosCsv')
describe("Testando", () => {

    test('Cenario', async () => {
        let csvData = await dadosCsv(__dirname + '/importar_notas_sp.csv')
        csvData.forEach(function(item) {
            // Trying to log data from within the array into the above function
            console.log(JSON.parse(item.msgRetorno))
        })
    })
})

I have created repl for you try  playing around it and find out more about promise and async-await
https://repl.it/repls/LovingUprightMp3


text:
Q: xfbml registration plugin validation error I used Facebook's demo scripts to understand registration plugin' system. I use this code:

    <title>Home</title>

<fb:registration redirect-uri="http://basarozcan.com/store_userdata.php"
  fields='[{"name":"name"},
           {"name":"username","description":"Username","type":"text"}]'
  onvalidate="validate_async"></fb:registration>

I opened the page and write username but script can not validate username and firebug show an error. Error is:
Permission denied to access property 'Arbiter'
if (p == parent || !p.Arbiter || !p.JSON) {

How can I solve this problem?
Thanks

A: I think you need to use HTTPS:


text:
Q: MKMapView - Is there a way to use MKUserTrackingModeFollow with a modified center/focus? I have a MapView that takes up the full screen and a few elements toward the top of the screen that overlay the map. These top elements potentially cover the blue location marker.
The map is currently tracking fine with MKUserTrackingModeFollow, but I'd like to move the tracking focus down about an inch (obviously the metric will vary by zoom level) to ensure the marker isn't covered. Is there a way to do this with MKUserTrackingModeFollow?
I've considered moving the map with the top elements, but due to design constraints this isn't an option.

A: Instead of using the userTrackingMode of the MKMapView object to follow the user's location, you could set up a delegate of CLLocationManager to receive location tracking events, and with each location update event you receive, set the center coordinate of the map view, with your vertical offset added to the coordinate value.
You can use the various Map Kit functions and MKMapView methods to convert your offset from some fraction of the map view's bounds.height to a MKMapPoint or CLLocationDistance value.


text:
Q: Can I convert for loop number pattern to while loop and do while loop? I'm learning java looping, and managed to print a number one pattern using the for loop.
I tried printing the number one pattern using the while and do while loop, but had difficulty. This is my code:
for (int i = 0; i <= 7; i++) {
    for (int j = 0; j <= 4; j++) {
        if ((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
            System.out.print("1");
        else
            System.out.print(" ");
    }

    System.out.println();
}

This is my while loop code:
int i = 0, j = 0;
        while (i <= 7) {
            while (j <= 4) {
                if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
                    System.out.print("1");
                else
                    System.out.print(" ");

                j++;
            }

            System.out.println();
            i++;
        }

A: Yes, any for loop can be converted into a while or do-while.
For example:
for(initialize; condition_check, statement1) {
    ......
}

Here statement1   =>  generally this is an increment or decrement of a variable used in the condition_check
Similarly the equivalent while loop would be:
initialize;
while (condition_check) {
     .......;
     statement1;
}

So it seems that you have forgotten to initialize one of the variables. The other answer has already given you that.
This answer would help in mapping the for loop to the while loop and vice-versa.
Hope it helps.

A: Need to reset j counter after first j_while end
int i = 0, j = 0;
while (i <= 7)
{
//could also reset here
j=0;
    while (j <= 4)
    {
     if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
         System.out.print("1");
     else
         System.out.print(" ");
         j++;
     }
       System.out.println();
       i++;
 }


text:
Q: Bigquery: Group timestamp by month I am new in bigquery and I can show timestamp like this.
select event_timestamp as timestamp1
          FROM `alive-ios.analytics_160092165.events_201810*`
          GROUP BY timestamp1

Output is like this. How can I group those by month? Is it like this?
https://www.pascallandau.com/bigquery-snippets/convert-timestamp-date-datetime-to-different-timezone/
I try with to_char, DATE , etc and it is not okay.

A: Below is for BigQuery Standard SQL
SELECT
  FORMAT_TIMESTAMP('%Y-%m', TIMESTAMP_MICROS(event_timestamp)) month,
  COUNT(1) events
FROM `project.dataset.table`
GROUP BY month

Note: most likely you want to count events for each month, so I added COUNT(1), but you can add whatever you need  - like SUM(amount) for example if you want to calculate some metric named value
Also, your wildcard expression is build in such a way that it will have only events for month of October 2018 (assuming the table name represent time of event) - so you will need to relax a little you wildcard expression to (for example) alive-ios.analytics_160092165.events_2018* so you will have events for months of whole 2018 year
Above assuming your event_timestamp is represented in microseconds
If in reality they are of TIMESTAMP type  - just remove use of TIMESTAMP_MICROS() function

A: It sounds like you want the TIMESTAMP_TRUNC function, e.g.
select TIMESTAMP_TRUNC(event_timestamp, MONTH) as timestamp1
FROM `alive-ios.analytics_160092165.events_201810*`
GROUP BY timestamp1

A: Building on Elliott's example, I think you need to convert the value to a timestamp first. From your example data I think you need TIMESTAMP_MICROS
TIMESTAMP_MICROS
select TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), MONTH) as timestamp1
FROM `alive-ios.analytics_160092165.events_201810*`
GROUP BY timestamp1


text:
Q: Jax-Rs Security Annotations : Missing Interactions with the JEE8 Security API ? i have issues when trying out the new jee8 security api
(https://github.com/andrebiegel/jax-rs-playground.git  take the jee8 branch )
When I declare the security-contraints with jax-rs annotations  (PermitAll, RolesAllowed) on a jax-rs resource , the HttpAuthenticationMechanism doesn't protects the resources. it only works when defining the constraints via web.xml.
I would like to define the constraints by annotations.
how does that work ? Other annotations ? I also testet that with a @DeclaredRoles/ @RolesAllowed combination


text:
Q: Can't use Python 3.8 version interpreter in PyCharm I've tried to upgrade Python version to 3.8 and when I want to add the interpreter in PyCharm I get the following:

I have no idea as to why this happens. When I type python -V in the command prompt I get Python 3.8.3.
EDIT: Python version actually is updated but PyCharm still marks the code as if the version is 3.


text:
Q: Change the chapter font in TOC without using "tocloft" package As using tocloft in book class produces some unexpected side-effect, I wonder how to change the chapter font (e.g. 1  Introduction) as sans serif without using any other packages?
For example, change the highlighted text to sans serif font.
MWE:
\documentclass{book}
\usepackage[UKenglish]{babel}
\usepackage{color}
\usepackage[lining ]{libertine}
\usepackage[ T1 ]{fontenc}

\definecolor{DarkBlue}{RGB}{0,51,153}
\usepackage[ ]{titlesec}
\titleformat{\chapter}[display]
  {\LARGE \color{DarkBlue}}
  {\vspace{-1 em} \flushright   \normalsize \color{black}  \MakeUppercase{  \bfseries \sffamily  \chaptertitlename } \hspace{1 em}  { \fontsize{70}{70}\selectfont \color{black} \sffamily \thechapter }} {20 pt} { \bfseries \sffamily \LARGE}

\titleformat{\section} {\Large \bfseries \sffamily \color{DarkBlue}}     {\thesection}{1 em}{}
\titleformat{\subsection}  {\large \bfseries \sffamily  \color{DarkBlue}}      {\thesubsection}{1 em}{}
\titleformat{\subsubsection}  {\normalsize \sffamily  \bfseries      \color{DarkBlue}}  {\thesubsubsection}{1 em}{}  %\slshape
\setcounter{tocdepth}{3}   % table of content depth
\setcounter{secnumdepth}{3}

\usepackage{lipsum}

\begin{document}

\frontmatter
\tableofcontents
\chapter{Preface}

\lipsum[1-3]
\mainmatter
\chapter{Introduction}
\section{Foo}
\lipsum[1-12]
\chapter{How to make nuclear bomb}
\section{Equations}
\lipsum[1-12]
\backmatter
\chapter{Appendix~A}
\lipsum[1-12]
\chapter{Appendix~B}
\lipsum[1-12]
\end{document}

A: This is not really tested for lack of copy-pastable code, but should work in the book class. Put in the preamble:
\makeatletter
\def\l@chapter#1#2{%
\ifnum \c@tocdepth >\m@ne \addpenalty {-\@highpenalty }\vskip 1.0em \@plus\p@
\setlength \@tempdima {1.5em}\begingroup \parindent \z@ \rightskip\@pnumwidth
\parfillskip -\@pnumwidth \leavevmode \bfseries \advance \leftskip \@tempdima
\hskip -\leftskip {\sffamily #1}\nobreak \hfil \nobreak \hb@xt@ \@pnumwidth
{\hss #2}\par \penalty \@highpenalty \endgroup \fi}
\makeatother

Update: if you want to achieve similar effect with memoir or scrbook then use rather the following code:
\makeatletter
\let\originall@chapter\l@chapter
\def\l@chapter#1#2{\originall@chapter{{\sffamily #1}}{#2}}
\makeatother

The above is actually preferable to the one I proposed earlier, also for the book class, as it will less encumber your preamble. Nevertheless the advantage of the first proposal is that you can also in case of need customize the hard-coded lengths therein.
\documentclass{book}
\usepackage{lipsum}

\makeatletter \def\l@chapter#1#2{%
  \ifnum \c@tocdepth >\m@ne \addpenalty {-\@highpenalty }\vskip 1.0em \@plus\p@
  \setlength \@tempdima {1.5em}\begingroup \parindent \z@ \rightskip\@pnumwidth
  \parfillskip -\@pnumwidth \leavevmode \bfseries \advance \leftskip \@tempdima
  \hskip -\leftskip {\sffamily #1}\nobreak \hfil \nobreak \hb@xt@ \@pnumwidth
  {\hss #2}\par \penalty \@highpenalty \endgroup \fi} \makeatother

\begin{document}

\tableofcontents

\chapter{One}

\section{A}

\lipsum[1]

\section{B}

\lipsum[2]

\chapter{Two}

\section{C}

\lipsum[3]

\section{D}

\lipsum[4]

\end{document}

And with the code provided in the question, one obtains:


text:
Q: XML::Simple doesn't seem to work with a URL. Is this correct? I am using the following script:
#!/usr/local/bin/perl -wT

use strict;
use warnings;

print "Content-type: text/html\n\n";
print "xml reader";

# use module
use XML::Simple;
use Data::Dumper;

#print Dumper (XML::Simple->new()->XMLin());

and it will read in my xml file called xml.xml
If I now move the xml file out of my cgi-bin, change its name and reference it using:
#print Dumper (XML::Simple->new()->XMLin("../resource.xml"));

It still works.
If I now try and use a url instead the script doesn't return anything:
print Dumper (XML::Simple->new()->XMLin("http://digitalessence.net/resource.xml"));

I have tried with and without the http://, without the www and all sorts of different ways of doing this but it doesn't return anything.
Have I done something silly here or will it just not load a remote url?
Thanks.

A: The XMLin() method in XML::Simple does not support fetching the XML from an URL. You would need to fetch the XML separately, either to a file or directly into a Perl scalar variable, before applying XMLin(). This is clear from the XML::Simple documentation.

A: You can modify your program as follows, using LWP to retrieve the remote resource:
[...]
# use module
use XML::Simple;
use LWP;
use Data::Dumper;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( GET => "http://digitalessence.net/resource.xml" );
my $res = $ua->request( $req );

print Dumper (XML::Simple->new()->XMLin( $res->content ));


text:
Q: Flutter build stream builder from app start I need to load the saved themes from shared preference async from app start. After it loaded, replace the placeholder two themes. But below code failed because even it loaded the results for several themes, the app always displays the two themes.
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  final bloc = AppThemeBloc();
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    bloc.getAppThemes();
    return buildApp();
  }

  Widget buildApp() {
    return StreamBuilder<List<AppTheme>>(
        stream: bloc.subject.stream,
        builder: (context, AsyncSnapshot<List<AppTheme>> snapshot) {
          if (snapshot.hasData) {
            return ThemeProvider(
              saveThemesOnChange: true,
              loadThemeOnInit: true,
              themes: snapshot.data,
              child: MaterialApp(
                home: ThemeConsumer(
                  child: HomePage(),
                ),
              ),
            );
          } else {
            return ThemeProvider(
              saveThemesOnChange: true,
              loadThemeOnInit: true,
              themes: [
                AppTheme.light(),
                AppTheme.dark(),
              ],
              child: MaterialApp(
                home: ThemeConsumer(
                  child: HomePage(),
                ),
              ),
            );
          }
        });
  }
}

A: After the data is received and the streambuilder is refreshed which updates the state so build function is being executed again thus calling:
bloc.getAppThemes();

again which waits for any data to pass in the stream returning your placeholder themes, place bloc.getAppThemes function in the initState function:
@override
void initState() {
   super.initState();
   bloc.getAppThemes();
}


text:
Q: How do I check if an element was created with a named constructor in dart? I was wondering if I can check which constructor I used to create the created element in an if statement in dart.
A simple example of what I want to do:
class Employee {
  int id;
  String name;
  String title;

  Employee.id(this.id);

  Employee.name(this.name);

  Employee.title(this.title);
}

Now I have an if statement somewhere in my code and want to check if I used the constructor Employee.id. In this case I would do something, somehow like this:
Employee e = new Employee.id(1)

//check if e was created with Employee.id constructur
if (e == Emploee.id) {
   print(e.id)
} else {
   print("no id")
}

Is there a way to do this? Thank you for your answer.

A: You can make your class a Union type using the freezed package and use the folding methods as shown below to see what constructor was used:
 import 'package:freezed_annotation/freezed_annotation.dart';

part 'tst.freezed.dart';

@freezed
abstract class Employee with _$Employee {
  const factory Employee.id(int id) = IdEmployee;

  const factory Employee.name(String name) = NameEmployee;

  const factory Employee.title(String title) = TitleEmployee;
}

void main() {
  Employee employee1 = Employee.id(0);
  Employee employee2 = Employee.name('some name');
  Employee employee3 = Employee.title('some title');

  employee1.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the first statement

  employee2.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the second statement

  employee3.when(
    id: (int id) => print('created using id contsrutor and id= $id'),
    name: (String name) => print('created using name const and name = $name'),
    title: (String title)=>print('created using title const and title = $title'),
  );//prints the third statement

  print(employee1 is IdEmployee);
  print(employee1 is NameEmployee);
}

and the output will be:
created using id contsrutor and id= 0
created using name const and name = some name
created using title const and title = some title
true
false

A: You can define private enum property for you to set private info like this, and print it with a function later on. Also don't forget to mark your constructors with factory.
enum _ConstructorType {
  Identifier,
  Name,
  Title,
}

class Employee {
  int id;
  String name;
  String title;
  _ConstructorType _constructorType;

  factory Employee.id(id) {
    return Employee._privateConstructor(_ConstructorType.Identifier, id: id);
  }

  factory Employee.name(name) {
    return Employee._privateConstructor(_ConstructorType.Name, name: name);
  }

  factory Employee.title(title) {
    return Employee._privateConstructor(_ConstructorType.Title, title: title);
  }

  Employee._privateConstructor(this._constructorType,
      {this.id, this.name, this.title});

  String constructorDescription() {
    return this._constructorType.toString();
  }
}

If you need this information not as a string, but as enum, you can always remove underscore on it, and make this info public for you to use outside of the class.


text:
Q: Android: In Eclipse project missing Google APIs? I have a work space with many projects. One of them is suddenly missing the Google APIs libraries even though it is clearly checked. the properties file lists it correctly.
How do I get Eclipse to add these to this one project?

A: once i had problem like this : i tried many but can't find and positive solution.(1)
  - make new project with required target and move src, res, ref and manifest to this new project.(2)- Just try remove auto build option from project menu and then delete gen folder and just build project and then clean & build project.

A: This often works for me:

*

*Select another build target and click 'Apply'. When the update is finished I select the previous build target and then 'Apply' again.

*Remove 'bin' and 'gen' directories from my project and select the clean option in the project menu.