text:
Q: Submission error messages should not disappear when entered on field level I am using redux form in my project. I have few input fields, a drop down and a submit button. When I click on a submit button, submission errors are displayed.
For example, I have an input field which can accept integers only. When I click on the submit button, an error message is displayed: "please enter integers only." But when I edit the input field and place the correct value, the error message is removed from submission errors without clicking on the submit button.
I don't want to remove error messages without clicking on the submit button.
Is there any property in redux form?

A: Onchange of input field and onclick of submit button are two different events. You can check the validity only on submit event.


text:
Q: how can I use polymer core-animated-pages events? I want to use core-animated-page's core-animated-pages-transition-prepare event.
How can I use polymer events?

A: you could use a event listener. give core-animated-pages a id (i am calling it 'animatedPages')
  animatedPages.addEventListener('core-animated-pages-transition-prepare', function (e) {});

or you could use the declarative method
 <core-animated-pages selected="{{selected}}" transitions="slide-from-right" on-core-animated-pages-transition-prepare="{{pagesPrepare}}">

then in js
 pagesPrepare: function (event) {}

hope it helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expectation regarding Brownian Motion This is a formula regarding getting expectation under the topic of Brownian Motion.
\begin{align}
E[W(s)W(t)] &= E[W(s)(W(t) - W(s)) + W(s)^2] \\
&= E[W (s)]E[W (t) - W (s)] + E[W(s)^2]
\\
&= 0+s\\
&=\min(s,t)
\end{align}
How does $E[W (s)]E[W (t) - W (s)]$ turn into 0?
Thanks alot!! Please let me know if you need more information.

A: $W(s)\sim N(0,s)$ and $W(t)-W(s)\sim N(0,t-s)$.  So both expectations are $0$.
(The step that says $\mathbb E[W(s)(W(t)-W(s))]= \mathbb E[W(s)] \mathbb E[W(t)-W(s)]$ depends on an assumption that $t>s$.)

A: Brownian motion has independent increments. This means the two random variables $W(t_1)$ and $W(t_2-t_1)$ are independent for every $t_1 < t_2$.
Independence for two random variables $X$ and $Y$ results into $E[X Y]=E[X] E[Y]$. This is zero if either $X$ or $Y$ has mean zero. Now, remember that for a Brownian motion $W(t)$ has a normal distribution with mean zero.


text:
Q: how to pass location.state values from react storybook? I have two pages. Register and Registered. On successful registration i am calling Registered page with an extra data email and token.
history.push('/register/success', { email: values.email, token: result.accessToken });

On Registered page i am getting above values by using useLocation hook.
const location = useLocation();
const email = location.state.email;
const token = location.state.token;

My problem is that i have created a storybook for my Registered page and i am getting blank white screen and i know why this is happening because i am not passing the email and token values. If the page accepted the props or the page have its own variables it will be easy but in this case the page is getting values from a state. I just want to know how will i use email and token values in my storybook?


text:
Q: Transform Curved Line into Straight Line I have a distribution of scores that is currently somewhat curved, reflecting bunching of values at certain ranges. I would like to flatten this curve out so that what is left is a straight, declining line between 0 and 100. I have no idea where to start to make this transformation.
I have attached an image of the data with a simple polynomial regression run against the LOG of the number in each range. I have also attached the raw data.

*

*1,3222266983662

*2,1033363424063

*3,572507179617

*4,397837772260

*5,272702109150

*6,214860801517

*7,159527368431

*8,124812092026

*9,106198945022

*10,94011464982

*11,85086955747

*12,67329749341

*13,60286421903

*14,53239501199

*15,47421127631

*16,45493388624

*17,36511487697

*18,35621046952

*19,31365292955

*20,28056229522

*21,29220769583

*22,28349820803

*23,24257887309

*24,21204595564

*25,24578641841

*26,21733803769

*27,18983788324

*28,23703186842

*29,20212830681

*30,15884718441

*31,14433647636

*32,16369809127

*33,14489654952

*34,16393976949

*35,13687318215

*36,13564259597

*37,12669104529

*38,12842214983

*39,14316929455

*40,9916745113

*41,13982804512

*42,10209890144

*43,10325057441

*44,12323446658

*45,11991480181

*46,13137405614

*47,11041316099

*48,13102375158

*49,9455056963

*50,10365710458

*51,10903436421

*52,8385862967

*53,10343275556

*54,12082021807

*55,8339347239

*56,12849613841

*57,8071241272

*58,11282598249

*59,4443425203

*60,4994315750

*61,6428917730

*62,3838092793

*63,5511016583

*64,4697686488

*65,11547998521

*66,6045899730

*67,978162537

*68,8007329393

*69,7376618323

*70,459680294

*71,10005522273

*72,2288139372

*73,629750530

*74,277579404

*75,169682480

*76,116877417

*77,111195051

*78,72702965

*79,72139333

*80,57057491

*81,50848577

*82,45481652

*83,40487540

*84,36464123

*85,31929677

*86,27622920

*87,21951750

*88,19000403

*89,15726659

*90,13170733

*91,11529975

*92,10763335

*93,9549124

*94,8900646

*95,7472734

*96,5010478

*97,2359271

*98,929536

*99,173419

*100,5

Curved to Straight Conversion


text:
Q: Black and White Photoshop effect on UIImage Hello I'd like to create the following Black and White Photoshop effect on a UIImage
https://drive.google.com/file/d/0B5dHxpdDwpPec3dPTWdLVnNhZFk/view?usp=sharing
In which you can change the brightness of each of the six colors (reds yellows green cyans blues magentas)
I used this to make the image black and white but it doesn't allow me to change the specific colors
self.imageView.image = chosenImage;

CIImage *beginImage = [CIImage imageWithCGImage:chosenImage.CGImage];

CIImage *blackAndWhite = [CIFilter filterWithName:@"CIColorControls" keysAndValues:kCIInputImageKey, beginImage, @"inputBrightness", [NSNumber numberWithFloat:0.0], @"inputContrast", [NSNumber numberWithFloat:1.1], @"inputSaturation", [NSNumber numberWithFloat:0.0], nil].outputImage;
CIImage *output = [CIFilter filterWithName:@"CIExposureAdjust" keysAndValues:kCIInputImageKey, blackAndWhite, @"inputEV", [NSNumber numberWithFloat:0.7], nil].outputImage;

CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef cgiimage = [context createCGImage:output fromRect:output.extent];
UIImage *newImage = [UIImage imageWithCGImage:cgiimage];

self.imageView.image = newImage;

Thank You for your time

A: I think you can accomplish that effect with the following function:
- (UIImage *)grayScaleImageWith:(UIImage *)image blackPoint:(CGFloat)blackPoint whitePoint:(CGFloat)whitePoint andGamma:(CGFloat)gamma  {

    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);

    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateCalibratedGray(whitePoint, blackPoint, gamma);

    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);

    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, imageRect, [image CGImage]);

    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    // Create a new UIImage object
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];

    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);

    // Return the new grayscale image
    return newImage;
}

Then call it filling the black and white values with the values selected on the UI:
CGFloat black[3] = { 0, 0, 0 }; // replace content with values from interface
CGFloat white[3] = { 100, 100, 100 }; // replace content with values from interface

[self grayScaleImageWith:image blackPoint:black whitePoint:white andGamma:1.8f];

I have not tested this code yet but I hope at least it points you in the right direction.


text:
Q: Adding Tab dynamically I have a tab and want another tab with click of button.
Another tab has VBox (Contains charts,grid etc).
It gives an error while adding code addChild(), removeChild() on button click.
The error is of null object reference.
Please suggest me.
Thanks

A: You're probably trying to access children of a tab that has not been initialized yet.  The simplest solution is to change the creationPolicy property of your TabNavigator to "all".
You can see an explanation of creationPolicy in the Adobe documentation.
If this is not the solution, you're probably going to have to post more specific code.


text:
Q: Postgres parallel/efficient load huge amount of data psycopg I want to load many rows from a CSV file.
The files contain data like these "article_name,article_time,start_time,end_time"
There is a contraint on the table: for the same article name, i don't insert a new row if the new article_time falls in an existing range [start_time,end_time] for the same article.
ie: don't insert row y if exists [start_time_x,end_time_x] for which time_article_y inside range  [start_time_x,end_time_x]  , with article_name_y = article_name_x

*

*I tried with psycopg by selecting the existing article names ad checking manually if there is an overlap --> too long

*I tried again with psycopg, this time by setting a condition 'exclude using...' and tryig to insert with specifying "on conflict do nothing" (so that it does not fail) but still too long

*I tried the same thing but this time trying to insert many values at each call of execute (psycopg): it got a little better (1M rows processed in almost 10minutes), but still not as fast as it needs to be for the amount of data I have (500M+)

*I tried to parallelize by calling the same script many time, on different files but the timing didn't get any better, I guess because of the locks on the table each time we want to write something

Is there any way to create a lock only on rows containing the same article_name? (and not a lock on the whole table?)
Could you please help with any idea to make this parallellizable and/or more time efficient?
Lots of thanks folks

A: Your idea with the exclusion constraint and INSERT ... ON CONFLICT is good.
You could improve the speed as follows:

*

*Do it all in a single transaction.

*Like Vao Tsun suggested, maybe COPY the data into a staging table first and do it all with a single SQL statement.

*Remove all indexes except the exclusion constraint from the table where you modify data and re-create them when you are done.

*Speed up insertion by disabling autovacuum and raising max_wal_size (or checkpoint_segments on older PostgreSQL versions) while you load the data.


text:
Q: onclick is not working. whenever I submit it automatically executes all onclick handlers Here is the code:
html+js
<input type="submit" onclick="chk();" />
function chk(){
var buttonnode= document.createElement('input');
buttonnode.onClick = ddiv(buttonnode);
}

buttonnode.onclick automatically calls ddiv function but I want it to wait for a click to proceed to that function. How to do that?

A: Try like below... it will work..
buttonnode.onclick = function (){ddiv(this);};

A: Try like below... it will give the result that you need...

<button onclick="myFunction()">Try it</button>
<input type="text" value="Click the Below Button" id="txtinfo"/>


text:
Q: How to ensure a set of Spring boot beans implementing an interface being first initalized before their container being initalized? I have a set of beans both implementing an interface
@Componet
class BeanA implements interfaceA{
   public void process(){
   }
}

@Componet
class BeanB implements interfaceA{
   public void process(){
   }
}

I want to get all beans of interfaceA and apply their process methods sequentially, so I have a container to collect these beans.
@Componet
class Container{

List<interfaceA> container;

@Autowired
private ApplicationContext applicationContext;

@PostConstruct
public void init()
{
    container=applicationCOntext.getBeansOfType(interfaceA.class).values().stream().collect(Collections.list());
    for(obj:container){
        obj.process();
    }
}

So how can I ensure Container be initialized after all beans of interfaceA, so I can get all beans of interfaceA in init() method of Container?
Or put it another way, can applicationContext.getBeansOfType always get all beans of interfaceA? what if Container get initialzed first?
By the way, Container does not have to be a componet.

A: You can inject a list with all the components implementing interfaceA:
@Componet
class Container{

    @Autowired
    List<interfaceA> container;

    @PostConstruct
    public void init()
    {
        for(obj : container){
            obj.process();
        }
    }
}

In such a case you don't need to worry about components creation order, Spring is smart enough to make it right.
Components scanning/initialization is a two-step process. First, Spring collects all beans definitions and builds a dependency graph (without creating any beans). After that, it knows in what order the beans should be initialized. When you inject interfaceA beans as a list, Spring knows, that the Container instance depends on them and will initialize them first. It wouldn't be the case if you obtained the components manually from the ApplicationContext (the dependency would be hidden) and you would need @DependsOn annotations on the interfaceA components.

A: *

*You can use @DependsOn(value = {"beanA", "beanB"}) on you Container class.

*And Make your Container class implement InitializingBean interface and override the afterPropertiesSet() method.

*And then move the logic that you've written in init method to afterPropertiesSet() method.


text:
Q: how to open files using a for loop in python So the purpose of this function is to test all the files in my files folder. I want to iterate through the for loop and test each and every single file but my problem is my return statement only returns the last file for testing. I need it to go through all the files and return an answer for each file, not just one. I am very confused and I am a beginner programmer so any help would be greatly appreciated thank you!
here is my defined function:
def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']

    for file in files:
        try:
            print(f'Testing {file}\n')
            f = open(file)
            mazeFiles = f.readlines()

        except:
            print('This File Does Not Exist.')

    f.close()
    return mazeFiles

My test function looks like this:
def test():
    mazeFiles = testFileOpener()
    m = Maze(mazeFiles)
    m.gridAssembly()
    m.solver(0,0,None)
    m.tester()

output is supposed to look like:
Testing maze.txt
-This line of code should be the returning the lines of each of maze.txt-
Testing maze50100.txt
-This line of code should be the returning the lines of each of maze50100.txt-
... Each file is passed into the tester which tests the mazeFiles so in each instance mazeFiles must be a different '.txt' file
etc... until we get to the last file but for some reason it gets to the last file and mazeFiles only returns that specific files lines.
Any help would be greatly appreciated
I tried:
def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
    random = []
    for file in files:

        print(f'Testing {file}\n')
        with open(file) as f:
            d = f.readlines()
            random.append(d)
    for i in random:
        mazeFiles = i
    return mazeFiles

A: It appears you only want the testFileOpener to load one file. If that is the case, the simplest solution is relocate your list to the test function
def testFileOpener(fname):
   try:
        print(f'Testing {fname}\n')
        with open(fname) as f:
            return f.readlines()
   except:
        print(f"File {fname} does not exist")

def test():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
    for f in files:
        mazeFiles = testFileOpener(f)
        m = Maze(mazeFiles)
        m.gridAssembly()
        m.solver(0,0,None)
        m.tester()

Otherwise, you need to append each readlines result to a list, then actually return that list. But, that would result in unnecessary memory usage, so best to only test one file at a time

A: When you have a function that logically returns a number of results you can form it into a generator where each result you send out with a yield instead of a return. so your code could look like this:
def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
    for file in files:
        print(f'Testing {file}\n')
        with open(file) as f:
            d = f.readlines()
            yield d # note that you can actually just `yield f` if you deal with each one sequentially
                    # since the file only gets closed after the next iteration
                    # this is one of the benefits of using a generator.

Then the caller of this function would probably want to iterate over the results:
def test():
    for mazeFiles in testFileOpener():
        m = Maze(mazeFiles)
        m.gridAssembly()
        m.solver(0,0,None)
        m.tester()


text:
Q: Error making a GUI... UnboundLocalError: variable 'clicks' reffered to before assignment When I run this code I get this error:  UnboundLocalError: variable 'clicks' reffered to before assignment. don't know what to do from here. If it helps, I am running python 2.7.5
from Tkinter import *
from ttk import *
clicks = 0
def press():
        clicks += 1

def displayclicks():
        print clicks

root = Tk()
root.title("Test GUI")
root.geometry("200x100")
app = Frame(root)
app.grid()
Label(app, text="press the button!").grid()
clicks = 0
x = Button(app, text="BUTTON", command=press)
x.grid()
y = Button(app, text="Print clicks", command=displayclicks)
y.grid()

root.mainloop()

A: In order to change a global variable, you need to explicitly refer to it. Since your method press() is adding to the global variable clicks, you need to use the global keyword to refer to it:
clicks = 0

def press():
    global clicks # make sure I am referring to the global
                  # variable, since I am going to modify it.
    clicks += 1

In your method displayclicks() you don't have to do this because you are simply printing the value, not modifying it.


text:
Q: Add multiple metadata in video using ffmpeg command Command to add single metadata working fine
ffmpeg -i '/var/www/html/public/uploads/wp-video/akka.mov' -metadata kKeyContentIdentifier='com.apple.quicktime.content.identifier' '/var/www/html/public/uploads/video-thumb/updated-akka.mov'

Add multiple metadata command, I pass the multiple metadata tag like below
ffmpeg -i '/var/www/html/public/uploads/wp-video/akka.mov' -metadata kKeyContentIdentifier='com.apple.quicktime.content.identifier' -metadata kKeyStillImageTime = 'com.apple.quicktime.still-image-time' -metadata kKeySpaceQuickTimeMetadata = 'mdta' '/var/www/html/public/uploads/video-thumb/updated-akka.mov'

Its not working, is there any other way to pass multiple metadata in command?

A: Try this
ffmpeg -i "/var/www/html/public/uploads/wp-video/akka.mov" -c copy -metadata kKeyContentIdentifier="com.apple.quicktime.content.identifier" -metadata kKeyStillImageTime="com.apple.quicktime.still-image-time" -metadata kKeySpaceQuickTimeMetadata="mdta" "/var/www/html/public/uploads/video-thumb/updated-akka.mov"

I replaced ' with ", added a -c copy flag and finally removed the whitespaces from the 2nd and 3rd -metadata declaration. I'm not quite sure if replacing ' with " is necessary but I often had troubles in the past using ' because it was read as if it was escaped instead of being a delimiter. I'm pretty sure you are not supposed to have whitespaces outside of either ' or ", that's why I removed them. Omitting -c copy will also make ffmpeg re-encode the file with standard preset likely giving you a bad result


text:
Q: Cannot see linked server properties in SQL Server 2008 R2 I configured a linked server in SQL Server 2008 R2; mirroring what currently exists in SQL Server 2000.
When viewing the properties of an existing linked you, you cannot see (or edit) any information in 2008R2 - where you can in 2000
Note: This is different from the unresolved bug where you cannot edit any details of a linked server in SQL Server 2008 R2 without it throwing an error.
So, how do i fix SSMS?

*

*SQL Server: Microsoft SQL Server 2008 R2 (SP1) - 10.50.2550.0 (X64)

*SQL Server Management Studio: 10.50.2550.0

A: What I have done for this issue is script out the linked server where I can then see the properties defined within the script that is produced. This is a less then ideal solution but at the very least a work around so to what appears to be a problem in SSMS.


text:
Q: Как сделать удаление без перезагрузки, с помощью AJAX?     <!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Learn js</title>
  <link rel="stylesheet" href="style.css">

  <button id="delete">Удалить юзера</button>

java script
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://localhost:3000/users', false);
xmlhttp.send(null);
var response = xmlhttp.responseText;
response = JSON.parse(response);

var usersDiv = document.getElementById('users');

for(let i = 0; i < response.length; i++) {
  usersDiv.innerHTML += 'id '+ response[i].id + '
' + response[i].name + '
' + response[i].email + '
' + '
';
}

var deleteBtn = document.getElementById('delete');
deleteBtn.addEventListener('click', function(){
  var deleteUser = +prompt('id юзера для удаления', '');
  $.ajax(`http://localhost:3000/users/${deleteUser}`, {
    method: 'Delete'
  });
});

Когда делаю удаление, нужно перезагрузить страницу чтобы в dom удалился юзер, как это сделать без перезагрузки ?

A: Не буду говорить, как лучше и т.п. как в комментариях, отвечу на твой вопрос - в js скрипте нужно добавить следующее
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://localhost:3000/users', false);
xmlhttp.send(null);
var response = xmlhttp.responseText;
response = JSON.parse(response);

var usersDiv = document.getElementById('users');

for(let i = 0; i < response.length; i++) {
  usersDiv.innerHTML += 'id '+ response[i].id + '
' + response[i].name + '
' + response[i].email + '
' + '
';
}

var deleteBtn = document.getElementById('delete');
deleteBtn.addEventListener('click', function(){
  var deleteUser = +prompt('id юзера для удаления', '');
  $.ajax(`http://localhost:3000/users/${deleteUser}`, {
    method: 'Delete'
  }).done(function() {
      // вот тут кусок кода, который нужен

      for(let i = 0; i < response.length; i++) {
           if(response[i].id == deleteUser) {
                response.splice(i, 1);
           }
       }
      usersDiv.innerHTML = '';
      for(let i = 0; i < response.length; i++) {
           usersDiv.innerHTML += 'id '+ response[i].id + '
' + response[i].name + '
' + response[i].email + '
' + '
';
      }
  });
});

То есть этим кодом я тебе показал, что нужно из уже существующего объекта response удалить нужный элемент с нужным id и все + полностью заново заполнить userDiv. Всю обработку нужно писать в .done() там ты можешь проверить, удалился ли этот элемент и потом уже обрабатывать и т.п.


text:
Q: How to make tikz macro work with two arguments in this MWE? I want to generate a table from a csv file using the very helpful tool datatool and insert a round photo of each person surrounded by a circle, the color of which should be taken from the provided csv file as well, see the MWE below:
MWE
\documentclass[fontsize=11pt,paper=a4,DIV=6,landscape]{scrartcl}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{datatool}

\newcolumntype{s}{>{\hsize=.05\hsize\centering\arraybackslash}X} %for id
\newcolumntype{n}{>{\hsize=.1\hsize\raggedright\arraybackslash}X} %for name
\newcolumntype{y}{>{\hsize=.2\hsize\centering\arraybackslash}X} %for everthing else
\newcolumntype{e}{>{\hsize=.3\hsize\raggedright\arraybackslash}X} %for email

\DTLloaddb[noheader]{data}{namelist.csv}

\newcommand{\circleme}[1]{\begin{tikzpicture}
  \begin{scope}
        \clip [rounded corners=.4cm] (0,0) rectangle coordinate (centerpoint) (.8,.8cm);
        \node [inner sep=0pt] at (centerpoint) {\includegraphics[width=.8cm, height=.8cm]{#1}};
      \end{scope}
      \draw[\mycolor,very thick] (.4cm,.4cm) circle (.4cm);
    \end{tikzpicture}}

  \begin{filecontents*}{namelist.csv}
    1,Name One,PhD,supervisor,Immunology,nameone@yahoo.com,logo,red
    2,Name Two,MSc,worker,Microbiology,nametwo@yahoo.com,logo,blue
    3,Name Three,BSc,worker,Chemistry,namethree@yahoo.com,logo,green
  \end{filecontents*}

  \newcommand{\tabcontents}{\begin{tabularx}{\textwidth}{@{}snyyyey@{}}
                            \toprule
                            & \multicolumn{1}{c}{\textbf{Name}}
                            & \multicolumn{1}{c}{\textbf{Qual}}
                            & \multicolumn{1}{c}{\textbf{Specs}}
                            & \multicolumn{1}{c}{\textbf{Descr}}
                            & \multicolumn{1}{c}{\textbf{E-mail}}
                            &}

  \begin{document}
  \thispagestyle{empty}
  \DTLforeach*{data}{\idcode=Column1,\name=Column2,\qual=Column3,%
    \descr=Column4,\spec=Column5,\email=Column6,\figpath=Column7,\mycolor=Column8}%
  {%
    \eappto\tabcontents{\noexpand\\\noexpand\midrule
      \idcode \noexpand&
      \name \noexpand&
      \qual \noexpand&
      \spec \noexpand&
      \descr \noexpand&
      \email \noexpand&
      \noexpand\raisebox{-.5\baselineskip}{\noexpand\circleme{\figpath}}}
  }%
  \appto\tabcontents{\\\bottomrule\end{tabularx}}

\tabcontents%
\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% TeX-engine: xetex
%%% End:

Output

The desired output is to have the first circle in red, the second in blue, and the third in green as dictated by the csv file. How to make tikz macro take this argument per the example above?

A: Just add another argument to \circleme and pass \mycolor to it:

\documentclass[fontsize=11pt,paper=a4,DIV=6,landscape]{scrartcl}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{filecontents}

\newcolumntype{s}{>{\hsize=.05\hsize\centering\arraybackslash}X} %for id
\newcolumntype{n}{>{\hsize=.1\hsize\raggedright\arraybackslash}X} %for name
\newcolumntype{y}{>{\hsize=.2\hsize\centering\arraybackslash}X} %for everthing else
\newcolumntype{e}{>{\hsize=.3\hsize\raggedright\arraybackslash}X} %for email
\usepackage{datatool}

\DTLloaddb[noheader]{data}{namelist.csv}

\newcommand{\circleme}[2]{\begin{tikzpicture}
  \begin{scope}
        \clip [rounded corners=.4cm] (0,0) rectangle coordinate (centerpoint) (.8,.8cm);
        \node [inner sep=0pt] at (centerpoint) {\includegraphics[width=.8cm, height=.8cm]{#1}};
      \end{scope}
      \draw[#2,very thick] (.4cm,.4cm) circle (.4cm);
    \end{tikzpicture}}

  \begin{filecontents*}{namelist.csv}
    1,Name One,PhD,supervisor,Immunology,nameone@yahoo.com,example-image-a,red
    2,Name Two,MSc,worker,Microbiology,nametwo@yahoo.com,example-image-b,blue
    3,Name Three,BSc,worker,Chemistry,namethree@yahoo.com,example-image-c,green
  \end{filecontents*}

  \newcommand{\tabcontents}{\begin{tabularx}{\textwidth}{@{}snyyyey@{}}
                            \toprule
                            & \multicolumn{1}{c}{\textbf{Name}}
                            & \multicolumn{1}{c}{\textbf{Qual}}
                            & \multicolumn{1}{c}{\textbf{Specs}}
                            & \multicolumn{1}{c}{\textbf{Descr}}
                            & \multicolumn{1}{c}{\textbf{E-mail}}
                            &}

  \begin{document}
  \thispagestyle{empty}
  \DTLforeach*{data}{\idcode=Column1,\name=Column2,\qual=Column3,%
    \descr=Column4,\spec=Column5,\email=Column6,\figpath=Column7,\mycolor=Column8}%
  {%
    \eappto\tabcontents{\noexpand\\\noexpand\midrule
      \idcode \noexpand&
      \name \noexpand&
      \qual \noexpand&
      \spec \noexpand&
      \descr \noexpand&
      \email \noexpand&
      \noexpand\raisebox{-.5\baselineskip}{\noexpand\circleme{\figpath}{\mycolor}}}
  }%
  \appto\tabcontents{\\\bottomrule\end{tabularx}}

\tabcontents%
\end{document}


text:
Q: Why does Mathematica 10.3.1 fail me on : Integrate[(x^3) [Log[2 Sin[x]]]^8, {x, 0, Pi}] All it gives me is a pretty restatement of my original request. When I use WolframAlpha PRO, I get a result of 624510 and a visual representation of the area in question. I know the ends of the interval [0,pi] are problematic. What am I doing wrong? The 'definite integral' in WolframAlpha PRO was given  x^3*ln(2*sin(x))^8  in the 'function to integrate' box. Ideally, what would be best, is if both programs would give me a closed form expression, if it exists. NIntegrate was not helpful either. You should know I am very new to Mathematica.

A: There doesn't look to be an analytic form of the integral (as mentioned in the comment by march), though numeric integration does match the expected result.
NIntegrate[x^3*Log[2*Sin[x]]^8, {x, 0, π}]
(*624510.*)

You can plot the corresponding area with
Plot[x^3*Log[2*Sin[x]]^8, {x, 0, π}, Filling -> Axis]


text:
Q: Getting a non-NULL-able warning when using SELECT * INTO When I execute the following proc, I get this warning:

Attempting to set a non-NULL-able column's value to NULL.

USE [DbTwo]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

alter proc [dbo].[TEST_warning_proc]
as

IF OBJECT_ID('MySchema..vitals', 'U') IS NOT NULL DROP TABLE MySchema..vitals
IF OBJECT_ID('MySchema..order_list', 'U') IS NOT NULL DROP TABLE MySchema..order_list

select * into MySchema..vitals
from DbOne..vitals
where FacilityID in
 (select FacilityID from DbTwo..MySchemaFacilities)

select * into MySchema..order_list
from DbOne..order_list
where FacilityID in
 (select FacilityID from DbTwo..MySchemaFacilities)

How can this be possible since I'm doing a SELECT * INTO? Shouldn't that create a new table that exactly mirrors the original table?
I tried setting:
SET ANSI_WARNINGS OFF

but that didn't help.

A: I'm suspecting your table isn't getting dropped--maybe there is a block going on for this helper function. You can verify this theory by placing a select top 1 * from vitals right after you attempt to drop it. This is avoidable by using sys.objects.
Using sys.objects
create table dbo.vitals (c1 int not null)

insert into vitals
values
(1)

if exists(SELECT 1 FROM sys.objects WHERE name = N'vitals')
begin
    drop table vitals
end

select null as c1 into vitals

select * from vitals

ONLINE DEMO

A: I found the issue...
When I was "sanitizing" my proc for posting here, I used the names
from DbOne..vitals

and
from DbOne..order_list

These two objects are actually views not tables. I tried running the original SELECT from the definition of the view and got:

Null value is eliminated by an aggregate or other SET operation.

Oops... My apologies.


text:
Q: Intuition behind m-out-of-n bootstrap I am trying to get some intuition on why m-out-of-n bootstrap works but haven't been able to find good explanation. I would really appreciate any input on this.
I think I do understand what bootstrap is about --  estimating how $\sqrt{n}(T_n(X_1,...,X_n)-T(X;F))$ behaves using $\sqrt{n}(T_n(X_1^*,...,X_n^*)-T(X;\hat{F_n}))$. ($X_1,...,X_n$ drawn from $F$, the true CDF. And $X_1^*,...,X_n^*$ drawn from $\hat{F_n}$, the ECDF). From my understanding, when $T$ is a smooth function, bootstrap works fine. Sometimes when T is non-smooth (such as extreme order statistics, or $|\mu|$), m-out-of-n bootstrap can "smooth" things out and works.
My main question is:

*

*Why does m-out-of-n bootstrap "smooth" things out?

I have two more things that I want to make sure I am understanding correctly.

*Since only $m$ samples are drawn, how can the behavior (variability, etc.) of $T_m(X_1^*,...,X_m^*)$ resemble that of a sample statistics using $n$ observations ($T_n(X_1,...,X_n)$). Or is it only known that asymptotically they are the same?

*When using m-out-of-n bootstrap method to find CI, do we need to scale the variance of $\sqrt{m}(T_m(X_1^*,...,X_m^*;\hat{F_n})-T(X;\hat{F_n}))$ by $\frac{n}{m}$ since we're drawing a smaller sample size from $\hat{F_n}$?
Hope my questions are clear.

A: I would argue that it's not so much that the $m$ of $n$ bootstrap does smoothing as that it makes smoothing unnecessary.
There are two components to the $m$ of $n$ bootstrap.  The first is sampling just $m$ observations; the second is knowing the convergence rate.
A big part of the advantage of the subsampling is being able to handle the correct rate.  If a statistic is $\sqrt{n}$-consistent and based on iid observations, the ordinary bootstrap pretty much has to work (Chapter 3.6 of van der Vaart & Wellner does this)
So, if you are looking to bootstrap the maximum, you need to know that it converges faster than $\sqrt{n}$ when you have a hard maximum. For example, with $U[0,\theta]$ you have $n(X_{(n}-\theta)=O_p(1)$. That means you need to scale the variance by $m^2/n^2$, not $m/n$.
Another big part is reducing ties. Again if you're going for the maximum, the ordinary bootstrap has the same maximum as the sample 0.632 of the time, whereas the sample never has the same maximum as the generating distribution.  Subsampling means that the bootstrap sample doesn't have the same maximum as the original sample and so you get a useful distribution over the bootstrap replicates. You don't need the smoothness in the statistic, because the distribution of replicates is less discrete.


text:
Q: IIS WCF Service Division/Separation I'm currently in the middle of a large ASP.NET application with many WCF services. Currently in IIS, all these services are listed under one application called Services.
I'm concerned that with more being added to our servers all the time and the uptake of our application increases, this is probably not the best way to manage things. Currently the VS project has a "web service host web application", which contains all the .svc files to be hosted. The advantage of having it all in one is the obvious use of the web.config for all services. The disadvantage is that if we need to do an update or deal with a critical issue, all our services are brought down at once, rather than those few that we know the problem is located.
I'm wondering if it is possible to keep this "host web application", but split the application into different "sub-applications" using separate Application Pools and allow VS to publish to individual services. I don't know if splitting it into folders under the "host web application" and hosting these as individual applications will work.
Or is the only way to have lots of host applications to run in separate application pools?
TL;DR; Should I split our application with all services into 5-6 applications with a few services?


text:
Q: x Points around a circle I would like to calculate x number of points around a circle using the circle's radius/diameter.
For example, if I wanted 24 equidistant points around a circle with radius 30, how could I go about that?
The circle's origin is (0, 0), radius 30 and I need to calculate 24 (X, Y) equidistant points around it.
Example with 17 points: http://i.imgur.com/Jibwr.png

A: If you start from the right wing of the $x$ axis, your points of the regular $n$-gon are
$$P_k=(r\cos\left(\frac{k\cdot 2\pi}{n}\right), r\sin\left(\frac{k\cdot 2\pi}{n}\right))$$
where $k=0,..,n-1$.
If the first angle, measured from the right wing of $x$ axis, counterclockwise, is not $0$ but some $\alpha_0$, then
$$P_k=(r\cos\left(\frac{k\cdot 2\pi}{n}+\alpha_0\right), r\sin\left(\frac{k\cdot 2\pi}{n}+\alpha_0\right))$$

A: First of all, observe that multiplication of coordinates preserves equality of distances: if points $a$ and $b$ are equidistant, then so are $\alpha a$ and $\alpha b$ for any number $\alpha$. Thus, we can reduce the problem to the case when the radius of the circle is equal to one.
Now, consider a function $f(\cos \varphi, \sin \varphi) = (\cos(n\varphi), \sin(n\varphi))$. As you can see, it wraps the circle around itself $n$ times, and $$\left|\frac{\mathrm{d}}{\mathrm{d}\varphi}f\right| = \left|(-n\sin(n\varphi), n\cos(n\varphi))\right| = \sqrt{n^2\sin(n\varphi)^2 + n^2\cos(n\varphi)^2} = n \sqrt{\sin(n\varphi)^2 + \cos(n\varphi)^2} = n,$$ so as $f$ wraps a circle around itself, it does so with constant velocity, so each 'lap' has the same length. Thus, for example, all points that $f$ maps to $(\cos \varphi_0, \sin \varphi_0)$ must be equidistant, and there are exactly $n$ of them.
So now all that's left for you to do is to solve the equation $f(\cos \varphi, \sin \varphi) = (\cos \varphi_0, \sin \varphi_0)$, and you'll arrive to Berci's answer.
One last thing, if you're familiar with complex numbers, $f(z) = z^n$, so any set of $n$ equidistant points on a unit circle is a set of $n$-th roots of some number of length one.


text:
Q: How to write dictionary to a text file properly I am trying to create a text file with dictionary  storing some value so that I can retrieve it later but the write creates multiple dictionary how can I create only a single dictionary also the type of data is returned is as string how can I use it as dictionary, kindly pardon I am new to python,
I tried with json dump method but I was getting typeerror-object-of-type-method-is-not-json-serializable
import json

mydic = {}

for i in range(3):
    uname = input("enter uname\n")
    pwd = input("enter pwd\n")

    mydic[uname] = pwd

print(mydic)

with open("cd.txt","a+") as file:
    file.write(str(mydic))

with open("cd.txt","r") as file:
    data = file.read()
    print(data,type(data))

Data is getting saved as below 1-3 I gave input in first attempt 4 -6 for second attempt U can see 2 different dictionay got created
{'1': '1', '2': '2', '3': '3'}{'4': '4', '5': '5', '6': '6'}

A: You are adding the string conversion of your dictionary onto the file. Each time you run your program, the a+ flag tells it to append as a string.
You can fix this by using a json format–like you imported:
import json

mydic = {}

# Read existing data
with open('cd.json', 'r') as jsonFile:
    mydic = json.load(jsonFile)

# Get usernames and passwords
for i in range(3):
    uname = input("enter uname\n")
    pwd = input("enter pwd\n")

    mydic[uname] = pwd

print(mydic)

# Write new values
with open('cd.json', 'w') as jsonFile:
    json.dump(mydic, jsonFile, indent=4, sort_keys=True)

First we read the existing values, then we run through the code you wrote to get usernames and passwords, and finally, we save all the data to a json file.

A: You need to handle the content in the file as JSON, that's the easiest way to update the content, not handling as string version of dictionnary that you would append
I used pathlib.Path to facilitate the file interactions
import json
from pathlib import Path

file = Path("cd.json")

if file.exists():  # load existing data
    mydic = json.loads(file.read_text())
else:  # create new
    mydic = {}

# add more data
for i in range(3):
    uname = input("enter uname\n")
    pwd = input("enter pwd\n")
    mydic[uname] = pwd

print(mydic)

# save in file
file.write_text(json.dumps(mydic))

# load back to verify
mydic = json.loads(file.read_text())
print(mydic)

A: Try writing the dictionary as Pandas Dataframe in a csv file. It's much simpler to write and read from an csv file. And in future if you are having multiple dictionaries then you can just make a list of dicts and write to the csv file.
import pandas as pd

df=pd.DataFrame([your_dictionary])
df.to_csv(file_name)

#read csv
read_df = pd.read_csv(file_name)
dict_list=read_df.to_dict('records')  #this will give you the list of dictionaries


text:
Q: package 'rJava' is in use and will not be installed I have been using R for a while without problems. Just a sudden, i have  several issues with Rjava errors. I searched online for clues, but found none.
The error is: Warning in install.packages :
  package 'rJava' is in use and will not be installed
and now every time i run install.packages, i get a pop box that says uploading loaded packages.....

sessionInfo()
  R version 3.5.2 (2018-12-20)
  Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows >= 8 x64 (build 9200)

Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
other attached packages:
[1] miniUI_0.1.1.1  tabulizer_0.2.2 rJava_0.9-10
Every time i start RStudio, i get this error:
Loading required package: rJava
Error: package or namespace load failed for 'rJava' in exists(what, mode = "function", envir = ns):
 reached elapsed time limit
I made sure that i had java versions for 64 bit and the environment was set correctly.
install.packages("rJava");library(rJava)
I want to have a solution so that rjava loads correctly when i start RStudio or install rjava

A: This looks like you are loading tabulizer on startup, which also loads rJava. I suspect the reason is that you have a file called .RDATA saved in your default working environment. That makes RStudio open and load it on starting. In that file, I suspect there is an object which needs tabulizer. This is why it is loaded on default and why you have these problems.
The solution is to delete or rename the .RDATA file. Use getwd() to find out your current working directory. You might need to make hidden files visible.


text:
Q: socket never got connected I was trying to use the socket to connect the server but when I put the parameter to be localhost, it works. but when I put my ip address in there it never works, So I don't know what was wrong, the ip address I got was from http://whatismyipaddress.com
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

    public static void main( String [] arg ) throws Exception
    {
        Socket      socket;
        BufferedReader  stdIn;
        BufferedReader  fromServer;
        PrintWriter toServer;
        String      s;
        String      result;

        socket = new Socket( "96.63.208.240", 5000 );
        stdIn = new BufferedReader( new InputStreamReader( System.in ) );
        fromServer = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
        toServer = new PrintWriter( new OutputStreamWriter( socket.getOutputStream() ), true );
        while ( (s = stdIn.readLine()) != null )
        {
            toServer.println( s );
            result = fromServer.readLine();
            System.out.println( "reverse: " + result );
        }
        socket.close();
    }
}

The sever side
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main( String [] arg ) throws Exception
    {
        ServerSocket    serverSocket = new ServerSocket( 5000, 10 );
        Socket      socket;

        serverSocket.setReuseAddress( true );
        while ( (socket = serverSocket.accept()) != null )
        {
            System.out.println( "Accepted an incoming connection" );
            new SessionThread( socket ).start();
        }
        serverSocket.close();
    }
}

A: You porbably forgot to set port forwarding, because you specified global IP router by default does not know to which device inside local network should it send to (devices in local network have local ip which you can find with cmd: ipconfig). So you manualy tell router to send every packet it come to port 5000 from internet to direct it to device with IP eg. 192.168.1.5

A: You need to understand the request flow to solve your problem.
With localhost you are making a request directly to your computer, he doesn't event get out to the network.
When you put your external IP (that you have found through whatismyipaddress.com) the request will exit your computer and ask your router where is the machine with that IP. That said, the request flow will be:

*

*Your computer

*Your router

*ISP DNS

*Your router again (because your ISP knows your IP)

*Your computer again

But in this last step there's is a problem. Due to security reasons your router will block any external request to access your private network. There's is the part where you must configure your router port forwarding (as mentioned before) and tell him that any request from outside of your private network must be redirected to your local IP, this way will work. To configure port forwarding just access your router through your browser (like 192.168.1.1), login and go to port forwarding or something similar. The configuration steps should be very explicit.
But don't forget, your local and event external IP can change, so if it stop work again check if the IP's remain the same.

A: Try this code: Maybe more useful for you.
import java.net.*;
import java.io.*;

public class Client {
    public static void main (String args[]) {
    // arguments supply message and hostname of destination
    Socket s = null;
        try{
            int serverPort = 7896;
        s = new Socket(args[1], serverPort);
        DataInputStream in = new DataInputStream( s.getInputStream());
        DataOutputStream out =
            new DataOutputStream( s.getOutputStream());
        out.writeUTF(args[0]);          // UTF is a string encoding see Sn 4.3
        String data = in.readUTF();
        System.out.println("Received: "+ data) ;
            }catch (UnknownHostException e){
            System.out.println("Sock:"+e.getMessage());
        }catch (EOFException e){System.out.println("EOF:"+e.getMessage());
            }catch (IOException e){System.out.println("IO:"+e.getMessage());}

        if (s != null)
            try {
                s.close();
            } catch (IOException e) {
                System.out.println("close:" + e.getMessage());
            }
    }
}

And for server side use this one.
import java.net.*;
import java.io.*;

public class Server {
    public static void main(String args[]) {
        try {
            int serverPort = 7896;
            ServerSocket listenSocket = new ServerSocket(serverPort);
            while (true) {
                Socket clientSocket = listenSocket.accept();
                Connection c = new Connection(clientSocket);
            }
        } catch (IOException e) {
            System.out.println("Listen :" + e.getMessage());
        }
    }
}

class Connection extends Thread {
    DataInputStream in;
    DataOutputStream out;
    Socket clientSocket;

    public Connection(Socket aClientSocket) {
        try {
            clientSocket = aClientSocket;
            in = new DataInputStream(clientSocket.getInputStream());
            out = new DataOutputStream(clientSocket.getOutputStream());
            this.start();
        } catch (IOException e) {
            System.out.println("Connection:" + e.getMessage());
        }
    }

    public void run() {
        try { // an echo server
            String data = in.readUTF();
            out.writeUTF(data);
        } catch (EOFException e) {
            System.out.println("EOF:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO:" + e.getMessage());
        }

        try {
            clientSocket.close();
        } catch (IOException e) {
            /* close failed */}
    }
}


text:
Q: how do overflow the buffer with a specific return address? Here is an array that I was given:
  char overflow[16]="\xEF\xBE\xAD\xDE\xEF\xBE\xAD\xDE"
                    "\xEF\xBE\xAD\xDE\xEF\xBE\xAD\xDE";

and here is the address: "0x1234B000"
how do I edit the array above to overflow and change the return address to the new address above??

A: It really depends on whats on the stack, which determines how many bytes you have to overwrite at a minimum.  function params  and local variables will be in the way of the stack pointer, which is what your trying to overwrite correct?  I would say overflow it with 1k of the same repreating byte pattern and step with gdb or some other debugger to get a stack trace.
ex1. (you need to write past the array, sizeof(int) bytes to get to the stack pointer.)
void testFunction(int arg0){
  char overflow[16] = {0};
  char HUGE_ARRAY[10000] = {0};// what does the stack look like in this case?  This giant block of memory should be on the stack AFTER your target array
  //do something that allows the user to overflow the overflow array for w/e reason
}

ex2. (you need to write past the array, sizeof(int) bytes + 10000 bytes to get to the stack pointer.)
void testFunction(int arg0){
  char HUGE_ARRAY[10000] = {0};// what does the stack look like in this case?  This giant block of memory should be on the stack BEFORE your target array.
  char overflow[16] = {0};
  //do something that allows the user to overflow the overflow array for w/e reason
}

If you know the target environment (sizeof int is known for example), the number and type of function params, and the number and type of local variables poped on the stack when you enter the function whos stack pointer your trying to overwrite, then you can theoretically write the exact bytes of the function's stack pointer.
Alternatively, you can figure this out by write 0x00 values past the overflow buffer and increasing the distance PAST the 16 bytes every time, until you seg fault.  Once you seg fault you have found the function's stack pointer.
In general, the stack grows by popping on the following things in the following order: return address-> function params-> locals.
In your case, you can probably test it by writing more bytes than you need. (will work as long as <4k was allocated to this functions stack prior to overflow being popped on the stack)
for (offset = 0; offset < 1000; offset++){
  (int)(*overflow + 4 + offset) = 0x1234B000;
}

GL.


text:
Q: PhpMailer not sending mails - TLS error? I have a problem sending emails with phpmailer .
The code that sends emails is:
$mail_User      = "site@xxxxxxx.com";
$mail_Password  = "My Password";
$mail_address   = "site@xxxxxxx.com";
$mail_Name      = "MyName";
$mail_Server    = "222.222.222.222";
$mail_Port      = 25;

    function SendHTMLMail($to, $cc, $bcc, $subject, $body)
    {
        global $mail_User, $mail_Password, $mail_address, $mail_Name, $mail_Server, $mail_Port;
        $correo = new PHPMailer;
        $correo->SMTPDebug = 3;                               // Enable verbose debug output
        $correo->SetLanguage("es", "/phpmailer/language/");
        $correo->IsSMTP();

        $correo->IsHTML(true);
        $correo->Host = $mail_Server;
        $correo->Port = $mail_Port;
        $correo->SMTPAuth =true;
        //$correo->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $correo->Username = $mail_User;
        $correo->Password = $mail_Password;
        $correo->From      = $mail_address;
        $correo->FromName  = $mail_Name;
        $correo->Subject = $subject;
        $correo->Body    = $body;
        $dest = explode (";", $to);
        for ($n=0; isset($dest[$n]); $n++) $correo->AddAddress($dest[$n]);
        $dest = explode (";", $cc);
        for ($n=0; isset($dest[$n]); $n++) $correo->AddCC($dest[$n]);
        $dest = explode (";", $bcc);
        for ($n=0; isset($dest[$n]); $n++) $correo->AddBCC($dest[$n]);
        if ($correo->Send())
            return "";
        else {
            AddLog("Correo no enviado: $correo->ErrorInfo");
            echo "
Correo no enviado: $correo->ErrorInfo
";
            return "Correo no enviado: $correo->ErrorInfo";
        }
    }

And the result is :
2016-02-24 04:58:17 Connection: opening to 222.222.222.222:25, timeout=300, options=array (
                                      )
2016-02-24 04:58:17 Connection: opened
2016-02-24 04:58:17 SERVER -> CLIENT: 220-srv1.abcdef.com ESMTP Exim 4.86 #2 Wed, 24 Feb 2016 14:47:17 +0100
                                      220-We do not authorize the use of this system to transport unsolicited,
                                      220 and/or bulk e-mail.
2016-02-24 04:58:17 CLIENT -> SERVER: EHLO www.site.com
2016-02-24 04:58:18 SERVER -> CLIENT: 250-srv1.abcdef.com Hello www.doznyk.com [181.181.181.181]
                                      250-SIZE 52428800
                                      250-8BITMIME
                                      250-PIPELINING
                                      250-AUTH PLAIN LOGIN
                                      250-STARTTLS
                                      250 HELP
2016-02-24 04:58:18 CLIENT -> SERVER: STARTTLS
2016-02-24 04:58:18 SERVER -> CLIENT: 220 TLS go ahead
2016-02-24 04:58:18 SMTP Error: Could not connect to SMTP host.
2016-02-24 04:58:18 CLIENT -> SERVER: QUIT
2016-02-24 04:58:19 SERVER -> CLIENT: 221 srv1.abcdef.com closing connection
2016-02-24 04:58:19 Connection: closed
2016-02-24 04:58:19 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Why phpmailer don't send emails? Why it try to use TLS if the code line is a comment?
I replace sensitive data with fake, like server name and IPs.
If I change port from 25 to 587 and uncomment the line tls, the result is almost the same.
Thank you

New test, same result.
I read the doc as  Synchro suggest me.
I changed the port from 25 to 587 and added the line $correo->SMTPAutoTLS = true;
$correo->SMTPAuth =true;
$correo->SMTPAutoTLS = true;
//$correo->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$correo->Username = $mail_User;
$correo->Password = $mail_Password;

The result is:
2016-02-24 06:05:36 Connection: opening to 222.222.222.222:587, timeout=300, options=array (
                                      )
2016-02-24 06:05:37 Connection: opened
2016-02-24 06:05:37 SERVER -> CLIENT: 220-srv1.abcdef.com ESMTP Exim 4.86 #2 Wed, 24 Feb 2016 15:54:37 +0100
                                      220-We do not authorize the use of this system to transport unsolicited,
                                      220 and/or bulk e-mail.
2016-02-24 06:05:37 CLIENT -> SERVER: EHLO www.myserver.com
2016-02-24 06:05:38 SERVER -> CLIENT: 250-srv1.abcdef.com Hello www.doznyk.com [181.229.171.247]
                                      250-SIZE 52428800
                                      250-8BITMIME
                                      250-PIPELINING
                                      250-AUTH PLAIN LOGIN
                                      250-STARTTLS
                                      250 HELP
2016-02-24 06:05:38 CLIENT -> SERVER: STARTTLS
2016-02-24 06:05:38 SERVER -> CLIENT: 220 TLS go ahead
2016-02-24 06:05:39 SMTP Error: Could not connect to SMTP host.
2016-02-24 06:05:39 CLIENT -> SERVER: QUIT
2016-02-24 06:05:39 SERVER -> CLIENT: 221 srv1.abcdef.com closing connection
2016-02-24 06:05:39 Connection: closed

A: Well. I made a lot of test and cannot see the section of doc that said me Synchro, but Synchro was right.
I added the next code and now works fine!
$correo->SMTPOptions = array(
        'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

Although I do not use SSL, I must clarify that I don't use SSL because phpmailer verifies that SSL is usable.
Or must be configured properly
Thanks!


text:
Q: Computer unable to run any VM. All VMs freeze I have a problem with my current PC:

*

*MSI Z97S SLI Krait Edition Motherboard

*Intel 4790K CPU

Every time I try to run any VM on that PC the VM ends up freezing at some point, requiring me to hard reset the VM to reboot it. This can happen form 30 seconds after booting the VM to 24 hours. It will always hard freeze with no logs to explain such behavior.
I've tried multiple virtualization apps: Windows Hyper-V, VMWare Workstation, Virtualbox. All of them exhibit the same behavior.
Also same behavior whether Intel VT is enabled or disabled in the bios.
Did anyone ever experience such a problem? How can I pinpoint what the problem is?
Thank you,

A: Task Manager for high level performance issues. Once process identified, check if it's a shared process. If shared, break out into own process. Monitor process in Performance Monitor looking for memory leak. If none, monitor process in Sysinternals Process Monitor checking for access denies. If none, find executable and enable Auditing check for additional errors. Do search for executable in Microsoft support cases, check if latest version...


text:
Q: Google geomap with jquery fails in IE I faced with problem that geomap by google fails with JQuery together in Internet explorer.
Otherwise in Firefox it looks like this:

(source: clip2net.com)
Here comes js references
<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=ABCDEFG">
</script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/js/ui.core.js" type="text/javascript"></script>
<script src="/js/ui.accordion.js" type="text/javascript"></script>

(source: clip2net.com)
Please anybody help with this...
Thanks in advise.

A: It's hard to debug javascript in IE, but it's even harder to debug without the actual url, or when using minified javascript.  You might want to switch to the full non-minified version of jquery temporarily, so that you can find the line where the error occurs and see what's going on.
Also, in firefox you can try using firebug to see if it throws any errors.  Even though the map is working in firefox, it may be silently recovering from an error that IE can't recover from.

A: Are you using a console.log() call to print to firebug? This will cause IE to throw errors. If thats the case maybe try something like this
var a = "hello";
try
{
console.log(a);
}
catch(err)
{
alert(a);
}

this will substitute the console.log with a plain old alert in IE

A: Fixed by removing JQuery.UI.Dialog from page.

A:
#map { float:left; width:700px; height:500px; margin-top:10px; }

That's all :-)


text:
Q: Como destruir o modal do Boostrap v4? Estou com um problema no modal do boostrap, que é o seguinte:

O modal é aberto clicando em um botão, assim que o modal é fechado o
  console mostra que ele abriu uma vez. Se eu clicar novamente no botão
  para abrir este mesmo modal, no console mostra que ele abriu mais de 3
  vezes seguidas, sendo que ele aparece uma vez só.

Porque isto acontece?
Eu preciso destruir o modal assim que fechar, então eu estou utilizando o seguinte:
$('#').modal('hide');

Eu já tentei utilizar este método abaixo, porém ele destroi o modal, mas o background "cinza opacity" do modal ainda fica e não sei porque isto acontece.
$('#').modal('dispose');

Exemplo do modal que utilizo:

                            Create New Floor

                        <form id="CreateNewFloorForm" action="">

                                        <input id="FloorID" class="form-control controls" type="text" placeholder="Enter the Floor ID" aria-label="FloorID" aria-describedby="ID do Floor para inserir no DBS">

                                        <input id="NewMapFloor" class="form-control" type="text" disabled required>

                                    The Map ID is Generated Automatically.

                                        <input id="NewFloorDateCreate" class="form-control" type="text" disabled required>

                                    The Date Create is Generated Automatically

                        </form>

                            <button id="RejectSaveNewFloor" class="btn btn-danger" type="button" data-toggle="modal" data-target="#CancelModal" data-dismiss="modal" aria-label="Close">Discard</button>
                            <button id="SaveNewFloor" class="btn btn-primary" type="button">Save New Floor</button>


text:
Q: How can i check real running time? I am learning algorithm using matlab.
I used the instruction; tic and toc.
In my opinion, however, these instructions are just calculating elapsed time. How can i find real running time only in the running state?
no in the waiting or ready state.

A: You're looking at cputime.  However, this is not the recommended way to calculate time for a set of statements.  It's better that you use tic/toc, but I personally recommend timeit for a proper measurement of time of a function.
See here for a list of reasons why using cputime is not recommended: http://www.mathworks.com/help/matlab/matlab_prog/measure-performance-of-your-program.html
However, if you don't want to read that all, the takeaway message from the link I referenced is this:

Although you can measure performance using the cputime function, the timeit or tic and toc functions are better for this purpose. Generally for CPU-intensive calculations that run on Microsoft® Windows® machines, the elapsed time from cputime and from tic and toc are close in value, ignoring any first-time costs. There are cases, however, that show a significant difference between these functions. For example, in the case of a Pentium 4 with hyperthreading running Windows, there can be a significant difference between the values returned by cputime versus tic and toc.
Like tic and toc, timeit provides more reliable results than cputime. However, the timeit function also considers first-time costs.


text:
Q: jQuery get specific class name I have a div with few classes in no specific order.

I'm interested in the styledark class. This can be styledark, stylewhite, stylered.... I want to get this class name no matter what color comes after the word style.  The question is, when i click on the div, how i do i alert this class name that start with the word style disregarding other classes in the div. The classes are in no specific order.

A: $('div').click(function() {
    var style = this.className.split(/\s/).filter(function( cn ) {
        return cn.indexOf('style') === 0;
    });

    alert(style);
});

Note this code uses Array.prototype.filter and .indexof(), which is not available in old'ish browsers. To make this more generic, it would look like:
$('div').click(function() {
    var name = '';

    $.each(this.className.split(/\s/), function( _, cn ) {
        if( cn.indexOf('style') === 0 ) { name = cn; return false; }
    });

    alert(name);
});

A: $('div').click(function(){
    var c = $(this).attr('class').split(/\s+/);
    for(var s in c)
        if(c[s].indexOf('style') == 0)
            alert(c[s]);
});

live example : http://jsfiddle.net/gion_13/rXkNy/1/

A: I used to use the classList attribute, but unfortunately it seems that it's not in safari. :(
The following is what I came up with, but the RegExp may need just a little tweaking.
$('div.button').each(function() {
        $m =  this.className.match(/(^|\s)style\S+(\s|$)/);
    if($m) {
        $(this).bind('click', { colorName : $m[0] }, function(e) {
            alert(e.data.colorName);
        );
    }
});

A: Found here:  http://forum.jquery.com/topic/jquery-how-to-pick-out-classes-that-start-with-a-particular-string
var icons = ["Star", "Plus", "Left", "Right", "Up", "Down"];

$("div.button").each(function() {
    var $dv = $(this);
    $.each(icons, function() {
        if ($dv.hasClass("icon" + this)) {
            $dv.append('');
            return false;
        }
    });
});

A: This is a great question. Although it can be done using many of the answers mentioned here, this is a little awkward and costly performance wise. The way i would recommend you do it is put the style class last, that way with only one line of code you can output the class name you are after.
$('element').attr('class').split(' ').pop();

A: Assuming you have the list of class names in a variable called "classes":
classes = classes.split(" ");
for (var i=0; i<classes.length; i++)
{
    var class = classes[i];
    if (class.indexOf("style") == 0)
    {
        alert(class);
    }
}

A: $("div[class]").click(function(e){
    $.each(this.className.split(/\s/), function(i, val) {
        if (/^style/.test(val)) {
            alert(val.substr(5));
            return false;
        }
    });
});

A: $('element').attr("class").split(" ").filter(getStyleClass);

function getStyleClass(value) {
    return value.indexOf("style") > -1;
}

And to alert the 'style' class on a click, as you specified:
$('element').click(function()[
    var style_class = $(this).attr("class").split(" ").filter(getStyleClass);
    alert(style_class);
}
// include the same getStyleClass from above

more depth:
$('element').attr("class").split(" ") is a good start - it puts the classes in an array, but .pop() simply removes the last element of the array, and that does not solve the problem.
.filter() is a great solution because you can write a small function that decides which elements you want.
In our case we only want elements of the array that have 'style'. We can use .indexOf() to decide if the string contains "style" like this: value.indexOf("style") > -1.


text:
Q: Reload the same page when click I want to Reload the same page when I click on reload button.any one give the C# code for achieve this?

A: You can use like this
Page.Redirect(Page.Request.RawUrl,false);

Or suppose you are on default.aspx and you want get back on the same page use
Page.Redirect("default.aspx",false);

A: You can use
Response.Redirect(Request.RawUrl);

Which I found by googling your title.
You can look there for more informations :

*

*How to reload the same page on a button click , with the data from database and ignoring the changes

*How do I refresh the page in ASP.NET? (Let it reload itself by code)

*http://www.vbforums.com/showthread.php?316778-How-to-programmatically-refresh-a-page-in-asp.net


text:
Q: Belongs to with different method name I have a bit of a problem with Rails. I have two models: Product & Category. Now a product has one category.
So I assumed I would just put a belongs_to in the class and be done with it but due to the weird table layout I've inherited the category_id column is called category. So I aliased the attribute as category_id and done belongs_to :category but it just returns nil. Any ideas?

A: Try this:
belongs_to :product_category, foreign_key: :category, class_name: "Category"


text:
Q: SQL Server : how I get AUTO_INCREMENT status If I have column with AUTO_INCREMENT in person table that was start with 1 and incremented by 2
now after I add a row in that table
I have
ID|Fname|Lname
---------------
1 |check|check2
3 |check3|check4

How in a SQL query can I get the status of the increment I mean I want to get in the SQL the value now and the increment by
In that example I want to get from the query like:
select
    increment_value, increment_by
from
    INFORMATION_SCHEMA.COLUMNS/sys.columns
where
    tablename= 'Person'

the result that I want to get is 3,2
if people is stuck with the same situation so
here my last code
in c#
    //check columns is auto incresment if yes = True or or not =False
string sql1 = string.Format("SELECT is_identity FROM sys.columns WHERE object_id = object_id('{0}') AND name = '{1}'","tablename","ColumnName");
string str = DoQueryWithReturn("db.mdf", sql1);
MessageBox.Show(str[0]);

//get the ident increment Seed = start value , INCR= how many it up , Current it what number right now, last row
sql1 = string.Format(" SELECT IDENT_SEED('{0}'),IDENT_INCR ('{0}'),IDENT_CURRENT('{0}') AS Identity_Seed ", "tablename");
str = DoQueryWithReturn("db.mdf", sql1);
if(str[0].Length!=0)
MessageBox.Show(str[0]+","+str[1]+","+str[2]);

A: For your edit to check if a column is auto_increment (identity); you can refer to this question
edit: to check the seed value; you can use:
IDENT_SEED ( 'table_or_view' )

see also: IDENT_SEED
to check the increment, you can use:
IDENT_INCR ( 'table_or_view' )

see also: IDENT_INCR

A: To get the result you require, try,
DECLARE @table varchar(50) = 'Person'

SELECT is_identity, IDENT_SEED(@table) AS Seed,
IDENT_INCR(@table) AS Increment,
IDENT_CURRENT(@table) AS Current_Identity
FROM sys.columns
WHERE
    object_id = object_id(@table)
    AND name = 'Id' -- column name

A: You can check whether a column is an IDENTITY column with this statement:
SELECT
    name,
    is_identity
FROM
    sys.columns
WHERE
    OBJECT_ID = OBJECT_ID('dbo.YourTableNameHere')
    AND name = 'ColumnNameHere'

To find out the seed value, the increment, and the last value used, use this statement:
SELECT
    ColumnName = name,
    TableName = OBJECT_NAME(object_id),
    seed_value ,
    increment_value ,
    last_value
FROM
    sys.identity_columns


text:
Q: Why is 0dp the same as wrap_content in this ConstraintLayout? New to XML and was trying practising an XML lab (https://github.com/harshitha-akkaraju/layoutlab)
What confuses me is that even though the width of the button is 0dp, it is if the width was wrap_content. I know that 0dp is the equivalent of "MATCH_CONSTRAINT" in a ConstraintLayout. However, doesn't that mean that 0dp should fill as much space as possible?
Is it because the button only has a constraint defined on its left side, which is why 0dp = wrap_content in this case?
0dp, which is the equivalent of "MATCH_CONSTRAINT
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="20dp"
        android:layout_marginTop="20dp"
        android:text="1"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Image of the Button Layout

A: In order for the button to match the parent layout, you need to set two opposite constraints....as in
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
<!-- Since you are setting width as 0dp, i presume you want the width to match... -->
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="20dp"
        android:layout_marginTop="20dp"
        android:text="1"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
<!-- You must add here another constraint to the right -->
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>```

A: You are missing this line app:layout_constraintRight_toRightOf="parent"
in your button 0dp works with parent when
app:layout_constraintLeft_toLeftOf="parent" and app:layout_constraintRight_toRightOf="parent"
then width should be 0dpand when
app:layout_constraintBottom_toBottomOf="parent" and app:layout_constraintTop_toTopOf="parent"
then height should be 0dp


text:
Q: Struts2 Spring Plugin: Dependency Injection with Annotated Actions does not work I have the following problem. I have a application with struts2, spring and struts2-spring-plugin up and running. The dependency Injection via Spring works in generally. (For exasmple. Inject a bean into an Action) But: My Action-classes are not Iinjected via spring per session as defined. The Actions constructor is called per reqiuest. It seems like spring doesn't use the Spring's object factory. When defining the Action in struts.xml instead of using the @Action Annotations the dependency injection works!
Here some snippets: Here ihave defined a bean and an Action. Injection of the bean works, but the Action is never created here, when using @Action annotation.
@Bean
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public PatientForm PatientForm(){
    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>> PatientForm() ");
    return new PatientForm();
}

@Bean(name="patient")
@Scope(value="request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public PatientAction PatientAction(){
    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>> PatientAction() ");
    return new PatientAction();
}

Here the implementation of the Action:
   public class PatientAction extends TherapyActionSupport {
        private static final Logger logger = LoggerFactory.getLogger(PatientAction.class);

        @Autowired
        private PatientForm form;

        public PatientAction(){
            logger.debug("Constructor called.");
        }

        @Override
        @Action( name="/patient",
         results={
          @Result(name=SUCCESS, location="/therapy/patient/edit.jsp"),
          @Result(name=ERROR, location="/therapy/patient/edit.jsp"),
          @Result(name=INPUT, location="/therapy/patient/edit.jsp")
          }
        )
        @SkipValidation
        public String execute() throws Exception {
            logger.info("Execute called.");
            return SUCCESS;
        }

        @Action(value="/save",
         results={
           @Result(name=SUCCESS, location="/therapy/patient/list.jsp"),
           @Result(name=ERROR, location="/therapy/patient/edit.jsp"),
           @Result(name=INPUT, location="/therapy/patient/edit.jsp")
           }
        )
        public String savePatient() throws Exception{
            try {
                logger.info("Saving patient.");
                getForm().savePatient();
                return list();
            } catch (Exception e) {
                e.printStackTrace();
                return ERROR;
            }
        }
    }

Calling the URL "http://localhost/myApp/patient" makes an Instance of the Action-Class on each request, without entering the public PatientAction PatientAction() method.
When I use this in struts,xml:
<package name="default" extends="struts-default">
    <action name="foo" class="patient">
        <result>list.jsp</result>
    </action>
</package>

And call "http://localhost/myApp/foo" the action is injected via spring.
This is my struts.properties file:
struts.i18n.encoding=UTF-8
struts.objectFactory = spring
## Tried settings with autoWire
#struts.objectFactory.spring.autoWire = auto
struts.objectFactory.spring.autoWire = type

Versions I use (via Maven:)
struts2-core 2.2.3.1
spring3 3.1.1.RELEASE
struts2-spring-plugin 2.3.1.2

Can anybody tell me what I'm doing wrong with annotations?

A: The value for struts.objectFactory is not correct, instead of "spring" it should be "org.apache.struts2.spring.StrutsSpringObjectFactory"
<struts>
  <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
  ...
</struts>

For further information see: http://struts.apache.org/2.3.1.2/docs/spring-plugin.html
Note that actions are instantiated per request, and so holding them in session would very likely cause weird things to happen with no discernible benefit (profile it).