text:
Q: JavaScript runtime error: Unable to get property 'className' of undefined or null reference I'm trying to code an image slider into my website but I'm receiving this error whenever I try to debug:

JavaScript runtime error: Unable to get property 'className' of
  undefined or null reference

When I use chrome to inspect the elements, it shows a null reference for the className property of the project# div tags, yet I defined the class for each of these tags in the html code. I'm so lost, I don't understand what's causing the detection error. Your help will be much appreciated. All the relevant code is below. Thank you :)
HTML:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Tebello | Projects</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

    <link href="style.css" rel="stylesheet" />
    <link href="default.css" rel="stylesheet" type="text/css" media="screen" />

Project name

A short description of the project

Project name

A short description of the project

Project name

A short description of the project

1

2

3

Javascript:
var links = document.querySelectorAll(".itemlinks");
var wrapper = document.querySelector("#wrapper");

for (var i = 0; i < links.length; i++) {
    var link = links[i];
    link.addEventListener('click', setPosition, false);
}

addClass(links[0], "active");

function setPosition(e) {
    removeActiveLinks();

    var clickedLink = e.target;
    addClass(clickedLink, "active");

    var position = clickedLink.getAttribute("data-pos");
    wrapper.style.left = position;
}

function removeActiveLinks() {
    for (var i = 0; i < links.length; i++) {
        removeClass(links[i], "active");
    }
}

function addClass(element, classToAdd) {
    var currentClassValue = element.className;

    if (currentClassValue.indexOf(classToAdd) == -1) {
        if ((currentClassValue == null) || (currentClassValue === "")) {
            element.className = classToAdd;
        } else {
            element.className += " " + classToAdd;
        }
    }
}

function removeClass(element, classToRemove) {
    var currentClassValue = element.className;

    // removing a class value when there is more than one class value present
    // and the class you want to remove is not the first one
    if (currentClassValue.indexOf(" " + classToRemove) != -1) {
        element.className = element.className.replace(" " + classToRemove, "");
        return;
    }

    // removing the first class value when there is more than one class
    // value present
    if (currentClassValue.indexOf(classToRemove + " ") != -1) {
        element.className = element.className.replace(classToRemove + " ", "");
        return;
    }

    // removing the first class value when there is only one class value
    // present
    if (currentClassValue.indexOf(classToRemove) != -1) {
        element.className = element.className.replace(classToRemove, "");
        return;
    }
}

A: I guess the problem is with place where you added your script.js file.
You are trying to include your javascript code in head tag. So the javascript code execute before the DOM has rendered and the element to which you are adding the class doesn't exists yet.
Include the script right before .

...more html...

...more html...
...more html...

I tested the code with correction and it works. I hope it helps.
Note: body tag is missing in code snippet you shared. I am assuming that is present in actual code.

A: In you case your JavaScript is executing before complete page loads and that's you your document.querySelectorAll(".itemlinks"); code is returning links with zero length.
Solution to your question to use JavaScript code on load. (Please refer below code)
 window.onload = function(){
        var links = document.querySelectorAll(".itemlinks");
        var wrapper = document.querySelector("#wrapper");

        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            link.addEventListener('click', setPosition, false);
        }

        addClass(links[0], "active");

        function setPosition(e) {
            removeActiveLinks();

            var clickedLink = e.target;
            addClass(clickedLink, "active");

            var position = clickedLink.getAttribute("data-pos");
            wrapper.style.left = position;
        }

        function removeActiveLinks() {
            for (var i = 0; i < links.length; i++) {
                removeClass(links[i], "active");
            }
        }

        function addClass(element, classToAdd) {
            var currentClassValue = element.className;

            if (currentClassValue.indexOf(classToAdd) == -1) {
                if ((currentClassValue == null) || (currentClassValue === "")) {
                    element.className = classToAdd;
                } else {
                    element.className += " " + classToAdd;
                }
            }
        }

        function removeClass(element, classToRemove) {
            var currentClassValue = element.className;

            // removing a class value when there is more than one class value present
            // and the class you want to remove is not the first one
            if (currentClassValue.indexOf(" " + classToRemove) != -1) {
                element.className = element.className.replace(" " + classToRemove, "");
                return;
            }

            // removing the first class value when there is more than one class
            // value present
            if (currentClassValue.indexOf(classToRemove + " ") != -1) {
                element.className = element.className.replace(classToRemove + " ", "");
                return;
            }

            // removing the first class value when there is only one class value
            // present
            if (currentClassValue.indexOf(classToRemove) != -1) {
                element.className = element.className.replace(classToRemove, "");
                return;
            }
        }
    }

Please up vote it if this code works fine.


text:
Q: C# array wont accept "size" the noob, again. todays question is:
int[] forArray = new int[10];
        for (int k = 1; k <= 10; k++)
        {
            forArray[k] = k * 2;
            Console.WriteLine(k); // test
        }
        for (int k = 0; k < 10; k++)
        {
            Console.WriteLine(forArray[k]);
        }

it gives an "out of bounds" error. I would like my program to output natural numbers from 2 to 20. Instead gives off an error. when I change the first for loops condition to k <= 9 it runs but gives me 0 instead of 20. its like it returns the last value as 0 and "re-positions" it to the "front". sorry for the really simple question.

A: Arrays are zero-based, when it comes to referencing the elements. So, for 10 items in an array (which is what you allocated), it's forArray[0] through forArray[9]. Your code tries to loop from forArray[1] through forArray[10], and there is no index position 10 (which is when you end up going out of bounds).
Your second for-loop is fine, as it goes from 0 to 9.
Note: Since your loop needs to be zero-based, you'll need to adjust how you calculate the number you stuff into the index positions, if you want it starting with 2.

A: Debug your code and step through, as you see below you are trying to assign to index [10], which doesn't exist.
{
    int[] forArray = new int[10];

    for (int k = 1; k < 10; k++)  // k < 10 instead of k <= 10
    {
        forArray[k] = k * 2;
        Console.WriteLine(k); // test

            //forArray[0] = SKIPPED
            //forArray[1] = 2
            //forArray[2] = 4
            //forArray[3] = 6
            //forArray[4] = 8
            //forArray[5] = 10
            //forArray[6] = 12
            //forArray[7] = 14
            //forArray[8] = 16
            //forArray[9] = 18
            //forArray[10] INVALID
    }
    for (int k = 0; k < 10; k++)
    {
        Console.WriteLine(forArray[k]);
    }
}

Tested here

A: Change your condition to k
forArray[k - 1] = k * 2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it good practise to extract strings from framework standard syntax? For example: In sonata admin, a single admin class has always recurring syntax like
$formMapper->add('test', null, ['label' => 'testlabel']);

$formMapper->add('test1', null, ['label' => 'testlabel1']);

$formMapper->add('test2', null, ['label' => 'testlabel2']);

In this case if i am adding several fields with the add method, our quality gate is telling me, that it is a code smell using the 'label' string more than 2 times. I should add a constant for that string ...
Is it now good or bad practise to have many many classes full of constants like
const KEY_LABEL = 'label'

$formMapper->add('test2', null, [self::KEY_LABEL => 'testlabel2']);

???
I can't figure out, whats the great benefit .. if someday the label key will change, which is given by the framework, i have to make changes to this stuff either way ...

A: Short answer: No. Symfony doesn't rename keys.
Long answer: Symfony has a pretty strict Backwards Compatibility Promise. It is not very likely the label key will be renamed. But that doesn't mean that it won't change.
If you have to 'rename' a key, it is very likely you have to change the value too. That means you're not renaming, but replacing it. Using a constant will help you rename the keys, but it won't help you refactoring the value.
I started working with Symfony many years ago (started with 2.1 and testing 3.4-beta right now) and I've had to perform some 'renaming' in the past. In almost all cases the key wasn't renamed but it was deprecated and later replaced by another key. One of the examples I can remember is the Choice form type refactorization, but I'm sure there are more and even better examples.


text:
Q: SQL Query output to a variable in Delphi? I Would like to know how Can I put the SQL Query result into a variable.
I'm aware of this
integerVariable := UniQuery1.RecordCount;

but this?
integerVariable := SELECT COUNT(*) FROM Orders WHERE Amount='1000'

A: what you need to do is first "execute" the sql, then check for result, if result is present, then store it in a variable, here's what I mean:
procedure ...;
var
  LCount: Integer;
begin
  LCount := 0;
  //
  // note that I am doubling the single quote to escape it
  //
  // set the query
  UniQuery1.SQL.Text := 'SELECT COUNT(*) FROM Orders WHERE Amount=''1000'';';
  //
  // "execute" it
  //
  UniQuery1.Open;
  //
  // SELECT COUNT(*) will return 1 record with 1 field
  // most likely the field name is 'count' <= lower case
  // but we are sure that there should be only 1 field so we
  // access it by Fields[Index].As[TYPE]
  //
  LCount := UniQuery1.Fields[0].AsInteger;
  ShowMessageFmt('Total count of orders with Amount = 1000: %d', [LCount]);
end;

EDIT:
thank you for point out that "COUNT" will always have a return.


text:
Q: how to limit _delete_by_query to a single type when using java client Api I want to delete some documents from es using java client, e.g
curl -X POST "localhost:9200/twitter/tweet/_delete_by_query?conflicts=proceed" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match_all": {}
  }
}
'

but from document Apis
BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
    .filter(QueryBuilders.matchQuery("gender", "male"))
    .source("persons")
    .get();
long deleted = response.getDeleted();

it seems you cannot limit _delete_by_query to a single type

A: You can always do it like this:
QueryBuilder query = QueryBuilders.boolQuery()
    .filter(QueryBuilders.termQuery("_type", "tweet"))
    .filter(QueryBuilders.matchQuery("gender", "male"));

BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
    .filter(query)
    .source("persons")
    .get();
long deleted = response.getDeleted();


text:
Q: Selecting * from 2 Tables without any similar row I'm new at Programming, so I have a question about selecting a data in MySQL. All the answer is about merging and joining that I'm not really looking for. returns
First table containing all the user data, and second table showing all posts by users.
I've tried doing this:
$sql="select * from wall, maintable where postverification="yes" AND userid='".$_SESSION['userid']."'";

$result=mysql_query($sql);

$row=mysql_fetch_array($result);

The reason I want to get these different data is so i can post to php a hidden field in the form that containing "who post what" in the same page called wall.php (Like a twitter concept, but the timeline showing all user post)
The code that i've tried above only selecting from 1 table whether "wall" or "maintable".
Why is this happening?

A: Perhaps you look for something like this:
SELECT a.field1, b.field2 FROM table1 AS a, table2 AS b WHERE a.field3=b.field3

Or using LEFT JOIN,the same query becomes:
SELECT a.field1, b.field2
FROM table1 AS a
LEFT JOIN table2 AS b ON a.field3=b.field3

You need to look at sql aliases.

A: You have to use a join  statement:
select * from wall inner join nmaintable on wall.'samefield'=postverification.'samefield'
 where postverification="yes" AND userid='".$_SESSION['userid']."'";

Also consider SQL injection, try using PDO.


text:
Q: a list inside a list - django views {% if latest_question_list %}

{% for question in latest_question_list %}

{{ question.question_text }}

{% endfor %}

{% else %}

No polls are available.

{% endif %}

and I have
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
    'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))

But how do I do an inner list?
Since its a list of lists how do I define the lists in such a way that they can be access correctly? The question model certainly doesn't contain any list of comments. I can do a  query but I really have no idea where to begin here.
Thanks for any suggestion.
edit:
 have a list of questions from the database. The code above lets me view them just fine. But every list has multiple comments. How do I list all the comments per question? I need another for loop in the html but I am not sure how to give each question its own data in the view.

A: This isn't at all a question about lists.
Presumably you have a separate Comment model, and that model has a ForeignKey to the Question model; if you don't have that structure, then you should.
Then it's simply a matter of following the reverse relationship for each question:
{% for question in latest_question_list %}
    ...
    {% for comment in question.comment_set.all %}
        {{ comment.text }}
    {% endfor %}
{% endfor %}

Note that this exact structure is well described in the tutorial, with the example of Poll and Choice.


text:
Q: uncaught at rootSaga at rootSaga at watchFecthUsers at takeLatest at fetUsers ReferenceError: error is not defined user.js get user
 import { FETCTH_FAIL, FETCTH_SUCCES, FETCTH_USER } from "../action/actionTypes";
    import { put, takeLatest } from "redux-saga/effects";
    import Api from "./App";

    function* fetUsers() {
      try {
        const users = yield Api.getUsers();
        yield put({ type: FETCTH_SUCCES, users: users });
      } catch (err) {
        yield put({ type: FETCTH_FAIL, error });
      }
    }

    export function* watchFecthUsers() {
      yield takeLatest(FETCTH_USER, fetUsers);
    }

rootSaga.js rootSaga
import { call, all } from "redux-saga/effects";
import { watchFecthUsers } from "./users";

export default function* rootSaga() {
  yield call(watchFecthUsers);
}

actionTypes.js action
export const FETCTH_USER = 'fetchuser';
export const FETCTH_SUCCES = 'fetchsucces';
export const FETCTH_FAIL = 'fetchfail';

I get Error mentioned below

D:\android_ios\sagaredux\node_modules\react-native\Libraries\Core\ExceptionsManager.js:71 uncaught at rootSaga at rootSaga
at watchFecthUsers
at takeLatest
at fetUsers
ReferenceError: error is not defined

A: I know it's very late to answer but just for the sake of clarity on this error
yield put({ type: FETCTH_FAIL, error });
In the above line 'error' is not defined hence the error occurs.
You can change this line to something like below:
yield put({ type: FETCTH_FAIL, error:err }); where 'err' is the catch block's variable name.


text:
Q: Having issues styling a table I have been digging around on the internet at other SOF questions and other various websites. I seem to be having issues getting the scrollbars/alignment of this table to work nicely.
I have a table of the following format:
Column 1 | Column 2 is slightly longer                                              | Column 3 | Column ......
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | some random text is in here and should make the column 2 expand this far | data     | .....
Data     | At this row I want it to not be showing and you have 2 scroll down 2 see | data     | .....
Data     | At this row I want it to not be showing and you have 2 scroll down 2 see | data     | .....

The challenging part I am having is I cannot seem to get the <thead><tr> part at the top (Column 1, Column 2) to continue to show as visible while scrolling down vertically. I also need to be able to scroll horziontally like in the code samplet that SOF displays shows up above and keep the <thead> and the <tbody> parts aligned.
Anyone have a jsfiddle or something similar handy that shows a proper example of this?
Thanks.


text:
Q: Why does this jQuery UI datepicker seem to be a noop if I try to change the format? I would like to have a Datepicker field that provides an ISO 8601 yyyy-mm-dd. I've done a little bit of research and have found other invocations that should specify an alternate format, but so far every dateFormat I've tried (should I be using altFormat?) results in a noop.
(If I click on the field after just calling jQuery().datepicker() with no arguments, it displays the datepicker, and submits with a format for the date that I don't want. However, if I call non-dictionary arguments, there is no logged error but it doesn't display the datepicker. I've tried:
1:  // jQuery('input#day').datepicker('option', 'dateFormat', 'yyyy-mm-dd');
2:  // jQuery('input#day').datepicker('option', 'dateFormat', 'yy-mm-dd');
3:  jQuery('input#day').datepicker();
4:  // jQuery('input#day').datepicker({'dateFormat': 'yyyy-mm-dd'});

3 is what I have now, and it works modulo submitting a value matching /\d{2}-\d{2}-\d{4}/. (I don't know which is submitted as month, does it do the worst of submitting mm/dd/yyyy in one part of the world and dd/mm/yyyy in others?)
1 and 2 are the ones I've tried that seem to convert the datepicker() call into a noop; 4 displays a datepicker and appears to work, but when I submit it after picking a date, the submitted date is empty.
How can I get the result of using the datepicker to match yyyy-mm-dd?

A: jQuery('input#day').datepicker({ dateFormat: "yy-mm-dd" });

Will return a date as four digit year - two digit month - two digit day
jQuery does not use yyyy for a four digit year.
jQuery format date options
Fiddle example


text:
Q: How can I change the class W1 into W2 Situation:
You can make a div bigger or smaller depending if you plus or minus with 1 week.
CSS
.w1{width: 32px;}
.w2{width: 64px;}
.w3{width: 96px;}
.etc...

HTML

    -1 week
    +1 week

Activity

JQuery
$(document).on('click','.j-week',function(e){
    //Get the number (+ or -1)
    var number =$(this).attr('data-week');
    //Select the class wX
    //Get the X and add the number to it
});

How do I get the jQuery working?
I have to work with these 2 conditions.

*

*Sometimes the class is w2 or w3, depending on how the div is
rendered by PHP

*Also the width of 32px is flexible. The user can
choose 3 sizes. Sometimes W1 represents 100px. Sometimes it
represents 200px; The CSS is rendered by PHP.

A: Try This:

$(document).ready(function(){

  $('.js-week').click(function(){

    var w = ($(this).attr("data-week") === '-1') ? -32 : +32;

    var curWidth = $('.w1').width();

    //If you want maximum 96px
    //w = ((curWidth + w) > 96 ) ? 0 : w;

    $('.w1').width(curWidth + w);

  })

})
.w1 {width: 32px;border: 2px solid orange; transition: all 500ms linear; margin-top: 10px;}

.j-week {cursor: pointer;}

  -1 week /

  +1 week

Activity


text:
Q: How to get url from a new window by using Selenium with phantomjs I want to get a new window url by using selenium, and using PhantomJs is more efficient than Firefox.
  python code is here:
from selenium import webdriver
renren = webdriver.Firefox()
#renren = webdriver.PhantomJS()
renren.get("file:///home/xjz/Desktop/html/easy.html")
renren.execute_script("windows()")
now_handle1 = renren.current_window_handle
all_handles1 = renren.window_handles
for handle1 in all_handles1:
    if handle1 != now_handle1:
        renren.switch_to_window(handle1)
        print renren.current_url
        print renren.page_source

In script "windows()", it will open a new window for http://www.renren.com/.
  When I use Firefox,I get current url and context of http://www.renren.com/ .     But I get "about:blank" of the url and "" of the context.It means I get failed when I use PhantomJS.
  So how can I get current url when I use selenium with PhantomJS.
  Thanks a lot.

A: You can add sleep time in your code before getting the current URL.
from selenium import webdriver
renren = webdriver.Firefox()
...
...
...
import time
    time.sleep(10)# in seconds
    print renren.current_url
..


text:
Q: put less values to a bigger 2d array I have a 2D array that I initialize like this: int[][] mat = new int [10][10]. Then I'm asking the user how many rows and cols he want. For example he insert row=3, col=4.
How can I work with this size ([3][4]) so I won't see all the zeros? I just want to insert 12 values to an 100 values array.
int[][] mat = new int[10][10];
int row, col;

do {
    System.out.println("enter rows: ");
    row = s.nextInt();
    if (row > 10) {
        System.out.println("value should be between 1-10, try again ");
    }
} while (row > 10);

do {
    System.out.println("enter cols: ");
    col = s.nextInt();
    if (col > 10) {
        System.out.println("value should be between 1-10, try again ");
    }
} while (col > 10);

mat[10][10] = mat[10 - 10 + row][10 - 10 + col];
System.out.println("enter: " + row * col + " values");
for (int i = 0; i < mat.length; i++) {
    for (int j = 0; j < mat[i].length; j++) {
        mat[i][j] = s.nextInt();
    }
}

A: What about postponing the creation of the matrix:
int row, col;

do{
    System.out.println("enter rows: ");
    row = s.nextInt();
    if (row > 10){
        System.out.println("valuse should be between 1-10, try again ");
    }

}while(row > 10);

do{
    System.out.println("enter cols: ");
    col = s.nextInt();
    if (col > 10){
        System.out.println("valuse should be between 1-10, try again ");
    }

}while(col > 10);
int[][] mat = new int[rows][cols];//create matrix here

Note that by postponing the creation of the matrix, you can allow more than 10 rows or columns. If a person would enter 100 and your program doesn't refuse this, a matrix with 100 rows/columns can be created.
You should also check that the input is greater than (or equal to) zero. Have you ever seen a matrix with -5 rows?
And this statement makes no sense at all:
mat[10][10] = mat[10-10+row][10-10+col];

It won't do any harm, since it is guaranteed that the bounds are correct, but it is useless since the values are initialized on 0.
And a small spelling fix: It's "values"; not "valuse" as well as "zeros" (instead of "zerows", unless you want to sound like a pirate of course ;).


text:
Q: linking an image and image map each located on a different page Is it possible to link an image map from one page to an img within a different page using usemap?
I have my image on "first page" and got the image map on "second page" and I want to link em using usemap attribute, I know that the hash symbol before the map name in usemap value is to indicates that this map exists in this page so I was wondering if I can, in this case, link an image map from another page
here is what I have done :
this is from the first page which contains the img only, this page name is "first.html"
    <img src="https://i.pinimg.com/564x/c5/79/c0/c579c0ebf4c0ea8f7e7f932c87af1cce.jpg" alt="product" usemap="second.html#mapo">

and this is from the second page which contains the img map only, this page name is "second.html"
    <map name="mapo">
        <area shape="rect" coords="390,417,172,191"  href="https://www.pinterest.com/pin/506655026846033319/">
    </map>

both pages/html files r in the same folder
I tried what I mentioned above but it didn't work and I don't know why


text:
Q: importxml xpath in Google sheets I need a some help in getting a ImportXML command to return the result I'm looking for. I'm using Google Sheets. This is the website: https://www.foresteu.com/butorajtok-es-tartozekaik/tomorfa/trieste/10000520000-tomorfa-trieste-116x146mm-mez
This xpath works, but it is way too long: //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][2] | //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][3] | //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][4] | //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][5] | //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][6] | //div[contains(@class, 'col-xs-120 nopad')]/div[contains(@class, 'col-xs-120 nopad')][7]
Can i make it shorter? I can't find a shorter xpath which works.

A: How about this xpath? I think that there might be more simple xpath. So please think of this as one of several answers.
Modified xpath:
//div[@class='col-xs-120 nopad'][./span]

*

*https://www.foresteu.com/butorajtok-es-tartozekaik/tomorfa/trieste/10000520000-tomorfa-trieste-116x146mm-mez is put in "A1".

*

*Formula is =IMPORTXML(A1,"//div[@class='col-xs-120 nopad'][./span]")

*//div[@class='col-xs-120 nopad'] means div that class is col-xs-120 nopad.

*[./span] means div which have span under div.

Result:

If this was not what you want, I'm sorry.


text:
Q: calls to sign_up utility test method in utility.rb fail I'm sort of new to writing tests on Rails, and I'm following along with the RoR tutorial at http://ruby.railstutorial.org.  I'm trying to add my own test utility method, sign_up, similar to the sign_in method already in utility.rb.  When calling it against my sign up page, though, I get this error:
2) User pages index pagination as an admin user to unlock new users
     Failure/Error: sign_up user
     Capybara::ElementNotFound:
       cannot fill in, no text field, text area or password field with id, name, or label 'Name' found
     # (eval):2:in `fill_in'
     # ./spec/support/utilities.rb:33:in `sign_up'
     # ./spec/requests/user_pages_spec.rb:63:in `block (5 levels) in <top (required)>'

My sign_up method looks like this:
def sign_up(user)
  visit signup_path
  fill_in "Name",         with: user.name
  fill_in "Email",        with: user.email
  fill_in "Password",     with: user.password
  fill_in "Confirmation", with: user.password
  click_button "Sign up"
end

It seems to start to go wrong even just visiting the signup_path - I'm not even sure it's going there.  Additionally, if I comment out the fill_in "Name" line, it will just choke on the fill_in "Email" line in the same way.
Any suggestions or ideas on what's going on here would be much appreciated.
Thanks,
-Matt

A: The light bulb finally went on.
When you create a user with the factory, it inserts it into the DB.  SO, when you go to the signup page and try to use that user it already exists and you get redirected to the home page.  This means none of the fields exist to be used with fill_in.  Simplified spec:
require 'spec_helper'

describe "signup page" do
  subject { page }

  describe "with valid information" do
    before { sign_up('em', 'em@em.com', '123456') }
    it { should have_title_and_h1('em') }
  end
end

utility method:
def sign_up(name, email, password)
  visit signup_path
  fill_in "Name",         with: name
  fill_in "Email",        with: email
  fill_in "Password",     with: password
  fill_in "Confirmation", with: password
  click_button "Create my account"
end

will create a user through the browser interface.


text:
Q: How to set JVM options for IntelliJ's RemoteMavenServer? I was playing with -XX:+CompressedOops in IntelliJ's idea.vmoptions and I noticed that the RemoteMavenServer process started by IntelliJ doesn't use those settings.
Adding the option to the Maven runner settings didn't help either.
Is there any way to configure the RemoteMavenServer JVM options?

A: The RemoteMavenServer process will use the JVM options specified in the MAVEN_OPTS environment variable (inherited from the IDEA process).
Please follow: http://youtrack.jetbrains.net/issue/IDEA-60719.

A: Anton's answer is no longer correct. IntelliJ 12.0.1 introduced a new UI for configuring the VM arguments of the RemoteMavenServer process instead of using MAVEN_OPTS:
File -> Settings -> Maven -> Importer -> VM options for maven import process


text:
Q: Spring MVC : How managing to get a java object from a GET request? I am trying to use SpringMVC to handle a form but now I am stuck and I'm here to ask for your help.
When the user submit the form, my controller returns the jsp result page and the user can check what he filled in. In that result page I have 2 buttons, one to send definitively the form and one to modify it.
Here my problem : when I click on modify all the fields of the form are again empty and I would like to keep the value filled by the user.
My controller :
@Controller
@RequestMapping( "/adhesion" )
public class FormController {

//Send the form
    @RequestMapping( method = RequestMethod.GET )
    public String getFormulaire( @RequestParam( value = "user", required = false ) T_demande_adhesion User, Map<String, Object> model ) {
        System.out.println( "user" + User ); //Null everytime
        model.put( "user", User );
        System.out.println( "Envoi formulaire !" );
        return "formulaireAdhesion";
    }

//Handle the form
    @RequestMapping( method = RequestMethod.POST )
    public String gestionAdhesion( @ModelAttribute( "formAdhesion" ) @Valid T_demande_adhesion user, BindingResult erreurForm, Map<String, Object> model )
            throws ServletException, IOException {

        final String CHEMIN_DOC_APP = "C:/DocumentsApp/";
        // Form JSP page
        final String FORMULAIRE_ADHESION = "formulaireAdhesion";
        // Result page
        final String AFFICHER_RESULT = "afficherResult";

        // Objet de validation du formulaire
        ValidationDmdAdhesion demandeAdhesion = new ValidationDmdAdhesion();

//Return AFFICHER_RESULT or FORMULAIRE_ADHESION
        String resultat = demandeAdhesion.validationUser( user, erreurForm, model, FORMULAIRE_ADHESION, AFFICHER_RESULT, CHEMIN_DOC_APP  );

        //putting the object to the request
        model.put( "user", user );

        return resultat;

    }
}

In JSP side I added the parameter 'User' in the request :
'
<input type="button" value="Modifier" onclick="document.location.href='<c:url value="adhesion?user=${user}"/>';" class="boutonAdhesion" />

'
But this send me a string and the url is :
/adhesion?user=com.user.entities.T_demande_adhesion@1dfe8158

When the user clicks on modifiy button (which is in the result page), I would like to get this object @ModelAttribute( "formAdhesion" ) @Valid T_demande_adhesion user on the GET request to fill in the form, in purpose to avoid the user to put again the same informations.
Any help ?
An extract from the form :
Nom *<input type="text" id="nom" name="identite.nom"  value="<c:out value ="${user.identite.nom}"/>" size="35" maxlength="30"  />
<spring-ext:errors path="identite.nom" class="erreur" firstErrorOnly="true"/>

It's here : value="<c:out value ="${user.identite.nom}"/>  that I want to get the value of nom.
Sorry for the English.
Frenchy.

A:
When I click on modify all the fields of the form are again empty and
  I would like to keep the value filled by the user

Because the form data is already available on the page at client side, there is no meaning of submitting the form again to the server & show the same data, which is an unnecessary round trip from the client to the server i.e.,
To keep the data on the form, do NOT to submit the form to the server/controller itself.

How can I check the validation of the information filled in without
  submit the form? How can I display them in my result page?

There is no need to validate the data that the user is anyhow going to modify. So, the validation of the form will be done only after the user completes the modifications and clicks on Submit. Once the validations are successful/failed, your can show the result on the results page.

A: In this case, I didn't find another way than using @SessionAttributes. In this point off my application I didn't to use a session but it seems that there isn't another way.


text:
Q: -webkit-appearance equivalent in CSS3 and IE I've been looking for a good alternative for appearance:none for sometime. I need to have a checkbox which is required to look different.
Also I got to know that CSS3 would be dropping appearance, although major browsers support it now. So, what would be the better alternative for it If I intend to keep the checkbox and not to use button?

*

*IE equivalent to -webkit-appearance?

*MSDN | -webkit-appearance property

*css3 appearance property for IE

*CSS Appearance

A: You can try this

input[type="checkbox"].novisible {
    display: none;
}
.checkboxCl {
  border:1px solid #333;
  width:30px;
  height:30px;
  display:block;
}
input[type="checkbox"].novisible:checked + label {
  border:1px solid red;
  width:30px;
  height:30px;
  background:url("http://www.clker.com/cliparts/a/L/I/b/q/o/green-check-mark-hi.png") 0 0 no-repeat;
  background-size:cover;
}
   <input type="checkbox" class="novisible" id="checkBox">
   <label for="checkBox" class="checkboxCl"></label>

A: You could try the following. This is the link to the documentation.
your selector::-ms-check {
your styles
}

A: After a long search, I found out an alternate method for appearance property.
Easiest of all is making use of :after and :before and hiding the applied object.
Also, it is important to note that IE won't add any content if the property is a checkbox/radio button. Make sure to add a label and for that add :after or :before.


text:
Q: getting International Mobile Subscriber Identity (IMSI) in win32 application I am developing a application, where I need to display the IMSI number from data card which has been plugged in to a vista system.I am using visual studio 2005 and microsoft SDK.
Is there any way to access the IMSI number of the data card(both GSM and CDMA) using any win32 api or any other way to access it
thanks in advance
Vinayaka Karjigi

A: Try to query your mobile device via AT commands using the usually installed serial interface (emulator). If supported, AT+CIM should give you the SIM IMSI.


text:
Q: worklight apps not working on after installed device I am developed sample worklight http adapter. it working fine then i am going to tested for worklight simulator and android simulator it's both are working fine. while i move to install the in that app on android device i am getting error for url connection is failure and connection refuse problem . then i am going customized change the ipaddress and port number on android project for wlclient.properties then generate APK file it's working fine. this is right way to develop the application or otherwise any configuration level shall i do this? please any think let me shared information

A: by default WL studio will inject one of the IPs available on your machine. If you're using WL 5.x you can change worklightServerRootUrl property in application-descriptor.xml
If your on WL 6.x right-click your app and select run->build for remote server


text:
Q: Bind mvvm light Relaycommand to page loading event I am working on Window phone 8.1.
I have a RelayCommand command which executes some method async.
I want to know how can I bind a page load event from a page to the RelayCommand in the view model?
All the example I see are binding RelayCommand to a Button.
How can I bind that to page load event? I see some example uses EventToCommand. But I am using Window phone 8.1, I dont' think I have the behaviour stuff some article I saw.

A: Make sure you add Behaviors extension to your References

then define that the event trigger invokes a command:
<Page
    x:Class="App31.PivotPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App31"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:App31.Data"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    mc:Ignorable="d">
    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Loaded">
            <core:InvokeCommandAction Command="{Binding MyCommandInTheViewModel}" />
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
//....
//.. rest of page code

Where MyCommandInTheViewModel is the command in your VM, and the DataContext of the page is set to your VM.


text:
Q: How to wrap multiples of images in divs? I am trying to wrap some divs round images using PHP to show a max of 8 images per div.
I am using custom fields WordPress plugin to pull out the images of the team but the need to wrap them in divs. I have it part working but it doesn't show a div for the remainder. I'm not sure if this is the best way but this is my code below.
function team($i,$t){

    $values = get_field('team_member'.$i);

if($values["url"]){

$answer = $i / 8;

    if(is_int($answer)){

        echo '
'. "\r\n";
        echo $t;
        $t  =   '';
        echo '
'. "\r\n";

    }

    $t .=''. "\r\n";
    $t .=''. "\r\n";
    $t .=''. "\r\n";
    $i = $i+1;

    team($i,$t);
    }

}

team(1,'');

I am trying to get a result like below.

    ..

    ..

    ..

A: Your method is confusing and hard to read. Take a look at this example and go from there.
$images = array('bear.jpg','cat.jpg','owl.jpg','dog.jpg','bird.jpg');
$itemsPerDiv = 3;
$count = 0;
echo '
';

foreach($images as $img)
{
    if ($count % $itemsPerDiv == 0 && $count != 0)
    {
        echo '

';
    }

    echo '';

    $count++;
}

echo '
';

This will output

If you need an explanation on how this works let me know. I think your problem is your using the division operator and not MOD which is a lot more suitable in this case as it determines the remainder which you are missing out.


text:
Q: Can't open browser from a terminal in Linux I've logged into Linux machine.
I issued the following commands to open a browser on the Linux server.
Still, I am unsuccessful.
07:53 AM tomcat@wb-ser1$ nautilus .
-bash: nautilus: command not found
07:53 AM tomcat@wb-ser1$ nautilus
-bash: nautilus: command not found
07:53 AM tomcat@wb-ser1$ xdg-open http://google.com/
-bash: xdg-open: command not found
07:53 AM tomcat@wb-ser1$ xdg -open http://google.com/
-bash: xdg: command not found
07:53 AM tomcat@wb-ser1$ lynx
-bash: lynx: command not found
07:55 AM tomcat@wb-ser1$ xdg-open http://stackoverflow.com
-bash: xdg-open: command not found
07:56 AM tomcat@wb-ser1$
07:56 AM tomcat@wb-ser1$ firefox
-bash: firefox: command not found

A: By the looks of it, you are on a Linux machine with no web browser installed.
To see what things are "installed" on the machine, first check the search path of your shell:
echo $PATH

This should yield a list of dirs seperated by ':'.  Like so:
/bin:/usr/bin:/usr/local/bin

next, you can list the files in each (probably a huge number, if it's a desktop install of linux):
ls /bin
ls /usr/bin
...

A: if you want to download the HTML, you just need to run wget or curl command
wget http://stackoverflow.com


text:
Q: Derive the level curves of the function by using polar coordinates. $F(x,y)= {2xy \over x^2+y^2}$ when $(x,y)$ is non-zero.
And $F(x,y) = 0$ when $(x,y)$ is zero.
I tried to solve this with beginning from when $z=1$ and I can't go on when $z=c ( > 1 ).$
( When $z=2 , (x-y/2)^2 + 3/4 y^2 = 0$ and it doesn't make sense. )
And also I can't understand polar coordinates method well.
Please help me

A: To convert to polar, you just have to substitute $x=r\cos\theta$ and $y=r\sin\theta$.  Your level curves become $$c = \frac{2r\cos\theta r\sin \theta}{r^2\cos^2\theta + r^2\sin\theta} = 2\cos\theta\sin\theta = \sin 2\theta.$$  Those should be familiar curves(?)


text:
Q: Vuescan problems I am a Ubuntu newbie, trying to get vuescan to work on my Ubuntu system, but with no luck. The software appears to install OK on my Lenovo, and the program opens up fine, but there does not seem to be any connection between PC and scanner. Vuescan works perfectly fine on my iMac and old apple laptop, so the scanner works just fine.
I've contacted ed Hamrick with details of the Vuescan.log file, after looking at this, he suggested it might be a problem with a missing libsys folder, but my version 16.04 has this installed.
Any suggestions as to what to check next would be welcome.
Thanks, Ken
system details:
Lenovo-G500
Intel® Core™ i3-3110M CPU @ 2.40GHz × 4
OS type Ubuntu 64 bit Version 16.04
canon scanner 9950
Vuescan version 9 x64  9.5.59 for linux


text:
Q: Run-time Exception Handling I am trying to define a generic error handling for my apex application. I have my try/catch blocks in controllers/extensions at various methods. I am able to check and catch business logic related exceptions ( and all other checked exceptions ). My question is related to unhandled or run time exceptions.
Is there a way to handle run time exceptions at a central level and show a generic error page (instead of system error page shown at present). Error handling needs to be elegant.
I know of similar features in java but was wondering if any such feature is available in apex as well.
Any pointers will be greatly appreciated.

A: You should be able to "predict" some of the run-time exceptions related to the platform governor limits by using the Limits Class, however I haven't seen anything yet that allows to handle a generic run-time exception.

A: Yeah, unfortunately, there are many "uncatchable" exceptions generated by Salesforce. Implementing Database.RaisesPlatformEvents will allow you to handle all exceptions thrown from a batch process - even the "uncatchable" ones. But other than that, the best shot you've got is to have disciplined development processes and follow best practices to avoid them.
Error handling / code quality is a personal passion of mine. I've created a library (Apex BOOST) that might provide you with some helpful boilerplate error handling. It includes persistent logging that works even if an exception rolls back the transaction, custom debug and assert methods with some huge benefits, and lots of productivity utilities. I'd love to get your impressions if you're interested in taking a look.


text:
Q: How can I redirect a specific URL to another after a delay? whenever I end up on a certain page, which has a certain URL ("A"), i want my browser (Chromium) to wait there 10 seconds (without doing nothing else) and then automatically redirect me to another specific URL ("B")
"A" is a page on a website that sometimes is automatically redirected to "B" in a few fractions of  a second (if some conditions are satisfied), but sometimes isn't and it remains stuck there for the rest of its lifetime
I want to force the redirection to happen in every case, and 10 seconds are enough to see if the automatic redirection happened or I have to make it happen in another way
I've found several Chrome extensions that can set up an automatic redirect request, like Requestly or Redirector, but with none of those it's possible to add a "waiting" feature before the redirection
however, Requestly (the most advanced one) allows to load custom CSS or JS code to run it
I don't know absolutely nothing about programming, so what could I write to make the extension do what I want to do?
at least two algorithms could work; a simpler one "detects when I end up on "A", wait 10 s and then redirect to "B" no matter what", or a more sophisticated one "detects when I end up on "A", wait 10 s, see if I'm still on "A" and if yes then redirect to "B" "
thanks in advance for the help!

A: setTimeout(
  function() {
    window.location.replace("http://stackoverflow.com");
  }, 10000);

EDIT:
If you want it to work for a specific page, you can wrap it with an if statement.
if (window.location.href === 'https://youtube.com') {
      setTimeout(
        function() {
          window.location.replace("http://stackoverflow.com");
        }, 10000);
}


text:
Q: SWT List cell renderer How to set a cell renderer for SWT list? I want to have a list with text, and every line must have a different foreground.

A: Sorry, but that cannot be done for list, only for a Table. See Table example snippet: draw different foreground colors for text in a TableItem.


text:
Q: issue with onKeyDown functionality in react app I am new to React and creating a calculator app with React-Redux to gain knowledge of the framework.
The app is working with the onClick event but some issues are there. I have created a sandbox for anyone to see.
https://stackblitz.com/edit/react-dezmon
While doing my Calculator app, I am facing 2 challenges.

*

*onKeyDown not working. Basically I want the same functionality as it is happening in the onClick event (which is working fine).

*After any operation (after clicking '='), when I click on any other digit, the previous state is not clearing. For eg, if I add 52 + 6, after clicking = when I click on any digit(2 for eg) it is picking as 62. It should clear basically.

Any help is very much appreciated.

A: You cannot use onKeyDown directly on your <Digits> because the event only fires when the element is currently focused and only 1 element can be focused at a time in a page.
What you need to do is to move your onKeyDown to the parent, and put this listener on the parent element.
Therefore the way you should handle the event is to parse which key on keyboard is being tapped, then run your operation based on that information.
See it here: https://stackblitz.com/edit/react-pmmntj


text:
Q: SharePoint 2013 search in List I'm quite new to SharePoint and hope this is the right place to ask. A through web search could not give me or my colleagues the answer.
We made a new list with information about employees and when they made certain certificates. The users started using the list and searching for people, to find out if they are allowed to do certain things which are only allowed due to the certifications.
When typing only one part of the name, let's say "Smi" out of "Smith" you need to use the Asterisk "*" to get search results.
The problem is with some names, for example "Zimmermann" the search gets results when you only search for "mann". Another Example would be "Eck" instead of "Eckes". In this case "Eck" will already lead to the correct search results.
Can someone please lead me to the right direction why the search only works like this sometimes? Our users are annoyed that sometimes they need to use the Asterisk, sometimes not.
We are a bit restricted, as such we do not have access to CA / Powershell / Designer.
Sorry for my kinda broken englisch.

A: It's just the way the javascript handles the info.
From what i've noticed, it's the second word after a space that causes confusion.
so Bo in Bob will find correctly, but his last name Joe
when you search Jo it won't find it.
There is a work around for this, which can be done by manipulating the search properties with javascript. If you do some browsing on stackoverflow, I know i've read about this and saw a sample code you can use.

A: There are a couple of websites that helped me understand how Search works. Text searches go from left to right so you can only add an wild card "*" at the end of some text. Search wont return results from characters in the middle of a word.
Keyword Query Language (KQL) syntax reference:
https://docs.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference
2 ways to search for files in SharePoint - Blog SharePointMaven:
https://sharepointmaven.com/2-ways-to-search-for-files-in-sharepoint/
icanSharePoint - blog search infographic:
http://icansharepoint.com/infographic-search-sharepoint/


text:
Q: Web-scraping Remax.com in python I am trying to follow the tutorial here to scrape data from Remax.com. At the moment I am just interested in getting the sqft of a particular home. Although I get this error:
Error during requests to https://www.remax.com/realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html : HTTPSConnectionPool(host='www.remax.com', port=443): Max retries exceeded with url: /realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-28b8e2248942> in <module>()
      1 raw_html = simple_get('https://www.remax.com/realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html')
----> 2 html = BeautifulSoup(raw_html, 'html.parser')
      3 for i, li in enumerate(html.select('li')):
      4         print(i, li.text)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\bs4\__init__.py in __init__(self, markup, features, builder, parse_only, from_encoding, exclude_encodings, **kwargs)
    190         if hasattr(markup, 'read'):        # It's a file-type object.
    191             markup = markup.read()
--> 192         elif len(markup) <= 256 and (
    193                 (isinstance(markup, bytes) and not b'<' in markup)
    194                 or (isinstance(markup, str) and not '<' in markup)

TypeError: object of type 'NoneType' has no len()

Here is my entire code thus far:
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup

def simple_get(url):
    """
    Attempts to get the content at `url` by making an HTTP GET request.
    If the content-type of response is some kind of HTML/XML, return the
    text content, otherwise return None.
    """
    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None

    except RequestException as e:
        log_error('Error during requests to {0} : {1}'.format(url, str(e)))
        return None
def is_good_response(resp):
    """
    Returns True if the response seems to be HTML, False otherwise.
    """
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status_code == 200
            and content_type is not None
            and content_type.find('html') > -1)

raw_html = simple_get('https://www.remax.com/realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html')
html = BeautifulSoup(raw_html, 'html.parser')
for i, li in enumerate(html.select('li')):
        print(i, li.text)

I am pretty new to web scraping so I am not sure how to fix this. Any suggestions would be greatly appreciated.

A: Not sure about your question, but if all you're interested is the square footage of the house on that page, you can use
    import urllib
    from bs4 import BeautifulSoup

    url = 'https://www.remax.com/realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html'

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
   'Accept-Encoding': 'none',
   'Accept-Language': 'en-US,en;q=0.8',
   'Connection': 'keep-alive'}

    request = urllib.request.Request(url, headers=hdr)
    html = urllib.request.urlopen(request).read()

    soup = BeautifulSoup(html,'html.parser')
    foot = soup.find('span', class_="listing-detail-sqft-val")
    foot.text.strip()

Output:
'7,604'

A: Your simple_get() function has been made to return None if the request fails. You should therefore test for this before using it. This could be done as follows:
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup

def simple_get(url):
    """
    Attempts to get the content at `url` by making an HTTP GET request.
    If the content-type of response is some kind of HTML/XML, return the
    text content, otherwise return None.
    """

    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None

    except RequestException as e:
        log_error('Error during requests to {0} : {1}'.format(url, str(e)))
        return None

def is_good_response(resp):
    """
    Returns True if the response seems to be HTML, False otherwise.
    """
    content_type = resp.headers['Content-Type'].lower()

    return (resp.status_code == 200
            and content_type is not None
            and content_type.find('html') > -1)

url = 'https://www.remax.com/realestatehomesforsale/25-montage-way-laguna-beach-ca-92651-gid100012499996.html'
raw_html = simple_get(url)

if raw_html:
    html = BeautifulSoup(raw_html, 'html.parser')

    for i, li in enumerate(html.select('li')):
            print(i, li.text)
else:
    print(f"get failed for '{url}'")

So to simplfy, the following would give you the same error message:
from bs4 import BeautifulSoup

html = BeautifulSoup(None, 'html.parser')


text:
Q: How to fix "Extra argument 'at' in call" in swift's playground I've got a problem with some code. While I was writing function to define variables in a table I had an "Extra argument 'at' in call" error. I was trying many, many things (including rewritting code from Udemy lesson) and sadly it is not working still.
Here's the code:
var tablica = [0,0,0,0,0,0]

func przypisywanie (position: Int) {
   tablica.insert(Int(arc4random() % 49) + 1, at: position ) {
   }
}

Thanks
Btw sorry if it is a silly question, but I'm complete beginner.

A: Delete the extra curly braces:
var tablica = [0,0,0,0,0,0]

func przypisywanie (position: Int) {
    tablica.insert(Int(arc4random() % 49) + 1, at: position )
}


text:
Q: Dynamically added radio button does not trigger click function There is a office list of radio button that a user can click on that will display the office information in a div. I have an option for the user to add an office to a list of radio buttons. When the user fills out the form, the radio button successfully gets added to the list but the click function does not trigger therefore does not update the office information in the div.  When I click the other radio buttons the div does get updated, just when I click the dynamically added radio button.  I have tried using .delegate() to the click function since the radio button was added after the initial page load, but without success.
Any help would be greatly appreciated!!!
How the radio button is added:
$(document).on("click", "#addOffice", function() {
  var officeadd = $('#officeAddForm').serializeArray();
  //console.log(officeadd);
  $.ajax({
      url:      'officeadd.php',
      type:         "POST",
      data:         officeadd,
      dataType: "json",
      success: function(data) {
              console.log(data);
              if(data.errorCode[0] === 'ok') {
                console.log('NO ERRORS');
                console.log(data.officeInfo[1]);
                $('#officecontrolgroup > div.ui-controlgroup-controls').append('<input type="radio" name="office" id="office' + data.officeInfo[0] + '" value="' + data.officeInfo[0] + '"/>' + data.officeInfo[1] + '').trigger('create');
                $('#officecontrolgroup').controlgroup("refresh");
                $("#deliveryInstructions").trigger("updatelayout");
                $('#officeAddForm').trigger('reset');
                var $office = '#office'+ data.officeInfo[0];
                console.log($office);
                $(function(){

                    $($office).prop('checked', true).checkboxradio("refresh");
                    $($office).trigger('click');
                })

      }
  });
  return false;
});

Click function for the radio buttons named office:
$('input[name=office]:radio').on('click', function() {
var $value = $(this).val();
console.log($value);
$.ajax({
    url:        'officeget.php',
    type:       "POST",
    data:       {q: $value},
    dataType:   "json",
    success: function(data) {
            console.log(data.officeName);
            $('#docoffice').hide();
            $('#docoffice').html(data.officeName).fadeIn(1000);
            $('#docaddress').hide();
            $('#docaddress').html(data.officeAddress).fadeIn(1000);
            $('#docsuite').hide();
            $('#docsuite').html('Suite '+data.officeSuite).fadeIn(1000);
            $('#doccitystate').hide();
            $('#doccitystate').html(data.officeCity+', '+data.officeState+' '+data.officePostalCode).fadeIn(1000);
            $('#docphone').hide();
            $('#docphone').html(data.officeTelephone).fadeIn(1000);
    }
});
});

HTML
<form id="officeChoice" class="submition">

<fieldset id="officecontrolgroup" class="ui-corner-all ui-controlgroup ui-      controlgroup-vertical ui-mini" style="margin-top:0px; width:100%;" data- mini="true" data-role="controlgroup" aria-disabled="false" data-disabled="false" data-shadow="false" data-corners="true" data-exclude-invisible="true" data-  type="vertical" data-init-selector=":jqmData(role='controlgroup')">

</fieldset>
</form>

Solution:
For this to work I need to change the 'click' to a 'change' event.
$('#officeChoice').on('change','input[name=office]:radio', function() {...

Fiddle Demo

A: you would need to delegate the event
$(container).on('click', 'input[name=office]:radio', function() {

Because your radio button was non existent at the time the event was bound.
container is the closest ancestor element on your DOM in which the radio elements are present.


text:
Q: AttributeError: type object 'Cliente' has no attribute 'query' This is my first project using Python.
I'm encountering a problem while displaying the values in my table.

AttributeError: type object 'Client' has no attribute 'query'

from flask import Flask, render_template, request, url_for, redirect
import os
from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref,sessionmaker

engine = create_engine('sqlite:///banco.db', echo=True)
db = declarative_base()

class Cliente(db):
    __tablename__ = 'cliente'

    _idCliente = Column(Integer, primary_key =True, autoincrement = True)
    nmCliente = Column (String)

    def __init__ (self, nmCliente):
        self.nmCliente = nmCliente

db.metadata.create_all(engine)

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route("/cadastros/cliente")
def cadastroCliente():
    return render_template ("cadastroCliente.html")

@app.route("/cadastrar/cliente", methods=['GET','POST'])
def cadastrarCliente():
    if request.method == "POST":
        nmCliente = request.form.get("nmCliente")

        if nmCliente:
            c = Cliente(nmCliente)
            db.session.add(c)
            db.session.commit()

    return redirect(url_for("cadastroCliente"))

@app.route("/consulta/cliente")
def consulta():
    cliente = Cliente.query.all()
    return render_template("consultaClientes.html", cliente = cliente)

if __name__ == '__main__':
    app.run(debug=True)

Python 2.7, what should i change?
I followed some tutorials and it worked

A: You query like that when using Flask-SQLAlchemy (from flask_sqlalchemy import SQLAlchemy)
In your code, you will need to use session, because you are using SQLAlchemy. So import session maker like this
from sqlalchemy.orm import sessionmaker

Then below engine = create_engine('sqlite:///banco.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

Then do your query using session
cliente = session.query(Cliente).all()

You can see the pros and cons of using Flask-SQLAlchemy (more integrated with flask) here and see you would want to go with it


text:
Q: Are there any thread managers java I have been making a threadmanager class in java and wanted it so you could input a class and it would run the threadrun method in that class but when I write my code my ide says:cannot find symbol threadrun
Code:
package thenetwork;

/**
 *
 * @author Jman
 */
public class Threadmanager implements Runnable
{
    Class clas;
    Object parameter1 = null;
    public Threadmanager(Class classobj)
    {
        clas = classobj;
    }
    public Threadmanager(Class classobj, Object param1)
    {
        clas = classobj;
        parameter1 = param1;
    }
    public void run() {
        if(parameter1 != null)
        {
            clas.threadrun(parameter1);
        }
        else
        {
            clas.threadrun();
        }
    }

}

If this is not clear comment it and I will edit my post
Edit:I need this class to be able to run multiple types of other classes

A: java.lang.Class doesn't have a method called threadrun.

A: I don't understand what you want this "thread manager" class to do, but for your information, this is the way that you launch a thread in Java:
Thread th = new Thread(runnable);
th.start();

This will create and start a new thread, and the thread will execute the code of the Runnable supplied as an argument.
The Runnable interface does not directly provide a way to pass a parameter into the run() method, but you can achieve the same effect by implementing other methods, implementing a constructor or by coding the run method to retrieve a value from an enclosing scope (if it is implemented as an inner class ...)

To answer the question expressed in the Question title: yes Java does have standard thread managers, and there are also third-party libraries that implement this kind of thing.  I'd recommend that you read the tutorial that @BalusC linked to ... and don't try to implement your own thread manager / thread pool.

A: There are lower-level constructs, like Thread that you can use, but I recommend starting with an ExecutorService. It handles most common threading needs, in a safe and robust manner.

A: Threadrun isn't an function of class.

A: You're missing an invocation of newInstance() against your class argument.  If you try to reference the class object directly, you're only going to be able to use methods available to the type Class rather than the type of class your object represents.  Your class should probably look something like (I've left out the parameter logic):
public class Threadmanager implements Runnable {
  MyThreadRunObject object;

  public Threadmanager(Class classobj) {
    object = (MyThreadRunObject) classobj.newInstance();
  }
  ...
  public void run() {
    object.threadrun();
  }
}

Additionally, if you're using Java 1.5+, I'd generify your class argument.  The nice thing about generifying it is that you can do a bounded generic type of T extends ThreadRunnable and put your threadrun method in an interface, allowing you to restrict the types your ThreadManager class would take as a class argument.


text:
Q: Force GVim to prompt before close I've been making a transition to GVim lately, because I find it to be more aesthetically pleasing and a little bit faster then vim in the terminal. I have this really bad habit that I'm trying to break. When I used vim from the command line my work flow was like this:
vim filename.txt
# make some edits
ZZ
# do other stuff
vim otherfile.txt
# make some edits
ZZ

Now using GVim, I end up closing the editor far too frequently. I'm wondering if there is a way to force just GVim to either prompt me or open an empty buffer when I do a :wq or ZZ. Any ideas?
EDIT: I know how to remap keys, but I'm wondering if there is a way to force GVim to have a different behavior then when vim is called from the command line.

A: Call a function on ZZ and if there is only one tab and window left, prompt whether to close or not (default is to close). See :help confirm().
nnoremap ZZ :call QuitPrompt()<cr>

fun! QuitPrompt()
   if has("gui_running") && tabpagenr("$") == 1 && winnr("$") == 1
      let choice = confirm("Close?", "&yes\n&no", 1)
      if choice == 1 | wq | endif
   else | wq | endif
endfun

A: Putting the following in your vimrc could be used to completely disable the ZZ shortcut altogether:
nnoremap ZZ   <Nop>

Or you could remap them to the standard behaviour of :q :
if has("gui_running")
    nnoremap ZZ :q
    nnoremap :wq :q
endif

A: Add this in your .vimrc:
set confirm

A: Gvim and vim handle quit a little differently.  Option 1 works as you would expect in both.  Option 2 works nice in vim, but in gvim you can get around it (in part) by pressing the "X" to close in X Windows. It will still confirm if the file is unedited, but it will just quit everything when everything is saved.  Maybe someone else knows how to deal with that issue.
Option 1: Confirm quit only when a file is unsaved
Add this in your .vimrc:
set confirm

Option 2: Confirm quit all the time (when you do ZZ or q)
Use this plugin
 Plugin 'vim-scripts/confirm-quit'

Or hand code it, following along with this to see what you need to do (BTW -- this plugin was born from this SE Question)


text:
Q: What is the best way to switch between projects in Vim? I use CtrlP to get around files within a project (which can usually be defined as being a git repo root), but often find myself using :cd to switch between different projects which seems unnecessarily time consuming.
I'd like vim to be able to remember different git repo roots I have visited and quickly jump between them.  Once there, all the files in the repo will be available to CtrlP and I can get to where I want.
Is there some way to get what I want with an existing plugin?

A: If you use fugitive.vim then I might have an option for you.
Put the following in your ~/.vimrc file:
set viminfo+=!

if !exists('g:PROJECTS')
  let g:PROJECTS = {}
endif

augroup project_discovery
  autocmd!
  autocmd User Fugitive let g:PROJECTS[fnamemodify(fugitive#repo().dir(), ':h')] = 1
augroup END

command! -complete=customlist,s:project_complete -nargs=1 Project cd <args>

function! s:project_complete(lead, cmdline, _) abort
  let results = keys(get(g:, 'PROJECTS', {}))

  " use projectionist if available
  if exists('*projectionist#completion_filter')
    return projectionist#completion_filter(results, a:lead, '/')
  endif

  " fallback to cheap fuzzy matching
  let regex = substitute(a:lead, '.', '[&].*', 'g')
  return filter(results, 'v:val =~ regex')
endfunction

Overview
The idea is that anytime fugitive activates a buffer the script stores the project directory path inside a g:PROJECTS dictionary. Adding ! to 'viminfo' will store capitalized global variables to the viminfo file thereby making the discovered projects persist. Once fugitive discovers a project the :Project command can be used to :cd to that directory with completion.
Notes and Warnings

*

*I have not tested any of this code. Use as-is.

*Requires Fugitive.vim

*Optionally uses Projectionist.vim completion if available

*Feel free to add directory paths to g:PROJECTS by other means

*Must visit a repository so that it can be discovered

*There is no clean up for missing project directories

*Vim has no concept of "project" so there is only so much that can be done

A: Try vim-rooter: when you enter a buffer it automatically changes directory to the buffer's "root" (e.g. git repo root) directory.

A: This tip suggests using uppercase marks as 'file bookmarks'.

For example, open your .vimrc, press mV, and close Vim. The next time you want to edit your .vimrc, just press 'V to open it.

A: Just put two project in a new directory, and open Vim in this directory, then you can use ctrlP to open file in both projects.
If you don't want to move the project, create soft link and put them in one directory.


text:
Q: What is a dynamic callback? I'm following Learn C The Hard Way online.
At a point the author talks about "dynamic callback" to a function.
Could someone explain me what it is exactly because I didn't get it?
EDIT
For context, here's an extract from Learn C the Hard Way:

Practical Pointer Usage

There are primarily four useful things you can do with pointers in C code:

• Ask the OS for a chunk of memory and use a pointer to work with it. This includes strings and something you haven't seen yet, structs.

• Pass large blocks of memory (like large structs) to functions with a pointer, so you don't have to pass the whole thing to them.

• Take the address of a function so you can use it as a dynamic callback.

• Scan complex chunks of memory, converting bytes off of a network socket into data structures or parsing files.

For nearly everything else, you might see people use pointers when they should be using arrays. In the early days of C programming, people used pointers to speed up their programs, because the compilers were really bad at optimizing array usage. These days, the syntax to access an array versus a pointer are translated into the same machine code and optimized in the same way, so it's not as necessary. Instead, you should go with arrays whenever you can, and then only use pointers as a performance optimization if you absolutely have to.

Excerpt From: Zed A. Shaw. "Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) (Brianne Kwasny's Library)."

A: One thing the author could be talking about is a function pointer
function getTokens(void (*callback)(char *)) {
   char *c;
   while(true) {
       c = malloc(100 * sizeof(char));
       if(scanf("%s", c) != 1) {
           break;
       }
       callback(c);
   }
   calloc(c);
}

Here, the function callback is called with each string read from standard input.
callback could do anything, and it passed to getTokens dynamically at runtime.
void printToken(char *c data) {
    printf("%s\n", data);
}

void ignoreToken(char *c) {
}

void (*tokenCallback)(char *) = (1 + 1 == 2) ? &printToken : &ignoreToken; //"dynamic"
getTokens(tokenCallback);


text:
Q: How to make div's height AND background image stretch to wrap around all content in the div? I while ago while making a site, I didn't set a height for a div section and filled it with content. Then I set the background-image to an image, and the image/div stretches to wrap the content since there is no height. I have been trying to replicate it but every time I do the same thing, the background image disappears but the content is still there (white text, can't see unless selected). This happens when I set it like:
#main{
    background-image: url("images/pizza-dark.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    clear: both;
}

I know there is a way to do this but I'm not quite sure. This is crucial to the site because I am using bootstrap columns and a set height won't give a good result on mobile. In the JSFiddle below, there is no set height and, as you can see, the background image doesnt show at all. Even if you set it to 100%, the content that folds down (coloumns from Bootstrap) wont show since the background image doesnt stretch that far.. I have tried height:auto too and that doesn't work either.
Here is a JS Fiddle:
https://jsfiddle.net/du53n862/
Thanks!

A: You forgot to add float property to main container. You can use vh units for the main container height, and it will fits to every screen size:
#main {
background-image: url("http://itspizzatime.ca/wp-    content/uploads/2015/09/4791207-9790062099-Pizza1.jpg");
background-repeat: no-repeat;
background-size: cover;
float: left;
width: 100%;
height: 100vh;
}

Here is a fiddle: fiddle link

A: I'm not sure if this is the behavior you want, but if you add a height of 100% and a scrolling overflow to your main div, the image will just be a fixed full-cover image in the background. This seems to be working fine in this fiddle.
#main {
  height: 100%;
  overflow: scroll;
  ...
}

A: This issue can easily be solved with flexbox. If you can drop support of older browsers here is the simple solution https://jsfiddle.net/1p1k41ot/.
I just added few lines in #main
#main {
...
display: flex;
flex: 1 1;
height: 100%;
}


text:
Q: windowing and Watermarking per key in Flink 1.15 I am using Flink 1.15 and trying to apply watermark on a keyed stream.
Here is my implementation,
`
var keyedUnifiedDistanceStream = odoDistanceStream.keyBy(msg ->
msg.getKey().getVehicleId()).assignTimestampsAndWatermarks(new
IdleDetectionTimestampExtractor());

`
I want to apply a window function on above result stream so that I can grab distance for each vehicle. Something like below
`
var outputStream = keyedUnifiedDistanceStream.Window(
      EventTimeSessionWindows.withGap(Time.seconds(WAIT_TIME_BEFORE_PUBLISHING_SEC)))
            .allowedLateness(Time.minutes(1))
            .process(new UnifiedDistanceOperator())

`
But somehow I am not getting window function instead it provides me windowAll function.
however, if I do below I am getting reference to Window -
`
var unifiedDistanceResultStream = keyedUnifiedDistanceStream.keyBy(key ->
              key.getKey().getVehicleId())
.window(EventTimeSessionWindows.withGap(Time.seconds(WAIT_TIME_BEFORE_PUBLISHING_SEC)))
            .allowedLateness(Time.minutes(1))
            .process(new UnifiedDistanceOperator())

`
Can someone please tell me -

*

*What is difference between 2 implementations?

*Where am I going wrong with first implementation.


text:
Q: Not seeing expected database/user in Docker postgres:* I am dockerizing an existing Django application, but am struggling with initializing a database and connecting. My db service starts up with the following config, which looks right to me:
db:
build:
  context: /Users/ben/Projects/project-falcon/project-falcon-containers
  dockerfile: Dockerfile-db-local
environment:
  POSTGRES_DB: falcon_db
  POSTGRES_PASSWORD: falcon
  POSTGRES_USER: falcon
ports:
- 5432:5432/tcp
restart: always

At this point, I would expect the separate api container to be able to connect but instead I get
django.db.utils.OperationalError: FATAL:  role "falcon" does not exist

the relevant settings file:
from .dev import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_SERVICE'],
        'PORT': os.environ['DB_PORT']
    }
}

which is built in api and configured thus
api:
 build:
   context: /Users/ben/Projects/falcon/falcon-backend
   dockerfile: Dockerfile
 depends_on:
 - db
 - redis
 environment:
   DB_NAME: falcon_db
   DB_PASS: falcon
   DB_PORT: '5432'
   DB_SERVICE: db
   DB_USER: falcon
 ports:
 - 8001:8001/tcp
 volumes:
 - /Users/ben/Projects/falcon/falcon-backend:/falcon:rw

So based on the documentation for the postgres container I expected the POSTGRES_* variables to create the user/database Django expects to connect as/to. But the error message sure makes me think it did not. So based on the docs and the following question:
How to create User/Database in script for Docker Postgres
I tried the older method of specifying a specific .sql file to run
#init.sql

CREATE USER falcon WITH PASSWORD 'falcon';
CREATE DATABASE falcon_db;
grant all privileges on database falcon_db to falcon;
ALTER USER falcon CREATEDB;
CREATE EXTENSION adminpack;

which is specified in the db service's Dockerfile
FROM postgres:alpine
COPY init.sql /docker-entrypoint-initdb.d/

Do I understand the documents correctly? Am I interpreting the error correctly? Is there a problem with the unix users on the VM? Any help will be much appreciated.


text:
Q: Run controllers only after initialization is complete in AngularJS with angular-global-resolve I am having a problem where my controllers are running before initialization of my app, and I came across this NPM package that works almost perfectly.  The only problem I'm having is the initialization function runs twice at almost the same time when the app starts.
Here is the relevant code:
app.config(function($stateProvider, $urlRouterProvider, $locationProvider, globalResolveProvider){

  $urlRouterProvider.otherwise('/venues/feed');

  globalResolveProvider.addGlobalDependenciesTo($stateProvider, {
    getGlobalDependacies: function ($http, $rootScope, $cookies) {
      'ngInject';
      if ($rootScope.apiUrl){
        return
      }
      console.trace('do stuff')
        return $http.get('/__/env.json')
        .then(function(response) {
          $rootScope.apiUrl = response.data.apiUrl;
          $rootScope.googleMapsApiKey = response.data.googleMapsApiKey;
          $rootScope.currentLocationLat = 40.7589;
          $rootScope.currentLocationLng = 73.9851;
        })
        .then(function(){
          hotelId = ''
          if ($cookies.get('hotel') === undefined){
            $http.get($rootScope.apiUrl + '/hotels')
            .then(function(dbHotels){
              hotelId = dbHotels.data[0]._id
              $cookies.put('hotelId', hotelId)
            })
          }
          if ($cookies.get('userId') === undefined){
            $http.get($rootScope.apiUrl + '/users')
            .then(function(dbUsers){
              index = dbUsers.data.length - 1
              userId = dbUsers.data[index]._id
              $cookies.put('userId', userId)
              $rootScope.$broadcast('update-itinerary-icon')
            })
          }
        })
    }
  })

  $stateProvider
  .state('venues', {
    url: '/venues',
    abstract: true,
    template:'<div ui-view></div>'

  ....more states....

  $locationProvider.html5Mode(true);
});

Any Idea on why this might be running twice?


text:
Q: Are there JNDI namespace conventions? I have downloaded JBoss EAP 6.1 and I am going to add a new data source. I must bind the data source to a JNDI name. By reading the JNDI name of the sample data source which is:
java:jboss/datasources/ExampleDS

I see that they have used datasources after java:jboss. Is this just a naming convention - that I am not able to find anywhere - or would it be fine using java:jboss/bananaboat/MyDS?`
Is it correct that the first part that is listed below - such as java:comp is the scope and the rest is just normal hierarchy organization?
java:comp/ - The namespace is scoped to the current component (i.e. EJB)
java:module/ - Scoped to the current module
java:app/ - Scoped to the current application
java:global/ - Scoped to the application server

https://docs.jboss.org/author/display/AS71/JNDI+Reference

A: I had to answer the same question to myself and pulled these links together.
In short, JNDI Naming Policies can be any but JEE defines its own:

JNDI is defined independent of any specific naming and
directory service implementation.
However, one important platform that does define a limited set of
naming policies for using the JNDI is ... JEE.

This would be the most conventional name for the datasource:

The enterprise namespace is rooted in a URL context for the java URL scheme.
For example, a JDBC Salary database might have the name "java:comp/env/jdbc/Salary".

*

*... comp is bound to a subtree reserved for component-related bindings.

*... env is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor.

*Resource factory references are placed in subtrees differentiated by their resource manager type.

*

*...jdbc for JDBC DataSource references.

JEE 7 Tutorial also details naming policies to reference EJBs in 32.4.1.1 Portable JNDI Syntax.
Note that @Resource annotation to inject DataSource often specifies JNDI name relative to java:comp/env - see this answer or this answer for portable and deployable solutions.
As mentioned in your updated link, java:jboss namespace is a custom extension provided by WildFly/JBoss only.

To answer the question, the sub-trees under standard namespaces are just normal hierarchy. Obviously, it only makes sense if these sub-trees are (widely) recognized by application server, documentation, processes, etc. Otherwise, I guess nearly flat key-value or random bananaboat/MyDS is fine but still has to be "mounted" under supported namespace like java:jboss.

A: This is all from memory (I was told by another team member a while ago):
The java: prefix is a JBoss/EE standard. It should be prefixed for all non serializable resources which means they are local to the jvm. After that you can name whatever you like to form the "directory" like structure. e.g. if you use JNDI to get binding "java:jboss/datasources", you will get back a subtree of all resources listed under that name. It will contain ExampleDS and possibly other DataSources as well.
To answer your question: you don't have to name it datasources after java:jboss. But it make sense to name it something meaningful.


text:
Q: Making use of a generated entity's class constructor when using Entity Framework Database First I'm using Database First, and for every update to my schema I update the EDMX file and it generates new classes for my model. Unfortunately it doesn't generate the default column values that I specified in the database though (columns such as 'TimeStamp' having 'getdate()' as the default).
Here's how a generated Student.cs class looks:
namespace ABC.Data
{
    using System;

    public partial class Student
    {
        public Student()
        {

        }

        public int StudentID { get; set; }
        public string Name { get; set; }
        public Nullable<System.DateTime> TimeStamp { get; set; }
    }
}

Is there a way I can make the constructor always set TimeStamp to the current date? I've tried creating a helper partial class in the same namespace with the same name etc. but it's not working. Maybe I'm doing the helper class wrong. Ideally I want the helper class to remain the same even after generating new model classes.

A: The DbContext class has an event called ObjectMaterialized which you can hook up to ...
context.ObjectMaterialized += ObjectContext_OnObjectMaterialized

This event handler can apply the default value.
private void ObjectContext_OnObjectMaterialized(
    object sender, ObjectMaterializedEventArgs e)
{
    if (e.Entity is Student)
        (e.Entity as Student).TimeStamp = <default value>;
}

You'll need to remember to use context.Set<Student>().Create() when you need a new instance of Student instead of newing up an instance.


text:
Q: Why is the array operation performance in Swift slower? When I try to solve the problem in Leetcode 1208 I notice the Swift code is much slower than Objective-C.
Here is my code in Swift:
func equalSubstring(_ s: String, _ t: String, _ maxCost: Int) -> Int {
    let list = zip(s,t).map { $0 }
    var costList = [Int].init(repeating: 0, count: list.count)
    for item in list.enumerated() {
        costList[item.offset] = abs(Int(item.element.0.asciiValue!) - Int(item.element.1.asciiValue!))
    }

    var maxLen = 0
    for i in 0..<costList.count {
        var len = 0, cost = maxCost
        for j in i..<costList.count {
            cost -= costList[j]
            if cost >= 0 {
                len += 1
            } else {
                break
            }
        }
        if len > maxLen {
            maxLen = len
        }
    }

    return maxLen
}

It takes 496.363 seconds to deal with the 100000 length input with maxCost 93020. Test case
But if I use same approach in Objective-C it takes only 19s:
- (int)equalSubstring:(NSString *)s t:(NSString *)t maxCost:(int)maxCost {
    NSMutableArray *costList = [[NSMutableArray alloc] init];
    for (int i=0; i<s.length; i++) {
        [costList addObject:@(abs([s characterAtIndex:i] - [t characterAtIndex:i]))];
    }

    int maxLen = 0;
    for (int i=0; i<costList.count; i++) {
        int cost = maxCost, len = 0;
        for (int j=i; j<costList.count; j++) {
            cost -= [costList[j] intValue];
            if (cost >= 0) {
                len += 1;
            } else {
                break;
            }
        }
        if (len > maxLen) {
            maxLen = len;
        }
    }

    return maxLen;
}

in Javascript will be even faster:
var equalSubstring = function(s, t, maxCost) {

    var maxLength = 0;
    for (var i=0; i<s.length; i++) {
        var cost = maxCost, len = 0;
        for (var j=i; j<s.length; j++) {
            let c = Math.abs(s.charCodeAt(j) - t.charCodeAt(j));
            cost -= c;
            if (cost >= 0) {
                len += 1;
            } else {
                break;
            }
        }
        if (len > maxLength) {
            maxLength = len;
        }
    }

    return maxLength;
};

What could be the reason make Swift so slow? Will the problem be the language itself?


text:
Q: PHP session not registering the first time I am having an issue with the session variables.
I am having a simple signup php page that uses ajax calls to verify username and email address if they already exist. It also has an ajax image uploader that gives a preview of the selected image.
Now this is how I am setting the session variable :-
session_start();
session_unset();
$_SESSION = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

session_destroy();
session_start();

$_SESSION['avurl'] = $filename;

$filename is valid as it is echoed in the above code just after this snippet.
In the page where I need to use this session variable I have this :-
session_start();

$av_url = $_SESSION['avurl'];

Now the weird thing is that whenever this runs the first time the session variable doesn't have any value. But the second time it works.
How I came to check this is that I created a test.php which just echos $_SESSION['avurl'] and the first time it never shows anything but the second time it does.
What I figured out from this is that once it echoes this session variable it starts working to store the value.
And all that code that I am using to set that variable is edited from just :-
session_start();

$_SESSION['avurl'] = $filename;

to that as this also didn't work and I thought that this could be a problem with already existing sessions.
Thankyou
Hope this is enough information for solving my problem !!

A: session_start();
session_unset();

This code delete Your session... Why You doing this?


text:
Q: Soap Call-Xml Open quote is expected for attribute "xmlns:soapenv" associated with an element type "soapenv:Envelope" I'm creating SoapCall using Curl command in Java.
Below is the Java sample code for soap call.
String input ="<soapenv:Envelope  xmlns:soapenv = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n" +
            "<soapenv:Header/>\n" +
            "<soapenv:Body>\n" +
            "<tem:TEBalanceQuery>\n" +
            "<tem:TelNum>+222</tem:TelNum>\n" +
            "</tem:TEBalanceQuery>\n" +
            "</soapenv:Body>\n" +
            "</soapenv:Envelope>";
            System.out.println("INPUT :"+input);
            String url = "http://localhost:9001/ws/fraud?wsdl";
            String[] mycommand = {"curl", "-v", "POST", "-H", "Content-type: text/xml;charset=UTF-8", "-d",input,url};
            System.out.println("command: "+mycommand.toString());
            String finalOutput="";
            ProcessBuilder processBuilder = new ProcessBuilder(mycommand);
            try
            {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String output ;

            while((output = reader.readLine()) != null)
            {
            finalOutput+=output;
            System.out.println("output :"+output);
            }
            System.out.println("output :"+output+reader.readLine());
            int exitCode = process.waitFor();
            System.out.println("Exited with code: "+exitCode);
            System.out.println("FinalOutput : "+finalOutput);
            }catch (IOException e)
            {
                System.out.println("error : "+e);
            e.printStackTrace();
            } catch (InterruptedException e) {
                System.out.println("error2 : "+e);
            // TODO Auto-generated catch block
            e.printStackTrace();
            }

When I run this getting below error response,Please help me to fix this issue.
 output :<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope" xmlns=""><faultcode>S:Client</faultcode><faultstring>Couldn't create SOAP message due to exception: XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,30]
    output :Message: Open quote is expected for attribute "xmlns:soapenv" associated with an  element type  "soapenv:Envelope".</faultstring></S:Fault></S:Body></S:Envelope>


text:
Q: IE8 and 9 don't open new tabs Internet Exporer 8 and 9 don't open a new tab when I middle-click, right click and select "Open in New Tab", or control-click. I've searched for a solution but I haven't found a working solution. The problem also occurs when in "No Addons" mode.

A: Try resetting Internet Explorer settings:

To use the Reset Internet Explorer Settings feature from Control Panel, follow these steps:
Exit all programs, including Internet Explorer (if it is running).
If you use Windows Vista or 7, click the Start
  button. Type the following command in
  the Start Search box, and then press
  ENTER: inetcpl.cpl
The Internet
  Options dialog box appears.
Click the
  Advanced tab. Under Reset Internet Explorer settings, click Reset. Then
  click Reset again.
When Internet
  Explorer finishes resetting the
  settings, click Close in the Reset
  Internet Explorer Settings dialog box.
Start Internet Explorer again.


text:
Q: On mouse over show information I have a list of items like here in stackoverflow list of question. For every item's owner name is a link clicking on which it navigates to the the profile page(like in stackoverflow also). But my current requirement is that on mouse over the link I have to show a popup(like in facebook) with some information of that person. So how do this?

A: Just use a Tooltip to display the extra information.
There are a number of these available, here's 15 of them to get you started.


text:
Q: Why can't sphinx-apidoc find the package in this travis/tox build? Travis build: https://travis-ci.com/Laurentiu-Andronache/he/jobs/184044676
conf.py: https://github.com/Laurentiu-Andronache/he/blob/master/docs/source/conf.py
tox.ini: https://github.com/Laurentiu-Andronache/he/blob/master/tox.ini (check out [testenv:doc8])

A: Sphinx cannot find your Python package and import it. Adjust your sys.path accordingly:
https://github.com/Laurentiu-Andronache/he/blob/master/docs/source/conf.py#L22
sys.path.insert(0, os.path.join(__location__, '../../src'))

You might need to append /he to that value if it does not work.


text:
Q: vba open csv file messed date format i'm using vba from foo.xlsm file, to open bar.csv file then copy it to the foo.xlsm file. however, surprisingly, it turns out that it will mess up with the date format, sometimes recognize as mm/dd/yyyy, sometims dd/mm/yyyy.
The csv file has a row like this:
"USD/MYR","TRF:1234","20/04/2017","01/06/2017","11/09/2017","01/06/2017"

, so all the dates are in dd/mm/yyyy format.
If I open bar.csv file manually, the 4 dates are shown correctly, as
20/4/2017   1/6/2017    11/9/2017   1/6/2017

However, if from foo.xlsm using vba to open bar.csv file, it turns out to be
20/04/2017  6/1/2017    9/11/2017   6/1/2017

, and hence later copied to foo.xlsm wrong dates.
It seems excel is tring to interprete the dates as mm/dd/yyyy first, only if that doesn't work, it'll read it as dd/mm/yyyy.
The vba code is like this:
Sub import_via_excel(source_file As String, source_sheet As String, target_sheet As String)
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Set wbThis = ActiveWorkbook
    Dim dest_sheet As Worksheet
    Set dest_sheet = wbThis.Sheets(target_sheet)

    Dim src_book As Workbook
    Set src_book = Workbooks.Open(source_file, True, True) ' Open in "ReadOnly" mode
    Dim src_sheet As Worksheet
    Set src_sheet = src_book.Sheets(source_sheet)
    src_sheet.Activate
    last_col = ActiveSheet.UsedRange.Columns.Count
    last_row = ActiveSheet.UsedRange.Rows.Count

    Dim row As Integer          ' row counter.
    Dim col As Integer          ' col counter.
    Dim src_data  As String
    For row = 1 To last_row
        For col = 1 To last_col
            src_data = src_sheet.Cells(row, col).Value
            dest_sheet.Cells(row, col).Value = src_data
        Next col
    Next row

    src_book.Close False ' close file without saving (FALSE)
    Set src_book = Nothing

    wbThis.Activate

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

What could went wrong?

A: If you are using Workbooks.Open to open your CSV file, Excel will convert dates to US format, unless it is impossible (so it will try other formats).
You can try adding an argument Local:=True to solve it.

A: Since it seems you're right that Excel is trying to interpret the dates as mm/dd/yyyy first, only if that doesn't work, it'll read it as dd/mm/yyyy:
Use the NumberFormat property to force the proper format:
For row = 1 To last_row
    For col = 1 To last_col
        dest_sheet.Cells(row, col).Select
        ActiveCell.NumberFormat = "dd-mm-yyyy"
        src_data = src_sheet.Cells(row, col).Value
        dest_sheet.Cells(row, col).Value = src_data
    Next col
Next row

Try that and see if it helps, forcing the proper date format onto each destination cell first.


text:
Q: how to display checkboxlist items as linkbutton in asp how to display checkboxlist items as linkbutton in asp. I want it so that i can check selected items and click on correponding link button to get related information.

A: You can use a repeater to achieve this. In the itemtemplate of the repeater, use a checkbox and Linkbutton


text:
Q: Nginx url rewrite error : [emerg] unexpected "}" I'm trying to rewrite urls in nginx, blow is my sample code :
server {
    listen 80;
    server_name example.com;
    root   /full/server/path/to/your/cms;
    index  index.php;

    location / {
        try_files $uri $uri/ /phphandler
    }

    location /phphandler {
        internal;
        # nested location to filter out static items not found
        location ~ .php$ {
            rewrite ^/([^/]*)(.*) /$1 break;
            fastcgi_pass   127.0.0.1:8080;
            ...
        }
    }
}

I'm using DirectAdmin and when I add this block of code manually from linux or from DirectAdmin, I face the same error :

nginx: [emerg] unexpected "}" in
  /usr/local/directadmin/data/users/admin/nginx.conf:178 nginx:
  configuration file /etc/nginx/nginx.conf test failed

Notice : I'm copy pasting this peace of code from Here
And I'm in doubt that the problem is where the 3 dots( ... ) are ( after fastcgi_pass   127.0.0.1:8080; ) I think there's some thing I should add here that I don't know?!
Is there anything I'm missing in this block of code?
Or there's another problem that I face this error?
Thanks in advance from anyone who helps me solve this problem :)

A: The problem is that you miss ; at the end of the try_files.
But also this doesn't help much too.
As you mentioned you're using DirectAdmin I recommend you use Nginx - Apache Reverse proxy.
First of all make sure you've got custombuild 2
cd /usr/local/directadmin/custombuild
./build version

You should see an output similar to the following:
2.0.0-RC7 (rev: 863)

Also make sure to have version of directadmin no less than 1.45.2 otherwise the things won't work.
/usr/local/directadmin/directadmin v

Run this code to build nginx + apache with custombuild:
cd /usr/local/directadmin/custombuild
./build update
./build update_da
./build set webserver nginx_apache
./build nginx_apache
./build rewrite_confs