text:
Q: Need tips on how to prioritize and schedule a bunch of work items It took me some time, but I've finally managed to write down all the tasks that need to go into Version 1.0 of the software product I'm working on.
The list is almost 1000 items long.
We are a 3-person team, and we've somehow managed to get this far using MindMeister, Google Docs, @todos in the code etc. Now, I have everything neatly grouped by feature, but how do I prioritize all this and turn it into a schedule?
Any advice would be greatly appreciated - I'm not looking for software recommendations, however - I'm seeking advice on how to take this enormous bag of tasks - ranging from bug-fixes to application modules - and find out in what order I should do them.

A: Prioritize ruthlessly.  1000 action items is a lot, and the odds are that as you go you'll modify some, toss others, and add new ones.  Your list will not survive the things you learn by actually building the software, and if you don't do the most important stuff first, you'll end up with a mess.
For every item or feature, you have to answer the question:  Can the product be at all usable or useful without this?  If yes, it can wait; everything else goes to the head of the queue.
After that, I like to group milestones by focus:  I'll do a features milestone (or multiple ones if there are natural small clusters of features), a UI milestone where I'll focus on AJAX/rich client interactivity, a performance milestone where I profile and do database & server tuning, etc.  Or break them up some other way - but definitely break them up.  Work in smaller bites with specific focus for each iteration, and make sure each iteration is solid before moving on.

A: My recommended approach will be based on Agile methodology best practices...
So, you have what in Agile terms is called a "backlog" defined- that's great - and an important first step.
A good Agile pace that is commonly used is a 2-3 week iteration length...and at the end you have a set of releasable features.  This will establish the "heartbeat" of your development process. Next, you'll decided how to organize and group the features into Stories and Tasks.
You'll want to grow the underlying architecture and let it naturally emerge based on the ordering of the Stories and Tasks that you select from your backlog.
Its important to mitigate risks early - so you'll want to select early those items that are either performance or implementation unknowns that might pose the largest risk - and could result in the largest rework impact.  For example - establishing the messaging infrastructure - might be an early architectural feature that might be included if you select a Story that required a persistent message to be delivered to complete a unit of work.
Can you group the set of features into functional categories that might naturally evolve to describe the 1.0 release as a System of Systems?  For example, the Administrative functions, the User Profile Management, Reporting, external integration layers, Database Access Objects, etc.
What are the simplest Story / Use Cases that you can write - that will map to some of the ~1,000 features / requirements you've defined?  Select a set of Stories (or individual Tasks from a Story - if the Story itself is too large to implement in a single interation).  It will take some additional effort - but recomposing your requirements into a set of Stories/Tasks is important.
You'll find that you will refactor during subsequent interations - but that your steady 2-week heartbeat iteration schedule will keep delivering real functionality.
At various points you may want to schedule an architecture iteration just to focus on some cleaning-up / refactoring - and that's ok too.

A: Since you are indicating that all these items are required, I will assume that there is not much chance of dropping items off the list (at least for now).  Given that, you have 2 large tasks at hand - deciding when to do items, and determining how long it will take to do them.
Since you have already conveniently grouped the items by feature, I would start by prioritizing the features.  Hopefully this will significantly reduce your working set, and allow you to actually get through it in a reasonable amount of time.
I would prioritize each feature based on its risk.  Some things are easy to implement and others are difficult.  Since they are all required, do the riskiest features first, when your schedule is more flexible to meet any unanticipated problems.  Wait until the end of your cycle, and Murphy's law will strike you down.
Given your small team, I would just send the list of features around and ask everyone to mark it if they consider it a risky or difficult feature to implement.  Add up all the marks and you have your "risk assessment", with the highest scoring items getting assigned first.
Alternatively, if you have easy access to your customer, ask them to rate the "risk" associated with each feature (in this case risk refers to the worst-case scenario of not having the feature - if not having something would be annoying, it is not risky.  If not having the feature would result in them not using your product, it is high-risk).
Now that you have a priority queue, it is time to estimate.  For the initial estimates, I would simply do an order of magnitude estimate for each of the features.  Since it sounds as if you have already broken the features up, you should be able to get a decent feel for whether something is going to take hours, days or weeks.  From the sounds of it, you are still early in development, so I don't believe there is much point in trying to get an accurate estimate on something that won't be implemented for another month or so.
As you pull items off your queue, have your team provide more accurate estimates by identifying granular tasks that shouldn't take more than a few hours.  If you want to refine your order of magnitude estimates, you can progressively provide quick estimates for the remaining tasks based on your up-to-date knowledge of the system.
This should provide you with a fairly accurate short term schedule, and a fuzzier long term schedule that will progressively get more accurate.
Finally, if you are facing a long development cycle, I would recommend you identify certain target goals or dates, and when you meet those goals, sit down and repeat this whole process.  I would never go longer than 2 weeks without revisiting these things.  New items will get added, others will get overtaken and become obsolete, and others will become higher risk as you better understand the problem.  All of this must be taken into account.


text:
Q: probability expected payment Company XYZ provides a warranty on a product that it produces. Each year, the number
of warranty claims follows a Poisson distribution with mean c. The probability that no
warranty claims are received in any given year is 0.60.
Company XYZ purchases an insurance policy that will reduce its overall warranty claim
payment costs. The insurance policy will pay nothing for the first warranty claim
received and 5000 for each claim thereafter until the end of the year.
Calculate the expected amount of annual insurance policy payments to Company XYZ.
My solution
y= payment by insurance company
$$y=\begin{cases}
{0} & \text{if } x=0\\
5000(x-1) & \text{if }  x\geq1,\\ \end{cases}$$
c=0.5018
$p(x=0)=\frac{(e^-c)*(c^0)}{0!}=0.60$ so $c=0.5108$ so the mean of x is 0.5108 so $E[x]=0.5108$
$E[y]=\sum 0*p(x=0)+5000(x-1)*p(x\geq1)=0*06+5000(x-1)*0.4=2000E[x]-2000=-976$
Correct answer is 554,I would like to know if my function for payment is correct and what would be my next step.

A: We know: $X\sim\mathcal {Pois}(c)$ and $\mathsf P(X=0)=0.60$.
Since the first fact means that $\mathsf P(X=x)~=~\dfrac{c^x\mathsf e^{-cx}}{x!}\mathbf 1_{x\in\Bbb N}$ , we can easily calculate $c$ knowing the second fact.

We know $Y := 5000(X-1)^+~$  which is $~Y=5000\max(X-1,0)$
Then $\mathsf E(Y) = 5000~\mathsf E(X-1\mid X\geq 1)~\mathsf P(X\geq 1) \color{silver}{+ \require{cancel}\cancel{0~\mathsf P(X=0)}}$
If only the Poisson distribution had some convenient property that allowed us to easily find this conditional expectation without messy summation.   Hmm...

redpajama_set_name: RedPajamaStackExchange


text:
Q: File upload in webwork not working While uploading file in action class I am getting null value for file property
and in console i am getting warning:

Item is a file upload of 0 size, ignoring

So, any one can help me to upload file.


text: Q: In SQL Server would misc pages be pushed out when an object grows within a mixed extent? In SQL Server 2008-2012, objects (including tables) are first put in a mixed extent. An extent can accommodate up to 8 pages and accommodates more than one type of page (meaning: pages from more than one object). Say ExtentA has pages from objects A(2), B(2) and C(4) - numbers in parentheses indicate how many pages they own within that extent. Object B grows, and my question is: Would SQL Server start kicking out A and C's pages before assigning B a new, uniform extent (assuming it eventually outgrows extentA) OR it just jumps to a new extent given extentA is already full.


text:
Q: DolphinDB: Create multiple in-memory tables with the same schema I want to create 100 tables in batches and preallocate enough underlying memory for them. In addition to using the for loop to dynamically add elements, is there any way more convenient?
//initialize tables list_tables
 list_tables=[table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE),
       table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE),
       table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE),
       table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE),
       table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE)]

A: You can use function each and lambda to create multiple tables.
list_tables=each(x->table(150000:0, `trade_day`secu_code`factor_value, `INT`INT`DOUBLE),1..100)
>list_tables[0];
trade_day secu_code factor_value
--------- --------- ------------


text:
Q: momentjs : Deprecation warning error in moment.js I need help I'm getting a warning on my code that has a value provided is not in a recognized ISO format.
Here's the warning error

Deprecation warning: value provided is not in a recognized ISO format.
  moment construction falls back to js Date(), which is not reliable
  across all browsers and versions. Non ISO date formats are discouraged
  and will be removed in an upcoming major release. Please refer to
  http://momentjs.com/guides/#/warnings/js-date/ for more info.
  Arguments: [0] _isAMomentObject: true, _isUTC: true, _useUTC: true,
  _l: undefined, _i: 2016-9-26 19:30, _f: undefined, _strict: undefined, _locale: [object Object]

Here is my code:
var componentDetails = {
  componentName: comp.componentName,
  companyName: comp.employerdetails.companyname,
  fromDate: (comp.employmentdetails.fromdate)?moment(comp.employmentdetails.fromdate).format("DD-MM-YYYY"): comp.employmentdetails.fromdate,
  toDate: (comp.employmentdetails.todate&&comp.employmentdetails.todate!='Present')?moment(comp.employmentdetails.todate).format("DD-MM-YYYY"): comp.employmentdetails.todate,
  designation: comp.employmentdetails.designation,
  currency: comp.employmentdetails.currency,
  ctc: comp.employmentdetails.lastctc,
  period: comp.employmentdetails.period,
  senderName: req.session.loggedInUser.firstName+" "+req.session.loggedInUser.lastName,
  empCode: comp.employmentdetails.empid,
  reason: (comp.others?comp.others.reasonforleaving: "")
};

so the above part only im getting the error what can i do?

A: These values comp.employmentdetails.fromdate OR comp.employmentdetails.todate are not in ISO-8601 format. Below are the formats:
An ISO 8601 string requires a date part.
2013-02-08  # A calendar date part
2013-W06-5  # A week date part
2013-039    # An ordinal date part

20130208    # Basic (short) full date
2013W065    # Basic (short) week, weekday
2013W06     # Basic (short) week only
2013050     # Basic (short) ordinal date

For more information check here


text:
Q: Extend HTML URL by JavaScript URL varriable shortcut Shortly
I need to extend classic html dynamic adress by adding javascript varriable with URL so it will make absolute URL. So if I will move to another hosting or domain, it will get new URL and all the stuff will be still working.
var url = window.location.host
  And will become to
LINK  And will become to LINK

Is there any possible way to just get varriable into href="" or src="" value?

A: function absoluteURL(elem) {
    if (elem.hasAttribute('src')) {
        elem.setAttribute('src') = elem.src;
    }

    if (elem.hasAttribute('href')) {
        elem.setAttribute('href') = elem.href;
    }
}

var links = document.getElementsByTagName('a'),
imgs = document.getElementsByTagName('img'),
i = 0;

for (i = 0; i < links.length; i++ {
    absoluteURL(links[i]);
}

for (i = 0; i < imgs.length; i++ {
    absoluteURL(imgs[i]);
}

Out of curiosity, why on earth do you need to do this when you can just use the relative URLs?


text:
Q: What is this "tree function" I see every once in a while? Sometimes I see or hear a reference to some kind of tree function in math, but every time I look it up, the term is so broad or vague that there's no consistent explanation of what it is or how it's used. Is there any kind of actual consensus on it? Because I have seen in occur in subjects ranging from the error function to graph theory to summations to properties of logarithms.

A: Perhaps you refer to something like this "Thus, the tree function T(z) is related to the W-Lambert function by T(z) = −W(−z)." from Euler Lambert and_the Lambert W-function today. This is in the context of graph theory used to enumerate labelled rooted trees as in the OEIS sequence A000169. The Lambert W function is related and has applications to logarithms and summation of series.


text:
Q: How do you nest Jekyll loops when using multiple collections types So I have 3 lots of collections set up:
testimonials
services
case studies
I have a homepage and also 2 templates for both services and case studies to handle output of the testimonials.
I want to achieve 3 things:

*

*On the case study template, using slick slider, display 1 'service related' testimonial from the testimonials collection. I'd want to achieve this through some front matter of the case study if possible, similar to categories. So that the user should only need to choose which service testimonial is appropriate for the case study e.g.
testimonial: Matthew Pope

*On the services template, using slick slider, display multiple related testimonials for that service that the user can choose from, possibly as an array so:
testimonials: [ Matthew Pope, Jon Vining ]

*On the homepage of the site using slick slider again, iterate through some case studies but only show the testimonial bit of the case study. The reason for this over just iterating over the testimonials collection is that I want to retain the case study link, so clicking on read more will take users to the case study that the testimonial features in.
Here is the code I have for the testimonial loop which is pretty much the same on each of the templates
{% assign testimonials = site.testimonials | where: 'title', page.testimonials | first %}
{% for testimonial in testimonials %}

{{ testimonial.content }}

{{ testimonial.title }}
{{ testimonial.job }}

{% endfor %}

Here is the front matter for each item in the testimonials collection:
---
title: Name
job: Job Title
avatar: "/assets/images/uploads/client-avatars/firstname-secondname-150x150.jpg"
solution: Service Name
---

Content here

I'm struggling to output the testimonials defined in the front matter of both case studies and services, I'm not sure how best to define the front matter.

A: {% assign testimonials = site.testimonials
   | where: 'title', page.testimonials %}

Returns nothing because page.testimonials is an array, and you cannot compare a testimonial.title (string) and a page.testimonials (array).
But you can test if an array contains a string:
{% for testimonial in site.testimonials %}
    {% if page.testimonials contains testimonial.title %}

...

    {% endif %}
{% endfor %}


text:
Q: UnivariateSpline equivalent for exponential functions? I currently have a set of data that I wish to make a function out of that is defined for all values of possible values of temp_vp (my x data in this case)
temp_vp = [280.0,290.0,300.0,310.0,320.0,330.0,340.0,350.0,360.0,370.0,380.0,390.0,400.0,410.0,420.0,430.0,440.0,450.0,460.0,470.0,480.0,490.0,500.0]
vp_in = [3.88e-52,5.16e-50,4.95e-48,3.53e-46,1.93e-44,8.26e-43,2.83e-41,7.93e-40,1.85e-38,3.62e-37,6.07e-36,8.79e-35,1.11e-33,1.25e-32,1.24e-31,1.11e-30,9.03e-30,6.66e-29,4.51e-28,2.81e-27,1.62e-26,8.72e-26,4.38e-25]

I have used UnivariateSpline before in order to interpolate between data points and give a constant values outside of the given data range. However, when I try and use it this time for this data, I get this:

Does anyone know how I can get a desired interpolated function for this data, to the requirements described previously?
My current code is given below:
import numpy as np
from scipy.interpolate import interp1d
from scipy import interp
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as plt

temp_vp = [280.0,290.0,300.0,310.0,320.0,330.0,340.0,350.0,360.0,370.0,380.0,390.0,400.0,410.0,420.0,430.0,440.0,450.0,460.0,470.0,480.0,490.0,500.0]
vp_in = [3.88e-52,5.16e-50,4.95e-48,3.53e-46,1.93e-44,8.26e-43,2.83e-41,7.93e-40,1.85e-38,3.62e-37,6.07e-36,8.79e-35,1.11e-33,1.25e-32,1.24e-31,1.11e-30,9.03e-30,6.66e-29,4.51e-28,2.81e-27,1.62e-26,8.72e-26,4.38e-25]

tempspace = np.linspace(200,10000,10000)
vp_f = UnivariateSpline(temp_vp, vp_in, k = 1, ext = 3)
fig=plt.figure(figsize=(4.5,3.6))
ax=fig.add_subplot(1,1,1)
ax.minorticks_on() # enable minor ticks
ax.set_axisbelow(True) # put grid behind curves
ax.grid(b=True, which='major', color='black', linestyle='-', zorder=1, linewidth=0.4, alpha = 0.12) # turn on major grid
ax.grid(b=True, which='minor', color='black', linestyle='-', zorder=1, linewidth=0.4, alpha = 0.12) # turn on minor grid
ax.scatter(temp_vp,vp_in, color = 'black', label = 'data', s= 5, zorder = 3)
ax.plot(tempspace, vp_f(tempspace), color = 'blue', label = 'Fit', zorder = 2)
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel('Temperature [K]')
ax.set_ylabel('Vapor Pressure [Pa]')
ax.legend(labelspacing=0.25, fontsize = 8)
plt.xlim([250,600])
#plt.ylim([1e-10,1e5])
plt.savefig('Al_vpdata.pdf', bbox_inches='tight', format='pdf')
plt.savefig('Al_vpdata.png', dpi=300, bbox_inches='tight', format='png')

A: Are you really measuring pressures of 1e-50 Pa?
You are probably having underflow errors.
If you multiply vp_in by 1e52 you get:


text:
Q: JsonUtility how to break json into new line I been follow the tutorial from this video.
The tutorial source code can be found at here...
I have a problem of my Json data all been stored in 1 single line,

I want the data break into new line for single object data

Here the code for the Json tutorial
Actor file
using UnityEngine;
using System.Collections;
using System;

public class Actor : MonoBehaviour {

public ActorData data = new ActorData();

public string name = "Tile";

string newline = "\n";

public void StoreData()
{
    data.name = name;
    data.pos = transform.position;
}

public void LoadData()
{
    name = data.name;
    transform.position = data.pos;

}

public void ApplyData()
{
    SaveData.AddActorData(data);
}

void OnEnable()
{
    SaveData.OnLoaded += LoadData;
    SaveData.OnBeforeSave += StoreData;
    SaveData.OnBeforeSave += ApplyData;

}

void OnDisable()
{
    SaveData.OnLoaded -= LoadData;
    SaveData.OnBeforeSave -= StoreData;
    SaveData.OnBeforeSave -= ApplyData;
}

}

[Serializable]
 public class ActorData
 {
    public string name;
public Vector2 pos;
 }

save data file
 using UnityEngine;
 using System.Collections;
 using System.Xml.Serialization;
 using System.IO;

 public class SaveData
 {

public static ActorContainer actorContainer = new ActorContainer();

public delegate void SerializeAction();
public static event SerializeAction OnLoaded;
public static event SerializeAction OnBeforeSave;

public static void Load(string path)
{
    actorContainer = LoadActors(path);

    foreach (ActorData data in actorContainer.actors)
    {
        GameController.CreateActor(data, GameController.playerPath,
            data.pos, Quaternion.identity);
    }

    OnLoaded();

    ClearActorList();
}

public static void Save(string path, ActorContainer actors)
{
    OnBeforeSave();

    //ClearSave(path);
    SaveActors(path, actors);

    ClearActorList();
}

public static void AddActorData(ActorData data)
{
    actorContainer.actors.Add(data);
}

public static void ClearActorList()
{
    actorContainer.actors.Clear();
}

private static ActorContainer LoadActors(string path)
{
    string json = File.ReadAllText(path);

    return JsonUtility.FromJson<ActorContainer>(json);
}

private static void SaveActors(string path, ActorContainer actors)
{
    string json = JsonUtility.ToJson(actors);

    StreamWriter sw = File.CreateText(path);
    sw.Close();
    File.WriteAllText(path, json);
 }
}

A: There are two overloads for the JsonUtility.ToJson function:

*

*public static string ToJson(object obj);

*public static string ToJson(object obj, bool prettyPrint);
Use the second one and pass true to it. It will format the output for readability making the json separated into lines.
Just replace string json = JsonUtility.ToJson(actors); with string json = JsonUtility.ToJson(actors, true);
If you are not satisfied with the result, use  Newtonsoft.Json for Unity and format the json like this:
string json = JsonConvert.SerializeObject(actors);
string newLineJson = JValue.Parse(json).ToString(Formatting.Indented);


text:
Q: Show div after scrollDown then scrollUp to top I want to show hidden div after scrollDown then scrollUp to top. This means that after I scroll down and then scroll up to top, the hidden div is show.
This is my js, but it's just scrollDown.
$(document).scroll(function() {
  let y = $(this).scrollTop();
  if (y > 100) {
    $('.latest_news').fadeIn();
   } else {
     $('.latest_news').fadeOut();
  }
});

I don't know how to after scrollUp, that div show for me?
Thank you.
Sorry about my English.

A: $(document).scroll(function() {
    if ($(this).scrollTop() === 0 && $(".latest_news").is(":hidden")) {
      $(".latest_news").fadeIn();
    } else {
      $(".latest_news").fadeOut(); // remove this else block if you do not want hidden on every scroll down
    }
});

A: I give you solution.
This is very simple.
You need to know scroll direction.
var lastScrollTop = 0;
$(window).scroll(function(event) {
  var st = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

  if (st > lastScrollTop) {
  // downscroll code

  } else {
  // upscroll code
  }

  lastScrollTop = st;
});

reference my blog: https://seunggabi.tistory.com/entry/JS-Browser-get-scroll-direction


text:
Q: Javascript: Add a class where class I am working with js and i need to remove one class and add another, in this case visible and invisible(self explanatory css i think), to all elements with the class 'edit'. Is it possible to use a class as a selector for adding a class?
I have tried:
$(function){
    $('#hide').click(function(){
        $('.edit').addClass('visible');
    });
};

This does not work. Any ideas?

A: You're missing an opening parenthesis.
$(function){

should be
$(function() {

Also, the }; at the end should be });. (Thanks, jmar777!)


text:
Q: Can I use Bash features in an RPM spec file? Searching open source projects, shows me that spec files in the wild do use bash constructs, for instance cat info|while read.
But is it really safe? Does the rpm documentation tells me I can count on the %build section being run by Bash?

A: The default shell invoked for each of the spec stanzas is given by %_buildshell. This defaults to /bin/sh, but can be overridden either globally or on a per-stanza basis.

A: Short answer: yes
Long answer: While bash has become the de facto standard of Linux shells and in practice you can count on having bash around, it does not hurt to specify %_buildshell to /bin/bash as already mentioned in @Ignacio Vazquez-Abrams 's answer


text:
Q: Display Bootstrap Form Validation Near Submit Button I have a form which has 40 some questions on it, some required, some optional. At the end when the uses clicks "submit" I'm using Bootstrap's form-validation.js to check things before the form is submitted. This all works fine.
However, the form is so long, when a user hit "submit" all they see are a bunch of green checkmarks on the bottom optional questions. (The only indication they have that the form didn't submit is the page doesn't reload.)
What's the best/easiest/cleanest way to notify users that elements off screen are not meeting validation requirements? (And that the form did not actually submit.)
Javascript is not my strong suite, but my first thought was to modify the form-validation script to make a small div near the submit button visible when an error was found, but I haven't been able to figure out how to make that work. (Could it be as simple as adding a line or two to the form-validation.js?)
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
  'use strict'

  window.addEventListener('load', function () {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation')
    // Loop over them and prevent submission
    Array.prototype.filter.call(forms, function (form) {
      form.addEventListener('submit', function (event) {
        if (form.checkValidity() === false) {
          event.preventDefault()
          event.stopPropagation()
        }
      }, false)
    })
  }, false)

}())

A: Got a suggestion on Twitter to just use the CSS Psuedo class that gets applied to an invalid form:
Twitter Suggestion:

Chimin' in from the peanut gallery here: the :invalid pseudo-class will be set on a form element if any input inside of it is invalid. You could do something like form:invalid > input[type=submit]:after { /* Your message */ }

Couldn't get the text to appear, but ended up adding some css to to grey out the button if form is invalid. Works like a charm.
            form:invalid > input[type=submit]{background-color:#ccc;}


text:
Q: Spring - @Value annotation not working when using context.getBean Here is my app config
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${sample.config.application-resources-encoding}")
    private String sMessageSourceEncoding_;

    public WebMvcConfig() {
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
        bean.setBasename("classpath:messages");
        bean.setDefaultEncoding(sMessageSourceEncoding_);
        return bean;
    }
}

Here is where I use context.getBean
public class Message {

    private MessageSource ms;

    public Message() {
        ApplicationContext context = new AnnotationConfigApplicationContext(WebMvcConfig.class);
        ms = (MessageSource) context.getBean("messageSource");
        ((AnnotationConfigApplicationContext) context).close();
    }
}

At first when WebMvcConfig is loaded, the @Value annotation is working fine but if I use context.getBean, the @Value annotation does not work anymore. Is there any way to make it work using context.getBean?
I know I can just use @Autowired but I'm trying to migrate a struts1 to spring and I need the MessageSource in new instance but I couldn't make the @Value annotation to work the way I want.


text:
Q: Tensorflow is unable to run code on too many GPUs? I have the following test code:
    import tensorflow as tf
import numpy as np

def body(x):
    a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
    b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
    c = a + b
    return tf.nn.relu(x + c)

def condition(x):
    return tf.reduce_sum(x) < 100

x = tf.Variable(tf.constant(0, shape=[2, 2]))

with tf.Session():
    tf.initialize_all_variables().run()
    result = tf.while_loop(condition, body, [x])
    print(result.eval())

when I run it on my GPU cluster, I produce the following error:
2018-03-30 18:10:33.473913: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10415 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:3d:00.0, compute capability: 6.1)
2018-03-30 18:10:33.591203: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:1 with 10415 MB memory) -> physical GPU (device: 1, name: GeForce GTX 1080 Ti, pci bus id: 0000:3e:00.0, compute capability: 6.1)
2018-03-30 18:10:33.688390: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:2 with 10415 MB memory) -> physical GPU (device: 2, name: GeForce GTX 1080 Ti, pci bus id: 0000:60:00.0, compute capability: 6.1)
2018-03-30 18:10:33.806845: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:3 with 10415 MB memory) -> physical GPU (device: 3, name: GeForce GTX 1080 Ti, pci bus id: 0000:61:00.0, compute capability: 6.1)
2018-03-30 18:10:33.913200: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:4 with 10415 MB memory) -> physical GPU (device: 4, name: GeForce GTX 1080 Ti, pci bus id: 0000:b1:00.0, compute capability: 6.1)
2018-03-30 18:10:34.018533: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:5 with 10415 MB memory) -> physical GPU (device: 5, name: GeForce GTX 1080 Ti, pci bus id: 0000:b2:00.0, compute capability: 6.1)
Killed

When I run the script using CUDA_VISIBLE_DEVICES='6' python script.py it aborts using the GPU. What could be causing this? Could this be a defective GPU?
nvidia-smi reports the following:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.25                 Driver Version: 390.25                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:3D:00.0 Off |                  N/A |
| 28%   21C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 108...  Off  | 00000000:3E:00.0 Off |                  N/A |
| 28%   21C    P8     7W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   2  GeForce GTX 108...  Off  | 00000000:60:00.0 Off |                  N/A |
| 28%   24C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   3  GeForce GTX 108...  Off  | 00000000:61:00.0 Off |                  N/A |
| 28%   25C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   4  GeForce GTX 108...  Off  | 00000000:B1:00.0 Off |                  N/A |
| 28%   19C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   5  GeForce GTX 108...  Off  | 00000000:B2:00.0 Off |                  N/A |
| 28%   20C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   6  GeForce GTX 108...  Off  | 00000000:DA:00.0 Off |                  N/A |
| 28%   22C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   7  GeForce GTX 108...  Off  | 00000000:DB:00.0 Off |                  N/A |
| 28%   21C    P8     8W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

Tensorflow version is 1.7.0 and CUDA version is 9.0.176

A: The problem was that I didn't request enough RAM space when creating a job to use that many GPUs. To use 8 GPUs, you need a good amount of space, perhaps ~60 Gi.


text:
Q: concurrent .net web api service calls returning duplicate data The setup
We have a web app hosted on IIS 7.5 that uses a .net web api rest service to short-poll a SQL Server 2008 database.  The service controller calls a stored procedure to read the data.
The problem
When concurrent requests are made to the same web service, we intermittently see the duplicate results, and sometime other processes results, returned to the browser.
C# service code
namespace ImageApp_REST_Services.Repositories {
public class ImageLinkRepository : IImageLinkRepository
{

    private List<ImageLink> ImageLinks
    {
        get;
        set;

    }

    public IEnumerable<ImageLink> Get(String userId)
    {

        ImageLinks = new List<ImageLink>();

        using (var cnnSQL = new SqlConnection(...))
        {

            // opend connection to DB
            cnnSQL.Open();

            try
            {

                SqlCommand cmmSQL = new SqlCommand("nVision_select_lcimagelinks_sp", cnnSQL);
                cmmSQL.CommandType = System.Data.CommandType.StoredProcedure;

                SqlParameter prmSQL = cmmSQL.Parameters.Add(new SqlParameter
                {
                    ParameterName = "@LCIMGLINKUSERID",
                    Value = userId
                });

                SqlDataReader rdrSQL = cmmSQL.ExecuteReader();

                if (rdrSQL.HasRows)
                {
                    while (rdrSQL.Read())
                    {

                        ImageLinks.Add(new ImageLink
                        {
                            // set new ImageLink object's properties
                            imageTopicId = DBReader.SQLString(rdrSQL, "LCIMGLINKIMGTOPICID"),
                            id = DBReader.SQLInt(rdrSQL, "LCIMGLINKPK"),
                            recordId = DBReader.SQLString(rdrSQL, "LCIMGLINKRECORDID"),
                            text = DBReader.SQLString(rdrSQL, "LCIMGLINKTEXT"),
                            topicId = DBReader.SQLString(rdrSQL, "LCIMGLINKTOPICID"),
                            topicItem = DBReader.SQLString(rdrSQL, "LCIMGLINKTOPICITEM"),
                            url = DBReader.SQLString(rdrSQL, "LCIMGLINKURL"),
                            user = DBReader.SQLString(rdrSQL, "LCIMGLINKUSERID")
                        });
                    }
                }
            }
            catch (Exception)
            {

            }

        }

        return ImageLinks;
    }

}

}
Again, when multiple requests are hitting the service simultaneously, we occasionally see either duplicate records returned, or records belonging to another service call.
We want the service to only return the data for the given request.  Does anyone know what is wrong???

A: Is ImageLinks defined as a static member? If it is, the contents will be shared across multiple threads and web requests. One thread will overwrite the other's results. Long shot, but fits your issue.


text:
Q: Powershell counting occurrences of specific value combinations in pipe separated values in array Sorry for the wording on the question as it's not brilliantly clear but this is what I'm trying to do.
I have an array containing 7 pipe separated values in each element. I need to count the combinations but not purely all unique combinations (there would be 896 of those).
Here is what the fields can be

*

*Field1 = 001 or 002

*Field2 = N or C

*Field3 = Y or N

*Field4 = Y or N

*Field5 = Y or N

*Field6 = C or not C

*Field7 = (L1 or blank) or (not L1 or blank) (i.e. a binary value as it is either one of those 2 or it isn't one of those 2)

If I've got the math correct, by switching them all to, effectively, a binary choice, I have reduced my combinations down to 128 as I can happily then split it into 2 subsets where field 2 is N or C and for the C ones I just need separate counts of the 2 possible values of Field 1 (i.e. 001 or 002) that would then reduce my further combinations down to 64 however, that's where I get stuck. For the two where field 2 is C I will just do something like,
$count1 = ($data|Select-String "^001\|C" | Measure-Object).count
So I would assume there is a way I could then do a a similar command to get the other counts, I just don't know how to handle Field 6 and 7.
When I know the values I can happily do the select but in the case of Field 6 I don't know how to do the "not C" and in the case of Field 7 where one of two values is one count and not one of those two values is the other then I'm struggling.


text:
Q: Проверка общей коллекции в многопоточном приложении У меня есть коллекция, в которой лежат объекты класса "Магазин". У каждого объекта "Магазин" есть числовое поле "Количество товаров".
Потоки перемещают товары из одного магазина в другой. Я хочу создать один поток, который будет следить за тем, что общее число товаров в магазинах не изменилось.
С синхронизацией процесса перемещения товаров проблем нет. Но для проверки я не могу синхронизироваться по общей коллекции, потому что это остановит работу всех остальных потоков.
Но если этого не делать, пока проверяющий поток будет ходить по списку магазинов и суммировать число товаров, какой-то из потоков может переместить товар из непроверенного магазина в уже проверенный, и таким образом получится недостача. Как мне этого избежать?
Не прошу писать код, просто подайте, пожалуйста, какую-нибудь идею. Я пробовал использовать CopyOnWriteArrayList, но он не дает нужного результата, потому что я получаю копию листа, а сами объекты, которые лежат внутри него, в это время все равно могут изменяться. Даже если я буду заменять объекты в листе на новые, при перемещении товаров из магазина в магазин будет совершаться две операции (обновление числа товаров в одном магазине и в другом), и в каждом случае будет создаваться копия, и я могу взять промежуточную версию.

A: Идея с проверкой перемещений правильная и сработает. Нужно только реализовать ее так, чтоб не было блокировок потоков, которые совершают транзакции, т.е. которые перемещают данные.
Общая идея решения это создать журнал транзакций, в который каждая транзакция пишет изменение, которое она сделала. Поток-наблюдатель читает журнал операций и проверяет, что после каждой операции условие выполняется. Есть много нюансов как реализовать детали, я не буду во все вдаваться, но буду по ходу упоминать.
class Shop {
  Integer id;
  ...
}

class Transaction {
  // хранит для каждого идентификатора магазина изменение в количестве товара
  Map<Integer, Integer> changes;
}

ConcurrentLinkedQueue<Transaction> transactionLog = new ConcurrentLinkedQueue<>();

Теперь каждая транзакция должна добавлять в transactionLog изменение, которое она делает.
Чтобы избежать ошибок и злонамеренных действий, можно изменить API вашего хранилища магазинов так, чтоб к самим магазинам клиенты не имели доступа. А работали чисто с объектами транзакций, т.е. API хранилища будет не List<Shop> какой-нибудь, где можно достать любой магазин и сделать что угодно, а что-то вроде:
class Shops {
  private List<Shop> shops;

  // клиенты, которые хотят переместить что-то из магазина в магазин могут
  // делать это используя только этот метод
  // список shops недоступен извне, а объекты Shop клиенты либо не могут достать вообще
  // либо они immutable, т.е. клиент не может изменять количество в обход process
  public void process(Transaction transaction) {
    // тут должна быть потокобезопасная обработка изменения
    // т.е. модификация значений в колекции shops используя данные из transaction
    ...

    transactionLog.add(transaction);
  }
}

Shops shops = ...

Тогда поток, который делает перемещение, будет выглядеть как-то так (тут я привожу вариант з неизменяемым(immutable) классом Shop):
// эта операция одновременно захватывает блокировку на запись к магазину
// чтоб никакой другой поток не мог параллельно его изменить
Shop shop1 = shops.getAndLock(SHOP_ID1);
Shop shop2 = shops.getAndLock(SHOP_ID2);
Map<Integer, Integer> moveTx = new HashMap<>();
moveTx.put(shop1.getId(), +20);
moveTx.put(shop2.getId(), -20);
shops.process(new Transaction(moveTx));
shops.releaseLock(shop2);
shops.releaseLock(shop1);

Поток-демон должен просто читать transactionLog и проверять, что после каждой транзакции у нас условие целостности выполняется.
Что касается блокировок/разблокировок отдельных магазинов в потоках. Пример, который я привел выше, демонстрирует, что должно происходить, само API конечно можно и нужно улучшить, чтобы не забыть разблокировать, например, и т.д.
Я имею ввиду что можно улучшить API класса Shops так:
  shops.update(asList(SHOP_ID1, SHOP_ID2), (Collection<Shop> shops, Transaction transaction) -> {
     transaction.add(SHOP_ID1, +20);
     transaction.add(SHOP_ID2, -20);
  });

  ...

  class Shops {

     interface TransactionCallback {
        void execute(Collection<Shop> shops, Transaction transaction);
     }

     void update(List<Integer> shopIds, TransactionCallback callback) {

       lockShops(shopIds);
       try {
          Transaction tx = new Transaction();
          List<Shop> shopsInTransaction = getShops(shopIds);
          callback.execute(shopsInTransaction, tx);
          process(tx); // теперь process будет private методом
       } finally {
         unlockShops(shopIds);
       }
     }
  }


text:
Q: Different between several proposition - Manifold, plate function. I have 3 different proposition and I really have problem to see in what they are that different.
Let $M$ a smooth manifold.

Prop 1 : Let $U\subset M$ an open and $C\subset U$ a compact. Then, there is a $f\in\mathcal C^\infty (M)$ s.t. $f|_C\equiv 1$ and $supp(f)\subset U$.
Prop 2 : Let $p\in M\backslash \partial M$. For all neighborhood $U_p$, there is $f\in\mathcal C^\infty (U)$ s.t. $f|_V\equiv 1$ where $V\subset U$ is a smaller neighborhood and $supp(f)\subset U$.
Prop 3 : Let $K\subset M$ a compact and $W\subset M$ an open s.t. $W\supset K$. Then, there is a $f\in\mathcal C^\infty (M)$ s.t. $f|_K\equiv 1$ and $supp(f)\subset W$.

Excepted some very little details, theses 3 propositions looks exactly the same to me (and almost equivalent). What are the subtlety between them ?

A: To me P1 and P3 are exactly the same. The difference is between P2 and P3.
P2) $f$ depend of $p$.
P3) You can take the same $f$ for all $p$ in $K$.


text:
Q: Generate Huge files containing sorted, random and almost sorted numbers Hey I need to create 1000 files each for random, sorted and almost sorted numbers.I did generate a file for sorted and random numbers by following shell command.
    vinod@localhost:~$ shuf -i 1-10000 -n 1000 > random_1.txt
    vinod@localhost:~$ shuf -i 1-10000 -n 1000 | sort > sorted_1.txt

But How can I generate file for almost sorted numbers? And How can I automate generation part in order to get the 1000 files for each type of list (sorted,random and almost sorted)?


text:
Q: Program exit code -SomeNumber i made a program using Qt for Symbian, its all working very well ... However, it always exits with a status code -10737something when i close the program
i think the problem is in the deconstructer, maybe some memory leaks ... any suggestion on how to solve this problem, or to find the error using Qt Creator?
thanks

A: Record the exact number, convert it to hexadecimal, then put the result into a search engine and see what you can find.
The exit code you've got is most likely an error code which would normally be represented in hexadecimal (but the operating system has chosen to report program exit codes in signed decimal format).

A: Symbian defines a lot of globally used error codes. The most complete error code reference I know of can be found on newlc.com page.
If you post the question on SO, please be as precise as possible, don't write "I got -128903something error, please help", because the answer to the question phrased this way is "You've got an error somewhere in your code".
So if you need more help, post the error code with all details.


text:
Q: my app electron doesn't recognize data from localstorage We have an application in html, js, css compiled by electron and we use firebase to store data, and render it on frontend but we store the data in localstorage and then display it in frontend, the problem is that in some laptops the data from local storage is not recognized and throw an error that it is not defined.
Uncaught (in promise) TypeError: Cannot read property 'encabezado' of null


text:
Q: Codeigniter - mPDF exports Blank Page I use mPDF for export PDF Documentation. But I get blank page when I export to PDF using mPDF. I want to show some Property Information according to Property Id but it creates blank page. mPDF works with welcome_message.php but I can't make PDF with my page. Where I do mistake?
Controller:
public function getReportProperties($cusId)

    {

        $this->lang->load('content', $this->session->userdata('people_lang'));

        $viewData['customers'] = $this->report_model->get_customers();

        $viewData['estateList'] = $this->report_model->getEstatesByCustomer($cusId);

        $viewData['byCustomer'] = $this->db->where("cusId", $cusId)->get("customer")->row();

        $data = [];
        //load the view and saved it into $html variable
        $html = $this->load->view('reportProperties', $viewData, $data, true);

        $html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');

        //this the the PDF filename that user will get to download
        $pdfFilePath = "properties.pdf";

        //load mPDF library
        $this->load->library('m_pdf');

        //generate the PDF from the given html
        $this->m_pdf->pdf->WriteHTML($html);

        //download it.
         $this->m_pdf->pdf->Output($pdfFilePath, "D");

    }

View:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html <?php if($this->session->userdata('people_lang') == "ar") { echo "dir='rtl'"; } else { echo ""; } ?>">

    <?php $this->load->view("common/head"); ?>

    <?php $this->load->view("reports/includes"); ?>

<?php echo $byCustomer->cosName. ' ' .$byCustomer->cosSurname; ?> | All Property List

                                    <?php echo date("d.m.Y"); ?>

                                        <img src="<?php echo base_url().'upload/report/logo.png' ?>" width="180" alt="">

                            <?php $i = 1; foreach($estateList as $estate) { ?>

<?php echo $i++ ?> Property Type: <?php echo $estate->estateTypeEng; ?>

City

<?php if($estate->cityName == '') { echo '-'; } else { echo $estate->cityName; } ?>

Property Address:

<?php if($estate->estateAddress == '') { echo '-'; } else { echo $estate->estateAddress; } ?>

Property Acreage m²:

<?php if($estate->estateCentare == '') { echo '-'; } else { echo $estate->estateCentare; } ?>

Heating Type:

<?php if($estate->heatingNameEn == '') { echo '-'; } else { echo $estate->heatingNameEn; } ?>

Garden Acreage m²: :

<?php if($estate->estateGardenArea == '') { echo '-'; } else { echo $estate->estateGardenArea; } ?>

Number of Room:

<?php if($estate->estateRoom == '') { echo '-'; } else { echo $estate->estateRoom; } ?>

Number of Bathroom:

<?php if($estate->estateBathroom == '') { echo '-'; } else { echo $estate->estateBathroom; } ?>

Number of Livining Room:

<?php if($estate->estateSalon == '') { echo '-'; } else { echo $estate->estateSalon; } ?>

Number of Balcony:

<?php if($estate->estateBalcony == '') { echo '-'; } else { echo $estate->estateBalcony; } ?>

Requirements

So slit more darn hey well wore submissive savage this shark aardvark fumed thoughtfully much drank when angelfish so outgrew some alas vigorously therefore warthog superb less oh groundhog less alas gibbered barked some hey despicably with aesthetic hamster jay by luckily.

                                                #
                                                Task
                                                Due date
                                                Description

                                                1
                                                Design mockup

                                                        <input type="text" class="form-control datepicker p-0 border-0 bg-transparent" value="21 January, 15">

                                                Create design mockups for a new app, must be delivered before 1st of March

                                                2
                                                User interface research

                                                        <input type="text" class="form-control datepicker p-0 border-0 bg-transparent" value="24 January, 15">

                                                Create a focus group with random people, provide a research statement

                                                3
                                                New icons set

                                                        <input type="text" class="form-control datepicker p-0 border-0 bg-transparent" value="28 January, 15">

                                                Create a full set of icons required for the iOS application, send them to team lead for review

                                                4
                                                Loading optimization

                                                        <input type="text" class="form-control datepicker p-0 border-0 bg-transparent" value="1 February, 15">

                                                Review image sizes, compress them as much as possible, make sure page loading time is less than 1 second

Uploaded files

A much goodness between destructive that save stupid firefly destructively dog goldfinch continually alas pinched for outside flailed inescapably hey brought rid crud and awakened sobbed extraordinarily wherever deer before tenable yet into dalmatian opposite save close ahead next independent mindful but far.

dashboard_draft.png

                                                        378Kb

profile_page.png

                                                        1.2Mb

shopping_cart.png

                                                        1.8Mb

sales_statistics.png

                                                        2.0Mb

                            <?php } ?>

                                    <?php echo $byCustomer->cosName. ' ' .$byCustomer->cosSurname; ?> has <?php
                                    $cusId = $byCustomer->cusId;
                                    $this->db->select('*');
                                    $this->db->where('cusId', $cusId);
                                    $query = $this->db->get('estate');
                                    $num = $query->num_rows();
                                    echo $num; ?> <?php if($num > 1) { echo 'Properties.'; } elseif($num = 1) { echo 'Property.'; } elseif($num = 0) { echo 'no any Property yet.'; }?>

                            <?php echo date('Y'); ?>

A: I'm not super familiar with mpdf but I do see an error:
$html = $this->load->view('reportProperties', $viewData, $data, true);
view only accepts 3 params: 1st view page, 2nd data array, 3rd bool to return view. $data should be removed.
$html = $this->load->view('reportProperties', $viewData, true);

A: The error occurred on loading view. It should be three parameters,but four was supplied.
I found that Mpdf just only display blank page if the error have been occurred.

A: In order to get the view content you need to pass a third optional parameter, TRUE (boolean) - please see: Returning views as data
Instead of
//load the view and saved it into $html variable
$html = $this->load->view('reportProperties', $viewData, $data, true);

you need to use:
//load the view and saved it into $html variable
$html = $this->load->view('reportProperties', $viewData, true);

Also, please add the content of the reportProperties view file.
EDIT 1 - after repostProperties uploaded
Your view is not valid for working with mpdf.
First, images url's need to be absolut and not relative.
Also, the for loop, I think here is a problem as you get many pages.
First start with simple view file and then, step by step add another data.
Please check the mPDF documentation to see what is supported and how you can paginate your content.


text:
Q: What is wrong with my overloaded operator<< function? ostream & operator<<(ostream &out, const IntList &rhs)
{
    IntNode *i = rhs.head;
    out << rhs.head;
    while (rhs.head != 0)
    {
        out << " " << i;
        i = rhs.head->next;
    }

    return out;
}

The program compiles successfully but does not print anything out. What could be the problem?

A: I assume that the input list is empty, therefore rhs.head != 0 condition fails? Otherwise it would actually result into infinite loop because rhs.head is tested instead of i. I suppose it should have been:
IntNode *i = rhs.head;
out << rhs.head;
while (i != 0) // note the i here
{
    out << " " << i;
    i = i->next; // again i here
}

The second question is what is out stream because at least head pointer should be printed there...

A: You need to use i instead of rhs.head
 while (i != 0)
 {
   out << " " << i;
   i = i->next;
 }

rhs.head != 0 can't be changed by what's in the loop, so if it's false, the loop will never run, if it's true, it will loop forever.
also i = rhs.head->next; will always set i to the 2nd node (the one after head), not the one after i.


text:
Q: Issues installing Ubuntu 12.04 on ASUS A46 CM I never had success installing Ubuntu 12.04_2 64bit on my ASUS A46 CM, can someone help me? it's always rebooting and never starts after selecting language option. I'm downloading from ubuntu server 1,6 GB and 700MB also.
ASUS A46CM spec:

*

*Intel Core i5 3317U 1.7 - turbo boost 2.6 GHz

*RAM 4 GB

*VGA nVidia 635m 2 GB.

*Sonic Master Audio

*HDD 500 GB

A: I have a similar machine (http://us.acer.com/ac/en/US/content/model/NX.M3AAA.006) on which I successfully booted ubuntu12.04. Below are the steps I did. Hope it helps you too. This machine has UEFI secure booting enabled.
a) Create a USB bootable for 12.04 (64-bit) from ISO in ubuntu website. Follow the steps provided in ubuntu website for creating a UEFI bootable disk.
b) Insert the pendive, enter BIOS and add the UEFI keys into it. Change the boot order to choose the new UEFI key (its grubxxx.efi)
c) Boot to ubuntu on pendrive and then partition the hard-disk as the installer asks.
d) When you reboot to boot to ubuntu on HDD, please enter the BIOS, and perform the same procedure to add the keys from ubuntu partition, and boot order.
e) I half-successfully booted ubuntu 12.04. Half-successfully because the grub isnt stable and cannot dual boot WIN8 and Ubuntu together. I have to change the boot order in BIOS everytime I need to switch OS. I am working to fix that now.
But I hope this helps you.


text:
Q: How to create if conditional inside a stored procedure postgresql? In my procedure I need to create if condition. I googled for that information and created that statement, but when I'm trying to execute that postgres throws "syntax error near if" error. May you help me, because I spent four hours trying to fix that error?
Here is code of procedure I'm trying to execute.
CREATE or replace PROCEDURE addLocomotive(addModel varchar(255),addNumber varchar(255), addFuelpriceper100km int,addYearofproduction int)
LANGUAGE SQL
AS $$
if 1>0 then
  select 1;
else
  select 0;
END if;
--insert into locomotives(model,number,fuelpriceper100km,yearOfProduction) values(addModel,addNumber,addFuelPriceper100km,addYearOfProduction);
$$;


text:
Q: Erorr: no operator ">>" matches these arguments int main()
{
char* NamePointer = new char;

std::cout << "Enter the file you want to edit (MUST BE IN THE PROJECT'S DIRECTORY): ";
std::cin >> &NamePointer;

const char* FileName = NamePointer;
delete &NamePointer;

return 0;
}

This returns me the error in the title:
std::cin >> &NamePointer;

Any ideas? This is probably something simple I'm missing, but when I looked it up I didn't get my answer.
JUST FIXED IT, SORRY FOR BOTHERING! I took out the "&" in "&NamePointer".
Yeah I just found out another way of doing this using c_str(). Sorry!

A: You should have:
std::cin >> NamePointer;

Also, you are just allocating an memory of one character, probably you meant:
char* NamePointer = new char[MAX_SIZE];

and dellocate it as:
delete []NamePointer;

Note that the, C++ way of doing this is to simply use std::string which takes care of the problem of buffer overflows you get with using char*:
std::string Name;
std::cin >> Name;

A: There's no need for the address of operator here. Simply:
std::cin >> NamePointer;

Some other things I've noticed:
char* NamePointer = new char;

You probably want more space than just one character. A simple start may be a large static allocation:
char NamePointer[1024];

In which case, you omit the delete statement at the end (which also doesn't use an address of operator, by the way).


text:
Q: Background color change Javascript Hi im a beginner to javascript!
im trying to to change color of the body background according to the select color from the form created.
Ive linked the script to the index.html but i cant seem to know why my body background wont change ... something is missing and can't seem to find it need help please.

Changer la couleur de fond

            <select name="pastelBgColor" id="pastelBgColor">
                <option value="azure">Azure</option>
                <option value="champagne">Champagne</option>
                <option value="cotton-candy">Cotton Candy</option>
                <option value="tea-green">Tea Green</option>
            </select>

            <button id="submit" >Changer</button>

Script file JS

    let button = document.getElementById("submit");
    //event
button.addEventListener('click',  (event) => {

        let listColor = document.getElementById('pastelBgColor').value;

        document.getElementById("myDocument").style.backgroundColor = listColor;
    });

A: So far so good, but it seems that you're mixing between two different ways to change the myDocument background color. I've split the two ways with working samples below to highlight the differences:
1) Use ClassName to change myDocument Color
In that case, we need to use className to add the selected class from the dropdown to the myDocument element as follows:

let button = document.getElementById("submit");
button.addEventListener("click", (event) => {
  let listColor = document.getElementById("pastelBgColor").value;

  document.getElementById("myDocument").className = listColor;
});
.azure {
  background-color: #f0ffff;
}

.champagne {
  background-color: #f3eace;
}

.cotton-candy {
  background-color: #fec8d8;
}

.tea-green {
  background-color: #d7ecc9;
}

Changer la couleur de fond

    <select name="pastelBgColor" id="pastelBgColor">
      <option value="azure">Azure</option>
      <option value="champagne">Champagne</option>
      <option value="cotton-candy">Cotton Candy</option>
      <option value="tea-green">Tea Green</option>
    </select>

    <button id="submit">Changer</button>

2) Use color value directly from the list
In that solution, we won't use the class name to change the color, instead, we will add colors as values in your <select> and add their value directly to style.backgroundColor to the myDocument. Also we don't need any CSS in that case, please take a look:

let button = document.getElementById("submit");
//event
button.addEventListener("click", (event) => {
  let listColor = document.getElementById("pastelBgColor").value;

  document.getElementById("myDocument").style.backgroundColor = listColor;
});

Changer la couleur de fond

    <select name="pastelBgColor" id="pastelBgColor">
      <option value="#f0ffff">Azure</option>
      <option value="#f3eace">Champagne</option>
      <option value="#fec8d8">Cotton Candy</option>
      <option value="#d7ecc9">Tea Green</option>
    </select>

    <button id="submit">Changer</button>

Please note that it's totally fine to have <option> value different from what the user sees, that's usually the normal scenario.


text:
Q: flipping card with more text on the back I am trying to make my cards as flipping cards, I have created the following CSS which explains what my card look like, however I am not able to make them flipping whenever I hover my mouse on it.

.row {
  padding-top: 25px;
}

.card {
  display: block;
  margin-bottom: 20px;
  line-height: 1.42857143;
  background-color: #E0E0E0s;
  border-radius: 2px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
  transition: box-shadow .25s;
  border-right: 100%;
}

.card:hover {
  box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.img-card {
  width: 100%;
  height: 200px;
  border-top-left-radius: 2px;
  border-top-right-radius: 2px;
  display: block;
  overflow: hidden;
}

.img-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: all .25s ease;
}

.card-content {
  padding: 15px;
  text-align: left;
}

.card-title {
  margin-top: 0px;
  font-weight: 700;
  font-size: 1.65em;
}

.card-title a {
  color: #000;
  text-decoration: none !important;
}

.card-read-more {
  border-top: 1px solid #D4D4D4;
}

.card-read-more a {
  text-decoration: none !important;
  padding: 10px;
  font-weight: 600;
  text-transform: uppercase
}

                            BMW X5 SERIES

        New Delhi, 2005, Petrol

                        BID NOW

I added hover class which was totally a wrong approach, please let me know which class might help me with it. thank you

A:

#f1_container {
  position: relative;
  width: 450px;
  height: 281px;
  z-index: 1;
}

#f1_container {
  perspective: 1000;
}

#f1_card {
  width: 100%;
  height: 100%;
  transform-style: preserve-3d;
  transition: all 1.0s linear;
}

#f1_container:hover #f1_card {
  transform: rotateY(180deg);
  box-shadow: -5px 5px 5px #aaa;
}

.face {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.face.back {
  transform: rotateY(180deg);
  box-sizing: border-box;
  padding: 10px;
  color: white;
  text-align: center;
}

                            BMW X5 SERIES
                         New Delhi, 2005, Petrol

                        BID NOW


text:
Q: Scipy.Optimize Python I am trying to optimize the parameters of a model I have built. Its a very simple model based predicting water runoff of a mountain. Part of a university coursework:
def model(params, snowProportion,temperature):
    '''
    Calculates predicted runoff.
    '''
    K = params[0]
    p = params[1]
    tempThresh = params[2]
    meltDays = np.where(temperature > tempThresh)[0]
    accum = snowProportion*0.
    for d in meltDays:
        water = K * snowProportion[d]
        n = np.arange(len(snowProportion)) - d
        m = p ** n
        m[np.where(n<0)]=0
        accum += m * water
    np.savetxt('2005predicted.dat', accum)

params = [2000, 0.96, 9]

I was told to use scipy.optimize.fmin_cg;
so I presume I do something along the lines of:
x = scipy.optimize.fmin_cg(model, params, args=[snowProportion, temperature])

I keep getting errors along the lines of:
TypeError: 'numpy.ndarray' object is not callable

So then I presumed I needed them to be in lists - but i got the same problem:
TypeError: 'list' object is not callable

I want to get better estimates of the params. SnowProportion and temperature are of the shape (365,)
RMSE:
import numpy as np
import scipy.optimize
def RMSE(params,temperature, snowProportion):
    '''
    Calculates the RMSE of a model from measured and predicted.
    '''
    measured = np.loadtxt('/home/david/Documents/HydroM/runoff2005.dat')
    K = params[0]
    p = params[1]
    tempThresh = params[2]
    meltDays = np.where(temperature > tempThresh)[0]
    predicted = snowProportion*0.
    for d in meltDays:
        water = K * snowProportion[d]
        n = np.arange(len(snowProportion)) - d
        m = p ** n
        m[np.where(n<0)]=0
        predicted += m * water
    err = np.sqrt((measured - predicted) ** 2).mean()
    return err

A: The first argument to scipy.optimize.fmin_cg -- named model in your code -- should represent the function that you want to minimize (presumably the error of your models estimates with the given set of parameters compared to some reference values...).
Specifically it should be a function that returns a scalar value.
The algorithm needs to know how 'well' the model performs with a given set of parameters.


text:
Q: canon LPB6000 installed on ubuntu 17.4 but doesn't work? Hy friends. I'm a beginner in Linux, I was on windows so I'm completely lost ! I can't find where is the problem with the printer installation ! After 3 days of research on Internet I finally could install canon LBP6000, it appear on printer localhost but doesn't print the job !!!
I need an answer please cause I don't wanna come back to windows I've a report to achieve.
Thank you.

A: I have the same printer and I had the same problem. On Xubuntu 18.04, I resolved it this way.
1) First, allow compatibility with needed i386 libraries (although drivers are labelled as 64bit, they depend on them). Enter the following
sudo sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libstdc++6:i386 libxml2:i386 zlib1g:i386 libpopt0:i386
sudo apt-get install libglade2-0:amd64

2) Install drivers as explained by pdc.
3) Register the printer
sudo lpadmin -p LBP6000 -m CNCUPSLBP6018CAPTS.ppd -v ccp://localhost:59787

Note that the port here must be the same as in UI PORT (see the screenshot in the second answer by pdc). Then
lpadmin -p LBP6000 -E

(I guess you can also give a combined command, as suggested by pdc.)
4) Register the printer in the ccpd deamon:
sudo ccpdadmin -p LBP6000 -o /dev/usb/lp0

Of course, change /dev/usb/lp0 with the right path if needed.
5) Start the ccpd deamon
sudo /etc/init.d/ccpd start

Connect the printer and check its status typing
sudo /etc/init.d/ccpd status

You should see two numbers in the output. If not, type sudo /etc/init.d/ccpd restart.
6) Try to print a test page from Settings>Printers. If the printer is still silent, type
captstatusui -P LBP6000 -e

to start Canon's printer monitor. Now the printer should work.
7) Perhaps you want ccpd and the printer monitor automatically start on boot. For the first one, type
sudo update-rc.d ccpd defaults

Next, you may run command at point 6) going to Settings>Startup or following, for instance, this answer.
Remark. If the printer return silent on reboot, try to restart ccpd and captstatusui. You may also try to power off and on the printer. That worked for me.

A: so this printer needs Canon's CAPT driver; which they update regularly; this post from yesterday on this forum is about the same CAPT driver; Any Way to make Canon LBP2900B Printer work on Ubuntu 17.04 Zesty? so have a read as it is very similar to yours; please delete any setup for your LBP6000 from the PRINTERS folder; if it does not work ... I assume you have 64bit install ..
so there are 4 steps to get it working:
1) install drivers; you need the latest drivers from here http://support-asia.canon-asia.com/contents/ASIA/EN/0100459601.html as they were issued 15th May 2017; SAVE as you download it and it should end up in your Downloads folder; then issue the following commands; by copying them; and pasting them one by one into a terminal; hit the ENTER key after each paste ..
cd Downloads
tar -zxvf linux-capt-drv-v271-uken.tar.gz
cd linux-capt-drv-v271-uken/64-bit_Driver/Debian
sudo dpkg -i cndrvcups-common_3.21-1_amd64.deb
and then  sudo dpkg -i cndrvcups-capt_2.71-1_amd64.deb and drivers now installed ...
2) register the printer again, please copy this and paste it into the terminal ..copy it all .. it is a long string of data ...
sudo /usr/sbin/lpadmin -p LBP6000 -P /usr/share/cups/model/CNCUPSLBP6018CAPTK.ppd -v ccp://localhost:59787 -E
3) Register the printer in the ccpd daemon setup file
sudo /usr/sbin/ccpdadmin -p LBP6000 -o /dev/usb/lp0
4) Start ccpd daemon
sudo /etc/init.d/ccpd start
at that point, your printer should print: please post back and tell us how things are: please, please ..!!

A: the command sudo ccpdadmin asks for the status of the ccpdadmin so please see how ours appears: we have 2 usb printers: the first is allocated to /usb/lp0 and the second, the LBP, is allocated to /usb/lp1 and if you have 2 printers on your usb, then if the LBP6000 is the second in the rankings, then it needs to be lp1


text:
Q: request for member 's' in something not a structure or union I'm trying to use an array of structs and everytime I try to assign a value to any struct, it gives me this error:
request for member 's' in something not a structure or union

My struct:
struct {
    char s;
    int lineNum;
} item;

I'm declaring it this way:
struct item * stack[100];

And then:
/* both lines gives me the error */
    stack[0].s = 'a';
    stack[0].lineNum = 1;

Am I missing something here?

A: You do not have a struct item.
stack is an array of 100 pointer to an as yet undefined struct.
Try
struct item {
    char s;
    int lineNum;
};

A: You need this:
struct item {
    char s;
    int lineNum;
} ;
...
struct item * stack[100];
...
stack[0]->s = 'a';
stack[0]->lineNum = 1;

but beware: you need to allocate memory for each item in stack. stack contains 100 pointers to struct items, but each of these pointers contains garbage (they all point to invalid memory).
For each element in stack you need to allocate memory like this stack[n] = malloc(sizeof struct item).

A: struct item stack[100] is what you want for your code that follows. What you have is an array of pointers, each of which if you wish to use, you will need to allocate, before your declaration.

A: You have not defined struct item. You currently have a single variable named item of an anonymous struct. It appears you forgot to include the typedef:
typedef struct { ... } a_t; // can use "a_t" as type.

struct a { ... }; // can use "struct a" as type.

typedef struct a { ... } a_t; // can use "struct a" or "a_t" as type.

A: stacks is not an array of items, it's an array of pointers to items, so you need to dereference them before attempting to use them:
(*(stack[0])).s = 'a';
(*(stack[0])).lineNum = 1;


text:
Q: R Bug in the Googleway Package I am using the Googleway package and I don't have any difference between
"pessimistic", "optimistic" & best_guess" as well as results are similar when mentioning "driving", "walking" or "cycling" modes.
Maybe I am wrong in my code:
google_distance(origins = "place Viarme 44000 nantes",
                             destinations = "rue de strasbourg Nantes",
                             mode="driving",
                             departure_time=heure_dep,
                             traffic_model='best_guess',
                             key = key,
                             simplify = T)
google_distance(origins = "place Viarme 44000 nantes",
                             destinations = "rue de strasbourg Nantes",
                             mode="bicycling",
                             departure_time=heure_dep,
                             traffic_model='best_guess',
                             key = key,
                             simplify = T)

Thanks

A: This should now be fixed in the latest release version (v2.2.0)
google_distance(origins = "place Viarme 44000 nantes",
                                destinations = "rue de strasbourg Nantes",
                                mode="driving",
                                departure_time=heure_dep,
                                traffic_model='best_guess',
                                key = key,
                                simplify = T)
# ...
# $rows
# elements
# 1 1.3 km, 1308, 6 mins, 368, 5 mins, 292, OK

google_distance(origins = "place Viarme 44000 nantes",
                                destinations = "rue de strasbourg Nantes",
                                mode="driving",
                                departure_time=heure_dep,
                                traffic_model='pessimistic',
                                key = key,
                                simplify = T)

# ...
# $rows
# elements
# 1 1.3 km, 1308, 6 mins, 368, 5 mins, 293, OK

google_distance(origins = "place Viarme 44000 nantes",
                                destinations = "rue de strasbourg Nantes",
                                mode="bicycling",
                                departure_time=heure_dep,
                                traffic_model='best_guess',
                                key = key,
                                simplify = T)

# ...
# $rows
# elements
# 1 1.4 km, 1364, 6 mins, 331, OK

google_distance(origins = "place Viarme 44000 nantes",
                                destinations = "rue de strasbourg Nantes",
                                mode="walking",
                                departure_time=heure_dep,
                                traffic_model='best_guess',
                                key = key,
                                simplify = T)
# ...
# $rows
# elements
# 1 1.2 km, 1187, 15 mins, 915, OK


text:
Q: Hide table rows on checkbox checked I have row of checkboxes received from database:
<?php foreach($user_types as $user_type): ?>

  <input type="checkbox" class="custom-control-input user-filter" data-id3="<?=$user_type['user_type']?>" name='user_type[]' value="<?=$user_type['user_type']?>">

  <?= $user_type['user_type'] ?>

<?php endforeach; ?>

usually it's something like :

And I have a table with users:

      users

      users

    <?php if(!empty($users)): ?>
    <?php foreach($users as $usr): ?>
      <tr class="filter-row" data-id3="<?=$usr['user_type'];?>" id="row<?=$usr['user_type'];?>"><?= strtolower($usr['username']); ?>

    <?php endforeach; ?>
    <?php endif; ?>

What I want to do is to apply filter. When I click on checkbox table should leave only required user_types.
What I tried in my script:
$(function() {
//    console.clear();
$('.user-filter').click(function() {
    var user_type = $(this).data("id3");
    $(".accordion-users tr").each(function() {
       var trow_id = $(this).data("id3"); // Here you go
       if(trow_id === user_type){
           //$("#row"+user_type).toggle('slow');
           //$('.filter-row').toggle('slow');
           console.log(trow_id);

       }
       //console.log(trow_id);
    });

    $('.test').html(user_type);
});
});

I tried to receive id of each row in the table and compare it. Now I am stuck not sure what should I do next. Are there any solutions on this? Thank you

A: I edited the selector for the each loop to select only the table rows with the clicked checkbox filter value. Then i'm checking wether the checkbox is checked or not. If it's checked I'm showing the tr, if it's not I'm hiding the tr.

$(function() {
  $('.user-filter').click(function() {
    var user_type = $(this).data("id3");
    var checked = $(this).is(':checked');
    $(".accordion-users tr[data-id3=" + user_type + "]").each(function() {
      if (checked)
        $(this).show(); //Show if checkbox is checked
      else
        $(this).hide(); //Hide if checkbox is not checked
    });

    $('.test').html(user_type);
  });
});

  <input type="checkbox" class="custom-control-input user-filter" data-id3="FT" name='user_type[]' value="FT" checked> FT
    <input type="checkbox" class="custom-control-input user-filter" data-id3="CT" name='user_type[]' value="CT" checked> CT

      users

      users

      Usr 1 (CT)

      Usr 2 (FT)

      Usr 3 (FT)


text:
Q: Mongoose keeps creating indexes for old fields that do not exist anymore So I had a model User with username and password fields. Later I changed it to use email instead of username. A similar change was made on another model - I renamed username to name. Both fields used unique validation from mongoose-unique-validator. Now, whenever I start the server, the mongoose created indexes for all fields, old and new. The first and the last things do not exist in the schemas anymore:
Mongoose: users.ensureIndex({ username: 1 }, { unique: true, background: true })
Mongoose: people.ensureIndex({ name: 1 }, { unique: true, background: true })
Mongoose: people.ensureIndex({ uri: 1 }, { unique: true, background: true })
Mongoose: people.ensureIndex({ username: 1 }, { unique: true, background: true })

Dropping database did not help, changing database did not help. I really do not understand where it might be coming from. Is there some sort of caching in mongoose?

A: Okay, the reason for this was the passport-local-mongoose that I was using incorrectly. It creates the indexes automatically. I needed to specify in the options, not just the local strategy, which fields I want to use for username and password. And for the second model it was just mistakenly plugged.


text:
Q: Disable jQuery datepicker on mobile, input type="date" I have a small problem with detection and disable jQuery date picker in mobile phones.
I have this JavaScript code (enable datepicker):
$( "input[type='date']" ).datepicker();

And CSS (hide Chrome native datepicker):
input::-webkit-calendar-picker-indicator{ display: none;}
input[type="date"]::-webkit-input-placeholder{ visibility: hidden !important;}

On the desktop, this works fine, but on mobiles, two date pickers are displaying.
I want hide jQuery Datapicker, but avoid scripts like Modernizr.
Maybe someone can help me with some CSS or little JavaScript?
example code:
<!DOCTYPE>
<html>
<head>
<title> Datepicker</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
input::-webkit-calendar-picker-indicator{ display: none;}
input[type="date"]::-webkit-input-placeholder{ visibility: hidden !important;}

</style>
</head>
<body>
    <form>
    <input type="date" />
    </form>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<script>
 $(function() {
  $( "input[type='date']" ).datepicker({
            dateFormat: "yy-mm-dd",
            firstDay: 1 })
});

</script>
</body>
</html>

I place this code here: http://www.stack.puniserv.pl/
I want to resign from jQuery date picker in mobile.

A: You can use CSS @media querys to hide elements on mobile viewports. Adjust breaking point to desired, 767px is used as example, so when viewport is above that it should be visible and when below hidden. Make sure you set the querys at the end of your CSS file.
@media (max-width: 767px) {
   input::-webkit-calendar-picker-indicator {
      display: none;
   }
   input[type="date"]::-webkit-input-placeholder {
      visibility: hidden !important;
   }
}


text:
Q: How can I type hint the return type of .values() in a custom dict subclass? When I type check the following class with mypy it throws an error

error: Returning Any from function declared to return "Optional[SomeDictValueType]"

in get_by_id as the type of .values() isn't defined/restricted properly.
class SomeDict(dict):
    def __init__(self) -> None:
        self._some_attribute: SomeRandomType = None

    def get_by_id(self, id: str) -> Optional[SomeDictValueType]:
        for p in self.values():
            if p._id == id:
                return p
        return None

I found similar questions online and tried the following things:

*

*adding type hints to __setitem__ as explained here
 def __setitem__(self, key: str, value: SomeDictValueType) -> None:
     super(SomeDict, self).__setitem__(key, value)

*using Mapping in the class header as explained here
 class SomeDict(dict, Mapping[str, SomeDictValueType]): ...

How can I get rid of this error without using # type: ignore? Instances of this class will never hold values of a type other than SomeDictValueType.

EDIT:
Here is a minimalistic example to reproduce the error. Save the following code snippet to a python file and execute mypy --strict <filename>.py on it.
from typing import Optional

class SomeDict(dict):  # type: ignore
    def __init__(self) -> None:
        self._some_attribute: Optional[str] = None

    def get_by_id(self, id: str) -> Optional[int]:
        for p in self.values():
            if p._id == id:
                return p
        return None

The following error should be thrown:

test.py:10: error: Returning Any from function declared to return
"Optional[int]"

A: mypy is correct. Since you iterate over values(), it can not tell what is the type of the dict value, it consider it as Any.

A: I think, I just figured it out. I thought you cannot subclass from a typing definition (I tried it once at the beginning but got another error and didn't look close enough).
In my opinion, the following snippet would be a solution for the minimalistic error reproducing example.
from typing import Optional, Dict

class SomeDict(Dict[str, int]):
    def __init__(self) -> None:
        self._some_attribute: Optional[str] = None

    def get_by_id(self, id: str) -> Optional[int]:
        for p in self.values():
            if p == 5:
                return p
        return None


text:
Q: "reentrant call to SetCurrentCellAddressCore" in event handlers - only where cell row and column indices are equal I am making a WinForms application which includes a form that uses a DataGridView to handle simple data manipulation. To ensure accurate entry while mitigating clutter (read: without using DataGridViewComboBoxColumn) I have a couple event handlers which temporarily turn a DataGridViewTextBoxCell into an equivalent DataGridViewComboBoxCell connected to values known to be "clean" when editing events are raised (typically when an editable cell is clicked):
private void OnCellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    //construct a textbox cell and set to current value
    DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
    cell.Value = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

    //color row if invalid or modified
    UpdateRowStyle(dataGridView.Rows[e.RowIndex]);

    //switch to the new cell and redraw
    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
    dataGridView.Refresh();
}

and
private void OnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    //construct a combobox cell, link to data, and set to current value
    DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
    cell.DataSource = mDropDownValues[dataGridView.Columns[e.ColumnIndex].Name];
    cell.Value = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

    //switch to the new cell and redraw
    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
    dataGridView.Refresh();
}

Most of the time this works perfectly - the last cell edited reverts to a DataGridViewTextBoxCell containing the newly selected data, and the cell selected for editing becomes a DataGridViewComboBoxCell linked to the data specified in the mDropDownValues[] dictionary. When editing a cell which has row and column indices that are equal, however, I run into trouble. The cell fails to change between the two types, throwing an exception on the dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell; line in both event handlers (once when handling CellBeginEdit and then again when handlingCellEndEdit). The exception states

"Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function."

What is causing this error, and why does it only happen when editing the cells along the DataGridView's diagonal? Is there some way I can achieve this functionality without throwing this exception?

A: You are doing battle with this statement in SetCurrentCellAddressCore(), edited for readability:
        // Allow the code to be re-entrant only as a result of
        // underlying data changing.
        if (this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] &&
           (this.dataConnection == null || !this.dataConnection.ProcessingListChangedEvent))
        {
            throw new InvalidOperationException(SR.GetString(SR.DataGridView_SetCurrentCellAddressCoreNotReentrant));
        }

The DATAGRIDVIEWOPER_inCurrentCellChange flag is true.  DataGridView has a lot of these kind of checks, no doubt added after extensive testing.  It limits the number of things you can do while an event is raised, ensuring that the re-entrancy does not corrupt internal state of the control.
The universal solution to these kind of re-entrancy problems is to perform the operation later, after the event is raised and the internal state of the control is stable again.  You can do so elegantly with the BeginInvoke() method, it runs when your program re-enters the dispatcher loop.  Like this:
private void OnCellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    this.BeginInvoke(new Action(() => {
        //construct a textbox cell and set to current value
        DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
        cell.Value = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

        //color row if invalid or modified
        UpdateRowStyle(dataGridView.Rows[e.RowIndex]);

        //switch to the new cell and redraw
        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
        dataGridView.Refresh();
    }));
}


text:
Q: _imex_ error in sas When I use PROC IMPORT for importing data from an excel file I get an error something like "IMEX". My excel is an older version.
If I change it to a newer version and run the same code I'm able to import the data.
Is there any way to import data from an older version of an excel?


text:
Q: What's the name of this nice spring contact? Ah, it is really a beauty isn't it (see picture below)? Around the package you see some spring contacts, really, really nice. I have some ESP8266MOD modules and like to use these spring contacts before soldering anything on the pins.

What is/are the name of this/these contact(s)?

Update 04/12/2018:
@bitsmack came up with the idea that these springs could be test-loops and search on it and found this picture:

He could be right!

A: I can't tell well enough from the image, but is there any chance they're these with a leg cut off? Are they about 2.7 mm dia.?

They're from Toby Electronics.


text:
Q: How do I fix "invalid command 'WSGIScriptAlias'" error when running mod_wsgi with Apache I am trying to run a Django project through Apache with Mod_wsgi on Windows. I installed Apache as a service and installed mod_wsgi to my Python, and then copied it over to my Apache modules. I added the configuration details that the mod_wsgi documentation talks about, but when I try to run Apache it triggers:
"Mod_Wsgi Error: "invalid Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration...."
mod_wsgi downloaded to Apache modules
Apache httpd.conf:
Define SRVROOT "C:\Users\(me)\Desktop\httpd-2.4.51-win64-
VS16\Apache24"

ServerRoot "C:\Users\(me)\Desktop\httpd-2.4.51-win64
VS16\Apache24"

WSGIScriptAlias /C:/Users/(me)/Desktop/coding_stuff/django_webpage_project/django_webpage_project/wsg
 i.py

WSGIPythonHome C:/Users/(me)/Desktop/coding_stuff/env/venv_1
WSGIPythonPath C:/Users/(me)/Desktop/coding_stuff/django_webpage_project

<Directory/C:/Users/(me)/Desktop/coding_stuff/django_webpage_project/django_webpage_project>
 <Files wsgi.py>
 Require all granted
 </Files>
 </Directory>

A: Issue was that the Mod_wsgi files I downloaded were missing the 'modules.so' shared object file that Apache needs to run Mod_wsgi. Still don't know where to acquire this file, but that is certainly the issue.


text:
Q: Implementing a rest api using zf3 I want to build a new REST API for my application on the base of zend framework 3. Because I'm very new in zend two things are a bit misunderstanding for me: I know there's a component named zf-rest and I also know how to include it via composer. But how does zf-rest "knows" that I want to work with ZF3?
And then I found some sample applications using zf-rest and some only using zend-mvc. So I guess that zend already has a rest implementation. What are the differences between zf-rest and zend-mvc and in which situations should I use which framework?


text:
Q: force jshint or syntastic to ignore html tags inside .js file I use jshint + syntastic, and inside my js file
  class Channel extends React.Component{
      onClick() {
          console.log("I was clicked", this.props.name);
      }
      render(){
          return (

{this.props.name}

          )
      }
  }

line with
 is an error "unclosed regular expression" how can i tell jshint or syntastic to ignore such errors?

A: With jshint you can mark such code with ignore:start / ignore:end to disable the jshint:
  render(){
      // jshint ignore:start
      return (

{this.props.name}

      )
      // jshint ignore:end
  }

Alternatively you can use jsxhint or eslint. Syntastic has checkers for both.
Update: eslint and jsxhint are not in the list of syntastic's default javascript checkers, so you will also need to add something like this into your .vimrc:
let g:syntastic_javascript_checkers = ['eslint']


text:
Q: Undefined Reference when using a C++ library function Using Code::Blocks and the GNU GCC compiler, I went along and made my own library:
//main.cpp (Library)
int SampleAddInt(int i1, int i2)
{
    return i1 + i2;
}

Compiled it to a .a file. I then made a separate project to test the library function with. Made sure I linked it correctly in the Build Options. Here's my code using it in my project:
//main.cpp (Test Project)
#include <iostream>

using namespace std;

//Declaration of function from library
int SampleAddInt(int i1, int i2);

int main(){
    int x = SampleAddInt(2, 4);
    cout << x << "test" << endl;
}

Got this error when trying to compile my Test Project:

main.cpp|9|undefined reference to `SampleAddInt(int, int)'|

For some reason it can't seem to find this function. I then wrapped extern "C" { ... } around the declaration in my Test Project main.cpp source and it built correctly.
Why, when my library was compiled from a main.cpp source, do I need to use extern "C" for my library to work with my Test Project? And why when I don't use extern "C", does the compiler tell me that the function is an undefined reference?

A: Got it working.
The problem was it had to do with Code::Blocks.
It was using the gcc compiler instead of g++ so I was forced to use extern "C" if I wanted to run any of my library code.
To fix this I right clicked main.cpp, clicked Properties, and changed the variable from "CC" to "CPP" and it now compiles with g++.


text:
Q: Change ST_Intersects default tolerance The default tolerance of PostGIS ST_Intersects query is "0.00001 meters" as indicated in the doc. I need to use the same query with another tolerance value but ST_Intersects takes only 2 input parameters (geom A and geom B).
Is there a way to change this default value?

A: PostGIS is opensource, indeed you can create a new function for ST_INTERSECT with Tolerance parameter as input or update the function itself with value you are interested in, then run it.
Here is the code snippet where tolerance is dynamic, you can run below script in your DB and it will be create under PUBLIC schema :
CREATE OR REPLACE FUNCTION ST_Intersects(geography, geography,float8)
    RETURNS boolean
    AS 'SELECT $1 && $2 AND _ST_Distance($1, $2, 0.0, false) < $3'
    LANGUAGE 'sql' IMMUTABLE ;

Link for original function of ST_Intersects(geo,geo):
https://github.com/postgis/postgis/blob/c0998a4e638048196a6abfab1504eca6b1a1462f/postgis/geography.sql.in#L720


text:
Q: Simple style change does not apply I've followed the first part of this guide by:

*

*Creating and applying my own theme.

*Using the web/css/source/_extend.less that's on the guide.

*Deleting the mentioned directories.

*Refreshing the page.

But the button style did not change.
What am I missing?

A: Login to admin, go to System -> Cache Management in the bottom of the page you could see the three flush cache button option. click the JS/css and static flush cache button then clear the cache of your browser also. load the page it will get reflect.
have good luck


text:
Q: Remove item from redux form field array by its name and not index Redux Form has FieldArray field:
https://redux-form.com/6.0.0-rc.3/docs/api/fieldarray.md/
I am trying to delete multiple of items from it but remove() method only works for a single removal perhaps because each time the fields get one item smaller and the index determined by me is bigger than the fields array:
      <MultiSelect
          placeholder="Delete project group"
          onChange={(v) => {
            const diff = difference(addedGroups, v)
            if (!isEmpty(diff)) {
              const groupToDelete = diff[0]
              forEach(projectsByGroup[groupToDelete], p => removeElement(addedProjects.indexOf(p)))
              deleteGroup(groupToDelete)
          }}
          options={projectGroupNames}
          value={addedGroups}
          inline
    />

Where removeElement is fields.remove FieldArray function. How to remove correctly multiple items from FieldArray selectively?

Update:

I have also tried to use change in my reducers like that:
import { change } from 'redux-form'

export const deleteVariantSearchProjectGroup = (projectGroupGuid) => {
  return (dispatch, getState) => {
    const state = getState()
    const projectsInGroup = state.projectsByProjectGroup[projectGroupGuid]
    const allProjectFields = getProjectsFamiliesFieldInput(state)
    const remainingProjectFields = allProjectFields.filter(projectField => !projectsInGroup.includes(projectField.projectGuid))
    change(SEARCH_FORM_NAME, 'projectFamilies', remainingProjectFields)
    dispatch({ type: UPDATE_VARIANT_SEARCH_ADDED_GROUPS, newValue: without(getState().variantSearchAddedProjectGroups, projectGroupGuid) })
  }
}

I get correctly an array remainingProjectFields but then change(SEARCH_FORM_NAME, 'projectFamilies', remainingProjectFields) does not do anything.

A: I was not able to actually find a way to remove fields one by one with fields.remove but ultimately I solved it by using a reducer and updating Redux Form state using change method:
import { change } from 'redux-form'

export const deleteVariantSearchProjectGroup = (projectGroupGuid) => {
  return (dispatch, getState) => {
    const state = getState()
    const projectsInGroup = state.projectsByProjectGroup[projectGroupGuid]
    const allProjectFields = getProjectsFamiliesFieldInput(state)
    const remainingProjectFields = allProjectFields.filter(projectField => !projectsInGroup.includes(projectField.projectGuid))
    dispatch(change(SEARCH_FORM_NAME, 'projectFamilies', remainingProjectFields))
    dispatch({ type: UPDATE_VARIANT_SEARCH_ADDED_GROUPS, newValue: without(getState().variantSearchAddedProjectGroups, projectGroupGuid) })
  }
}

and deleteVariantSearchProjectGroup = deleteGroup in the very first jsx code snippet in the question.


text:
Q: Broyden's method implementation in Python I am trying to write an implementation of the Broyden method in Python. I have an example in Matlab, trying to rewrite it but unsuccessfully.
+A is the Jacobian matrix
F - 4 eloquent matrix:
function F=f(X)
 F(1)=X(1)+2*X(2)+X(3)+4*X(4)-20.7;
 F(2)=X(1)^2+2*X(1)*X(2)+X(4)^3-15.88;
 F(3)=X(1)^3+X(3)^2+X(4)-21.218;
 F(4)=3*X(2)+X(3)*X(4)-7.9;
 F=F(:);

for iii=1:itmax
    deltax=-A\f(x);

    x=x+deltax; fi1=f(x);
    %A=A+(fi1-fi-A*deltax)*deltax'/(deltax'*deltax);
    a1 = A*deltax;
    a2 = fi1-fi;
    a3 = a2-a1;
    a4 = a3*deltax';
    a5 = deltax'*deltax;
    a6 = a4/a5;
    A=A+a6;

    tikslumas=norm(deltax)/(norm(x)+norm(deltax));

    if tikslumas < eps
        fprintf(1,'\n x ='); fprintf(1,'  %g',x);
        fprintf(1,'\n  f ='); fprintf(1,'  %g',f(x));
        break
    elseif iii == itmax
        fprintf(1,'\n ****failed: x ='); fprintf(1,'  %g',x);
        fprintf(1,'\n  f ='); fprintf(1,'  %g',f(x));
        break
fi=fi1;
end

I am trying to do the same in Python:
for i in range(1, itmax):
    deltax,resid,rank,s = np.linalg.lstsq(A, f(x))
    for j in range(len(deltax)):
        deltax[j] = -deltax[j]
    for j in range(len(deltax)):
        x[j] = x[j] + deltax[j]
    fi1=f(x);
    deltaxT = np.matrix(deltax).T
    a1 = np.multiply(A, deltax)
    a1 = a1.sum(axis=1)
    a2 = np.subtract(fi1,fi)
    a3 = np.subtract(a2,a1)
    a4 = np.multiply(a3,deltaxT)
    a4 = np.matrix(a4).T
    a5 = (np.multiply(deltax,deltax)).sum(axis=0) #???? gal???
    a6 = np.divide(a4,a5)
    A=A+a6;

But the result after 3-4 for cycle aren't the same and final result is totally different