text:
Q: XQuartz crashing in infinite loop -- El Capitan edition I have a MacBook Air running OSX El Capitan, version 10.11.6. I downloaded XQuartz 2.7.11, but when the program that uses it launches it (or I double-click it in the Utilities folder), XQuartz begins an infinite loop in which the logo appears briefly in the dock, then an "Xquartz quit unexpectedly" window pops up. There's also a crash report, but I can't make heads or tails of it and it's too long to fit within the character limits here.
What seems to be a bit more helpful is what appears in the logs recommended here, which records the following over and over:
Nov  8 22:17:19 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18311]: syntax error
Nov  8 22:17:08 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18150]: expr: syntax error
Nov  8 22:17:08 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18150]: xauth:  file /Users/XXXXX/.serverauth.18151 does not exist
Nov  8 22:17:08 XXXXX-MacBook-Air org.macosforge.xquartz.X11.stub[18295]: Xquartz: Unable to locate waiting server: org.macosforge.xquartz.X11
Nov  8 22:17:08 XXXXX-MacBook-Air org.macosforge.xquartz.X11.stub[18296]: Xquartz: Starting X server: /Applications/Utilities/XQuartz.app/Contents/MacOS/X11 --listenonly
Nov  8 22:17:08 XXXXX-MacBook-Air org.macosforge.xquartz.X11.stub[18295]: Xquartz: start_x11_server: (ipc/mig) server died
Nov  8 22:17:10 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18150]: /opt/X11/bin/xinit: giving up
Nov  8 22:17:10 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18150]: /opt/X11/bin/xinit: unable to connect to X server: Connection refused
Nov  8 22:17:10 XXXXX-MacBook-Air org.macosforge.xquartz.startx[18150]: /opt/X11/bin/xinit: server error
Nov  8 22:17:10 XXXXX-MacBook-Air com.apple.xpc.launchd[1] (org.macosforge.xquartz.startx[18150]): FairPlay decryption failed on binary.
Nov  8 22:17:10 XXXXX-MacBook-Air com.apple.xpc.launchd[1] (org.macosforge.xquartz.startx): Service only ran for 2 seconds. Pushing respawn out by 8 seconds.

I get that there's apparently a syntax error, but why would there be, and what am I expected to do about it?
I found this post, but it's from four years ago and is about Mountain Lion. Nevertheless, I attempted to do what solved the problem then -- moving ~/.xinitrc.d out of the way -- but I cannot find an .xinitrc.d on my system. Same with the other suggestion about /sw/bin/init.sh. I also moved every rc/profile file into a different folder, to no effect.
I also completely uninstalled and reinstalled XQuartz, but it only resulted in the same problem.
I'm tearing my hair out. Any suggestions?


text:
Q: How to merge lines of a list into phrases (help to complete the code)? I have a list as follows:
[
 '"The investment would also benefit the company's',
 'ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material',
 'usage by replacing cardboard boxes with reusable',
 'plastic tote bins and cutting daily vehicle movements through the accurate management of',
 'fixed cyling schedules.",',
 '"The core brands of Cadbury Roses and Heroes are',
 'produced and packaged at the Bournville production facility. The wrapped chocolates that make',
 'up these assortments have traditionally been',
 'managed through the factory in cardboard boxes.'
]

I need to drop " and merge lines into phrases in order to get the following result:
[
 'The investment would also benefit the company's ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material usage by replacing cardboard boxes with reusable plastic tote bins and cutting daily vehicle movements through the accurate management of fixed cyling schedules.',
 'The core brands of Cadbury Roses and Heroes are produced and packaged at the Bournville production facility.",
 'The wrapped chocolates that make up these assortments have traditionally been managed through the factory in cardboard boxes.'
]

How can I do it?
This is what I started doing:
final_list = []
temp_list = []
for l in lines:
    temp_list.append(l)
    if "." in l:
        phrase = ' '.join(map(str, temp_list))
        final_list.append(phrase)
        temp_list = []

final_list

It generates the following output, which is not exactly a match of my expected output:
[
 '"The investment would also benefit the company's ongoing commitment to the Kraft Foods Sustainability Programme; substantially reducing material usage by replacing cardboard boxes with reusable plastic tote bins and cutting daily vehicle movements through the accurate management of fixed cyling schedules.",',
 '"The core brands of Cadbury Roses and Heroes are produced and packaged at the Bournville production facility. The wrapped chocolates that make',
 'up these assortments have traditionally been managed through the factory in cardboard boxes.'
 ]

A: Try the following. It will check only if there is a period near the end, and it will remove the extra quotation marks and comma that you remove in between your test and output case, but will not remove extra characters.
final_list = []
temp_list = []
for l in lines:
    temp_list.append(l)
    if "." in l[-3:]:
        phrase = ' '.join(map(str, temp_list)).strip('", ')
        final_list.append(phrase)
        temp_list = []

print(final_list)

A: I hope this can help you. lines is the name I gave to the array.
for i in range(1,len(lines)):
lines[0] += " " + lines[i]

lines = [line.split("\"")[1] for line in lines[0].split(", ")]
print(lines)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt standard dialogs example: Open file I'm beginning to learn Qt for use in one of my projects, and what I need to do is create a GUI that allows the user to open a file. I was looking through the examples and I found one of them that has exactly what I need; the problem is that it's also got a whole lot of other stuff, to the point where I have no idea what I'm looking at or what I'm looking for.
Basically, my question is this:
How do I make what you can see below in the image, where after clicking on the button and selecting the relevant file, it shows and stores the file path in the box to the right?

I have already figured out how to make the button open the file dialog, my only problem is getting it to store and display the filepath.

A: Solved it with this:
void OpenXMLFile::on_File1Button_clicked()
{
    file1Name = QFileDialog::getOpenFileName(this,
         tr("Open XML File 1"), "/home", tr("XML Files (*.xml)"));
    ui->File1Path->setText(file1Name);

}

void OpenXMLFile::on_File2Button_clicked()
{
    file2Name = QFileDialog::getOpenFileName(this,
         tr("Open XML File 2"), "/home", tr("XML Files (*.xml)"));
    ui->File2Path->setText(file2Name);

}

Where this is my GUI:

(The boxes next to the buttons are Line Edits if anyone was wondering)


text:
Q: How to rotate an image R raster I have code below which saves an image to my pc. I would like to rotate that image by 45,90 and 135 degrees around its center (or bottom left hand corner) and then save as 3 different images. How could I do that?
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
png(width=50, height=50)
par(mai=c(0,0,0,0))
image(x)
dev.off()

---------update1-------------------------
Based upon the accepted answer the working code is as below
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
r1
x <- crop(r1, extent(0,ncol(r1),0,nrow(r1)))
plotRGB(x)

x1 <- 0:ncol(x)
y1 <- 0:nrow(x)
z <- matrix(1, nrow=length(x1), ncol=length(y1))

col.mat <- t(apply(matrix(rgb(getValues(x)/255), nrow=nrow(x), byrow=TRUE), 2, rev))

# Rotate 45 degrees
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90,
      col = col.mat, scale=FALSE, border=NA, box=FALSE)
png("SaveThisPlot.png")
persp(x1, y1, z, zlim=c(0,2), theta = 20, phi = 90,
      col = col.mat, scale=FALSE, border=NA, box=FALSE)
dev.off()

A: For the 90 degree rotations, this is an easy solution:
image(t(flip(x, 1)))
image(t(flip(x, 2)))
plotRGB(t(flip(x, 1)))
plotRGB(t(flip(x, 2)))

For the 45 degree and 135 degree rotation, it will be a bit trickier.  There are probably other ways, but I'll use the persp function and give different angles to the theta argument.
It's just a matter of setting up the call to persp properly.  x1, y1, and z are just inputs for the persp function (see ?persp for more about the arguments to that function).  col.mat is a matrix holding color values.
x1 <- 0:ncol(x)
y1 <- 0:nrow(x)
z <- matrix(1, nrow=length(x1), ncol=length(y1))
col.mat <- t(apply(matrix(rgb(getValues(x)/255), nrow=nrow(x), byrow=TRUE), 2, rev))
# the transposing and reversing are just to get the colors in the same
# spots as they're in when viewing plotRGB(x).
#
# getValues(x) is how you get the rgb colors, in the form of a 3-column matrix.
# rgb(getValues(x)/255) converts them into hex code, which is convenient enough here.

If you find that this is the mirror image of what you're looking for, try filling up the color matrix differently.  For example:
col.mat <- matrix(rgb(getValues(x)/255), nrow=nrow(x))

As you can tell, filling up the color matrix properly is the key to making this approach work for you.  I'll leave it as an exercise to the reader to figure out how to do any other manipulations to the color matrix.
Now, call persp.  Here, I set the zlim values so there is a range including 1.  Because I made all the z values 1, you need to set a valid range, otherwise, persp will throw an error about invalid limits.  It doesn't like a range from 1 to 1.
# Rotate 45 degrees
persp(x1, y1, z, zlim=c(0,2), theta = 45, phi = 90,
    col = col.mat, scale=FALSE, border=NA, box=FALSE)

Here's a 135 degrees:
# Rotate 135 degrees
persp(x1, y1, z, zlim=c(0,2), theta = 135, phi = 90,
    col = col.mat, scale=FALSE, border=NA, box=FALSE)

Saving the plots can be done in the same way you show in your question:
png("SaveThisPlot.png")
persp(x1, y1, z, zlim=c(0,2), theta = 135, phi = 90,
    col = col.mat, scale=FALSE, border=NA, box=FALSE)
dev.off()

A: The way to do it without throwing an error or warning message (after reading the help page and playing with the example:)
extent(x) <- extent(0, 360, -90, 90)
rr <- rotate(x)
 png()
 plotRGB(x)
dev.off()

But you may not like it because it assumed a particular coordinate system tat you probably did not. If you want to pull the data elements out then use the @ operator:
str(x)  The slots are named 'data' and 'values'
image(x)
image(matrix(x@data@values[,1], 50, byrow=TRUE)) # rotate one layer


text:
Q: Excel, VBA: How to pass multiple variables to .OnAction I am trying to pass multiple variables to a .OnAction call for a button.  I have not been able to find answers that relate to multiple variables, and I can do it with just one variable.  Here is what I have that works for one variable:
shpBar.OnAction = "'Button_Click """ & strText & """'"

How can I add two other variables to this (such as VarA and VarB)?

A: Assuming that VarA and VarB are variants or numeric variables, this would work:
.OnAction = "'Button_Click """ & strText & """," & varA & "," & varB & " '"

If they are strings, you need to add two more double-quotes around each variable name.
.OnAction = "'Button_Click """ & strText & """,""" & varA & """,""" & varB & """ '"


text:
Q: Calling (require ...) on a MELPA installed package gives FlyCheck error "Cannot open load file" I want to require some packages installed through MELPA so that i can access their variables and functions without getting "free variable" or "undefined function" warnings.
However, when I try to load a package it isn't found by Flycheck and i get a "Cannot open load file" error. It seems that the bytecode compiler doesn't read into the directory with the files installed by MELPA, but I don't know how to solve this.
I'm using Emacs 26.3 with Purcell's config that includes Flymake-Flycheck.  This snippet covers the relevant parts of the init-elpa.el custom files where you can see the at the end that even if I install and then (require ...) a package it still is marked with an error by Flycheck.
;;; init-elpa.el --- Settings and helpers for package.el -*- lexical-binding: t -*-

(require 'package)
(require 'cl-lib)

;;; Install into separate package dirs for each Emacs version, to prevent bytecode incompatibility
(setq package-user-dir
      (expand-file-name (format "elpa-%s.%s" emacs-major-version emacs-minor-version)
                        user-emacs-directory))

;;; Standard package repositories
(add-to-list 'package-archives '( "melpa" . "https://melpa.org/packages/") t)

(defun require-package (package &optional min-version no-refresh)
  "Install given PACKAGE, optionally requiring MIN-VERSION.
If NO-REFRESH is non-nil, the available package lists will not be
re-downloaded in order to locate PACKAGE."
  ...)

(defun maybe-require-package (package &optional min-version no-refresh)
  "Try to install PACKAGE, and return non-nil if successful.
In the event of failure, return nil and print a warning message.
Optionally require MIN-VERSION.  If NO-REFRESH is non-nil, the
available package lists will not be re-downloaded in order to
locate PACKAGE."
  ...)

;;; Fire up package.el
(setq package-enable-at-startup nil)
(package-initialize)

(defvar sanityinc/required-packages nil)

(defun sanityinc/note-selected-package (oldfun package &rest args)
  "If OLDFUN reports PACKAGE was successfully installed, note that fact.
The package name is noted by adding it to
`sanityinc/required-packages'.  This function is used as an
advice for `require-package', to which ARGS are passed."
  ...)

(advice-add 'require-package :around 'sanityinc/note-selected-package)

(when (fboundp 'package--save-selected-packages)
  (require-package 'seq)
  (add-hook 'after-init-hook
            (lambda ()
              (package--save-selected-packages
               (seq-uniq (append sanityinc/required-packages package-selected-packages))))))

;; READ HERE: now i try to install and require some packages.
(require-package 'fullframe)
(require-package 'evil)
(require 'fullframe) ;; Flycheck gives an ERROR: cannot open load file, files or directory does not exist
(require 'evil) ;; same as above
(require 'python) ;;this gives no error, since it's built-in i guess.

(provide 'init-elpa)
;;; init-elpa.el ends here

You can see that (package-initialize) is called so the load-path should be set. Also, I have flycheck-emacs-lisp-load-path set to 'inherit, which should mean that the bytecode compiler reads the same dirs as a normal emacs instance.
What should I do in order to make the bytecode compiler recognize my ELPA directory?

A: Check out flycheck-emacs-lisp-load-path variable

flycheck-emacs-lisp-load-path is a variable defined in 'flycheck.el'.
... When set to 'inherit', use the 'load-path' of the current Emacs
session during syntax checking.

E.g you could do:
(use-package flycheck
  :diminish ""
  :custom
  (flycheck-emacs-lisp-load-path 'inherit)
...


text: Q: Is there a way to call a file outside of the public folder from an HTML file inside the public folder? Is it possible to access files outside of the public folder from a file in the public folder? I've searched everywhere for the answer and I can't find it. One of the things I'm trying to do here is call a js file in the root of my project from index.html in the public folder using a script tag, and doing something like <script src="../script.js"></script> doesn't work. Is there any other way to call the js file (even if it requires calling it from another js file in the public folder called by the html file), or do I have to put the js file in the public folder? This HTML page is being run by node.js, if that makes a difference.


text:
Q: Recent Windows Update causing Admin issues in Windows 7 After a recent Windows Update in December 2014 or January 2015, I now have to run a lot of programs as Administrator in order to avoid access/security errors.  I'm not sure why, as I'm a local administrator on my machine.  I am running Windows7 x64.
For instance, if I run a Command Prompt without running-as Administrator, and try using "net start" or "net stop" to modify a service, I will get various errors, such as "System error 5 has occurred" or "Access is denied".  However, if I open up my Services window, I am able to start and stop the same services without issue.  I had always been able to start/stop services from Command Prompt until after a recent reboot.  So, either a Group Policy or a Windows Update is at play here.

A: My issues turned out to be caused by a new Group Policy at work.  Once the NT Admins pushed a newer policy to correct this, the issue went away for me and other coworkers.  However, the fix suggested by @magicandre1981 also worked for others before the updated GP got pushed out, so people should try that if they stumble upon this question.


text:
Q: NodeJS - 'config' is not able read form configuration files I've been trying to set the environment variables using 'dotenv' pkg.
const dotenv = require('dotenv');
dotenv.config();

and this is my .env file,
NODE_ENV=development

PORT=3001

NES_POSTGRES_DB=***
NES_POSTGRES_HOST=***
NES_POSTGRES_USER=***
NES_POSTGRES_PASSWORD=***
NES_POSTGRES_PORT=***
NES_POSTGRES_REGION=***

Working fine. BUT the problem is, 'config' pkg is not able to read these.
Following is my 'custom-environment-variables.json' file under the config directory of my project.
{
    "databases":{
        "test":{
            "database": "NES_POSTGRES_DB",
            "host": "NES_POSTGRES_HOST",
            "username": "NES_POSTGRES_USER",
            "password": "NES_POSTGRES_PASSWORD",
            "port": "NES_POSTGRES_PORT",
            "dialect": "postgres"
        }
    },
    "node_port": "PORT"
}

Now, using the config.get function to access the environment variable PORT (which was earlier set by dotenv, and it is accessible by process.env.PORT)
const port = config.get('node_port');

Error: Configuration property "PORT" is not defined.
Following is my server.js file,
const dotenv = require('dotenv');
const config = require('config');
const helmet = require('helmet');
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const routes = require('./routes/index');

console.log(`Before dotenv.config() call -> NODE_ENV : ${process.env.NODE_ENV}`); // undefined
dotenv.config();
console.log(`After dotenv.config() call -> NODE_ENV : ${process.env.NODE_ENV}`); // 3001

const expressApp = express();

expressApp.use(helmet());
expressApp.use(morgan('tiny'));

const port = config.get('node_port');

expressApp.listen(port, () => {
    console.log(`Express App (NES) is running on port: ${port}`);
});

And following is my folder structure.

Any sort of help will be much appreciated. Thanks in advance!

A: I would definitely agree with aitchkhan, using two separate packages for config management may not be best practice. Without using the config package, you can access the environment variables you set up with dotenv using process.env like so:
In .dotenv:
NODE_ENV=development

PORT=3001

NES_POSTGRES_DB=***
NES_POSTGRES_HOST=***
NES_POSTGRES_USER=***
NES_POSTGRES_PASSWORD=***
NES_POSTGRES_PORT=***
NES_POSTGRES_REGION=***

And in server.js:
// import dotenv and express
const express = require('express');
const dotenv = require('dotenv');
enter code here
// initialize server
const expressApp = express();

// initialize dotenv
dontenv.config()

// access port from process.env after initialization
const port = process.env.PORT

// should now log the correct port number
expressApp.listen(port, () => {
    console.log(`Express App (NES) is running on port: ${port}`);
});

If you would prefer to continue using the config package, it looks like it looks for its default config at ./config/default.json (as mentioned in its quick start guide).


text:
Q: Unexpected Verilog bit manipulation I am a C programmer with lots of experience with bit manipulation and 2s compliment. I find Verilog doesn't act quite like I expect, which causes me to do more trial and error than I would like.
I understand that signed arithmetic in Verilog, requires that everything should be signed. I wonder it there is some other rule that I am missing.
Question 1:
reg signed [12:0] position;
position = position - 1'b1;  //this worked

position = position - 1'sb1  //this seemed to subtract a negative 1, the opposite of my intention.

Did the synthesizer fill my 1 out to 13 bits carrying out the sign bit?  Should I have used 13'sb1 instead.  When can I get away with the conceptually simpler 1'b1, or even just 1?
Question 2:
reg signed [12:0] position, PWMgo;

reg doForward, doReverse;

if(position  > PWMgo - 1'sd1) begin   //this works

if(position  > PWMgo - !(doForward || doReverse))  begin // this doesn't work

if(position  > PWMgo - ~(doForward | doReverse))  begin // this doesn't work either

Explanation: In the C world doForward and doReverse are both bits and can either be used as bits or as the numbers 0 or 1. My intention here is to do some bit manipulation on these two bits and subtract the result (a 1 or 0) from PWMgo. I am doing this to avoid several confusing lines of if statements.
I have been asked what I mean by "this doesn't work".  What I mean is that I was expecting PWMgo to be either decremented, or unchanged, an expectation that was unfulfilled.

A: 1'sb1 is a single bit 1. Marking it as a signed value is making it a 2's complement representation. But 1 when interpreted as a single-bit 2's complement is actually -1. So you expression
position = position - 1'sb1;

is subtracting negative 1, that is adding positive 1.
(Here is a demonstration)
Same for the second question. Your comment "this works" cannot be true, unless your expectations are opposite to the intention. Consequently the "this doesn't work" ones are probably working.


text:
Q: redirect to localized route after login in laravel 8 I am using localized routes in laravel 8 application everything works fine, how can I change the redirect HOME variable in RouteServiceProvider:20 to include the route {locale} parameter in HOME variable?
Currently it redirects to http://localhost/dashboard after successfully login, I want it to redirect to whatever the locale parameter is: for example http://localhost/ar/dashboard
web routes:

Route::prefix('{locale}')->group(function ($locale) {
    Route::get('/', function (Request $request) {
        return view('welcome');
    });

    Route::middleware(['auth:sanctum', 'verified'])->group(function () {
        Route::get('/dashboard', function (Request $request) {
            return view('dashboard');
        })->name('dashboard');
    });

    require_once __DIR__ . "/fortify.php";

    require_once __DIR__ . "/jetstream.php";
});

RouteServiceProvider:
'
'
'
public const HOME = '/dashboard';
'
'

A: You can check out this article that probably solves your problem:
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

A: I made the next to fix this issue:
Find this line of code in the different controllers of auth folder:
RouteServiceProvider::HOME

And replace with this:
route('dashboard')

You have to check if the first line is inside of intended() here is an example:
return redirect()->intended(route('dashboard'));

In my web.php I have the next line:
Route::get(LaravelLocalization::transRoute('routes.dashboard'), [DashboardController::class, 'index'])->middleware(['auth','verified'])->name('dashboard');


text:
Q: Black triangle drawn on grid background instead of grid's contents in WinRT So I have a grid with a background.  Inside the grid is a WebView and then some space on the left hand side of the screen where I have just placed a Button for now.
As the program runs, the left hand bar (that shows the grid with the background and the button laid out on it) doesn't render, instead I get the background, no controls on it and a black triangle (or geometric shape) at the bottom.
I suspect it's an issue with the VM and the video driver.  I had a similiar issue with WPF a few years ago and MS's response was that I had an incompatible video driver that was causing the form to not render correctly at all times (this is very much the same behavior).
What can I do to prevent this?  I'm including an image.
I'm going to include the small XAML I used and then a screenshot of the behavior (The XAML I rekeyed by hand):
<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="Media/Background.jpg" />
    </Grid.Background>
    <TextBlock FontSize="24" Margin="15,15,0,0">Sample Label</TextBlock>
    <WebView x:Name="wv1" Margin="250,0,0,0"></WebView>
    <Button Content="Do Something" HorizontalAlignment="Left" Height="42" Margin="57,131,0,0" VerticalAlignment="Top" Width="170" Click="Button_Click1" />
</Grid>

A: VMs don't work well with multimedia. You should expect all sorts of problems with video.


text:
Q: How do I show 'Names and Pictures' by default in Messages.app? I am running the latest Mavericks version, 10.9.2.

A: There is an option for this in the View menu.

It should carry over to every conversation.

A: This option doesn't exist in my messages app.  I only see initials for contacts, sometimes pictures.  How can I revert?

A: I ran into this question earlier today. Figured out that I had to just drag the scroll bar between the conversation pane on the right and the pane on the left that shows the contacts over to the right and then the names showed up. That menu does not appear on my MacBook Air running 10.11.2 or my iMac running 10.11.1.
Seems easier once you know you can just drag it over. That menu was hidden.
Hope this helps.


text:
Q: HTML Form Field - How to require an input format What I want to do here is require that phone numbers be entered into my HTML form as (XXX) XXX-XXXX and that SS Numbers are entered as XXX-XX-XXXX. Thats it.
The only reason I am doing this is so that the form submission results are consistent and easy exported to Excel.
I have been told to use Javascript to do this but perhaps I am not advanced enough to understand all the steps in doing that.
Can someone please point me in the right direction here keeping in mind that I am a beginner?
Wow thank you so much Ethan and @suman-bogati!  I am ALMOST there now!  The field now pops an error stating to use the correct format of 555-55-5555.  Thats great.  But no matter what I enter enter into that field the popup persists. I tried 555-55-5555 and also 555555555 and neither are accepted.  Here is the HTML for that field:

            Social Security Number:
            <input id="ssn" required pattern="^d{3}-d{2}-d{4}$"
                title="Expected pattern is ###-##-####" />

A: The easiest way to do that is by simply using multiple fields:

    Phone:
   (<input type="text" name="phone-1" maxlength="3">)
   <input type="text" name="phone-2" maxlength="3">-
   <input type="text" name="phone-3" maxlength="4">

    SSN:
    <input type="text" name="ssn-1">-
    <input type="text" name="ssn-2">-
    <input type="text" name="ssn-3">

While this approach is certainly easy, it's not great.  The user has to press tab or click on each field to enter the data, and there's nothing (other than common sense) from preventing them from entering things other than digits.
I always feel that, when it comes to validation, the less you can get in the user's way, the better.  Let them enter their phone number in whatever format they like, then you scrub it, removing everything but digits.  That way the user can enter "5555551212" or "(555) 555-1212", but the database will always hold "5555551212".
The other thing to consider is that HTML5 offers some nice specific types for phone numbers (but not SSNs).  A modern browser will take care of all the input validation and, even better, mobile devices will show the numeric keypad instead of the whole keypad.
Given that, the best way to display your form is this:

    Phone:
    <input type="tel" id="fieldPhone" placeholder="(555) 555-1212">

    SSN:
    <input type="text" id="fieldSsn" name="ssn" placeholder="555-55-5555" pattern="\d{3}-?\d{2}-?\d{4}">

If the user has a modern browser, this will handle the user side of the input validation for you.  If they don't, you'll have to use a validation library or polyfill.  There's a whole list of HTMl5 form validation polyfills here:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms
So all that remains is now to normalize your data when you save it to the database.
The ideal place to do that would be the back end; it doesn't say where your form is going, though, so maybe you don't have any say on how things are processed on the back end.  So you can do this in the front end instead.  For example, using jQuery:
$('form').on('submit', function(){
    $(this).find('input[type="tel"]').each(function(){
        $(this).val() = $(this).val().replace(/[\s().+-]/g, '');
    });
    $(this).find('input[name="ssn"]').each(function(){
        $(this).val() = $(this).val().replace(/-/g, '');
    });
});

This is not a perfect approach either: if you do validation in this function, and the validation fails, the user will see his or her input replaced by the normalized versions, which can be disconcerting.
The best approach would be to use AJAX and .serialize; not only can you have better control over the UI, but you can do all the validation you want.  But that's probably a little beyond what you need to do right now.
Note that phone validation is the trickiest.  The HTML5 phone validation is very permissive, allowing people to enter international phone numbers, which can have pretty complicated formats.  Even people in the US will sometimes enter phone numbers like "+1 (555) 555-1212", and then you have 8 digits instead of 7.  If you really want to restrict them to 7 digits, you'll have to add your own custom validation:
/^\(?\d{3}\)?[.\s-]?\d{3}[.\s-]\d{4}$/

This will cover all the common variations people use (periods, spaces, dashes, parentheses), and still allow only 7-digit US phone numbers.
Here's a jsfiddle demonstrating the HTML5 validation and normalization:
http://jsfiddle.net/Cj7UG/1/
I hope this helps!

A: Use this patterns if you want two patterns should be matched as asked in question.
//for (XXX)-XXX-XXXX
var pattern =  /^\(\d{3}\)\-\d{3}\-\d{4}$/;

//for XXX-XXX-XXXX
var pattern2 = /^\d{3}\-\d{3}\-\d{4}$/;

DEMO

A: Here is a complete solution using jquery and jquery tools validator:
regex pattern that would handle both cases is :

^(\d{3}-|(\d{3})\s)\d{2}-\d{4}$

HTML:

<link href="http://jquerytools.org/media/css/validator/form.css" type="text/css" rel="stylesheet">

<form id="myform">
    <input type="text" name="name" pattern="^(\d{3}-|\(\d{3}\)\s)\d{2}-\d{4}$" maxlength="30" />

    <input type="submit" name="submit" value="submit" />
</form>

Click here for demo on jsfiddle

A: use can use sth like this:

<input type="text" id="ok">

I tested it in ff


text:
Q: jQuery animate() to position issue I'm just working on my personal website, giving it a bit of a revamp.
I've implemented a sort of 'accordion' menu feature, where if a menu button is clicked, the "non-clicked" buttons disappear, and then the clicked button is moved to the top of the list, where then a panel animates down in which I will be putting text content.
In Firefox this works perfectly, however in IE and Chrome the button jumps to the top of the page and then animates to position, instead of animating from where it started from.
Anyone any ideas how to fix this?
Offending code:
function Accordion(e)
 {
  var o =
  {
   init: function()
   {
    o.button = e;
    o.addClickHandler();
   },

   addClickHandler: function()
   {
    o.button.click(function(){
     o.button.removeClass('unselected');
     o.button.addClass('selected');
     o.fader();
    });
   },

   fader: function()
   {
    $j('.unselected').animate({opacity:0}, 1000);

    var wait = setInterval(function() {
     if(!$j('.unselected').is(":animated") ) {
      clearInterval(wait);
      o.shifter();
     }
    }, 100);
   },

   shifter: function()
   {
    o.button.css({'position':'absolute'});
    o.button.animate({top:91}, 500, o.createInfoBox);
   },

   createInfoBox: function()
   {
    var buttonParent = o.button.parent();
    buttonParent.append("

");
    $j('.infoBox').animate({height:390});
   }
  }

  o.init();
  return o;
 }
}

The issue lies within the shifter function, where I'm setting the position to absolute and then animating so the desired effect can be achieved. I understand why it's doing this (presume it's just resetting itself to top:0 and then animating to top:91) but does anyone have a quick solution? It's late and it's doing my head in.
Much appreciated,
Dave

A: HAve you tried using the current position of the element when you switch it to absolute... for example:
function() {
  var currentp = $(this).offset();
  o.button.css({'position':'absolute', top: currentp.top});
  o.button.animate({top:91}, 500, o.createInfoBox);
}

Note there are two different offset functions and im not sure which one you want use here so you might want to review the docs on that.
Also you could always just re-theme the jQuery-ui accordian and save yourself the trouble ;-)


text:
Q: When does reinterpret_cast modify bits? From the C++ standard:

5.2.10.3
The mapping performed by reinterpret_cast might, or might not, produce
  a representation different from the original value.

I've been trained at this very site to believe and repeat this.  (Even if it's possibly just trivia).  A reinterpret_cast from float* to int* is allowed to produce a different bit pattern.  The only guarantee is that reinterpret_cast-ing that result back to float* will produce the original bit pattern.
My question:  Does this ever happen?  Is there an existing, real-world platform or CPU or compiler that actually reinterpret_casts to a different bit pattern?  If not, are there any real-world situations where reinterpret_cast has any runtime overhead?
In all my experience with reinterpret_cast, the cast was a directive to the compiler, not the runtime.

A: Pointers can in principle be different sizes. The largest pointer, if there is any difference (disregarding member pointers, talking about real pointers), is char*, since a char by definition is a byte and can be anywhere, no alignment. void* must be able to represent char*.
On a system with int* using fewer bits than char*, reinterpret-casting in that direction might be a bit risky.
I think with these pointers (heh) you can find this in the standard. It's the requirement about void* being large enough for any pointer, and the thing about alignment: the stricter/larger, the fewer bits needed for pointer to that type. But I have not ever heard of any extant system where there is such difference.

Standardese regarding void* being able to represent char*:
C++11 §3.9.2/4:

"
  A pointer to cv-qualified (3.9.3) or cv-unqualified void can be used
  to point to objects of unknown type. Such a pointer shall be able to hold any object
  pointer. An object of type cv void* shall have the same
  representation and alignment requirements as cv char*

The "any object pointer" implies vaguely that there are different sizes of pointer.

Standaredese regarding the alignment of referent:
C++11 §5.2.10/7:

"
  An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type "pointer to T1" is converted to the type "pointer to cv T2", the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment
  requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type
  "pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment
  requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer
  value. The result of any other such pointer conversion is unspecified.

It's worth noting that later on in the standard there is some support for C-style emulation of class derivation, that apparently contradicts the "any other" at the end above:
C++11 §9.2/20,

"
  A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its
  initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

In this case the two objects necessarily have the same alignment, while the previous cited paragraph talked only about alignment of types – but clearly the formal little contradiction is not a practical problem, as I see it.

A: I've worked on platforms where char* was larger than int*,
and on platforms where they had a different layout, even though
the size was the same.  Neither of the machines in question are
particularly relevant today, however (although the second, the
PDP-10, was one of the more important machines in its heyday).
It's also conceivable that some compilation modes on an Intel in
native mode (or what used to be called native mode) would
"normalize" pointers in a reinterpret_cast, or even an
implicit conversion, in order to facilitate address comparisons.
It's also conceivable (although I've not seen it) that such
conversions enforce correct alignment, e.g. a conversion from
char* to int* might force the 2 low-order bits to 0.  In
practice, however, I don't think, today, that you're likely to
see a reinterpret_cast make any changes between data pointer
types.  The issue is more historic.  (But I'm not sure about
modern embedded processors.  From what I understand, many of them
are word addressing, and so if sizeof(int) != sizeof(char), they're
likely to need a special format to address char.)


text:
Q: Using setAttribute on a selected option I am new to Javascript and I cannot figure out how to use setAttribute on a selected option.
I have a select element in my html with id = employee (adding options using javascript)
<select name="employee" id="employee"></select>

Now, using javascript (or jquery) I am trying to add a "dept" attribute to the selected option dynamically.
However, below code doesn't work. What I am doing wrong here?
var sel = document.getElementById("employee");
var selected = sel.options[sel.selectedIndex];
selected.setAttribute("data-dept", Support);

I also tried:
$("#employee option:selected").setAttribute("data-dept", "Support");

That also didn't work. Can you help me please?

A: Try this:
    <!DOCTYPE html>

        <TITLE>Test</TITLE>

                                        <select name="employee" id="employee"></select>

                                        <input type="text" id="emp-dept" disabled="true"/>

 <input type="button" id="gen-dept" value="Generate Dept."/>

A: Your code is fine, you just need to run it on change event jsfiddle
document.getElementById('employee').addEventListener('change', function() {
    this.selectedOptions[0].setAttribute('data-dept', 'Employee');
});


text:
Q: Get URL parameters in laravel In my route I have like this
Route::get('/library/{id?}', 'LibraryController@index')->name('library');

and returning my url to http://localhost/dmb/library/2017
In my blade how can I check and display if I have that 2017 in my url?

A: this code will help you
if you want to get library
then you should used
$segment = Request::segment(1);

for 2017 then used segment(2)
$segment = Request::segment(2);


text:
Q: Inserting wav file within a wav file using naudio I have a recorder application(CSHARP) where i use NAudio to record/playback audio. Our need is to Insert and overwrite audio in an existing wav file.
Currently, for inserting audio, i use the current position of the wav file and do a split. Merge the new wav file to original one and merge with the rest of the file.
When overwrite, i take the current position of the original audio and merge the new audio from that position.
This process seem to work ok but for some reason i think reading the file and writing a file takes a big toll. When we do a fast recording,stop recording, rewinding, recording, stop recording and so on.. the request to file gets clogged up and at some point i get File IO exception error saying "The file is in use by another process.."
(Note: We use a footpedal equipment with 3 keys assigned for recording, play and rewind. The issue we have is when we bang on the pedals faster.)
i am really stuck at this point as i am unable to resolve this issue. I will need some expert help.
Is there a way to insert audio from a specific position in a file without doing Split and Merge? PLSSSSSSSSS Help!!

A: Overwriting audio in a WAV file is not too difficult, and when I need to do this, I use a customised version of WaveFileWriter that can open an existing WAV file, and lets you reposition within the data chunk.
Inserting on the other hand is always going to be problematic, since you need to shift all the audio after the insert point forwards. I'd be tempted to create a separate "insert" wav file, and then after your whole recording session is finished, stitch the parts together into a final WAV file.


text:
Q: Убрать элемент до перезагрузки страницы, jquery Приветствую! Нужно убрать элемент со страницы до её закрытия: юзер заходит, нажимает кнопу "не интересует", и до того как он закроет страницу и откроет её заново, элемент не показывается даже при перезагрузке страницы. Как это сделать, и возможно ли это сделать только с помощью javascript?

A: Удалить элемент:
document.getElementById("my-element").remove();

Сделать невидимым:
document.getElementById("my-element").style.display = "none";

если нужно сохранить какую-то инфу то можно использовать не куки а
Window.localStorage


text:
Q: jQuery - Toggle div class on click No, this is not a straight forward toggle question.  I am aware of the toggle() functions and how to simply hide/show a div.  Imagine a box with a label inside:

My Section

When you click anywhere on the entire div, it should remove class hidden.  The box then looks expanded.  Now that the box is not of class hidden it should not be clickable.
Instead, when you click the div.section-legend it should add class hidden to the main div again.  Obviously the click event for the legend needs to stopPropagation(). Now the legend should not be clickable anymore and once again you must click the entire div to open it.
I can't get anything to work properly, and I know this is stupid code:
$(document).ready(function() {

    $('.section.hidden').click(function() {
        $(this).removeClass('hidden');
        $(this).find('.section-legend').click(function(e) {
            $(this).parent().addClass('hidden');
            e.stopPropagation();
        });
    });

    $('.section-legend').click(function(e) {
        $(this).parent().addClass('hidden');
        e.stopPropagation();
        $(this).parent().click(function() {
            $(this).removeClass('hidden');
        });
    });

});

A: $('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden');
});

This is assuming the section-legend is just as large as it's container in 'hidden state'.
EDIT: changed some code, solution is this:
$('.section').live('click',function(){
    $(this).removeClass('hidden');
});
$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden'); return false;
});

return false did the trick!
demo: http://jsfiddle.net/RUfN7/2/

A: First add an onclick event on the div that needs clicking:

My Section

And add this javascript to the html

A: $('.section').click(function() {
    $(this).removeClass('hidden');
});

$('.section-legend').click(function(e) {
    var $parent = $(this).parent();
    if(!$parent.hasClass('hidden')) {
        $parent.addClass('hidden');
        return false;
    }
});


text:
Q: How to validate an array of different objects using dry-schema gem Given I have such JSON object having an array of various objects like:
{
  "array": [
    {
      "type": "type_1",
      "value": 5
    },
    {
      "type": "type_2",
      "kind": "person"
    }
  ]
}

According to JSON schema validation, I can validate this schema using this JSOM schema definition:
{
  "type": "object",
  "properties": {
    "array": {
      "type": "array",
      "items": {
        "oneOf": [
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "type_1"
                ]
              },
              "value": {
                "type": "integer",
                "enum": [
                  5
                ]
              }
            }
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "type_2"
                ]
              },
              "kind": {
                "type": "string",
                "enum": [
                  "person"
                ]
              }
            }
          }
        ]
      }
    }
  }
}

How can I validate the input JSON using the dry-schema gem? Do you have any ideas?


text:
Q: WPF - set changed event handler for single entry in listbox In my wpf application, I want to write changed event handler for my listbox entry. This entry consist of comboboxes and TimePickers. My listbox linked with some web account so all entries of listbox saved there. When I try to save my edited entry, all the entries are saved. To avoid this problem,I want to write changed event handler so that it will give me only updated entry. how to write changed event handler for only edited entry instead of all entries.
xaml for listbox:
<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" SelectionMode="Single" SelectionChanged="listBox1_SelectionChanged">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="MouseDoubleClick" Handler="listBox1_MouseDoubleClick">
                    </EventSetter>
                </Style>
            </ListBox.ItemContainerStyle>
</ListBox>

ListBox contains below in single entry-
<StackPanel Orientation="Horizontal" Width="596">
                <TextBox Text="{Binding ClientNameBinding,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="145"/>
                <TextBox Text="{Binding ApplicationNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="90"/>
                <xctk:TimePicker Name="StartPicker" Value="{Binding StartValue, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
                <xctk:TimePicker Name="EndPicker" Value="{Binding EndValue, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>
                <TextBox Text="{Binding TaskNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="71"/>
                <ComboBox x:Name="ProjectComboBox" ItemsSource="{Binding Path=projectList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name"  SelectedItem="{Binding ProjectNameBindingClass, Mode=OneWayToSource}" Width="130" Background="Yellow" BorderThickness="0"/>
</StackPanel>

A: It's a general practice to keep a flag, that shows is there any changes in data or not.
MVVM-style sample could be like this:
1) The base view model, which implements INotifyPropertyChanged:
public abstract class ViewModel : INotifyPropertyChanged
{
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

2) The view model of your list entry. Note, that here's HasChanges property. When any other view bound property has changed, HasChanges becomes true:
public class MyListEntryViewModel : ViewModel
{
    public string ClientName
    {
        get { return clientName; }
        set
        {
            if (clientName != value)
            {
                clientName = value;
                OnPropertyChanged("ClientName");
            }
        }
    }
    private string clientName;

    // the rest of bindable properties (ApplicationName, StartPicker, etc.)

    public bool HasChanges
    {
        get { return hasChanges; }
        set
        {
            if (hasChanges != value)
            {
                hasChanges = value;
                OnPropertyChanged("HasChanges");
            }
        }
    }
    private bool hasChanges;

    protected override void OnPropertyChanged(string propertyName)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName != "HasChanges")
        {
            HasChanges = true;
        }
    }
}

3) The view model of your editor (the thing, that keeps your list entries and a commands for adding, deleting, saving, etc.):
public class MyEditorViewModel : ViewModel
{
    private void SaveChanges()
    {
        var changedItems = Items
            .Where(item => item.HasChanges);

        // send changed items to server
    }

    private bool CanSaveChanges()
    {
        return Items.Any(item => item.HasChanges);
    }

    public MyEditorViewModel()
    {
        SaveChangesCommand = new RelayCommand(SaveChanges, CanSaveChanges);
    }

    public ObservableCollection<MyListEntryViewModel> Items
    {
        get
        {
            return items ?? (items = new ObservableCollection<MyListEntryViewModel>());
        }
    }
    private ObservableCollection<MyListEntryViewModel> items;

    public RelayCommand SaveChangesCommand { get; private set; }
}


text:
Q: exceptions.TypeError: can only concatenate tuple (not "int") to tuple I called this:
for count in result:
    print "Exist: %s" % count
    self.IdCode = count

self.IdCode += 1

and received this error:
exceptions.TypeError: can only concatenate tuple (not "int") to tuple

What's going on here?

A: self.IdCode is a tuple of values (e.g. (1, 2)), and you cannot add a integer to a tuple (an explanation of why is easily found if you Google your error message).
From your code, it seems that self.IdCode += 1 is to be incrementing an integer. However, each count in result (or at least the last count) is a tuple, not an integer. self.IdCode is being assigned to such a tuple, then you try to add an integer, which you cannot do.

A: It's probably due to version difference! I can concatenate two tuples by creating a 3rd tuple in IPython notebook and v3.4. However, I get the same error in v2.7.
Not sure why does this happen.
from IPython:
t1 = (1,2)
t1
(1, 2)
t2 = (2,3)
t3 = t1 + t2
t3
(1, 2, 2, 3)

*Learning Python! :)


text:
Q: DataLabels hide themselves even after allowOverlap is set to true. How to fix it? HIGHCHARTS

Please Have a look at JSFIDDLE. In this Example, the "Opera" dataLabel is hidden even if allowOverlap is set to true. How to fix this? Please share your ideas.
EDIT:
Here is the updated JSFIDDLE.

A: With such density, not all labels will display. The solution for that problem is setting padding of data labels to 0, increasing distance property or simply changing height of chart to higher value.
API Reference:
http://api.highcharts.com/highcharts/chart.height
http://api.highcharts.com/highcharts/plotOptions.pie.dataLabels.padding
http://api.highcharts.com/highcharts/plotOptions.pie.dataLabels.distance
Examples:
http://jsfiddle.net/u86cosyg/ - increasing height and setting padding to 0
http://jsfiddle.net/7xLm1xma/ - increasing distance


text:
Q: Visual Studio 2015 Build Rebuild Clean not Working I am working on windows services C#, I have commented out a few lines so that i can test specific code, cleaned and rebuild the project successfully, however when i step into the code the commented lines with execute. I have tried to exit visual studio and come back again but the same thing happens.
I deleted the bin directory manually but the same thing happens.

A: First Build project in Debug mode then,
You need to replace your new .dll file with previous one in your installation folder or
Once again install your .dll file using Visual Studio Command prompt.
Then Restart your service.
http://www.c-sharpcorner.com/UploadFile/8a67c0/create-and-install-windows-service-step-by-step-in-C-Sharp/


text:
Q: timestamp delete hours and seconds i have a timestamp 1390107800 is Sun, 19 Jan 2014 05:03:20 GMT How could get this date? Sun, 19 Jan 2014 00:00:00 GMT
I want any given timestamp add the first hour of the day it would be 00:00
thanks.

A: You should be able to hard-code the zeros without issues but escape the GMT with back-slashes to make them literally show:
echo date('D, d M Y 00:00:00 \G\M\T', 1390107800);

// another option
echo date('D, d M Y', 1390107800).' 00:00:00 GMT';

For future reference: date

A: Just hardcode the hours minutes and second..?
date("d/m/Y 00:00:00", $timestamp);


text:
Q: Returning an echo using session control I am working with sessions in PHP. The user enters in his name and password and this is then posted to a php page which starts a session if the credentials exist in the database table which then allows the user to view certain pages if valid, or return to login if invalid.
Everything with the database and session works, except when the user is not logged in it is supposed to echo "You are not logged in". and return to the login page. It returns to the login page just fine, but I am not seeing the message anywhere. Can anyone tell me if the order of the code is incorrect, or another method to display the error without having a page just to display the error?
    <?php
session_start();

echo '
Employees Only
';

if (isset($_SESSION['valid_user']))
{
    if ($_SESSION['valid_user'])
    {
        echo "
You are currently logged in as " . $_SESSION['valid_user'] . "
";

        $form  = "<form action=\"logout.php\" method=\"post\">";
        $form .= "<input type=\"submit\" name=\"logout\" value=\"Log Out\">";
        $form .= "</form>";
        echo $form;
    }
    else
    {
        echo "
You are not logged in.
";
        header("Location:login1.html");
        exit();
    }
}
else
{
    echo "
You are not logged in.
";
    header("Location:login1.html");
    exit();
}
    ?>

The echo "You are not logged in". will not display, but it is returning to login1.html

A: Use this, it will wait for 5 seconds and after that it will redirected to login1.html.
header( 'refresh: 5; url=login1.html' );
echo '
You will be re-directed in 5 seconds...
';

A: I reckon it's because you're using header('location:login1.html'). It redirects the client immediately.
Try using header( 'Refresh:2; url=login1.html' );. It will wait for x seconds (2 in this case), and then redirect. You can read more about it here.

A: You can't redirect the user and at the same time expect he has time to see the message you are sending. You need to take a step back and divide the process, save it into a variable and show it to the user on the next page for instance.
There are various ways of accomplishing that, the most popular though, used by most web frameworks is making a "flash message" that will only exist in the session until the next page reload, thus displaying only once to the user.
This article shows you how to do it. There are a bunch more on google if you wish to use something existing.


text:
Q: Django Model - choices versus foreign key? I understand that in Django, the ORM doesn't support the ENUM type in MySQL or PostgreSQL, as this was originally a MySQL extension, and not portable across other DB types. So the two options are to use a "choices" argument to your model, or using a foreign key reference.
What are the pros and cons of these approaches?
For something like gender, I assume you would use "choices", e.g.:
GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
...
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

However, for something like state names, what are the reason for and against using a separate table, and foreign keys to that table?
state = models.ForeignKey(AustralianState)

Under what circumstances would you use one versus the other?
Cheers,
Victor

A: You should also consider foreign keys when the number of potential choices is large. That's one of the reasons to consider using FK for countries or states. Otherwise, you're effectively hard-coding a lot of data in your source code.

A: I would recommend using lookup tables by default, otherwise you are maintaining data in your code. It also makes the lookup values accessible to users that access the database directly, not via your application (e.g. BI/reporting functions).
A notable exception - where I would use choices instead of a lookup table - is a lookup entity that has values that control code-level logic. You often find this with "status" or "type" entities (e.g. BillingType), where the logic depends on the value of the "type" field. In these cases, the code usually refers to explicit identifiers (codes) of those types, and the addition of a new type would require logic changes (in code) in any case.

A: I would use choices where the choices wouldn't change over time. If they would, a FK with a new model would be better.


text:
Q: the else inside if nest doesn't work in php i dont know what's wrong with this code, the statement in else doesn't echo out. i've read it numerous time and still cannot figure it out.. :(
    if(isset($_POST['ad_lg'])){
        $lg= $_POST['ad_lg'];

        if(!empty($lg)){
            $insert_lg = "INSERT INTO 'urlg' VALUE('$lg')";
            $insert_lg_run= mysql_query($insert_lg);
            header("location: index.php");
        }else{
            echo 'sth';
        }
    }

help me please. thanks in advance^^

A: Move your second ifstatement from the first if:
$lg = '';
if(isset($_POST['ad_lg'])){
    $lg= $_POST['ad_lg'];
}

if(!empty($lg)){
        $insert_lg = "INSERT INTO 'urlg' VALUE('$lg')";
        $insert_lg_run= mysql_query($insert_lg);
        header("location: index.php");
    }else{
        echo 'sth';
}

A: You need to put an else on the isset(...) aswell
if(isset($_POST['ad_lg'])){
    $lg= $_POST['ad_lg'];

    if(!empty($lg)){
        $insert_lg = "INSERT INTO 'urlg' VALUE('$lg')";
        $insert_lg_run= mysql_query($insert_lg);
        header("location: index.php");
    }else{
        echo 'sth';
    }
}else{
    echo 'sth';
}

otherwise you will echo nothing if $_POST['ad_lg'] is not set.

A: For this code to reach echo 'sth', you would need your ad_lg POST variable to be both set and empty.
I believe ad_lg="" would work.

A: Try this code :
if(!empty($_POST['ad_lg'])){
  $lg= $_POST['ad_lg'];
  $insert_lg = "INSERT INTO 'urlg' VALUE('$lg')";
  $insert_lg_run= mysql_query($insert_lg);
  header("location: index.php");
} else{
  echo 'sth';
}

Empty checks if the variable is set and if it is it checks it for
  null, "", 0, etc

With empty, the following things are considered empty:

*

*"" (an empty string)

*0 (0 as an integer)

*0.0 (0 as a float)

*"0" (0 as a string)

*NULL

*FALSE

A: isset actually checks whether the variable exist and has a value.
so your $lg has a value inside if(isset), so else won't print.


text:
Q: Custom filter attributes inject dependency I'musing ASP.NET Web API and I need to have authorization so I've created custom authorization attribute
public class CustomAuthorizationAttribute : AuthorizeAttribute

In order to inject dependency inside constructor I have following :
        public CustomAuthorizationAttribute(IAccountBL accountBl)
    {
        _accountBL = accountBl;
    }

In IAccountBL I have method which interacts with database checking if user is authorized to make request.
Inside Member API controller I've register that attribute
    [CustomAuthorization]
public class MemberController : ApiController

But I get following error

Project.Account.AccountBL' does not contain a constructor that takes 0 arguments

And if I register it like
[CustomAuthorization(IAccountBL)]

Thank you

A: You can get dependency in your filter by using extension method GetDependencyScope for class HttpRequestMessage. It's not a canonical way for dependency injection, but can be used as workaround. A basic example may look like this:
    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var dependencyScope = context.Request.GetDependencyScope();
        var dependency = dependencyScope.GetService(typeof (MyDependencyType));
        //use your dependency here
    }

This method may be used with constructor injection to simplify unit testing:
public class MyAuthenticationFilter : Attribute, IAuthenticationFilter
{
    private Func<HttpRequestMessage, MyDependencyType> _dependencyFactory;

    public MyAuthenticationFilter() :
        this(request => (MyDependencyType)request.GetDependencyScope().GetService(typeof(MyDependencyType)))
    {
    }

    public MyAuthenticationFilter(Func<HttpRequestMessage, MyDependencyType> dependencyFactory)
    {
        _dependencyFactory = dependencyFactory;
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var dependencyScope = context.Request.GetDependencyScope();
        var dependency = dependencyFactory.Invoke(context.Request);
        //use your dependency here
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public bool AllowMultiple { get; private set; }
}

A: If anyone finds similar issue here's how I manage to solve it.
My custom filter inherits IAutofacAuthorizationFilter. Besides this one you can also inherit IAutofacExceptionFilter and IAutofacActionFilter.
And inside my DI container I've register this filter for each controller I want to use like this
        builder.Register(c => new CustomAuthorizationAttribute(c.Resolve<IAccountBL>()))
               .AsWebApiAuthorizationFilterFor<MemberController>()
               .InstancePerApiRequest();

A: Action filters are just attributes. You do not have control over when those attributes are instantiated by the CLR. One possibility is to write a marker attribute:
public class CustomAuthorizationAttribute : Attribute { }

and then the actual action filter:
public class CustomAuthorizationFilter : ActionFilterAttribute
{
    private readonly IAccountBL accountBL;
    public CustomAuthorizationFilter(IAccountBL accountBL)
    {
        this.accountBL = accountBL;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<CustomAuthorizationAttribute>().Any() ||
            actionContext.ActionDescriptor.GetCustomAttributes<CustomAuthorizationAttribute>().Any())
        {
            // here you know that the controller or action is decorated
            // with the marker attribute so that you could put your code
        }
    }
}

and finally register it as a global action filter:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        IAccountBL accountBL = ...
        config.Filters.Add(new CustomAuthorizationFilter(accountBL));
    }
}

and finally you could use the marker attribute:
[CustomAuthorization]
public class MemberController : ApiController
{
    ...
}

A: If you registered your service on the application using any container, it's very easy to get the instance of your service from anywhere in the scope. Just follow the below code to get your service.
var myService = DependencyResolver.Current.GetService(typeof(IMyService)) as IMyService;
Please make sure you have included System.Web.Mvc in the file.
Happy coding!!!


text:
Q: batch syntax error(s) I am trying to write a batch that will copy the names of the profile folders to a txt file, then take each line (profile) and query ad with it. the two problems I seem to be having are:

*

*it says there is a syntax error in the way I wrote my for loop

*if I break it down for debugging, the loop seems to just set the variable over and over, then use the final value only to perform the commands in the subscripts

@echo off

@setlocal enabledelayedexpansion
pushd "c:\documents and settings"

mkdir c:\pulls
copy \\mint\testfolder\forfiles.exe c:\pulls\
copy \\mint\testfolder\psexec.exe c:\pulls\
rem call \\mint\testfolder\copy.bat c:\pulls\
set queryid=
set checkid=

rem finds all profiles that have been logged into in the last 18 months

c:\pulls\forfiles.exe /p "c:\documents and settings\" /d -540 /c "cmd /c if @ISdir==true deltree @isdir"

dir/b > "c:\documents and settings\profiles.txt"

%queryid% > "c:\documents and settings\tmp.txt"

rem active directory query

:adquery

for /f  "tokens=*" %%n IN ("c:\documents and settings\profiles.txt") do (
    set queryid=%%n
    call :sub
)

goto :end

:sub

c:\pulls\psexec.exe \\computer-u domain\user -p password dsquery user -name %queryid%     > "c:\documents and settings\tmp.txt"
set /p checkid= < "c:\documents and settings\tmp.txt"
del "c:\documents and settings\tmp.txt"

::checks to see if variable is an empty string

if [!%checkid%==!] goto :process1

if [%checkid%==] %queryid% >> c:\documents and settings\final.txt

goto :eof

:process1

c:\pulls\psexec.exe \\computer -u domain\user -p password dsquery user -name %queryid%     -desc *termed* > "c:\documents and settings\tmp.txt"
set /p checkid= < "c:\documents and settings\tmp.txt"
del "c:\documents and settings\tmp.txt"

::checks to see if variable is an empty string

if [!%checkid%==!] goto :amending
if [%checkid%==] goto :process2

goto :eof

:process2

c:\pulls\psexec.exe \\computer -u domain\user -p password dsquery user -name %queryid%     -disabled > "c:\documents and settings\tmp.txt"
set /p checkid= < "c:\documents and settings\tmp.txt"
del "c:\documents and settings\tmp.txt"

::checks to see if variable is an empty string

if [!%checkid%==!] goto :amending

goto :eof

:amending

%checkid% >> "c:\documents and settings\final.txt"

 goto :eof

:end

 notepad.exe "c:\documents and settings\final.txt"

del c:\pulls /y

del "c:\documents and settings\profiles.txt"

del "c:\documents and settings\final.txt"

rem copies selected profiles

rem c:\pulls\copy.bat

A: I haven't traced your entire logic to see if you have any other problems. But I have identified the problem with your FOR /F loop.
You are trying to read a file, but your IN() clause is double quoted, so it is interpreted as a string instead of a file name. (Type FOR /? for help on FOR command). You want to use double quotes because your path includes spaces, but you need it to be interpreted as a file name - that is what the USEBACKQ option is for!
for /f  "usebackq tokens=*" %%n IN ("c:\documents and settings\profiles.txt") do ...


text:
Q: Adjusting the CSS menu Here is my menu test page with all the css:

body {
    margin: 0;
}

.z-depth-0 {
    box-shadow: none !important
}

nav {
    width: 100%;
    height: 56px;
    color: #fff;
    line-height: 56px;
    background-color: rgb(238, 110, 115);
}

.dark-blue {
    background-color: darkblue;
}

nav .nav-wrapper {
    height: 100%;
    position: relative;
    top: 0;
}

.right {
    float: right !important
}

#nav-mobile li {
    display: inline-block;
    margin: 0 1.5em 1.5em 1.5em;
}

#nav-mobile li a {
    text-decoration: none;
    color: white;

}

#nav-mobile li .dropdown-content {
    display: none;
}

#nav-mobile li:hover .dropdown-content {
    display: block;
}

#nav-mobile .dropdown-button .dropdown-content li a {
    display: none;
}

#nav-mobile .dropdown-button:hover .dropdown-content li a {
    display: block;
}

Links

Home

Access

Zone

User

My Profile

Log Off

I want the first ul menu to be right aligned on the page and I want the dropdown menu to be displayed with items one under the other when user hovers over Links or User. Instead, the dropdown content gets displayed in line. Can anyone help me fix the menu?
Also I want Links and User to be displayed a little higher

A: Ok to get the options to display top down you want to add
#quicklinkdrop li{
                 display:list-item;
             }
 #userdrop li{
                 display:list-item;
             }

This should fix them being inline and put items on top of each other

A: You need to position your items as relative and absolute. Parent items get a position: relative; and children get a position: absolute;
Best of luck!
<!DOCTYPE html>

    <title>Test Menu</title>

Links

Home

Access

Zone

User

My Profile

Log Off


text:
Q: Windows Firewall - Laravel Artisan Serve - Allow Port in Inbound Rule (not working) I'm using Laravel..And i develop a website... And I want try to access the site from other devices....
.
.
I run php artisan serve --port=4042 --host=0.0.0.0 in my computer (windows 10)..
And I allow port 4042 by create new Inbound Rules in Windows Firewall (as in picture below):

But when I access from my mobile phone, it shows error as in picture below:

But I can access the web if I turn off the whole Firewall....

But I dont want disable the whole Firewall, I just want to allow port 4042 only)....
Thanks..

A: What a silly mistake.... I just found the problem after hours googling and searching the solution.
The problem is the Firewall block php.exe program.... I don't know at what time I add that rule... So, i just delete that rule...And the problem solved.


text:
Q: Switch IFrame with Codeception using ID How can I switch to an IFrame with Codeception using ID? Actually I can use the name of the IFrame but not the ID -> Codeception SwitchToIFrame
IFrame Example:

Codeception Example:
<?php
# switch to iframe
$I->switchToIFrame("another_frame");
# switch to parent page
$I->switchToIFrame();

Is it maybe a Codeception <-> Facebook Webdriver Connection Problem?
EDIT: I reinstalled Codeception, followed the Quick Step Guide. Result - the Problem is still the same: Codeception and the Facebook Webdriver doesn't want to work together. My Codeception Code
acceptance.suite.yml:
actor: AcceptanceTester
modules:
  enabled:
    - \Helper\Acceptance
    - WebDriver:
            url: https://xxxxxxxxxxxxxx.com
            browser: chrome
            window_size: maximize
            clear_cookies: true

codeception.yml:
paths:
tests: tests
output: tests/_output
data: tests/_data
support: tests/_support
envs: tests/_envs
actor_suffix: Tester
extensions:
enabled:
    - Codeception\Extension\RunFailed
settings:
colors: true

*

*OS: Windows 10

*PHP: 7.1.7

*PHPUnit: 6.4.4

*Selenium Server: 3.8.1

*Codeception: 2.3.7

*Chrome: 63.0.3239.108

A: I had this issue, testing a page with a Google reCaptcha in it ... the reCaptcha is in its own iframe, and since that iframe is generated by 3rd-party code, we have no control over its name attribute (at least when it's first generated).
What I ended up doing was running a javascript snippet which can find the iframe based on other things, and then giving it an id, so that Codeception Webdriver could switch to it:
    public function _clickOnCaptcha(AcceptanceTester $I)
{
    // give the recaptcha iframe a name so codeception webdriver can switch to it
    $recaptcha_frame_name = 'recaptcha-frame';
    $I->executeJS("$('.g-recaptcha iframe').attr('name', '$recaptcha_frame_name')");
    $I->switchToIFrame($recaptcha_frame_name);
    $I->see('not a robot');
    $I->seeElement('.rc-anchor');
    $I->click(['id' => 'recaptcha-anchor']);
    $I->switchToIFrame(); // switch back to main window
}

I did have control over the containing elements, so in this case, it's contained within an element with class g-recaptcha ... so we use jquery to find the iframe inside that element: $('.g-recaptcha iframe'), and then give it a name attribute: .attr('name', '$recaptcha_frame_name').
Then we can use Codeception to switch to it and click the captcha checkbox:

    $I->switchToIFrame($recaptcha_frame_name);
    $I->click(['id' => 'recaptcha-anchor']);

Then, when we're done, switch back out to the main frame so we can submit our form:

    $I->switchToIFrame(); // switch back to main window

NB, I'm using the reCaptcha test keys, as specified here, in the testing environment so that it will never actually ask to solve a captcha.
https://developers.google.com/recaptcha/docs/faq

With the following test keys, you will always get No CAPTCHA and all  verification requests will pass.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
    Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
    The reCAPTCHA widget will show a warning message to claim that it's only for testing purposes. Please do not use these keys for your production traffic.

A: First of all, in your case the problem might be that you're not calling the acceptance tester. You should start your script with this:
<?php
$I = /*am a */ new AcceptanceTester($scenario);

Now to get into an IFrame in Codeception using the WebDriver:
You just have to name the IFrame in a string, using EITHER the ID or the name. Here is an example:
There is a page with the IFrame:

This IFrame contains the string, "No one knows who discovered water" but the parent frame does not. I tested this Cept with PhantomJS and Selenium.
<?php

$I = /*am a */ new AcceptanceTester($scenario);

$I->wantTo('See how Iframes work');
$I->amOnUrl("https://wordpress-bdd.com/codeception-iframe/");
$I->dontSee("No one knows who discovered water");

//Switch by name
$I->switchToIFrame("IFrameByName");
$I->see("No one knows who discovered water");

//switch back to parent
$I->switchToIFrame();
$I->dontSee("No one knows who discovered water");

//Switch by ID
$I->switchToIFrame("IFrameByID");
$I->see("No one knows who discovered water");
$I->dontSee('Lorum Ipsum');

//switch back to parent
$I->switchToIFrame();
$I->dontSee("No one knows who discovered water");


text:
Q: Ember.js Computed Properties (Overwriting get and set) I am working on an Ember.js application and I'm using ember-cli 2.7.
I'm trying to overwrite the properties for get and set, but when I do, I get an unexpected token error.
Here is the code of my controller file:
  import Ember from 'ember';

  export default Ember.Controller.extend({

  isDisabled: true,

  emailAddress: '',

  actualEmailAddress: Ember.computed('emailAddress', function(){
    get(key){
      return `getting email...${this.get('emailAddress')}`;
    }
  }),

  emailAddressChanged: Ember.observer('emailAddress', function(){
    console.log('observer is called: ', this.get('emailAddress'));
  })
});

This seems like a simple solution, but I do not find the bug and it's killing me. Please help me and thank you.

A: It's a syntax error. function shouldn't be at there. Computed property definition should be like this:
actualEmailAddress: Ember.computed('emailAddress', {
    get(key){
      return `getting email...${this.get('emailAddress')}`;
   },
   set(key, value){
       //...
   }
}),

If you only have a get operation at a computed property, then you can write it as following:
actualEmailAddress: Ember.computed('emailAddress', function(){
    return `getting email...${this.get('emailAddress')}`;
}),


text:
Q: Computing $\int_1^\infty\frac{\ln(x)}{x^2}\,dx.$ I'm computing $$\int_1^\infty\frac{\ln(x)}{x^2}\,dx.$$
I have the proper antiderivative.
My first strategy in finding the limit involved splitting the limit into two, resulting in:
lim t>inf (-ln(x)/x) - lim t>inf (1/x), evaluated from 1 to t
I then used L'Hospital's rule to eliminate inf/inf in the first limit, and then evaluated each from 1 to t.
Using this method, I got 2.
Then I did the same thing, but kept the fraction intact: -(ln(x) + 1)/x.  Using L'HR here and then evaluating from 1 to t, I got 1 (which is the answer all the calculators give me).
What am I missing with the first method?  Did I not use L'HR properly (only on one of the limits). Obviously, the second method gets rid of the 1/x when using L'HR, but I can't find something that tells me I can't do that.  Even my professor is stumped right now.
Thanks

A: Substitute $\ln(x)=t$ to get $\displaystyle \int_{1}^{\infty}\frac{\ln(x)}{x^{2}}dx=\int_{0}^{\infty}te^{-t}dt=\Gamma(2)=1$

A: Notice that
$$\int_1^\infty \frac{\log x}{x^2}dx = \lim_{t\to\infty}\int_1^t \frac{\log x}{x^2}dx = \lim_{t\to\infty}\left.-\frac{\log x}{x}\right\rvert^t_1+\int_1^\infty\frac{dx}{x^2}= \lim_{t\to\infty}\left.-\frac{\log x}{x}\right\rvert^t_1\left.-\frac1x\right\rvert^t_1.$$
Now, both limits exist independently and
\begin{aligned}
\lim_{t\to\infty}\frac{\log t}{t} = \lim_{t\to\infty}\frac 1t = 0.
\end{aligned}
Therefore, since $\log 1 = 0$,
$$\int_1^\infty \frac{\log x}{x^2}dx = 1.$$

A: For $a\gt1$,
$$
\begin{align}
\int_1^\infty\frac{\log(x)}{x^a}\,\mathrm{d}x
&=-\frac{\mathrm{d}}{\mathrm{d}a}\int_1^\infty x^{-a}\,\mathrm{d}x\tag1\\
&=-\frac{\mathrm{d}}{\mathrm{d}a}\frac1{a-1}\tag2\\
&=\frac1{(a-1)^2}\tag3
\end{align}
$$
Explanation:
$(1)$: $-\frac{\mathrm{d}}{\mathrm{d}a}x^{-a}=\frac{\log(x)}{x^a}$
$(2)$: integrate
$(3)$: differentiate

A question was raised about the interchange of the integral and the derivative in step $(1)$. We can justify that with Fubini-Tonelli and the Fundamental Theorem of Calculus:
$$
\begin{align}
-\frac{\mathrm{d}}{\mathrm{d}a}\int_1^\infty\frac{\mathrm{d}x}{x^a}
&=-\frac{\mathrm{d}}{\mathrm{d}a}\int_1^\infty\int_a^\infty\frac{\log(x)}{x^t}\,\mathrm{d}t\,\mathrm{d}x\\
&=-\frac{\mathrm{d}}{\mathrm{d}a}\int_a^\infty\int_1^\infty\frac{\log(x)}{x^t}\,\mathrm{d}x\,\mathrm{d}t\\
&=\int_1^\infty\frac{\log(x)}{x^a}\,\mathrm{d}x
\end{align}
$$


text:
Q: How can I use variables passed between jobs in a condition? I am building a YAML pipeline in Azure DevOps. I'm generating couple of variables in first job, which I'm passing to other job and want to use them to conditionally run some steps.
Here's how the code looks like:
     stages:
      - stage: ConditionalVars
        jobs:
        - job: outputVars
          steps:
            - pwsh: |
                Write-Host "##vso[task.setvariable variable=varExample;isOutput=true]testVar"
              name: setVars
        - job: useVars
          dependsOn: outputVars
          variables:
            varFromJob: $[ dependencies.outputVars.outputs['setVars.varExample']]
          steps:
          - ${{ if eq($(varFromJob), 'testVar')}}:
            - pwsh: |
                Write-Output "Conditionally run"

I am able to print $(varFromJob) variable in step in job useVars. But I'm not able to use it in this if (condition) example.
I was trying different approaches like variables.varFromJob and other taken from https://learn.microsoft.com/en-us/azure/devops/pipelines/process/conditions?view=azure-devops&tabs=yaml.
Have you guys been struggling with similar issue? How could I define it to make it work?
Thanks a lot!
Rafal

A: Try to use a condition for the step:
steps:
   - pwsh: |
       Write-Output "Conditionally run"
     condition: eq(variables['varFromJob'], 'testVar')

${{ if eq... }} is a compile-time expression that is evaluated when the YAML file is compiled.


text:
Q: is there any way to define httpheaders in single class,interface or annotation in java? is there any way to define httpheaders in single class in java? It is something like creating a wrapper class for userdefined httpHeaders used in my application. instead of defining all headers in my controller method.
@PostMapping
public <ResponseEntity<Book>> getBooks(
   @ModelAttribute("requestContext") RequestContext context, @PathVariable("bookId") String bookId,
   @RequestHeader(value="x-institute-id") String instituteId,
   @RequestHeader(value="x-customer-last-logged-time") String xCustomerLastLoggedTime,
   @RequestHeader(value="x-customer-ip-address") String xCustomerIpAddress,
   @RequestHeader(value="x-interaction-id", required=false) String xInteractionId){

     ---implementation

   }

So that It can be interface or annotations. Like:
public class MyApplicationHeaders{
   @RequestHeader(value="x-institute-id") String instituteId,
   @RequestHeader(value="x-customer-last-logged-time") String xCustomerLastLoggedTime,
   @RequestHeader(value="x-customer-ip-address") String xCustomerIpAddress,
   @RequestHeader(value="x-interaction-id", required=false) String xInteractionId)
}

So that we can use it as :
@PostMapping
public <ResponseEntity<Book>> getBooks(
   @ModelAttribute("requestContext") RequestContext context, @PathVariable("bookId") String bookId, @MyApplicationHeaders appHeaders{

     ---implementation

   }

A: According to the docs of @RequestHeader

If the method parameter is Map<String, String>, MultiValueMap<String, String>, or HttpHeaders then the map is populated with all header names and values.

This means you can use either a Map or HttpHeaders as a parameter type to hold multiple header values. In your case, Map is applicable since you are working on non-standard headers:
@PostMapping
public ResponseEntity<Book> getBooks(
    @ModelAttribute("requestContext") RequestContext requestContext,
    @PathVariable("bookId") String bookId,
    @HttpHeaders Map<String, String> appHeaders) {

    String instituteId = appHeaders.get("x-institute-id");
    // do something else
}


text:
Q: Is there any ways to update multi collections at the same time in Mongodb based on some system arch, i may need to update multiple collection under some name rule, e.g. [m_aaaa_info], [m_aaab_info] .etc
thus i may need to update all the collections named by [m_*_info], with the same select & update conditions like update({"isDeleted": false}, {$set:{"isDeleted": false}})
so, is there any tool/commend can do this operations?
e.g. db.getCollection('m_*_info').update({"isDeleted": false}, {$set:{"isDeleted": false}}, upset=false, multi-update=true)

A: var c = db.getCollectionNames();
c.forEach(function(name) {
            if (/m_[a-z]*_info/i.test(name)) {
                db[name].update({
                        "isDeleted": false
                    }, {
                        $set: {
                            "isDeleted": true
                        }
                    }
                }
            })


text:
Q: Handle devise 401 gracefully during sign in I have a very simple sign_in page for a devise user. Upon submitting incorrect data, the log shows a '401 Unauthorized' and redirects me back to the sign_in page. I couldn't figure out a way to show error messages to the user.
I looked at devise::sessions_controller#create which is as follows,

 # POST /resource/sign_in
  def create
    resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_in_path_for(resource)
  end

  def auth_options
    { :scope => resource_name, :recall => "#{controller_path}#new" }
  end

The flow gets interrupted at warden.authenticate in case of a failed authentication and the user get redirected to the 'new' which is the sign_in page.
I just need to show the user a invalid_credentials tooltip/flash_message. So I did it by modifying :recall => "#{controller_path}#handle_create_fail" (look at auth_options) which calls  handle_create_fails  when authentication fails, inside which I setup the error messages.
I am not sure if I overlooked something that devise already provides.
How can I handle this better?

A: 'devise' stores error messages in rails 'flash', using flash[:notice] for success messages and flash[:alert] for problems.
Here's this from the devise documentation:

Remember that Devise uses flash messages to let users know if sign in
  was successful or failed. Devise expects your application to call
  "flash[:notice]" and "flash[:alert]" as appropriate.

This means that in your view file (or more generally in your application layout file) you should include something similar to these lines:
<%= content_tag(:div, flash[:error], :id => "flash_error") if flash[:error] %>
<%= content_tag(:div, flash[:notice], :id => "flash_notice") if flash[:notice] %>
<%= content_tag(:div, flash[:alert], :id => "flash_alert") if flash[:alert] %>

Here are some similar questions/answers:
Rails - Devise - Error messages when signing in?
Devise errors are displayed twice
devise - Customizing the User Edit Pages

A: I am not sure if I am understanding you correctly, but by simply placing 'alert' in your view (sign_in.html.erb), Devise will flash the error message.
<div class="alert">
  <%= alert %>
</div>

A: I wanted to be able to do something similar, along the lines of form-specific error messaging like you might have on most Rails forms (as opposed to a layout-wide, global flash).
You can check out what I came up with in this Github gist: https://gist.github.com/3792471
Basically (notes below assume a devise scope of :user):

*

*Add/use a custom FailureApp, used by devise+warden, which simply adds a "scoped" flash "indicator".  That is, if devise+warden is exiting quickly due to a failed login and has, therefore, set the flash.now[:alert], add flash.now[:user] = [:alert]

*Extend FormBuilder (actually, SimpleForm::FormBuilder in my gist, but should work with others) to add a #flash method, which checks for the scoped indicator(s). If found, the matches are extracted/deleted from the FlashHash and rendered. If not found (that is, flash[:alert] may or may not exist, but flash[:user] either does not exist or does not include :alert), do nothing so the flash remains available for the default use case.

*Add rendering to relevant views/layouts.

Note that the layout in my example gist does not have conditional logic around the layout-rendered flash messages. I did that just do I could test to see what does and does not show up under various circumstances.


text:
Q: Getting data directly from a website to a hdfs How do I get data directly which is entering on a website concurrently on hdfs?

A: If you plan to have High availability read and writes, then you can use Hbase to store the data.
If you are using REST API, you can store the data directly to Hbase as it has dedicated Hbase REST API that can store into Hbase Tables.
1) Linear and modular scalability.
2) Strictly consistent reads and writes.
3) Automatic and configurable sharding of tables.
For more about HBase :- https://hbase.apache.org/
Else if you want some streaming data into HDFS from any source, you can look into confluent platform ( which has inbuilt kafka ) and can store into HDFS.

A: This entirely depends on what data you have and how willing you are to maintain extra tools on top of Hadoop.
if you're just accepting  events from a logfile, Flume, Fluentd, or Filebeat are your best options.
If you are accepting client side events, such as clicks or mouse movements, for example, then you need some backend server accepting those requests. For example, Flume TCP Source, but you probably want some type of authentication endpoint in front of this service to prevent random external messages to your event channel.
You can also use Kafka. The Kafka REST Proxy (by Confluent) can be used to accept REST requests and produce to a Kafka topic. Kafka HDFS Connect (also by Confluent) can consume from Kafka and publish messages to HDFS in near real time, much like Flume
Other options include Apache Nifi or Streamsets. Again, using a TCP or HTTP event source listener with an HDFS destination processor


text:
Q: Live program output monitoring tool I would like to know if there is a tool that would enable you to watch how the program output changes live. Something like tail -f but instead of monitoring the file changes, it would repeatedly call some executable and display it live.
For example, if the tool is caled foobar and I would call foobar 'ps -Al', it would behave kind of like top - displaying the output in real time.

A: Try watch. From the manpage:

Name
watch - execute a program periodically, showing output fullscreen
Synopsis
watch [-dhvt] [-n <seconds>] [--differences[=cumulative]] [--help] [--interval=<seconds>] [--no-title] [--version] <command>

Description
watch runs command repeatedly, displaying its output (the first screenfull). This allows you to watch the program output change over time. By default, the program is run every 2 seconds; use -n or --interval to specify a different interval.
The -d or --differences flag will highlight the differences between successive updates. The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. [...]
watch will run until interrupted.

Note that "realtime" would have to be approximated by "once a second" (for example) here...


text:
Q: How to find the angles of hyperbolic triangles? State the simplest way of explaining how to find the angles of hyperbolic triangles.

(Think that you are explaining it to a 15-years-old kid)

Thank you in advance!


text:
Q: Make Button Visibility Hidden on click from another button Im trying to set Visibility property on my button to Hidden by click from another button. That code works pretty well:
<Button x:Name="Button">
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=HideBar, Path=IsPressed}"
                             Value="True">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Like you can see above, IsPressed in Path property on binding works pretty ok, but the button is hidden only when i have mouse button pressed down. How to make button visibility set to Hidden permanently after click on "Hidebar" button that is mentioned in Binding ElementName=HideBar ? Im tyring to work with MVVM but in my opinien DataTriggers are simpler for coding view.

A: Well, turns out you don't need to change the checkbox style to be based on a button, as there is a toggle button in WPF:
<ToggleButton x:Name="HideBar"  Content="Click"/>
<Button x:Name="Button" Content="Testing">
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=HideBar, Path=IsChecked}"
                     Value="True">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


text:
Q: Check if the given String points to a Python installation in Java Is there any way I can check in Java if the String I'm receiving points to a valid Python installation directory?
The idea is to force the user to only give a valid path to his Python installation folder, and if the path  is not valid, return an error to let them know.

A: This solution has a couple of problems. On *nix machines, there is not really such a thing as a installation directory.
So, instead of a directory, you might want the use to select an executable.
This will also allow you to run a python --version to check if the version is ok.


text:
Q: If a div inside of a div is empty change the background color of the parent CSS I am trying to check if status_comment_holder is empty and if it is then I want to change the background of comment-container without having to refresh the page, at the moment, I am appending comments to status_comment_holder and removing the comment when they remove their comment, I am not too sure if I can do this with css or jquery so I have marked tags for both.

I have tried:
if($('#image_comment').is(':empty')){
    alert("fhfhf");
    $('.well').css('background-color', '#ffffff');
}

With no avail, it's not even alerting for some reason.

A: Just select by pseudo-selector in jquery than use closest.

$(".status_comment_holder:empty")
  .closest(".well")
  .css("background-color", "red");
.well {
  height: 1.2em;
  background-color: green;
  margin: 1em;
}

Should be Green

A: Here's one solution using plain vanilla javascript:

function checkText() {

var imageComment = document.getElementById('image_comment');
var commentContainer = document.getElementById('comment-container');

if (imageComment.textContent.length === 0) {
    commentContainer.style.backgroundColor = 'rgb(255,0,0)';
}

else {
    commentContainer.style.backgroundColor = 'rgb(191,191,191)';
}

}

var imageComment = document.getElementById('image_comment');
imageComment.addEventListener('input',checkText,false);
#comment-container {
width:400px;
height:100px;
padding:25px;
background-color: rgb(191,191,191);
}

#image_comment {
height:48px;
line-height:48px;
padding:12px;
font-size:48px;
background-color: rgb(255,255,255);
}

Delete this text...

A: Please use this:
if ( $('#image_comment').text().length == 0 ) {
    alert("fhfhf");
    $('.well').css('background-color', '#ffffff');
}

A: $(document).ready(function() {
    if($('#image_comment').is(':empty')){
       alert("fhfhf");
       $('.well').css('background-color', '#ffffff');
    }
});

You can see jsfiddle

A: Check this out:
How do I check if an HTML element is empty using jQuery?
Your idea seems to be fine enough, maybe the div actually has a whitespace inside? you could try something like
if($.trim($("selector").html())=='')

or, as Adriano Repetti said in the comments:
if($("selector").children().length == 0)

which is more CPU-efficient
Hope it helps!

A: Search for functions/DOM like change(function()) , keyup(function()) , text()
Hope you will get an answer for what your are looking.


text:
Q: Making XAML Grid width full screen I m creating Windows Phone 8.1 app with Visual Studio Where I m putting XAML grid but could not make full width. If I give width to each column then grid will be not full width in all resolution of Phone
My codes are as below
<ListView Name="lvData" Margin="5,0" HorizontalAlignment="Stretch" Grid.Row="2" BorderBrush="Black"
                                    BorderThickness="1" Foreground="#000" VerticalAlignment="Center">
                    <ListView.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                </Grid.ColumnDefinitions>
                                <GridViewHeaderItem Grid.Column="0" x:Uid="_Number" Style="{StaticResource GridViewHeader}" />
                                <GridViewHeaderItem Grid.Column="1" x:Uid="_Dep" Style="{StaticResource GridViewHeader}" />
                                <GridViewHeaderItem Grid.Column="2" x:Uid="Arr" Style="{StaticResource GridViewHeader}" />
                                <GridViewHeaderItem Grid.Column="3" x:Uid="CurrentStatus" Style="{StaticResource GridViewHeader}" />
                            </Grid>
                        </DataTemplate>
                    </ListView.HeaderTemplate>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                    <ColumnDefinition Width="90"/>
                                </Grid.ColumnDefinitions>
                                <GridViewItem Grid.Column="0" Style="{StaticResource GridViewItem}" Content="{Binding Number}"/>
                                <GridViewItem Grid.Column="1" Style="{StaticResource GridViewItem}" Content="{Binding DepTime}" />
                                <GridViewItem Grid.Column="2" Style="{StaticResource GridViewItem}" Content="{Binding ArrTime}"/>
                                <GridViewItem Grid.Column="3" Style="{StaticResource GridViewItem}" Foreground="{Binding Color}" Content="{Binding CurrentStatus}"/>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

My Style
<Style TargetType="GridViewHeaderItem" x:Key="GridViewHeader">
            <Setter Property="Background" Value="#48649F"/>
            <Setter Property="Foreground" Value="#fff"/>
            <Setter Property="Height" Value="40"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
        </Style>
        <Style TargetType="GridViewItem" x:Key="GridViewItem">
            <Setter Property="Foreground" Value="#000"/>
            <Setter Property="BorderBrush" Value="#000"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Height" Value="40"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>

A: Try stretch HorizontalContentAlignment of ListViewItem:
<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
  </ListView.ItemContainerStyle>
      ...
</ListView>


text:
Q: use a switch to change background color in XCode I'm essentially brand new to developing iOS in XCode, so this is probably a really simply question. I want to know how I can change the background color of my View Controller using a simple switch- in other words, how do I make it so that when a switch is tapped, the background is no longer white? I know how to do this in the interface builder, but it's not interactive.

A: You need to create a method to do it, such as:
- (void)changeColor:(UISwitch *)mySwitch {
    if (mySwitch.isOn)
        [self.view setBackgroundColor:color];
    else
        [self.view setBackgroundColor:[UIColor whiteColor]];
}

Then, you hook the method up to the switch like:
[mySwitch addTarget:self selector:@selector(changeColor:) forControlEvent:UIControlEventValueChanged

A: The simplest way to do this would configure your switch or button to an IBAction method.
You write a method and right click and drag to this method to connect the switch.
- (IBAction)changeBackgroundColor: (id) sender {
    if(sender.on) {
        self.view.backgroundColor = [UIColor blueColor];
    } else {
        self.view.backgroundColor = [UIColor redColor];
    }

}