text:
Q: javax.mail not sends emails and not showing any error I have some Java function that should send emails to users.
In the past this function works as well, but i dont understand why it is not working anymore.
When i try to use this function, it is not send email and it is not show any error.
Can you explain me what could be the problem?
[The tool that contains this function, run on a Linux server (CentOS)]

This is the function:
public static void sendEmail(String to) throws JSONException, IOException {
        String from = "test@test.com";                  // Sender's email ID needs to be mentioned
        String host = "localhost";                                  // Assuming you are sending email from localhost

        Properties properties = System.getProperties();             // Get system properties
        properties.setProperty("mail.smtp.host", host);             // Setup mail server
        Session session = Session.getDefaultInstance(properties);   // Get the default Session object.

        try{
            MimeMessage message = new MimeMessage(session);         // Create a default MimeMessage object.
            message.setFrom(new InternetAddress(from));             // Set From: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));    // Set To: header field of the header.

            // Set Subject: header field
            message.setSubject("Some test subjet");

            // Now set the actual message
            message.setText("test message");

            // Send message
            Transport.send(message);
        }
        catch (MessagingException mex) {
            mex.printStackTrace();
        }

    }


text:
Q: Jax vectorization: vmap and/or numpy.vectorize? what are the differences between jax.numpy.vectorizeand jax.vmap?
Here is a small snipset
import jax
import jax.numpy as jnp

def f(x):
     return jnp.exp(-x)*jnp.sin(x)

gf = jax.grad(f)
x = jnp.arange(0,1,0.1)

jax.vmap(gf)(x)
jnp.vectorize(gf)(x)

Both computations give the same results:
DeviceArray([ 1.        ,  0.80998397,  0.63975394,  0.4888039 ,
0.35637075,  0.24149445,  0.14307144,  0.05990037,
-0.00927836, -0.06574923], dtype=float32)
How to decide which one to use, and if there is a  difference in terms of performance?

A: jax.vmap and jax.numpy.vectorize have quite different semantics, and only happen to be similar in the case of a single 1D input as in your example.
The purpose of jax.vmap is to map a function over one or more inputs along a single explicit axis, as specified by the in_axes parameter. On the other hand, jax.numpy.vectorize maps a function over one or more inputs along zero or more implicit axes according to numpy broadcasting rules.
To see the difference, let's pass two 2-dimensional inputs and print the shape within the function:
import jax
import jax.numpy as jnp

def print_shape(x, y):
  print(f"x.shape = {x.shape}")
  print(f"y.shape = {y.shape}")
  return x + y

x = jnp.zeros((20, 10))
y = jnp.zeros((20, 10))

_ = jax.vmap(print_shape)(x, y)
# x.shape = (10,)
# y.shape = (10,)

_ = jnp.vectorize(print_shape)(x, y)
# x.shape = ()
# y.shape = ()

Notice that vmap only maps along the first axis, while vectorize maps along both input axes.
And notice also that the implicit mapping of vectorize means it can be used much more flexibly; for example:
x2 = jnp.arange(10)
y2 = jnp.arange(20).reshape(20, 1)

def add(x, y):
  # vectorize always maps over all axes, such that the function is applied elementwise
  assert x.shape == y.shape == ()
  return x + y

jnp.vectorize(add)(x2, y2).shape
# (20, 10)

vectorize will iterate over all axes of the inputs according to numpy broadcasting rules. On the other hand, vmap cannot handle this by default:
jax.vmap(add)(x2, y2)
# ValueError: vmap got inconsistent sizes for array axes to be mapped:
# arg 0 has shape (10,) and axis 0 is to be mapped
# arg 1 has shape (20, 1) and axis 0 is to be mapped
# so
# arg 0 has an axis to be mapped of size 10
# arg 1 has an axis to be mapped of size 20

To accomplish this same operation with vmap requires more thought, because there are two separate mapped axes, and some of the axes are broadcast. But you can accomplish the same thing this way:
jax.vmap(jax.vmap(add, in_axes=(None, 0)), in_axes=(0, None))(x2, y2[:, 0]).shape
# (20, 10)

This latter nested vmap is essentially what is happening under the hood when you use jax.numpy.vectorize.
As for which to use in any given situation:

*

*if you want to map a function across a single, explicitly specified axis of the inputs, use jax.vmap

*if you want a function's inputs to be mapped across zero or more axes according to numpy's broadcasting rules as applied to the input, use jax.numpy.vectorize.

*in situations where the transforms are identical (for example when mapping a function of 1D inputs) lean toward using vmap, because it more directly does what you want to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VB.NET 2015 Nullable Integer Not Working with If() operator? Why is this result 0 (zero) and NOT Nothing?
Dim foobar As Integer? = If(False, 1, Nothing)

From Microsoft Documentation:

If a variable is of a value type, the behavior of Nothing depends on
  whether the variable is of a nullable data type. To represent a
  nullable value type, add a ? modifier to the type name. Assigning
  Nothing to a nullable variable sets the value to null. For more
  information and examples, see Nullable Value Types.

Further research yields even more interesting results:
Dim foo As Integer? = If(False, 1, Nothing)             '0
Dim bar As String = If(False, 1, Nothing)               '"0"
Dim bar2 As String = If(False, "1", Nothing)            'Nothing
Dim bar3 As Integer? = If(False, "1", Nothing)          'Nothing
Dim bar4 As Integer? = If(False, CStr(1), Nothing)      '0

Does the following suggest that the result type is predicated on the type second value?
Dim bar3 As Integer? = If(False, "1", Nothing)          'Nothing

EDITED with additional finding  and desired result, but why should BOTH arguments need to be evaluated and not just the short-circuited version of If()?
Dim foo As Integer? = IIf(False, 1, Nothing)             'Nothing

A: A fix for If operator,
Dim foo As Integer? = If(False, 1, New Nullable(Of Integer))

and one other
    Dim foo As Integer?
    If True Then
        foo = 1
    End If

A: In addition to dbasnett's answer, you can do:
Dim foo As Integer? = If(False, 1, CType(Nothing, Integer?))


text:
Q: Products of Dirac delta distributions in multiple dimensions Following up on Integral over product of Dirac delta functions, I have the following generalization of the question (arising from a problem in quantum mechanics):
If I have the product of two Dirac delta distributions with non-identical arguments
$$\tag{1}\label{eq:1}
\langle r_{rel} r_{cm} \vert r_1 r_2 \rangle
    = \delta\big( (r_1-r_2) - r_{rel} \big) \times \delta\big( \tfrac12 (r_1+r_2) - r_{cm} \big),
$$
can I somehow argue that it is "equivalent" to the alternate form
$$\tag{2}\label{eq:2}
\langle r_1 r_2 \vert r_{rel} r_{cm} \rangle
    = \delta\big( (r_{cm} + \tfrac12 r_{rel}) - r_1 \big) \times \delta\big( (r_{cm} - \tfrac12 r_{rel}) - r_2 \big) ?$$
(Note here that we can consider these as representing the change of variables $(r_1,r_2)\rightarrow(r_{rel},r_{cm})$ and $(r_{rel},r_{cm})\rightarrow(r_1,r_2)$, respectively.)

If I try to show that these two forms are equivalent by, e.g., integrating against test functions, I either end up with an integration variable appearing in the argument to two of the delta distributions or with some reordering of integration which I'm not sure I can justify. (In that sense, this may also be a question about Fubini's theorem in the theory of distributions.)
For instance, integrating each of these against the test functions $f(r_1,r_2)$, $g(r_{rel},r_{cm})$, I get
$$\tag{3}\label{eq:1int}
\int dr_1\, dr_2 \int dr_{rel}\, dr_{cm} \, f(r_1,r_2) g(r_{rel},r_{cm}) \delta\big( (r_1-r_2) - r_{rel} \big) \delta\big( \tfrac12 (r_1+r_2) - r_{cm} \big) \\= \int dr_1 \, dr_2 \, f(r_1,r_2) g(r_1-r_2, \tfrac12(r_1+r_2))
$$
$$\tag{4}\label{eq:2int}
\int dr_{rel}\, dr_{cm} \int dr_1\, dr_2 \, f(r_1,r_2) g(r_{rel},r_{cm}) \delta\big( (r_{cm} + \tfrac12 r_{rel}) - r_1 \big) \delta\big( (r_{cm} - \tfrac12 r_{rel}) - r_2 \big) \\= \int dr_{rel} \, dr_{cm} \, f(r_{cm}+\tfrac12 r_{rel},r_{cm}-\tfrac12 r_{rel}) g(r_{rel},r_{cm})
$$

*

*Is it a problem that I'm doing the multiple integrals in a different order between $\eqref{eq:1int}$ and $\eqref{eq:2int}$ if I want to show the equivalence of $\eqref{eq:1}$ and $\eqref{eq:2}$?

*Is it sufficient to do the somewhat trivial change of variables $(r_1,r_2)\rightarrow (r_{rel},r_{cm})$ on $\eqref{eq:1int}$ to show that it is equal to $\eqref{eq:2int}$, and is that sufficient to establish the equality/equivalence of $\eqref{eq:1}$ and $\eqref{eq:2}$?

A: *

*Let us for concreteness consider a 3D position space $\mathbb{R}^3$. (The generalization to other dimensions is straightforward.) Consider position operators $\hat{\bf r}_1$ and $\hat{\bf r}_2$ for 2 non-identical particles.

*In a rigged Hilbert space we define eigenkets
$$|{\bf r}_1,{\bf r}_2\rangle, \tag{1} $$
such that
$$ \hat{\bf r}_1 |{\bf r}_1,{\bf r}_2\rangle~=~{\bf r}_1|{\bf r}_1,{\bf r}_2\rangle, \qquad
\hat{\bf r}_2 |{\bf r}_1,{\bf r}_2\rangle~=~{\bf r}_2|{\bf r}_1,{\bf r}_2\rangle, \tag{2}$$
and
$$ \langle {\bf r}_1,{\bf r}_2 | {\bf r}^{\prime}_1,{\bf r}^{\prime}_2\rangle
~=~\delta^3({\bf r}_1\!-\!{\bf r}^{\prime}_1)\delta^3({\bf r}_2\!-\!{\bf r}^{\prime}_2) .\tag{3}$$

*Define operators
$$ \hat{\bf r}_{\rm cm}~:=~\frac{\hat{\bf r}_1+\hat{\bf r}_2}{2},\qquad \hat{\bf r}_{\rm rel}~:=~\hat{\bf r}_1-\hat{\bf r}_2, \tag{4} $$
and corresponding kets
$$|{\bf r}_{\rm cm},{\bf r}_{\rm rel}\rangle\!\rangle~:=~|{\bf r}_1,{\bf r}_2\rangle, \qquad
{\bf r}_{\rm cm}~\equiv~\frac{{\bf r}_1+{\bf r}_2}{2},\qquad
{\bf r}_{\rm rel}~\equiv~{\bf r}_1-{\bf r}_2. \tag{5} $$

*One may use eqs. (2), (3), (4) & (5) to show that the kets (5) are eigenkets
$$ \hat{\bf r}_{\rm cm} |{\bf r}_{\rm cm},{\bf r}_{\rm rel}\rangle\!\rangle~=~{\bf r}_{\rm cm}|{\bf r}_{\rm cm},{\bf r}_{\rm rel}\rangle\!\rangle, \qquad
\hat{\bf r}_{\rm rel} |{\bf r}_{\rm cm},{\bf r}_{\rm rel}\rangle\!\rangle~=~{\bf r}_{\rm rel}|{\bf r}_{\rm cm},{\bf r}_{\rm rel}\rangle\!\rangle, \tag{6}$$
and normalized
$$ \langle\!\langle {\bf r}_{\rm cm},{\bf r}_{\rm rel} | {\bf r}^{\prime}_{\rm cm},{\bf r}^{\prime}_{\rm rel}\rangle\!\rangle
~=~\delta^3({\bf r}_{\rm cm}\!-\!{\bf r}^{\prime}_{\rm cm})\delta^3({\bf r}_{\rm rel}\!-\!{\bf r}^{\prime}_{\rm rel}). \tag{7}$$
In eq. (7) we used how higher-dimensional Dirac delta distributions transform under coordinate transformations, cf. e.g. my Math.SE answer here. It is important that the Jacobian of the transformation (4) is one.

*Similarly, one may show that the overlap is
$$ \langle {\bf r}_1,{\bf r}_2 | {\bf r}^{\prime}_{\rm cm},{\bf r}^{\prime}_{\rm rel}\rangle\!\rangle
~=~\delta^3(\frac{{\bf r}_1+{\bf r}_2}{2}\!-\!{\bf r}^{\prime}_{\rm cm})\delta^3({\bf r}_1-{\bf r}_2\!-\!{\bf r}^{\prime}_{\rm rel}), \tag{8}$$
etc.


text:
Q: Example of finding the conditional expected amount of time a person spends waiting in line given that she is eventually served This is an Example from Ross' Introduction to Probability Models. I don't understand the answer to this question. Namely, why $W_n$ is given in the below equation from the argument given in the preceding sentence. I would greatly appreciate it if anyone could explain this in more detail.
Example 5.10. Suppose that customers are in line to receive service that is provided sequentially by a server; whenever a service is completed, the next person in line enters the service facility. However, each waiting customer will only wait an exponentially distributed time with rate $\theta$; if its service has not yet begun by this time then it will immediately depart the system. These exponential times, one for each waiting customer, are independent. In addition, the service times are independent exponential random variables with rate $\mu$. Suppose that someone is presently being served and consider the person who is $n$th in line.
(b) Find $W_n$, the conditional expected amount of time this person spends waiting in line given that she is eventually served.
Solution. To determine an expression for $W_n$, we use the fact that the minimum of independent exponentials is, independent of their rank ordering, exponential with a rate equal to the sum of the rates. Since the time until the $n$th person in line enters service is the minimum of these $n+1$ random variables plus the additional time tehreafter, we see , upon using the lack of memory property of exponential random variables, that
$$W_n = \frac{1}{n\theta + \mu}+W_{n-1}$$
Repeating the preceding argument with successively smaller values of $n$ yields the solution
$$W_n = \sum_{i=1}^n \frac{1}{i\theta + \mu}$$

A: The time spent waiting for service when you are the $n^\text{th}$ customer in line is equal to the time spent in the $n^\text{th}$ position plus the time spent in the $n-1^\text{th}$ position, plus the time spent in the $n-2^\text{th}$ position, and so on.
By construction, the time spent in all the positions but the $n^\text{th}$ is $W_{n-1}$. Hence, all we need to figure out is how long in expectation it will take you to leave the $n^\text{th}$ position in line.
You leave the $n^\text{th}$ spot when someone in front of you decides to depart, or if the first customer in the queue is served. This time is exponentially distributed with rate $n\theta + \lambda$, hence the expression in the first term of $W_n$.


text:
Q: Axis labels off-center when broken over multiple lines I am using graph twoway scatter and adding my own ylabels.
I often have long labels and break them over multiple lines. However, I encounter a problem when I want to break some labels over two lines, but not others.
When I do this, the single-line labels are off-center relative to their tick marks, as if Stata expected them to also have two lines.
See below for a simple illustration:
sysuse auto, clear

/* This graph has one long label and one short but both are off-center
relative to their tick marks */

twoway scatter length weight, ytitle("") ylabel(220 ///
`" "This one is a very long" "label, broken up" "' 140 "This one is not", ///
ang(horizontal))

/* The order of labels on the graph *does not* appear to matter */

twoway scatter length weight, ytitle("") ylabel(180 ///
`" "This one is a very long" "label, broken up" "' 220 "This one is not", ///
ang(horizontal))

/* But the order in the command *does* appear to matter */

twoway scatter length weight, ytitle("") ylabel(220 ///
"This one is not" 140 `" "This one is a very long" "label, broken up" "', ///
ang(horizontal))

This is not a huge problem, but one I have noticed for years and knowing why my graphs behave this way would be nice.

A: It is not clear what exactly causes this but one can make an educated guess.
It appears that if you change your code to include all strings in double quotes, the problem goes away. Using your toy example:
sysuse auto, clear

twoway scatter length weight, name(gr1) ytitle("") ylabel(220 ///
`" "This one is a very long" "label, broken up" "' 140 `" "This one is not" "', ///
ang(horizontal))

twoway scatter length weight, name(gr2) ytitle("") ylabel(180 ///
`" "This one is a very long" "label, broken up" "' 220 `" "This one is not" "', ///
ang(horizontal))

twoway scatter length weight, name(gr3) ytitle("") ylabel(220 ///
`" "This one is not" "' 140 `" "This one is a very long" "label, broken up" "', ///
ang(horizontal))

This probably has to do with how the code is parsed internally and suggests that Stata expects the second string to have the same number of quotes as the first one.
Only StataCorp can definitively answer your question, but hopefully the above example provides you with a clue about what is going on.


text:
Q: How to avoid magic string in class field_name in python, something like nameof() in c# for example, in this python code.
from scrapy.loader import ItemLoader
from myproject.items import Product

def parse(self, response):
    l = ItemLoader(item=Product(), response=response)
    l.add_xpath('name', '//div[@class="product_name"]')
    l.add_xpath('name', '//div[@class="product_title"]')
    l.add_xpath('price', '//p[@id="price"]')
    l.add_css('stock', 'p#stock]')
    l.add_value('last_updated', 'today') # you can also use literal values
    return l.load_item()

How to avoid use 'name', 'price' as a string.
there are any way to use, something like
 l.add_xpath(getname(Product.name), '//div[@class="product_title"]')
 l.add_xpath((getname(Product.price), '//p[@id="price"]')

Thanks

A: By using getattr builtin function
 product = Product()
 l.add_xpath(getattr(product, 'name'), '//div[@class="product_title"]')


text:
Q: Оптимальный и безопасный способ доступа извне к приватному std::string с гарантией readonly Мне, как человеку избалованному Qt implicit sharing, хочется понять как грамотно действовать в следующей ситуации в стандартном C++. Имеется класс, содержащий приватную переменную (например std::string) с большим объемом данных. Необходимо иметь к ней доступ без копирования, с гарантией того, что хитровыделанный пользователь класса не поменяет ее извне. Пример:
using namespace std;
class A
{
public:
    // data - большой текстовый массив
    A(string* data) : _data(data) {}
    // копирование (медленно)
    string data_1() const { return *_data; }
    // const_cast позволит залезть в _data
    const string* data_2() const { return _data; }
private:
    string* _data;
};

Как обычно поступают в таком случае?

A: Такой вариант Вам удобен?
using namespace std;
class A
{
public:
   // используем std::move для "тяжелого объекта"
   explicit A(std::string data) : _data(std::move(data)) {}
   // ничего не копируем
   const std::string& data() const noexcept { return _data; }
private:
   // тоже const, все равно инициализируем строку в конструкторе
   const std::string _data;
};


text:
Q: boost::asio, threads and synchronization This is somewhat related to this question, but I think I need to know a little bit more.  I've been trying to get my head around how to do this for a few days (whilst working on other parts), but the time has come for me to bite the bullet and get multi-threaded.  Also, I'm after a bit more information than the question linked.
Firstly, about multi-threading.  As I have been testing my code, I've not bothered with any multi-threading.  It's just a console application that starts a connection to a test server and everything else is then handled.  The main loop is this:
while(true)
{
    Root::instance().performIO(); // calls io_service::runOne();
}

When I write my main application, I'm guessing this solution won't be acceptable (as it would have to be called in the message loop which, whilst possible, would have issues when the message queue blocks waiting for a message.  You could change it so that the message-loop doesn't block, but then isn't that going to whack the CPU usage through the roof?)
The solution it seems is to throw another thread at it.  Okay, fine.  But then I've read that io_service::run() returns when there is no work to do.  What is that?  Is that when there's no data, or no connections?  If at least one connection exists does it stay alive?  If so, that's not so much of a problem as I only have to start up a new thread when the first connection is made and I'm happy if it all stops when there is nothing going on at all.  I guess I am confused by the definition of 'no work to do'.
Then I have to worry about synchronizing my boost thread with my main GUI thread.  So, I guess my questions are:

*

*What is the best-practice way of using boost::asio in a client application with regard to threads and keeping them alive?

*When writing to a socket from the main thread to the IO thread, is synchronization achieved using boost::asio::post, so that the call happens later in the io_service?

*When data is received, how do people get the data back to the UI thread?  In the past when I used completion ports, I made a special event that could post the data back to the main UI thread using a ::SendMessage.  It wasn't elegant, but it worked.

I'll be reading some more today, but it would be great to get a heads up from someone who has done this already.  The Boost::asio documentation isn't great, and most of my work so far has been based on a bit of the documentation, some trial/error, some example code on the web.

A: 1) Have a look at io_service::work. As long as an work object exists io_service::run will not return. So if you start doing your clean up, destroy the work object, cancel any outstanding operations, for example an async_read on a socket, wait for run to return and clean up your resources.
2) io_service::post will asynchronously execute the given handler from a thread running the io_service. A callback can be used to get the result of the operation executed.
3) You needs some form of messaging system to inform your GUI thread of the new data. There are several possibilities here.
As far as your remark about the documention, I thing Asio is one of the better documented boost libraries and it comes with clear examples.

A: boost::io_service::run() will return only when there's nothing to do, so no async operations are pending, e.g. async accept/connection, async read/write or async timer wait. so before calling io_service::run() you first have to start any async op.
i haven't got do you have console or GUI app? in any case multithreading looks like a overkill. you can use Asio in conjunction with your message loop. if it's win32 GUI you can call io_service::run_one() from you OnIdle() handler. in case of console application you can setup deadline_timer that regularly checks (every 200ms?) for user input and use it with io_service::run(). everything in single thread to greatly simplify the solution

A:
1) What is the best-practice way of using
  boost::asio in a client application
  with regard to threads and keeping
  them alive?

As the documentation suggests, a pool of threads invoking io_service::run is the most scalable and easiest to implement.

2) When writing to a socket from the main
  thread to the IO thread, is
  synchronization achieved using
  boost::asio::post, so that the call
  happens later in the io_service?

You will need to use a strand to protect any handlers that can be invoked by multiple threads. See this answer as it may help you, as well as this example.

3) When data is received, how do people
  get the data back to the UI thread? In
  the past when I used completion ports,
  I made a special event that could post
  the data back to the main UI thread
  using a ::SendMessage. It wasn't
  elegant, but it worked.

How about providing a callback in the form of a boost::function when you post an asynchronous event to the io_service? Then the event's handler can invoke the callback and update the UI with the results.

A:
When data is received, how do people get the data back to the UI thread? In the past when I used completion ports, I made a special event that could post the data back to the main UI thread using a ::SendMessage. It wasn't elegant, but it worked

::PostMessage may be more appropriate.
Unless everything runs in one thread these mechanisms must be used to safely post events to the UI thread.


text:
Q: The before_action call back do not execute while running the integration test cases rails using ruby 2.6.5, Rails 6.0.3.7
There is before_action filter which are working fine when running the project in the development server. But while running the integration tests of the rails application.
The call back do not execute and the request goes directly to the called function rather than going to the before action first.
Here attaching my controller and integration test case and error output.
Controller
class TvSeriesController < ApplicationController
  before_action :check_file, only: [:create, :tv_seriel_comments]

  require 'roo'

  def index
    @tv_series = TvSeriel.includes(:comments).all
  end

  def show
    @series = TvSeriel.includes({ comments: [:user] }).find(params[:id])
  end

  def create
    spreadsheet = Roo::Spreadsheet.open(params[:file])
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |line|
      row = HashWithIndifferentAccess[[header, spreadsheet.row(line)].transpose]
      tv_serial = TvSeriel.new
      tv_serial.name = row['TV Series']
      tv_serial.genre = row["Genre"]
      tv_serial.seasons = row["No of seasons"]
      tv_serial.release_date = row["Date of First Release"]
      tv_serial.director = row["Director"]
      tv_serial.actor = row["Actor"]
      tv_serial.shoot_location = row["Shoot location"]
      tv_serial.country = row["Country"]
      tv_serial.save
    end
    flash[:notice] = 'TV series uploaded!'
    redirect_back(fallback_location: tv_series_index_path)
  end

  def tv_seriel_comments
    spreadsheet = Roo::Spreadsheet.open(params[:file])
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |line|
      row = HashWithIndifferentAccess[[header, spreadsheet.row(line)].transpose]
      comment = Comment.new
      user = User.find_by_name(row["User"])
      comment.user = user
      tv_serial = TvSeriel.find_by_name(row['TV Series'])
      comment.tv_seriel = tv_serial
      comment.stars = row['Stars']
      comment.review = row['Review']
      comment.save
    end
    flash[:notice] = 'TV series comment uploaded!'
    redirect_back(fallback_location: tv_series_index_path)
  end

  def destroy
    TvSeriel.find(params[:id]).destroy
    flash[:notice] = 'TV series removed success!'
    redirect_back(fallback_location: tv_series_index_path)
  end

  def search_actor
    @tv_series = TvSeriel.includes(:comments).where("actor like ?", "%#{params[:actor]}%")
    render 'tv_series/index'
  end

  ## check if uploaded file is a cvs
  def check_file
    unless params[:file].blank?
      if params[:file].content_type.eql?("text/csv")
      else
        flash[:alert] = "file format Invalid, expected: text/csv Got #{params[:file].content_type}"
        redirect_back(fallback_location: :tv_series_index_path)
      end
    else
      flash[:alert] = 'Please provide a file to be uploaded !'
    end
  end
end

Integration test:
require 'test_helper'

class UserFlowsTest < ActionDispatch::IntegrationTest
  fixtures :all
  include Devise::Test::IntegrationHelpers
  include Warden::Test::Helpers

  test 'Get list of all users' do
    @user = users(:vidur)
    sign_in(@user)
    get "/users"
    assert_response :success
    assert_select "h2", "User List"
  end

  test 'Update Series' do
    @user = users(:vidur)
    sign_in(@user)
    post '/tv_series'
    assert_response :success
  end

end

Error:
# Running:

E

Error:
UserFlowsTest#test_Update_Series:
TypeError: no implicit conversion of nil into String
    app/controllers/tv_series_controller.rb:15:in `create'
    test/integration/user_flows_test.rb:19:in `block in <class:UserFlowsTest>'

Here the before_action filter do not execute and the request goes directly to the defined action can any body give the reason why only running test, and how to correct it, Thanks in advance.
Here is the git repo for complete code: https://github.com/vidurpunj/sopra_test.

A: It's because you don't have a file parameter.
So your check_file is using this part:
flash[:alert] = 'Please provide a file to be uploaded !'

And since you don't render or redirect, the controller action is called normally. See the Rails documentation on filters for more details:

If a "before" filter renders or redirects, the action will not run


text:
Q: Update client computer using web application I am developing an e-commerce web application, and in that ads from other giants pop up. I figured out that this is done by PriceFountain, which is actually a spyware. I found the steps to remove that from my laptop. more found here.
but the problem is my clients can also have this adware. I want to programmatically do following or either of them, on the client side:: (and if it is not possible at least inform the user to do so)

*

*If, PriceFountain is present, uninstall it from their system. If it is an add-on, remove that.

*Activate the pop-up blocker (deactivation can be achieved through javascript and jquery). But I want to activate. My site does not need pop-ups.

*Alter the registry of user for the contents of PriceFountain.
I know this is somewhat an unethical hack, but can this be achieved and if so, how?
More of that, it is just my curiosity can we affect client site settings.?

A: You used to be able to do that (with jscript/vbscript) in IE if and only if the user added your site to his trusted sites (and allowed pretty much everywhere there), or if it was the intranet-site with relaxed permissions.
Back in the old day's I had such a thing for the intranet-help-site where users could browse through the faq and click on the 'execute solution' button for the common 'problems' (previously solved and added to DB).
For rather obvious security-reasons this is no longer the case (although one can still pull some stuff in legacy IE environments).
The point is: you can't do this on other browsers then IE (unless maybe you'd develop separate plug-ins for them and ask your users to install something that will essentially give you access to their whole machine). Realize that effectively what you are asking for is a way to fully control the user's machine. Would you install such a browser (on your parents pc)?
The best course of action would be to face-up, inform your users on your main-website (enter-page) that something bad spread throughout an ad-network and guide them through the steps (that you already found) necessary to relieve them from their problem.
Even if what you asked was possible, you'd still need the user's cooperation somewhere along the way, even if you'd were to write an application for this that the users could download and run (administrative/elevated)..
Good Luck!
EDIT: for the registry you might try something with the answers in this question: read/write to Windows Registry using Java
Still, you'd still need the user's co-operation.


text:
Q: Sublime TextEditor 2 in Vintage mode completion I have several problem with my autocompletion which I want to fix:

*

*I have completion by Space. I want that when I press Space means I don't want completion I want a space symbol now.

*I want to choose a completion of a word by Tab, it is possible in SE2, but the completion popup list is closing when Tab is pressed. I want to see avoid closing in this case.

*How to make popup list window bigger?

*I use SublimeClang and the completion is very lagging (despite Core i7 3rd gen with 8G Memory). I know this plugin has fast_completion mode, but it is very bad, so that there is no sense in this completion at all. How to make this plugin to show the last parsing result of completion and prepare new result in another tread?


text:
Q: How To Choose Subsets To Form A Matrix Of Combinations I have created (after a few months of learning VBA and then switching to Python) a script that will backtrack and select the combinations of a number, n, in an order that is equivalent to the combinations of n of a higher selection, k.
Or another way of saying it: I create a matrix of 5 supersets by doing 5C4. I create a list of 10 subsets by doing 5C2. I then use backtracking to choose each subset to form the supersets.
Example using [A, B, C, D, E]:
5C4 = 5 supersets -> [ABCD,
ABCE,
ABDE,
ACDE,
BCDE]
Likewise, 5C2 = 10 subsets -> [AB,
AC,
AD,
AE,
BC,
BD,
BE,
CD,
CE,
DE]
Finally, 5(subsets)*2(groups)=10(supersets) results into something like:
[[(A, B), (C, D)]
 [(A, C), (D, E)]
 [(A, D), (B, E)]
 [(A, E), (B, C)]
 [(B, D), (C, E)]]

*

*granted there are a few different matrix solutions that could arise based on the order you have the list of 5C2.. but I have spent way toooo much time on figuring out the correct/general way of doing this, which seems like unnecessary information. I have also gone down the rabbit hole of making sure that I can arrange the subsets in a way that each element of result[row][col][element] appears in the col a specific number of times. And after I find a faster way of selecting subsets, I will reorder them to do this (as a bonus if anyone knows how to do this; I am thinking permutations). Did you know that you can get occurrence of each element from Pascal's triangle... But I digress.

Backtracking works for smaller numbers, but if I do something larger, let's say 17C15(superset) = 17C3(subset)*5(groups), the code runs too long (stopping it after +40h).
In these examples here is the logic of why I think this should work:
5C2 = 10
5C4 =  5
5C4 * 2(groups) = 10

17C3  = 680
17C15 = 136
17C15 * 5(groups) = 680

1.) Is my logic correct? I considered that when choosing an n, k_1 < (n/2), k_2 > (n/2), and k_1|k_2 (k_2 is a multiple of k_1).
2.) If this is the most practical way of choosing subsets, then can anyone help optimize my code?
from itertools import combinations, chain

families = range(1, 6)
choose = 2
groups = 2
size = int(choose*groups)
teams = list(combinations(families, choose))
cluster = list(combinations(families, size))
team_len = int(len(teams)/groups)
zero_set = [(0) for _ in range(choose)]

def check(grid, row, column, subset):
    # check if combo(subset) is a subset of cluster's row
    if ((set(subset) & set(cluster[row])) != set(subset)):
        return False
    check = set(x for x in chain(*grid[row]))
    if(set(tuple(x) for x in grid[row]).intersection(set(subset))):
        return False
    if(check.intersection(set(subset))):
        return False
    for x in range(team_len):
        for y in range(groups):
            # check if used already
            if (grid[x][y] == subset):
                return False
    return True

def solve(grid, row, column):
    if(row == team_len and column == groups - 1): return True
    if(row == team_len):
        column += 1
        row = 0

    if grid[row][column] > zero_set:
        return solve(grid, row, column + 1)

    for subset in teams:
        if check(grid, row, column, subset):
            grid[row][column] = subset
            if solve(grid, row + 1, column):
                return True
        grid[row][column] = zero_set
    return False

grid = [[zero_set]*groups for _ in range(team_len)]
if solve(grid, 0, 0):
    print("success")
for x in grid:
    print(x)

print("finished")

This returns:
success
[(1, 2), (3, 4)]
[(1, 3), (2, 5)]
[(1, 5), (2, 4)]
[(1, 4), (3, 5)]
[(2, 3), (4, 5)]
finished

Success criteria would be to have all 680 combinations used once (no repetitions) in the final matrix, grid.
families = range(1, 18)
choose = 3
groups = 5


text:
Q: Traversing Scheme function as a list Isn't it possible to treat functions in Scheme as any other list?
Basically, what I want do to is something like this:
(define (foo) "hello")

(cdr foo)  ; or similar, should return the list ((foo) "hello")

I've found a similar discussion about this, and I feel a bit disappointed if this is not possible with Scheme.  If so, why is this impossible?  Is it possible in other lisps?
EDIT:  Changed (cdr 'foo) to (cdr foo) -- it was misleading.  I'm asking, why can't I access a function as a list?

A: I have often wanted to be able to do the same thing csl.
Below is a quick example of how you could go about doing this in mzscheme.
DrScheme 4.2
(module qdefine mzscheme
  (provide ;(all-from-except mzscheme let)
   (rename define olddefine)
   (rename quote-define define)
   (rename quote-cdr cdr)
   (rename quote-car car))

  (define define-list '())
  (define define-list-add
    (lambda (key value)
      (set! define-list (cons `(,key ,value) define-list))))

  (define-syntax quote-define
    (syntax-rules ()
      ((_ (pro-name args ...) body ...)
       (begin
         (define (pro-name args ...) body ...)
         (define-list-add pro-name  '((pro-name args ...) body ...))))
      ((_ pro-name pro) (begin
                          (define pro-name pro)
                          (define-list-add pro-name 'pro)))

      ))

  (define quote-cdr (lambda (lst)
                      (if (procedure? lst)
                          (cdr (cadr (assoc lst define-list)))
                          (cdr lst))))

  (define quote-car (lambda (lst)
                      (if (procedure? lst)
                          (car (cadr (assoc lst define-list)))
                          (car lst))))
  )
(require 'qdefine)

(define testfunc (lambda (args) args))
(cdr testfunc)
(car testfunc)

(define (testfunc2 test) 'blah)
(cdr testfunc2)
(car testfunc2)

(define testlist '(1 2 3 4 5 6 'a))
(cdr testlist)
(car testlist)

Outputs:
((args) args)
lambda
('blah)
(testfunc2 test)
(2 3 4 5 6 'a)
1
>

A: Your define form is not a function but a function definition.  In fact, it is a shorthand for
(define foo
  (lambda ()
    "hello"))

Lambda can be thought of as a "compiler invocation".  In this case, it produces a function which returns that string.  Define then binds this function to the symbol 'foo.
Compare this to
(define foo "hello")

which binds just the string to the symbol 'foo.  What would (cdr foo) return?
Now, it is imaginable that some Scheme implementation actually saves or has the option to save the lambda form when binding a function to a symbol.  You will have to check the documentation, but the kind of pure interpretation this implies surely would have an impact on performance.
If you manage to get this, though, it will return the lambda form, not the define form.

A: MIT Scheme has the ability to do this. (If you really want, comment on this and I'll give you the code. I had to find some undocumented functions to make it happen.)
However, it's not in the Scheme language definition, so implementations don't have to allow it. The reason for this is that in order to make functions faster, a good Scheme implementation will modify the functions. This means both rewriting them in a different language (either machine code or something fairly low-level) and taking out any bits you don't need - for instance, the + function must in general check whether its arguments are numbers, and if so, what sort of numbers, but if your function is a loop which calls +, you can just check once at the beginning, and make the function a lot faster.
Of course, you could still keep the lists around without too much trouble, even with all of these things. But if you tried to modify the lists, how would it work?
(Again, you could make it work. It would just be more work for implementers, and since it's not usually used in programs, most people probably just don't want to bother.)

A: In guile,

guile> (define (foo bar) 'baz)
  guile> (procedure-source foo)
   (lambda (bar) (quote baz))
  guile> (cdr (procedure-source foo))
   ((bar) (quote baz))
  guile>

A: 'foo evaluates to a symbol, you can't take the CDR of a symbol.
What you may want to do is (cdr foo), but this does not work. The value of a FOO is a procedure, not a list.

A: You might be able to access the function as a list using pp or pretty-print.  That said, you might also need to run your code in debug mode.   This is very implementation dependent however. I know it can work in Gambit-C.

A: (define (foo) ...) produces a compiled object, and it's a value - a procedure.
You cannot iterate over it because it is not an s-expression.
Like what other suggested, you should check out your programming environment and see
if it has any facilities for such tasks.


text:
Q: Lambda Function(Go) can't send email with SES SMTP Hello I've followed the instructions here to try and get my lambda function able to send email via SES SMTP https://docs.aws.amazon.com/ses/latest/dg/send-email-set-up-vpc-endpoints.html
In my Lambda Function I use the net/smtp package and when I try to send the email it gives me this error

Error sending email alert dial tcp: lookup email-smtp.us-east-1.amazonaws.com on ..*.1:53: no such host

Here is the code for sending the email that is giving me issues. Note when I rung this Go code locally it works fine.

    user := os.Getenv("SMTP_USER")
    password := os.Getenv("SMTP_PASSWORD")

    to := []string{
        "testemail@gmail.com",
    }

    addr := "email-smtp.us-east-1.amazonaws.com:587"
    host := "email-smtp.us-east-1.amazonaws.com"

    msg := []byte("From: test@test.com\r\n" +
        "To: test@test.com\r\n" +
        "Subject: Test mail\r\n\r\n" +
        "Email Body \r\n")

    auth := smtp.PlainAuth("", user, password, host)

    err = smtp.SendMail(addr, auth, from, to, msg)```

A: I was able to finally get the SMTP working. Everything in that document in the OP was correct except the security group part. In order to get it to work, I had to set the inbound and outbound rules of my security group (not entirely sure if outbound is necessary) to use the entire IP address range of the subnet in my VPC for use1-az1 for source/destination respectively.


text:
Q: Add see more/see less button customized I want to add a see more/see less button with customization: the custom is a plus (+) icon as the image below.

I was able to doing this with the following code:

function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");

if (dots.style.display === "none") {
 dots.style.display = "inline";
 btnText.innerHTML = "See more here";
 moreText.style.display = "none";
} else {
 dots.style.display = "none";
 btnText.innerHTML = "See less";
 moreText.style.display = "inline";
}
}
/*read more button*/
#more {
display: none;
}

.fa-plus-circle {
font-size: 40px;
float: left;
margin: 5px;
vertical-align: super;
color: #a41a3c;
}

.fa-plus-circle:before {
content: "\f055";
}

#myBtn {
background-color: #fff;
border: none;
width: 13%;
}

#myBtn h4 {
font-size: 13px;
margin: 17px 0 0 0;
}

 <button onclick="myFunction()" id="myBtn">

See more here

 </button>

The problem is when I click the button, the style of the button disappear and the icon as well as below image:

I would like to keep the style of the button and also change the icon with a minus (-) icon.
Can anybody help me on this situation please?

A: The problem i see is basically because of the more div in your code as everything else is placed in it as a child so when more display gets none you don't see the style getting applied.I think you should avoid changing styles of the more div and then see whats happening

A: I think the btnText.innerHTML where reversed in the function. Also, you forgot to look for the h4, you were replacing everything of #myBtn.
Note: It's better to add css classes than to change style.
Try

function myFunction() {

 var dots = document.getElementById("dots");
 var btnText = document.querySelector("#myBtn h4");

 if (dots.classList.contains("hidden")) {

   dots.classList.remove("hidden");
   btnText.innerHTML = "See less";
 } else {
   dots.classList.add("hidden");
   btnText.innerHTML = "See more here";
 }
}
/*read more button*/

.hidden {
   display: none;
}

.centering {
   text-align: center;
}

.bottom_spacer {
   margin-bottom:20px;
}

.fa-plus-circle {
   font-size: 40px;
   float: left;
   margin: 5px;
   vertical-align: super;
   color: #a41a3c;
}

.fa-plus-circle:before {
   content: "\f055";
}

#myBtn {
   background-color: #fff;
   border: none;
   width: 13%;
}

#myBtn h4 {
   font-size: 13px;
   margin: 17px 0 0 0;
   white-space: nowrap
}
(+) something  (+) somethingelse

  <button onclick="myFunction()" id="myBtn">

See more here

  </button>


text:
Q: How to add the AM or PM to time date format in ANT task? I have a date and time stamp that I would like to add the AM or PM value to. I haven't found the way to do this. Here is my code:
<target name="updateDate">

    <propertyset id="tdate"></propertyset>

    <tstamp>
        <format property="tdate" pattern="MM-dd-yyyy HH:mm"/>
    </tstamp>

    <echo>Updating build date to: ${tdate}</echo>

    <replaceregexp byline="true">
        <regexp pattern="BUILD_DATE:String\s+=\s+(['|"])([a-zA-Z0-9-:\s]+)(['|"])"/>
        <substitution expression="BUILD_DATE:String = \1${tdate}\3"/>
        <fileset dir="project/src/model">
            <include name="ProjectModel.as"/>
        </fileset>
    </replaceregexp>

</target>

A: Straight from the documentation:

a     Am/pm marker    Text    PM

So
<format property="tdate" pattern="MM-dd-yyyy HH:mm a"/>

Note that this is redundant with HH, since HH prints the hour from 00 to 23. Use hh to get the hour from 01 to 12.


text:
Q: Is it possible to have dedicated page for parent/child taxonomy? I've been working non-stop on this for the past few days. I have a post type, floorplan, which has a hierarchical taxonomy called County. Each County taxonomy has child taxonomies with the names of communities within each county, which I've been able to apply to the post permalinks by following This Guide. So my post urls are now floorplans/{parent-county}/{child-county}/{the-floorplan}
Now, I have a custom county-taxonomy.php template that displays all posts of this type that have the county taxonomy assigned. The url is floorplans/{parent-county} where parent county is the parent taxonomy. This template will also display if you navigate to the url floorplans/{child-county} where child-county is the child taxonomy.
HOWEVER, if I try to navigate to floorplans/{parent-county}/{child-county}, I get a 404.
So my basic question, is it possible to modify the permalink of the taxonomy page such that it includes both parent and child?


text:
Q: Unknown Shape definition [CIRCLE] I'm trying to create a new document unfortunately I'm facing this kind of exception:

Unable to parse shape given formats "lat,lon", "x y" or as WKT because
java.text.ParseException: Unknown Shape definition [CIRCLE (2.175888
41.388587, 20)]

This is my request :
/update
{

  "id": 4,
  "document_type_id": 4,
  "geo": "CIRCLE (2.175888 41.388587, 20)"

}

This is my filetype:
  <fieldType name="location_rpt" class="solr.SpatialRecursivePrefixTreeFieldType" maxDistErr="0.001" spatialContextFactory="org.locationtech.spatial4j.context.jts.JtsSpatialContextFactory" validationRule="repairBuffer0" distErrPct="0.025" distanceUnits="kilometers"  autoIndex="true" geo="true"/>

This is my geo field:
<field name="geo" type="location_rpt" multiValued="true" indexed="true" stored="true"/>

A: CIRCLE shape is no more supported with Sorl. We should use instead SHAPE(POINT(lon lat), DISTANCE in °degree).


text:
Q: PDF processing library in Erlang I am looking for a PDF processing library written in Erlang, but I was unable to find any yet. ErlGuten, the only library I found could only generate PDFs not process them.
Anyone aware of such library?

A: I think your best option is to bridge with a 3rd party PDF library. Such as Adobe's own PDF Library SDK or another lesser known vendor.
See; http://www.adobe.com/devnet/pdf/library/

A: There is an open source library based on webkit: WKHTMLTOPDF
It generates PDF from an HTML template.
And here is small tutorial of how we are using it whith an Erlang backend.

A: Maybe Jinterface is the best way.Try to process PDFs with Java.


text:
Q: Installing LaTeX on Macbook Pro I have recently bought Macbook Pro and want to install LaTeX. I am using TeXstudio, but I need to install MiKTeX which I was using earlier in Windows. Please suggest what to install as an alternative to MiKTeX for my Mac.

A: Just out of curiosity why do you need MiKTeX? What is a particular TeX functionality you are seeking which is present in MiKTeX but not in MacTeX?
You question actually have a very simple answer and I am going to offer to you even though I am sure it will be down voted by the members of the community. It looks to me that you are very familiar with Windows but not so much with OS X. The good news is that Windows runs better on MAC hardware than on the native PC hardware.
All you need to do is go and by $300 of your favorite operating system. Unlike PC MAC do not have BIOS but Extensible Firmware Interface. Once you brake into it you can install Windows on Macbook Pro just like on any PC. Word of caution though. Once installed Windows will look really ugly as it will miss drivers for most of MAC hardware. No worries Apple people have already sold you hardware so they will give you Windows drivers. You just need to go to Apple store and get Boot Camp. Once you run it, it will automatically detect missing drivers and install it for you. After one more reboot you will have a magnificent Macbook Pro running you beloved Windows. Now you are ready for the final step. You can go download and install MikTeX just like you would do on the regular PC. IIRC the prefered way of installing MikTeX is using ProTeXt distribution.
Disclaimer: I not BS-ing you. I have actually done all of above for my boss who loves Apple hardware but prefers to run Windows mostly because of Microsoft Office product which is his bread and butter. Having compared MS Office Windows and OS X version I could tell you that makes lots of sense.

A: The cheapest, most stable, most popular option is (as Paulo says) to install MacTeX.
It is downloadable as an all-in-one package file (.pkg); just double-click and you're good to go.
MacTeX comes with a few editors, namely TUG's TeXworks and the acclaimed TeXShop, but you can also get TeXstudio for Mac as well.
You will find that, as OS X is a UNIX-based environment, working with TeXnology may prove to be a little simpler than doing so under Windows.


text:
Q: Need meaning of below debug message while authenticating via LDAP Got Ldap context on server

This is a part of Debug message.Was the first bind successful?
2X Mar 201X 15:36:36,880 DEBUG [ambari-client-thread-37] FilterBasedLdapUserSearch:115 - Searching for user 'XXXX', with user search [ searchFilter: '(&(sAMAccountName={0})(objectClass=posixAccount))', searchBase: '', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ]
2X Mar 201X 15:36:36,917 DEBUG [ambari-client-thread-37] AbstractContextSource:349 - Got Ldap context on server 'ldap://rXXX92.corp.XXX.com:389/DC=corp,DC=XXX,DC=com'
2X Mar 201X 15:36:36,929 DEBUG [ambari-client-thread-37] DefaultAuthenticationEventPublisher:94 - No event was found for the exception org.apache.ambari.server.security.authorization.InvalidUsernamePasswordCombinationException
2X Mar 201X 15:36:36,929 DEBUG [ambari-client-thread-37] AmbariBasicAuthenticationFilter:185 - Authentication request for failed: org.apache.ambari.server.security.authorization.InvalidUsernamePasswordCombinationException: Unable to sign in. Invalid username/password combination.

A: No.
Looks like LDAP credentials are wrong: "Unable to sign in. Invalid username/password combination"


text:
Q: R - Combine multiple random forests contained in a list Is there a quick and easy way to pass randomForest objects contained in a list into the combine() function?
As a result of calling randomForest through lapply(), I now have 10 randomForests in a list (rfors).
I want to combine all 10 of them. Understandably combine(rfors) doesn't work as it doesn't recognise the individual forests within the list.
I have spend quite sometime messing around with unlist(), lapply() and apply() to try and extract the information in a suitable format but to no avail. The only thing that works is combine(rfors[[1]], rfors[[2]] ...etc).
This is a bit cumbersome though, not least because the number of random forests I'll need to combine is likely to change. Any sleek and elegant solution to this someone can suggest?

A: Using the example from ?combine:
data(iris)
rf1 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf2 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf3 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf <- do.call(combine,list(rf1,rf2,rf3))


text:
Q: Is there an efficient algorithm to distribute resources in a way that both avoids conflict and allows bias? Background

(Skip this if you only care about the algorithm)
At the university where I work, one of the biggest hassles in our department is classroom scheduling. For illustration purposes and to lay out the scope of the problem, here's how we do scheduling now:

*

*Professors give us a list of the classes they're teaching with the time slots they'd prefer to teach, ranked in order of priority (most desired to least desired).

*Administration gives us a list of the rooms we may assign along with the times those rooms are available for our department's use.

*We start assigning professors to rooms trying (at first) to take into account the preferences of the various professors.

*Inevitably, conflicts arise, professors start asking for changes, and the plan falls to pieces somewhere around professor number 30, at which point we start assigning rooms basically wherever we can fit them in, crumpled pieces of paper are everywhere, and nobody's happy. (If you've ever wondered why your class was at 9.30 in the morning on Thursday but 4 pm every other day, now you know)

I have been asked to quietly investigate whether software could do this more optimally.

The Actual Question
Is there an algorithm to efficiently schedule a set of resources such that the following criteria are met:

*

*The algorithm must never assign two professors to the same room at the same time.

*The task is not complete until every professor has been assigned a room / time.

*The algorithm need not worry about having too many professors for the amount of time slots available.  (We're not that well funded.)

*As much as is possible the algorithm should respect the scheduling preferences of the individual professors.

I feel like I can't be the first one to ask this.  Is there a efficient algorithm for this, or is this the sort of problem that can only be brute-forced?

A: There have been papers written on timetabling and scheduling problems for some time. A web search on the two words "timetabling package" turns up commercial and other packages for this.
I know of a problem domain where, despite spasmodic attempts to seek sophisticated solutions, people have ended up writing pretty basic programs implementing ad-hoc solutions - there has been no obvious sign of institutional learning in this field. The stated reason for this is that the users need to understand why the program makes its decisions, especially if it fails to solve the problem and they need to relax the constraints.
It sounds possible that your particular problem - if it is as simple as it at first sounds - could be solved by using the http://en.wikipedia.org/wiki/Assignment_problem, where you assign particular courses to particular room time-slots instead of agents to tasks.
It is possible that a program or algorithm will be influenced by the relative order of constraints in its input, especially if it encounters ties, where two solutions come out as equally good. I would be included to check for this, and, if so, to randomly re-order the input before presenting it to the program or algorithm in an attempt to at least turn bias into random luck.


text:
Q: Page_ClientValidate is not defined I Write a js function In MaterPage
 function CheckClientValidate(Validations) {
        Page_ClientValidate(Validations);
        if (Page_IsValid) {
            return true;
        }
        else {
            return false;
        }
    }

and i use the MaterPage in my webProject,amost the Page in the Project can use the func
but one get error like Page_ClientValidate is not defined
i can use the FireBug to find the func Page_ClientValidate but why show the error only the page?

A: May be your are not using master page on that particular page.


text:
Q: How to regroup Series after groupby? After some operations I have a series that i got after grouping by phone number and counting different calls. I need to count the phone numbers that have an equal number of calls. I mean, if there is 5 people who made 3 calls I need to get a series or a dataframe looking like:
num_calls
3    5
1    100
...

My series now looks like
phone_num
89248089190  5
48048102481  6
12948148014  2
14091404108  5

A: .value_counts() does that thing

A: For creating a DataFrame I did the following:
numbers = [89248089190, 48048102481, 12948148014, 14091404108]
calls = [5, 6, 2, 5]

df = pd.DataFrame({'numbers': numbers,
                   'calls': calls})

I then groupby 'calls'
num_calls = df.groupby('calls')

And then count the number of occurrences
count = num_calls.count()

        numbers
calls
2       1
5       2
6       1


text:
Q: Jquery won't load So hey guys, I'm trying run a html file for this angular 2 course I'm taking. After creating the dependancies for the app I downloaded them with npm. Now when I try to run the app, I get this error..
file:///Users/Rocky/Angular2-course/skeleton/node_modules/jquery/dist/jquery.min.js
Failed to load resource: net::ERR_FILE_NOT_FOUND
This is how I wrote the jquery script..
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/tether/dist/js/tether.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

A: If your files are in "./node_modules/jquery/dist/". Then, the script tag in your pages just looks like this:
<script src="/scripts/jquery.min.js"></script>

If you were using express with nodejs, a static route is as simple as this:
app.use('/scripts', express.static(__dirname + '/node_modules/jquery/dist/'));

Then, any browser requests from /scripts/xxx.js will automatically be fetched from your dist directory.
Note: Newer versions of NPM put more things at the top level, not nested so deep so if you are using a newer version of NPM, then the path names will be different than indicated in the OP's question and in the current answer. But, the concept is still the same. You find out where the files are physically located on your server drive and you make an app.use() with express.static() to make a pseudo-path to those files so you aren't exposing the actual server file system organization to the client.

A: If your'e using Angular, you want to try and avoid using jQuery since Angular comes with jqLite.
Try to the version of Bootstrap made for Angular 2.
Check out https://ng-bootstrap.github.io/#/getting-started
Also, ever though of linking them?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>


text:
Q: how to delete in phpmyadmin sql - all users with certain condition and all dependencies I have in my wordpress website a bunch of pages that has
mydomain.com/author/gertielamrertyk/
can someone help me create an sql that will delete all users with certain condition (in my case it is a jobsite using jobroller plugin - all users without job posting or resume) and cascade the delete (such as these author pages).
There are bunch of DDOS attack going into this author pages.


text:
Q: Silverlight Dropdown-box alphabetically ordered I've been busy with this for two days, and I can't get any further on it.
I have a Dropdown-box/Combobox (not sure what it's called) in Microsoft Silverlight, and my editor is Microsoft Visual Studio 2010. The Dropdown-box has to be alphabetically ordered, but I do not know where to find the source. This is what I do know:

*

*If I select the Dropdown box in the Designer, I can see that the
Data Binding is called "par_Customer(item)".

*On the left side of the Designer is a list of tables, including the
par_Customer table.

*Almost all tables have the text "Edit Query" next to them, and by
clicking on that the program opens a query editor with the right
query in it.

*The table I need, "par_Customer", does not have the text "Edit
Query" on it.

*When I right-click on the table, I get the options to Delete or Edit
the table.

*When I click Edit, I see a list of all the attributes (columns) of
that table and its relationships, yet no query or anything

*The Dropdown box is not filled by code.

What I would like to know: where do I find the source of this dropdown box? Where is it "filled"?
I would really appreciate any help or input on this problem, since I have no idea where to look any information will be of value.


text:
Q: Create Transformer Center-tap From 2nd Secondary After ordering this 200VA, 32V transformer, I realized that it doesn't have a center tap on each secondary, which I need to have. (duh on my part) So I want to use 110V across the 220V primary leads to give me half the voltage at each secondary, resulting in a single secondary of 32V and a center tap.
I know that this works because I have done it and observed that the output is 32V RMS with a center tap, but I want to make sure I'm not throwing away half the VA rating by doing so. I read TONS about transformers trying to get a definitive answer to this, and I think that the core saturation and the secondary wire size and associated voltage drop and heat are the main concerns, along with the fact that the ratio of number of turns is proportional to the ratio of the voltages and inversely proportional to the ratio of the currents in the primary and secondary. So on those points, I think I'm not reducing the usable 200VA, with the possible exception of secondary wire heating.
To illustrate what I mean using the image below, I would wire-nut the middle black and red primary wires together and connect 110V across the top red and bottom black wires. And on the secondary, I would connect the middle blue and green wires and use that connection as my center tap. I would use the top green and the bottom blue wires as my supply rails and there would be 32V RMS across these rails. If that's confusing for me to say rails, I'll add that I'm using a bridge rectifier and 2 shunt capacitors to make them into +/- 45-ish volt rails for an amplifier.

Yes, I know that this is NOT standard, and this is not for a commercial product, so please don't reply simply that this is not standard or that it will void my warranty.
There is a similar question here with 2 answers to my question, but unfortunately those two answers contradict each other exactly. Also, here is a question with a very promising title, but the answers don't answer my question. The other similar questions don't have answers which address the current-rating-doubling part.
Please weigh in if you know whether I can safely get the full 200VA in this way.

A: You will halve the rated VA of the transformer if you run it at half the rated input voltage.
The rated maximum VA is the product of maximum allowable Volts and maximum allowable Amps. The Amps will be unchanged, that's limited by wire heating. You've halved the Volts, so you've halved the VA, to first order at least. Running the core at half the field reduces the core losses, so the thermal load on the transformer is not quite so high. This means you can increase the thermal loading on the copper a little, at the expense of voltage drop aka voltage regulation. Maybe then the rated VA has only fallen to 55% and not to 50% of what it was.
If you have a centre-tapped 32 V, ie 16-0-16, you can bridge rectify that to about +/- 22 V. If you want +/- 45 V (that is, a total of 90 V from positive to negative, with ground in the middle), then the simplest way to get there is with a centre-tapped 64 V secondary (two 32 V secondaries in series), leaving your transformer configured and supplied as it sounds like it was meant to be, and like my audio amp transformer is.

simulate this circuit – Schematic created using CircuitLab

A: Transformer manufacturers generally don't leave much margin between what their device is capable of, and how they advertise it. If the transformer is advertised to handle 200VA, with two 32V secondaries, then it's nominal operating condition would be 3.125A in each secondary or a total of 6.25A. (6.25*32=200VA). Can you run 6.25A through those wires wired in series? Well, I would say no. You might be lucky, but there is a good chance there will soon be smoke coming out of your transformer.


text:
Q: Mysql, is it possible to get the total sums before doing calculation? i'm trying to do a calculation base on the condition but i got an error Error Code: 1111 Invalid use of group function
select sum( price - (price * if(sum(price)>200, 0.5, 0) ) ) from mytables; -- error

what i'm trying to do is, if the total sum of all price more than 200, than the calculation goes like this price - (price * 0.5) otherwise, price - (price * 0)
UPDATED
so if we sum all we will get 471, so the condition is true which is more than 200, so by right the formula should be like this price - (price * 0.5) so the answer/output should be 235.5
below are my schema: link to db fiddle
CREATE TABLE `mytables` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` int(11) DEFAULT 0,
  `name` varchar(255) NOT NULL,
  `price` int(11) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `mytables` (`id`, `role_id`, `name`, `price`) VALUES
  ('1', '1', 'nameA', '32'),
  ('2', '3', 'nameB', '45'),
  ('3', '1', 'nameC', '3'),
  ('4', '1', 'nameD', '86'),
  ('5', '3', 'nameE', '45'),
  ('6', '2', 'nameF', '31'),
  ('7', '3', 'nameG', '96'),
  ('8', '1', 'nameH', '87'),
  ('9', '2', 'nameI', '34'),
  ('10', '1', 'nameJ', '12');

A: I think you might be looking for this:
SELECT SUM(price) * IF(SUM(price) > 200, 0.5, 1.0) FROM mytables;

The outcome is 235.5.
I've use the simplified expressions. price - (price * 0) is equal to price and price - (price * 0.5) is equal to 0.5 * price. So it's either 1.0 times the price or 0.5 times the price based on the price.
I sum all prices up using SUM(). I use a IF() to calculate the factor that is applied to this summed price.
I would like to suggest to use a better name for the table.


text:
Q: TypeScript: undefined is not assignable to type 'boolean | ConnectionOptions | undefined I am working with the below code-block, I built it a couple of months ago in JavaScript, but las week I decided to start learning TypeScript. I cant seem to find how to properly defined the data types. Does any one have any hints or resources that can aid me to solve this issue?

this is the exact error message:
src/utils/pool.ts:5:5 - error TS2322: Type '"" | { rejectUnauthorized: false; } | undefined' is not assignable to type 'boolean | ConnectionOptions | undefined'.
Type '""' is not assignable to type 'boolean | ConnectionOptions | undefined'.
5     ssl: process.env.PGSSLMODE && { rejectUnauthorized: false },

Thanks so much!
import { Pool, PoolConfig } from 'pg';

 export const pool = new Pool({
      connectionString: process.env.DATABASE_URL,
      ssl: process.env.PGSSLMODE && { rejectUnauthorized: false },

    })

 pool.on('connect', ()=> console.log('Postgres connected'))

A: From what the error indicates seems like you are using a string where a type 'boolean | ConnectionOptions | undefined' is expected
Try this syntax instead
import { Pool, PoolConfig } from 'pg';

 export const pool = new Pool({
      connectionString: process.env.DATABASE_URL,
      ...( process.env.PGSSLMODE ? {ssl: { rejectUnauthorized: false }} : {}),
    })

 pool.on('connect', ()=> console.log('Postgres connected'))

A: If you interpret the log output it clearly states there is an issue is with the type which is expected and the type which you have declared.
The Expected type is,
boolean or ConnectionOptions or undefined.
The Given type is,
"" or { rejectUnauthorized: false; } or undefined
You need to assign a variable of the appropriate type or update the type of currently assigned variable.


text:
Q: How to reverse a string in O(1) complexity (runtime)? I faced an interview today and I was asked to reverse a string in single operation . I was feeling like it is impossible in less than O(n) . By the way ,  I was given a clue , "Swapping" ! So . . . does any answer exist ?

*

*Sample Input : "abcdefghi" (or , any strings )

*Sample Output :"ihgfedcba"

*No built in function can be used . ( ex : strrev() )

*The answer is not tricky like just printing/iterating reversely .

A: You cannot reverse a string in O(1) time, however, you can do so with O(1) space complexity.

reverse a string in single operation

Most likely it was reverse it in one-liner, as it's not even clear what an "operation" is really is.
You can use std::reverse algorithm to reverse a string in one line:
#include <string>
#include <algorithm>

int main()
{
    std::string str = "Hello world!";
    std::reverse(str.begin(), str.end());
    std::cout << "reverse is: \"" << str << '\"' << std::endl;
}

Output:
reverse is: "!dlrow olleH"

or you may as well use a simple loop to do it:
for (size_t i=0; i<str.size()/2; ++i)
    std::swap(str[i], str[str.size()-1-i);

this is however is O(N) runtime, and O(1) space (just like std::reverse).
Usually interviews with simple reverse string algorithm questions isn't about some tricks, most likely your interviewer wanted to see that kind of loop implemented. Also, don't forget that interviewers are also humans and sometimes they simply make mistakes and ask for impossible. Or, they simply wanted you to say that it is not possible to reverse a sequence in O(1).

A: Reverse a string? Just iterate it from rbegin() to rend(). Or std::copy that range to a new string.
A "reversed string" is just the same as the original string, just read the other way.

A: You can't do it. Even if there is some existing function somewhere that does it, internally it will certainly still take O(n). Although technically the complexity for a swapping is O(n) for an even number of characters and O(n-1) for an odd number of characters (so one could "technically" say that swapping a 3-character string is O(1)), each operation is a little more complex because you have to store one swapped character in a local variable while you swap the other. So for practical reasons swapping would be slower, not faster.


text:
Q: PowerShell terminate all RDP sessions of a user I need a script that terminates all RDP sessions of an AD user.
Only the username should be given, whereupon the script terminates all RDP sessions of this user (if necessary also enforces them).
Unfortunately, the Get-RDUserSession cmdlet does not work (the ConnectionBroker cannot be found).
Unfortunately, I cannot process the result of the CMD command qwinsta in PowerShell.
Any ideas or tips?
Thank you.

A: You can create custom objects from qwinsta's output, filter them and use rwinsta to kill the session.
Function Get-TSSessions
{

param (
    [Parameter(Mandatory = $true, Position = 0 )]
    [String]$ComputerName
    ) # End Parameter Block

qwinsta /server:$ComputerName |
ForEach-Object{
    If($_ -notmatch "SESSIONNAME")
    {
    New-Object -TypeName PSObject -Property `
    @{
        "ID"           = [Int]$_.SubString(41,05).Trim()
        "ComputerName" = $Computer
        "User"         = $_.SubString(19,22).Trim()
        "State"        = $_.SubString(47,08).Trim()
        }
    }
}

} # End Function Get-TSSessions

Get-TSSessions -ComputerName <ServerName> |
Where-Object{$_.User -eq "SomeUser"} |
ForEach{ & "rwinsta /Server:$($_.ComputerName) $($_.ID)" }

Obviously, you can improve by wrapping up the rwinsta command in its own function.  At the moment I only have reporting work written around this sort of thing, so in the spirit of answering the question without writing the whole thing, this should get you through.
Also, I believe there are a number of scripts and functions available for this on the PowerShell Gallery. In fact, I think there were functions Get/Stop-TerminalSession in the PowerShell Community Extensions, which you can install as a module.

A: param
(
    [Parameter(Mandatory = $false,
               HelpMessage = 'Specifies the user name (SamAccountName).',
               DontShow = $false)]
    [SupportsWildcards()]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({
            Import-Module -Name 'ActiveDirectory' -Force
            if (Get-ADUser -Filter "sAMAccountName -eq '$_'") {
                return $true
            } else {
                return $false
            }
        })]
    [string]$Username = $env:USERNAME
)

$ErrorActionPreference = 'SilentlyContinue'
Import-Module -Name 'ActiveDirectory' -Force

foreach ($system in (Get-ADComputer -Filter ("Name -ne '$env:COMPUTERNAME' -and OperatingSystem -like 'Windows Server*'"))) {
    [string]$system = $system.Name
    $session = ((quser /server:$system | Where-Object {
                $_ -match $Username
            }) -split ' +')[3]
    if ($session) {
        logoff $session /server:$system
    }
}


text:
Q: How to validate using Javascript an input tag of type text in an html form that the content of it will be Arabic/Englsih/Number? How to validate using Javascript an input tag of type text in an html form that the content of it will be one of the following:-

*

*Arabic or English Characters ONLY -OR-

*Arabic and English Characters ONLY -OR-

*Arabic characters only -OR-

*English Characters only -OR-

*Number only -OR-

*Arabic Characters and Number only -OR-

*English Characters and Number only -OR-

*Arabic or Number ONLY -OR-

*English Characters or Number ONLY -OR-

*Arabic or English Characters or Number ONLY -OR-

*Phone Number -OR-

*Email -OR-

*English string that starts with specific character like 'A' -OR-

*English string that ends with specific character like 'A' -OR-

*English string that contains specific character like 'A' -OR-

*English string that does not contain specific character like 'A'

Thanks in advance ..

A: First, I need a definition of "English", "Arabic" and "Numbers" characters.

*

*The definition of the English character boundary should at least include a-z, A-Z. Non-word characters (comma, dot, parentheses) should also be included, but since you didn't specify the purpose of your validation, I will limit these to a-z, A-Z.English RegExp: [a-zA-Z]

*I'm not skilled in the Arabian language, so I grab include all characters as definied at this source.RegExp: /[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]/

*The numbers are defined as \d (in JavaScript: 0-9).RegExp: \d (equals [0-9] in JavaScript)

*The beginning and the end of a string are matched by a ^ and $, using Regular expressions.

Brought together:

*

*Arabic and/or English Characters ONLY -OR-/^[a-zA-Z\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$

*Arabic characters only -OR-/^[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$/

*English Characters only -OR-/^[a-zA-Z]+$/

*Number only -OR-/^\d+$/

*Arabic Characters and/or Number only -OR-/^[\du0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$

*English Characters and/or Number only -OR-/^[\dA-Za-z]+$/

*Arabic and/or English Characters and/or Number ONLY -OR-/^[a-zA-Z\d\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$/

*Phone Number -OR- Phone numbers are too locale-dependent, construct your own RE

*Email -OR-^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ source 2 (very basic mail RegExp)

*English string that starts with specific character like 'A' -OR-/^A/

*English string that ends with specific character like 'A' -OR-/A$/

*English string that contains specific character like 'A' -OR-/A/

*English string that does not contain specific character like 'A'^[^A]+$
Of course, the English character set should include more characters than a-zA-Z if you're validating sentences. I recommend to use [\x20-\x7e] instead of [a-zA-Z], so commonly used punctuation characters are also available.

References / See also

*

*MDN: Regular expressions - A guide to use Regular Expressions in JavaScript

*Regulsr Expressions.info - Summary of character boundaries

*UTF8-chartable.de - Browser through all characters

*Unicode.org/charts - An official reference which documents all boundaries in a deeper detail


text:
Q: Incompatible pointer type and return makes integer without a cast issue I'm attempting to create a knapsack program out of the use of linked list but ive run into an issue that i can quite figure out. In nearly all of my functions im getting this error on the same line of an incompatible pointer type and i'm confused on how to fix it. The other issue im running into is a return makes integer from pointer without a cast errors. Full code and errors below. The error lies in the knapsack.c file, test_knapsack.c is just given for a main function example for testing purposes.
ERRORS
knapsack.c: In function 'KnapsackRemove':
knapsack.c:37:16: warning: return makes integer from pointer without a cast [-Wint-conversion]
         return NULL;
                ^
knapsack.c:47:29: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
                     knapsack=(*present)->next;

knapsack.c:59:12: warning: return makes integer from pointer without a cast [-Wint-conversion]
     return *knapsack;
            ^
knapsack.c: In function 'KnapsackPrint':
knapsack.c:69:17: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             temp=(*temp)->next;
                 ^
knapsack.c: In function 'KnapsackItemCount':
knapsack.c:82:13: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
         temp=(*temp)-> next;
             ^
knapsack.c: In function 'KnapsackSize':
knapsack.c:94:13: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
         temp=(*temp)-> next;

knapsack.c
#include <stdio.h>
#include "knapsack.h"
#include <stdlib.h>

listitemptr KnapsackAdd(listitemptr *knapsack, int item){
    if(knapsack == NULL){
        listitemptr newer = (listitemptr)malloc(sizeof(listitemptr));
        newer-> item = item;
        newer-> count = 1;
        newer-> next = NULL;
        return newer;
    }else{
        listitemptr *temp = knapsack;
        listitemptr previous = NULL;
        while(temp!= NULL){
            if((*temp)->item == item){
                (*temp)->count=(*temp)->count+1;
                break;
            }
            previous = *temp;
            *temp = (*temp)->next;
        }
        if(temp == NULL){
            listitemptr newer = (listitemptr)malloc(sizeof(listitemptr));
            newer->item = item;
            newer->count =1;
            newer->next = NULL;
            previous->next = newer;
            return newer;
        }
        return *temp;
    }
}

int KnapsackRemove(listitemptr *knapsack, int item){
    if(knapsack==NULL)
        return NULL;
    listitemptr *present = knapsack;
    listitemptr previous = NULL;

    while(present != NULL){
        if((*present)->item == item){
            if((*present)-> count > 1){
                (*present)->count=(*present)->count-1;
            }else{
                if(previous==NULL){
                    knapsack=(*present)->next;
                }else{
                    previous->next=(*present)->next;
                    free(present);
                }
            }
            break;
        }
        previous=*present;
        *present=(*present)->next;
    }

    return *knapsack;
}

void KnapsackPrint(const listitemptr *knapsack){
    if(knapsack == NULL)
        printf("(nothing)\n");
    else{
       const listitemptr *temp = knapsack;
        while(temp!= NULL){
            printf("%d (%d), ",(*temp)->item, (*temp)->count);
            temp=(*temp)->next;
        }
        printf("\n");
    }
}

unsigned int KnapsackItemCount(const listitemptr *knapsack, int item){
    if(knapsack== NULL)
        return 0;
    const listitemptr *temp = knapsack;
    while(temp != NULL){
        if((*temp)-> item== item)
            return (*temp)-> count;
        temp=(*temp)-> next;
    }
    return 0;
}

unsigned int KnapsackSize(const listitemptr *knapsack){
    if(knapsack == NULL)
        return 0;
   const listitemptr *temp = knapsack;
    unsigned int sum = 0;
    while(temp!= NULL){
        sum+= (*temp)-> count;
        temp=(*temp)-> next;
    }
    return sum;
}

knapsack.h
/* knapsack.h
 * implements simple knapsack data structure as a linked list
 * NOTE: a function may update the value of input argument *knapsack if it changes the first node of the knapsack to another node. Such a change include the case when an item is added to an empty knapsack
 */

typedef struct listitem* listitemptr;

struct listitem {
  int item;           // actual int item
  unsigned int count; // number of the same item in the knapsack; should be >= 1
  listitemptr next;   // pointer to next item
};

listitemptr KnapsackAdd(listitemptr *knapsack, int item);

int KnapsackRemove(listitemptr *knapsack, int item);

void KnapsackPrint(const listitemptr *knapsack);

unsigned int KnapsackItemCount(const listitemptr *knapsack, int item);

unsigned int KnapsackSize(const listitemptr *knapsack);

test_knapsack.c
#include "knapsack.h"
#include <stdio.h>
#include <assert.h>

int main(){
   //knapsack k1
   listitemptr head=KnapsackAdd(NULL,10);
   KnapsackAdd(&head,-20);
   KnapsackAdd(&head,10);
   KnapsackAdd(&head,15);
   KnapsackAdd(&head,-20);
   KnapsackAdd(&head,10);

   KnapsackPrint(&head);

   int count=KnapsackItemCount(&head,10);
   assert(count==3);

   count=KnapsackItemCount(&head,8);
   assert(count==0);

   count=KnapsackSize(&head);
   assert(count==6);

   //knapsack2
   listitemptr head2=KnapsackAdd(NULL,5);
   KnapsackAdd(&head2,10);
   KnapsackAdd(&head2,15);
   KnapsackAdd(&head2,20);
   KnapsackAdd(&head2,-5);

   KnapsackPrint(&head2);

   KnapsackRemove(&head2,15);
   count=KnapsackSize(&head2);
   assert(count==4);

   count=KnapsackItemCount(&head2,15);
   assert(count==0);

   KnapsackRemove(&head2,10);
   count=KnapsackSize(&head2);
   assert(count==3);

   KnapsackAdd(&head,10);

   count=KnapsackSize(&head2);
   assert(count==3);

   count=KnapsackSize(&head);
   assert(count==7);

   return 0;
   }

A: Regarding the warning -
knapsack.c:37:16: warning: return makes integer from pointer without a cast [-Wint-conversion]
     return NULL;

The definition of NULL is compiler dependent, probably in your compiler NULL is defined as (void*)0, therefore you are trying to return a pointer but your function is defined as int KnapsackRemove(...) so it expects an int value to be returned.
Regarding -
knapsack.c:59:12: warning: return makes integer from pointer without a cast [-Wint-conversion]
 return *knapsack;

You are trying to return a listitemptr type from a function returning an int.
regarding the other warnings, you are trying to assign listitemptr to a listitemptr* type. (*present)->next is of type listitemptr and knapsack is of type listitemptr*.

A: Looking at the line
temp=(*temp)->next;

temp is defined as const listitemptr *temp, meaning its type is const listitemptr *.
To find the type of (*temp)->next, we can look at its pieces. We already know temp is a const listitemptr *, so de-referencing it results in a listitemptr.
Looking at your source, we can then find the type of next,
struct listitem {
  listitemptr next;   // pointer to next item
};

now we can see that next, and therefore (*temp)->next, has the type listitemptr.
So you are assigning a listitemptr to a const listitemptr *.
It looks like most of these errors are caused by confusing listitemptr for a pointer to listitemptr*.


text:
Q: Force a connect to mysql My Mysql server instance has crashed (I assume its been 10 hours and its not running) - I have tried show full processlist but the new connection can't connect. I've tried using mysqladmin and that can't connect either. I'd really like to not have to reset it because we use replication (master to master) which I'm hoping (pos naively) is still running. Can I somehow force a connection to mysql or access a file somewhere where I can see / kill the bad process?
Additionally if a user already has a connection and the mysql server grinds to a halt is that connection still going to work? I.e. if following this I setup a PHP script which ran on an endless loop with a connection monitoring query times would that work even if the server ground to a halt or would that active connection be affected as well?

A: You should definitely check if you can start the mysql server again. The replication setup will sync everything and you will be fine.
If one master is down you can only connect to the other one. You may consider using some connection pool with both connections for the app to have a solid failover.


text:
Q: How to search data with ng-click in angular js I want to search data with ng-click function in angularJS, but when I try this code, it doesn't work.
First my button code:
<button id="veg" ng-click="myFilter = {type: 1}" title="veg">

My data display code:
<div class="side-body padding-top fade in  tab-pane"  id="<?php echo $tt3->id; ?>">

        <div ng-if='r.pro_category == <?php echo $tt3->id; ?>'
             ng-repeat = "r in groups | filter : searchGroups | filter:myFilter">

@{{r.pro_name }}

@{{r.price}}

My script code:
var GroupsApp = angular.module('GroupsApp',[]);
GroupsApp.controller('GroupsController', function ($scope, GroupsService) {

    getGroups();

    function getGroups() {
        GroupsService.getGroups()
            .success(function (grps) {
                $scope.groups = grps;

                 return (val.type != 2);
                console.log($scope.groups);
            })
            .error(function (error) {
                $scope.status = 'Unable to load Product data: ' + error.message;
                console.log($scope.status);
            });
    }
});

var url = window.location.pathname;
var productid = url.substring(url.lastIndexOf('/') + 1);

GroupsApp.factory('GroupsService', ['$http', function ($http) {
    var GroupsService = {};

    GroupsService.getGroups = function () {
        return $http.get('../showproduct/'+productid);
    };
    return GroupsService;
}]);

When I run above code it doesn't show anything.

A: <button href="#" id="veg" ng-click="myFilter = {active: 1}" title="All Menu Items"  class="bbb1 btn btn-info btn-lg "  >


text:
Q: Half H-Bridge using IR2104 doesn't work I'm trying to build a half H-bridge using an IR2104 driver. I want to use it for driving "high power" things such as a brushless motor (100V, 40A), or high power LED (200W).
But it doesn't work as expected: When I increase the "power" voltage (50V on the schematic) to more than 10V, the voltage at the output of the half H-bridge (Uout) doesn't increase to more than 10V. I measured the voltage between the gate and the source of the IGBT Q1, there is nearly no voltage difference (0.3V). Q1 and Q2 are FGH40N60. The Arduino is powered by an external 12V power supply, so the Vin pin of the Arduino also outputs 12V.
On the input side of the IR2104, I have an Arduino Uno which sets IN (pin 5 on the Arduino) to 0V (LOW) and pulses -SD (pin 3 on the Arduino) 5 microseconds HIGH and 1 microsecond LOW in the main loop.
Can somebody help me to increase the output voltage to be nearer to the power supply voltage?
The code on the Arduino is:
void setup() {
  pinMode(3,OUTPUT);
  pinMode(5,OUTPUT);
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delay(500);
}

void loop() {
  digitalWrite(5,HIGH);
  delayMicroseconds(5);
  digitalWrite(5,LOW);
  delayMicroseconds(1);
}

And the schematic:

A: Do you understand how the IR2104's bootstrap diode and capacitor are supposed to work?
C1 is intended to be charged up to 12V and then floated up to be between Q1's gate and source so a 12V source-referenced voltage is available to turn on Q1.
The diode prevents the C1's charge from dumping back into the supply when it is floated up and it's negative terminal is at a voltage higher than GND.
But C1 has to be charged from somewhere, and it has to be charged periodically. Are you aware that Q2 has to turn on frequently and periodically in order to refresh the charge on C1? Only when Q2 conducts does current flow from 12V to GND through D1 and C1 to GND in order to charge up C1.
At startup, Q2 must be turned on before Q1 in order to pre-charge C1. Then during operation Q2 has to periodically turn on to continue to refresh C1 so that Q1 can turn on. Usually Q2 turns on frequently enough during regular operation (like commutating a motor, switching an inverter, or synchronous rectification) of the half-bridge that no special switching of Q2 needs to be done.

A: Thanks for the reply.
DKNguyen: No i didn't understand the "mecanics" of this circuit before you explain me (wanted to try before going further). Thanks, I checked and Q2 seems to turn on sometimes (at least the gate is activated) sometimes.
Heath Raftery: I checked what you said.
Here is the IN in yellow and SD in green:

Here is the HO in yellow and the LO in green:

Here is the VB in yellow and the LO in green:

I put the "high power" voltage at 20V for the measure provided above. As we can see, VB seems to saturate at 12v instead of going to 20v(high power voltage)+12v(voltage provided to the vcc of the ir2104 and used to charge C1). I don't understand why...
I also checked the voltage at bornes of C1 (mass of the scope at VS and probe at VB) and it seems to be charged at 12v continously.


text:
Q: What is the antiderivative of $\int x dx$? I am confiused when it comes to these two formulas: $\int 1 dx=x +C$ and $\int a dx=ax +C$ I am confiused when it comes to these two formulas:
$\int 1 dx=x +C$
and
$\int a dx=ax +C$
which one would apply to $\int x\ dx$ ? and why
Can someone explain the difference?

A: Well, ask yourself:

*

*Is "$x$" the same as "1"?

*Is "$x$" the same as "$a$"?
If so, then that one applies. If neither is true, then neither apply, and you need some other rule . . .

A: None of them is applicable. The second one is exactly the first one when you take $a=1$.
None of them contain $x$. You need $\int xdx=x^2/2+C$.

A: This is a great question.
$\int 1 \,dx$ is just notation for the antiderivative of $1$, i.e., the function that, when you differentiate it, gives you $1$.  Well, we know the derivative of $x$ is $1$.  So is the derivative of $x + 1$, $x + 2$, $x + \pi$, $x - 500$, $x + \dfrac{\sqrt{7}}{e}$.  So, since all of these have derivative $1$, we say that the antiderivative can be any of them, i.e., it is $x + C$ for any constant real number $C$.
Now, if $a$ is any number (not a variable), then $\int a \,dx = \int a \cdot 1 \,dx = a \int 1 dx = a(x + C) = ax + C'$.  Remember that we are allowed to pull constant numbers out of the integral; that's why I pulled out the $a$.
Now, to figure out $\int x \,dx$ you can't use any of the information above, because when we were working above, we were finding the antiderivative of a number.  Here, we are finding the antiderivative of a variable $x$.  We are asking for the function such that its derivative is $x$.  This turns out to be $\dfrac{x^{2}}{2}$, but also $\dfrac{x^{2}}{2} + 1$, $\dfrac{x^{2}}{2} + 5$, $\dfrac{x^{2}}{2} -19$, $\dfrac{x^{2}}{2} + \pi$,  etc.  So, the antiderivative's general form is $\dfrac{x^{2}}{2} + C$ for a constant $C$.

A: Neither applies directly, but you could apply integration by parts and use the first formula in the process.
$$\int xdx=x\int dx - \int xdx$$
directly leads to
$$\int xdx=\frac{x^2}{2}+C.$$
Can you fill in the intermediate steps?

A: Initial commentary:
In my opinion, the notation for "antiderivation" and integration is among the worst of mathematics, alongside the notation for partial derivatives.  All doubts of students regarding this notation are justified. For an answer regarding the notation for integration, see this answer I gave on another question.

Back to the matter at hand: What does this notation mean? It holds on itself a lot of dense information. Let's step back and try to define things again. Forget what you know. We take functions with domain $\mathbb{R}$ instead of an interval just for the sake of cleanness. Also, we always assume functions to be continuous.
Definition: An anti-derivative of a function $f: \mathbb{R} \rightarrow \mathbb{R}$ is a function $F$ such that $F'=f$. We denote such an $F$ by $\displaystyle \int f$.
It may not be obvious at first, but it follows from the mean value theorem that all such $F$'s are related by the fact that they differ by a constant. Hence, if we find one anti-derivative, every other one can be found by adding a constant. Therefore, it does us no harm to denote $\displaystyle \int f=F+c$, for instance. Non-uniqueness is not a big issue. Just keep in mind that we are considering $c$ to be a constant, and the equation is more to be interpreted as "every anti-derivative is of this form" than an actual equation. Note that no "dummy variables" or anything of the sort was introduced anywhere.
For example: Take the function
$$f: \mathbb{R} \rightarrow \mathbb{R}$$
$$x \mapsto x^2.$$
A straight-forward calculation leads us to the fact that the function
$$F: \mathbb{R} \rightarrow \mathbb{R}$$
$$x \mapsto \frac{x^3}{3}$$
is an anti-derivative for $f$. Hence, we have that $\displaystyle \int f =F+c$, or $\displaystyle (\int f) (x)=\frac{x^3}{3}+c$.
Now, what means $\int x dx$? First of all, you have to interpret this as:
$$\int x dx$$
$$\int \quad (x) \quad (dx)$$
The first thing to understand is that the second parenthesis gives you what is being taken to be the "input". The first parenthesis is the "expression $P$ in terms of the input". Therefore, what you are really evaluating, in our previous notation, is
$$\int (x \mapsto P(x)).$$
This justifies why:
$$\int 1 dx=x+c$$
After all, $x \mapsto 1$ is the constant function $\equiv 1$. Hence, $x$ is an antiderivative.
Also,
$$\int x dx= \frac{x^2}{2}+c$$
since $x \mapsto x$ has the function $x \mapsto \frac{x^2}{2}$ as anti-derivative. Note now that:
$$\int a dx=ax+c$$
Since $x \mapsto a$ is the constant function $\equiv a$, having $ax$ as anti-derivative.
The point is: whether you are taking an antiderivative or integrating, you are always working with functions. You are operating functions. This mainstream notation for antiderivative and integration just helps on immortalizing the confusing, "insightless" and naive interpretation of functions as expressions, a notion which, when finally recognized to be inherently limited, lead to considerable progress in mathematics.

A: Neither applies to $\int x dx$.
Both $\int 1 dx$ and $\int a dx$ are integrals of constant functions: $f(x) = 1$ and $g(x) = a$ respectively. With $\int x dx$ you're integrating a linear function, $h(x) = x$. What's a function whose derivative is $h$? Well, $ {x^2} / 2$. So:
$$ \int x dx = \frac {x^2} 2 + C$$


text:
Q: Is it possible to have the value in a variable stay the same, even when the object changes? For instance, I have something like this:
MyFirstSess = ((string)Session["WindowName"]);

and then later on I have:
MySecondSess = ((string)Session["WindowName"]);

The object (for me) is to check the WindowName at various points in a function.  However, every time I try to compare them they're equal.  So, I'm trying to figure out how to store MyFirstSess so that it never changes, even if it's object (in this case, ((string)Session["WindowName"]);) does.
Is this possible?
EDIT:  Full code:
public partial class PreventMultipleWindows : System.Web.UI.UserControl
{
    public string MyFirstSess;
    public string MySecondSess;

    protected void Page_Load(object sender, EventArgs e)
    {
        MyFirstSess = ((string)Session["WindowName"]);

       string MySess = ((string)Session["WindowName"]);
        if (MySess != null)
        {
            MySecondSess = ((string)Session["WindowName"]);
        }

        if (MyFirstSess != MySecondSess)
        {
            string WindowName = "InvalidPage";
            Session["WindowName"] = WindowName;
            return;
        }

    }

    public string GetWindowName()
    {
        string WindowName = Guid.NewGuid().ToString().Replace("-", "");
        Session["WindowName"] = WindowName;
        return WindowName;
    }

}

A: That's already the behavior that you have.  Changes to the session value won't change the string variable that you have.


text:
Q: Sorting, removing, and appending elements using jQuery isn't working in IE This function that sorts my links works like a charm on Chrome/Safari/Firefox but not in IE. Can someone tell me why?
Symptom: everything disappears (line2) nothing appears (line3)
HTML:

   absurdism
   action
   adult
   adventure
   about comics

SCRIPT:

sorted = $('.genres a').sort(function(a, b) {
    return a.innerHTML > b.innerHTML
});
$('.genres').html('');
sorted.each(function(i, a) {
    $('.genres').append(a)
});

Fiddle: http://jsfiddle.net/MWkJg/2/
The online page of this code is on http://www.lambiek.net/webshop.html (click on "genre" button)

A: You need to replace this:
$('.genres').html('');

with
$('.genres').empty();

html uses the innerHTML property to remove contents, and this is handled inconsistently among browsers as you have just seen. empty, however, uses the removeChild method, and works consistently across browsers. (Incidentally jQuery 2.0 uses textContent.)
Also, for your sort method to work consistently, it needs to return a numeric value:
var sorted = $('.genres a').sort(function(a, b) {
    return a.innerHTML  b.innerHTML) { return 1; };

Possible duplicate of JS sort works in Firefox but not IE - can't work out why.