text:
Q: How to show values in textbox from database? Hi i have database like this
Users Table
     user_id |   username  |  branch_id(foreignkey)|  Approved_id(foreignkey)
  -------------------------------------------------------------------------------
    1          jprescott         2                          1
    2          lpausch           1                          3

Branch Table

Branch_id    BranchName
1                abc
2               asjdv
3               ydgfs

Approvetable

     ApproveId  ApprovedBy
          1         Anil
           2         ghouse
           3         raghu

now i have 3 textboxes,how do i these fields in the textboxes
          txtusername.text=username from table 1;
          txtapprovedname=approved by from table 2;
          txtbranchname=branchname from table 3;

when user 1 logins it should check the branch id and go to the branch table and disply the branch name,and check the approveid and go to the approvedtable and displya the approvedname in textboxes.....
now how to write a select statement for this can any one help me plz...........

A: select UsersTable.username, ApproveTable.ApprovedBy, Branchtable.BranchName
from UsersTable, Branchtable, Approvetable
where UsersTable.branch_id = BranchTable.branch_id
AND UsersTable.approved_id = ApproveTable.ApproveId
AND UsersTable.User_id = %CurrentUserID%


text:
Q: How to convert a class T object into a Future[T] object in akka I am trying to do something with akka and scala and i am new to it. I want to append the result of an 'Any' Future into one of the fields in the class
So i have class called T defined as
class T {
  var a: String =_
  var result = List[Any]= List()
}

Now i have a variable which receives a future value
var futureResult:Future[Any] = //receives a future value

in a function called addResult which takes an T object and returns a future T object.
def addResult(obj1:T):Future[T] ={
  var obj2:T = new T()
  obj2.a = obj1.a
  obj2.result = obj1.result
  //I want to append results of futureResult into obj2.result when it is completed
  // obj2.result = futureResult :: obj2.result

  return Future(obj2)
}

I have to finally call this function from a flow.
val b = Flow[T].mapAsync[T](1)(addResult(_))

A: You can change the commented line like this:
futureResult.map { res =>
  obj2.result = res :: obj2.result
  obj2
}

And then you won't need the last line.

A: First, as @riccardo.cardin noted using T as a name of a class is very bad idea, because of T usual points to generic.
However, you can put any logic in Future with a simple closure, in your case, it looks like this:
Future {
 new T("some string", 1 :: 2 :: 3 :: Nil)
}

After that, you can combine asynchronous computation via flatMap, map or with for comprehensive or even use cats black magic with |@|:
for {
    f1 <- future1()
    f2 <- future2(f1.id)
} yield f2.name

(future1 |@| future2) map { _ - _ }

In your case this transformation depends from logic of your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: httpclient call to webapi to post data not working I need to make a simple webapi call to post method with string argument.
Below is the code I'm trying, but when the breakpoint is hit on the webapi method, the received value is null.
StringContent stringContent = new System.Net.Http.StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url.ToString(), stringContent);

and server side code:
 // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

please help...

A: If you want to send a json to your Web API, the best option is to use a model binding feature, and use a Class, instead a string.
Create a model
public class MyModel
{
    [JsonProperty("firstName")]
    public string FirstName { get; set; }
}

If you wont use the JsonProperty attribute, you can write property in lower case camel, like this
public class MyModel
{
    public string firstName { get; set; }
}

Then change you action, change de parameter type to MyModel
[HttpPost]
public void Post([FromBody]MyModel value)
{
    //value.FirstName
}

You can create C# classes automatically using Visual Studio, look this answer here Deserialize JSON into Object C#
I made this following test code
Web API Controller and View Model
using System.Web.Http;
using Newtonsoft.Json;

namespace WebApplication3.Controllers
{
    public class ValuesController : ApiController
    {
        [HttpPost]
        public string Post([FromBody]MyModel value)
        {
            return value.FirstName.ToUpper();
        }
    }

    public class MyModel
    {
        [JsonProperty("firstName")]
        public string FirstName { get; set; }
    }
}

Console client application
using System;
using System.Net.Http;

namespace Temp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter to continue");
            Console.ReadLine();
            DoIt();
            Console.ReadLine();
        }

        private static async void DoIt()
        {
            using (var stringContent = new StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json"))
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://localhost:52042/api/values", stringContent);
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                }
            }
        }
    }
}

Output
Enter to continue

"JOHN"

A: Alternative answer: You can leave your input parameter as string
[HttpPost]
public void Post([FromBody]string value)
{
}

, and call it with the C# httpClient as follows:
var kvpList = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);

string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
    try
    {
        HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
        if (resp != null && resp.Content != null) {
            var result = await resp.Content.ReadAsStringAsync();
            //do whatevs with result
        } else
            //nothing returned.
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ResetColor();
    }
}

A: For the record I tried the above and could not get it working!
I couldn't get it working because my API was in a separate project. Which is fine right? no, I was doing Dependency Injection into the controller while using the Startup class against the Base project.
You can resolve this by using the WebAPI's config and configuring Dependency Injection there with Unity. The below code works for me:
WebApiConfig.cs:
 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            RegisterUnity();
        }

        private static void RegisterUnity()
        {
            var container = new UnityContainer();

            container.RegisterType<IIdentityRespository, IdentityRespository>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }

I hope it helps others :-)


text:
Q: Outgoing brute force attacks from my server One of the servers I look after appears to be participating in brute force attacks against Wordpress installations.
I've been on the receiving end of this many times, so am very familiar with steps that can be taken to prevent this. What I'm struggling with, however, is detecting outgoing attacks. The server is a typical Apache server with a number of vhosts on it - this is where the complication comes of course - if there was just one on there, it wouldn't be as difficult!
I'm currently using tcpflow to log traffic going from any port on this server to port 80 on any other machine using this command:
tcpflow -i eth0 dst port 80 and src host <my_servers_ip> and port not 22

I've found this preferable to tcpdump. Looking through its output can be somewhat brain-melting after a while :) tcpflow puts each request into a separate file..
Here is some output from a file which I believe to be suspicious activity:
POST /wp-login.php HTTP/1.1
User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Host: somedomain.com
Accept: */*
Cookie: wordpress_test_cookie=WP+Cookie+check
Content-Length: 97
Content-Type: application/x-www-form-urlencoded

log=jacklyn&pwd=london&wp-submit=Log+In&redirect_to=http://somedomain.com/wp-admin/tes1a0&testcookie=1

Please note, I've obfuscated the "Host:" above, I believe that's the host being attacked (is this correct?).
So my question really, is how do I go about detecting the vhost that is generating this malicious traffic? If I can do that, I can let my client know, and he can take steps to investigate the site and make the necessary changes to stop it..
Any solutions very gratefully received :)

A: I assume from what you say that you are in a setup where you can't restrict url download from your clients with allow_url_fopen.
In which case it is actually quite hard to go back to the originating php script, as the tcpflow log you show doesn't actually embed that information.
One easy option to consider would be forcing any outgoing request to have a revealing user-agent that you could use to identify the actual client that made it.
For instance, you could add to the vhost definition of client1 website an instruction
php_admin_value user_agent client1

That will force any http request made by that website to user the user-agent "client1", which will show up in your tcpflow log thus allowing you to know who originated it.
Note that if privacy is a concern, you may want to use a user_agent that only you can map to the actual client (such as an encryption of the client's name).
It may however harm usability, as some website will display differently depending on the provided user_agent, and that this setup purposely prevent any attempt made by your client to change it.


text:
Q: python3: singledispatch in class, how to dispatch self type Using python3.4. Here I want use singledispatch to dispatch different type in __mul__ method . The code like this :
class Vector(object):

    ## some code not paste
    @functools.singledispatch
    def __mul__(self, other):
        raise NotImplementedError("can't mul these type")

    @__mul__.register(int)
    @__mul__.register(object)                # Becasue can't use Vector , I have to use object
    def _(self, other):
        result = Vector(len(self))           # start with vector of zeros
        for j in range(len(self)):
            result[j] = self[j]*other
        return result

    @__mul__.register(Vector)                # how can I use the self't type
    @__mul__.register(object)                #
    def _(self, other):
        pass # need impl

As you can see the code , I want support Vector*Vertor , This has Name error
Traceback (most recent call last):
  File "p_algorithms\vector.py", line 6, in <module>
    class Vector(object):
  File "p_algorithms\vector.py", line 84, in Vector
    @__mul__.register(Vector)                   # how can I use the self't type
NameError: name 'Vector' is not defined

The question may be How can I use class name a Type in the class's method ? I know c++ have  font class statement . How python solve my problem ? And it is strange to see result = Vector(len(self)) where the Vector can be used in method body .

After have A look at http://lukasz.langa.pl/8/single-dispatch-generic-functions/
I can choose this way to implement :
import unittest
from functools import  singledispatch

class Vector(object):
    """Represent a vector in a multidimensional space."""

    def __init__(self, d):
        self._coords = [0 for i in range(0, d)]
        self.__init__mul__()

    def __init__mul__(self):
        __mul__registry = self.__mul__.registry
        self.__mul__ = singledispatch(__mul__registry[object])
        self.__mul__.register(int, self.mul_int)
        self.__mul__.register(Vector, self.mul_Vector)

    def __setitem__(self, key, value):
        self._coords[key] = value

    def __getitem__(self, item):
        return self._coords[item]

    def __len__(self):
        return len(self._coords)

    def __str__(self):
        return str(self._coords)

    @singledispatch
    def __mul__(self, other):
        print ("error type is ", type(other))
        print (type(other))
        raise NotImplementedError("can't mul these type")

    def mul_int(self,other):
         print ("other type is ", type(other))
         result = Vector(len(self))           # start with vector of zeros
         for j in range(len(self)):
             result[j] = self[j]*other
         return result

    def mul_Vector(self, other):
        print ("other type is ", type(other))
        #result = Vector(len(self))           # start with vector of zeros
        sum = 0
        for i in range(0,len(self)):
            sum += self._coords[i] * other._coords[i]
        return sum

class TestCase(unittest.TestCase):
    def test_singledispatch(self):
        # the following demonstrates usage of a few methods
        v = Vector(5)              # construct five-dimensional <0, 0, 0, 0, 0>
        for i in range(1,6):
            v[i-1] = i
        print(v.__mul__(3))
        print(v.__mul__(v))
        print(v*3)

if __name__ == "__main__":
    unittest.main()

The answer is strange :

other type is  <class 'int'>
[3, 6, 9, 12, 15]
other type is  <class '__main__.Vector'>
55
error type is  <class 'int'>
Traceback (most recent call last):
  File "p_algorithms\vector.py", line 164, in <module>
    print(v*3)
  File "C:\Python34\lib\functools.py", line 710, in wrapper
    return dispatch(args[0].__class__)(*args, **kw)
  File "p_algorithms\vector.py", line 111, in __mul__
    raise NotImplementedError("can't mul these type")

v.__mul__(3)  can work but v*3 can't work. This is strange From my option v*3 is just the same as v.__mul__(3) .

Update after @Martijn Pieters's comment, I still want implement v*3 in class. So I try this
import unittest
from functools import  singledispatch

class Vector(object):

    @staticmethod
    def static_mul_int(self,other):
         print ("other type is ", type(other))
         result = Vector(len(self))           # start with vector of zeros
         for j in range(len(self)):
             result[j] = self[j]*other
         return result

    @singledispatch
    @staticmethod
    def __static_mul__(cls, other):
        print ("error type is ", type(other))
        print (type(other))
        raise NotImplementedError("can't mul these type")

    __mul__registry2 = __static_mul__.registry
    __mul__ = singledispatch(__mul__registry2[object])
    __mul__.register(int, static_mul_int)

    def __init__(self, d):
        self._coords = [0 for i in range(0, d)]
        self.__init__mul__()

    def __init__mul__(self):
        __mul__registry = self.__mul__.registry
        print ("__mul__registry",__mul__registry,__mul__registry[object])
        self.__mul__ = singledispatch(__mul__registry[object])
        self.__mul__.register(int, self.mul_int)
        print ("at last __mul__registry",self.__mul__.registry)

    # @singledispatch
    # def __mul__(self, other):
    #     print ("error type is ", type(other))
    #     print (type(other))
    #     raise NotImplementedError("can't mul these type")

    def mul_int(self,other):
         print ("other type is ", type(other))
         result = Vector(len(self))           # start with vector of zeros
         for j in range(len(self)):
             result[j] = self[j]*other
         return result

    def __setitem__(self, key, value):
        self._coords[key] = value

    def __getitem__(self, item):
        return self._coords[item]

    def __len__(self):
        return len(self._coords)

    def __str__(self):
        return str(self._coords)

class TestCase(unittest.TestCase):
    def test_singledispatch(self):
        # the following demonstrates usage of a few methods
        v = Vector(5)              # construct five-dimensional <0, 0, 0, 0, 0>
        for i in range(1,6):
            v[i-1] = i
        print(v.__mul__(3))
        print("type(v).__mul__'s registry:",type(v).__mul__.registry)
        type(v).__mul__(v, 3)
        print(v*3)

if __name__ == "__main__":
    unittest.main()

This time .  v.__mul__(3) have error :

Traceback (most recent call last):
  File "test.py", line 73, in test_singledispatch
    type(v).__mul__(v, 3)
  File "/usr/lib/python3.4/functools.py", line 708, in wrapper
    return dispatch(args[0].__class__)(*args, **kw)
TypeError: 'staticmethod' object is not callable

For me static method should act like the instance method.

A: This is a little ugly, as you need to defer binding the implementation of Vector/Vector multiplication until after Vector is actually defined. But the idea is that the single-dispatch function needs the first argument to be of arbitrary type, so Vector.__mul__ will call that function with self as the second argument.
import functools

class Vector:

    def __mul__(self, other):
        # Python has already dispatched Vector() * object() here, so
        # swap the arguments so that our single-dispatch works. Note
        # that in general if a*b != b*a, then the _mul_by_other
        # implementations need to compensate.
        return Vector._mul_by_other(other, self)

    @functools.singledispatch
    def _mul_by_other(x, y):
        raise NotImplementedError("Can't multiply vector by {}".format(type(x)))

    @_mul_by_other.register(int)
    def _(x, y):
        print("Multiply vector by int")

@Vector._mul_by_other.register(Vector)
def _(x, y):
    print("Multiply vector by another vector")

x = Vector()
y = Vector()
x * 3
x * y
try:
    x * "foo"
except NotImplementedError:
    print("Caught attempt to multiply by string")

A: You cannot use functools.singledispatch on methods at all, not as a decorator at least. Python 3.8 adds a new option, just for methods: functools.singledispatchmethod().
It doesn't matter that Vector isn't defined here yet; the first argument to any method is always going to be self, while you'd use single dispatch for the second argument here.
Because decorators apply to the function objects before the class object is created, you could just as well register your 'methods' as functions instead, outside of the class body, so you have access to the Vector name:
class Vector(object):

    @functools.singledispatch
    def __mul__(self, other):
        return NotImplemented

@Vector.__mul__.register(int)
@Vector.__mul__.register(Vector)
def _(self, other):
    result = Vector(len(self))           # start with vector of zeros
    for j in range(len(self)):
        result[j] = self[j]*other
    return result

For non-supported types, you need to return the NotImplemented singleton, not raise an exception. This way Python will try the inverse operation too.
However, since the dispatch is going to key on the wrong argument (self) here anyway, you'll have to come up with your own single dispatch mechanism.
If you really want to use @functools.singledispatch you'd have to delegate to a regular function, with the arguments inversed:
@functools.singledispatch
def _vector_mul(other, self):
    return NotImplemented

class Vector(object):
    def __mul__(self, other):
        return _vector_mul(other, self)

@_vector_mul.register(int)
def _vector_int_mul(other, self):
    result = Vector(len(self))
    for j in range(len(self)):
        result[j] = self[j] * other
    return result

As for your updates using __init__mul__: v * 3 is not translated to v.__mul__(3). It is instead translated to type(v).__mul__(v, 3), see Special method lookup in the Python datamodel reference. This always bypasses any methods set directly on the instance.
Here type(v) is Vector; Python looks up the function, it won't use a bound method here. Again, because functools.singledispatch dispatches on the first argument, always, you cannot use single dispatch directly on the methods of Vector, because that first argument is always going to be a Vector instance.
In other words, Python will not use the methods you set on self in __init__mul__; special methods are never looked up on the instance, see Special method lookup in the datamodel documentation.
The functools.singledispatchmethod() option that Python 3.8 adds uses a class as the decorator which implements the descriptor protocol, just like methods do. This lets it then handle dispatch before binding (so before self would be prepended to the argument list) and then bind the registered function that the singledispatch dispatcher returns. The source code for this implementation is fully compatible with older Python versions, so you could use that instead:
from functools import singledispatch, update_wrapper

# Python 3.8 singledispatchmethod, backported
class singledispatchmethod:
    """Single-dispatch generic method descriptor.

    Supports wrapping existing descriptors and handles non-descriptor
    callables as instance methods.
    """

    def __init__(self, func):
        if not callable(func) and not hasattr(func, "__get__"):
            raise TypeError(f"{func!r} is not callable or a descriptor")

        self.dispatcher = singledispatch(func)
        self.func = func

    def register(self, cls, method=None):
        """generic_method.register(cls, func) -> func

        Registers a new implementation for the given *cls* on a *generic_method*.
        """
        return self.dispatcher.register(cls, func=method)

    def __get__(self, obj, cls):
        def _method(*args, **kwargs):
            method = self.dispatcher.dispatch(args[0].__class__)
            return method.__get__(obj, cls)(*args, **kwargs)

        _method.__isabstractmethod__ = self.__isabstractmethod__
        _method.register = self.register
        update_wrapper(_method, self.func)
        return _method

    @property
    def __isabstractmethod__(self):
        return getattr(self.func, '__isabstractmethod__', False)

and apply that to your Vector() class. You still have to register your Vector implementation for the single dispatch after the class has been created, because only then can you register a dispatch for the class:
class Vector(object):
    def __init__(self, d):
        self._coords = [0] * d

    def __setitem__(self, key, value):
        self._coords[key] = value

    def __getitem__(self, item):
        return self._coords[item]

    def __len__(self):
        return len(self._coords)

    def __repr__(self):
        return f"Vector({self._coords!r})"

    def __str__(self):
        return str(self._coords)

    @singledispatchmethod
    def __mul__(self, other):
        return NotImplemented

    @__mul__.register
    def _int_mul(self, other: int):
        result = Vector(len(self))
        for j in range(len(self)):
            result[j] = self[j] * other
        return result

@Vector.__mul__.register
def _vector_mul(self, other: Vector):
    return sum(sc * oc for sc, oc in zip(self._coords, other._coords))

You could of course also create a subclass first and dispatch based on that, since dispatch works for subclasses too:
class _Vector(object):
    def __init__(self, d):
        self._coords = [0] * d

class Vector(_Vector):
    def __setitem__(self, key, value):
        self._coords[key] = value

    def __getitem__(self, item):
        return self._coords[item]

    def __len__(self):
        return len(self._coords)

    def __repr__(self):
        return f"{type(self).__name__}({self._coords!r})"

    def __str__(self):
        return str(self._coords)

    @singledispatchmethod
    def __mul__(self, other):
        return NotImplemented

    @__mul__.register
    def _int_mul(self, other: int):
        result = Vector(len(self))
        for j in range(len(self)):
            result[j] = self[j] * other
        return result

    @__mul__.register
    def _vector_mul(self, other: _Vector):
        return sum(sc * oc for sc, oc in zip(self._coords, other._coords))


text:
Q: How to add a custom "under maintenance" page? I'm trying to add a custom page to my web application for the times I'm performing maintenance.
I'm trying to test the referred page on my development environment but the Symfony page always appears. I had already created a module with a proper action and template and also configured those on the settings.yml file.

A: Have you tried this: "Website Temporarily Unavailable" error page

A: In your app's settings.yml set these:
all:
  .settings:
    module_disabled_module: security   # To be called when a user requests
    module_disabled_action: disabled  # A module disabled in the module.yml

In the module's module.yml set this:
prod:
  enabled:     false

This will disable the your module for prod environment, but it will still be available for dev and test environments.
Hope it helps.
Regards,
Radu.


text:
Q: How can I adjust the coefficients in the constraints of a Linear Programming problem with no objective function until I get a solution? I have a system of linear equations that I need a solution for that is strictly positive. I have 4 solutions and 4 unknowns, and the solution I obtain for my current system involves negative numbers.
For illustrative purposes, here is the system:
$$x_1+ x_2 + x_3 + x_4 = 1$$
$$0.2895 x_1+1.2312 x_2 + 0.8360 x_3+ 0.5515 x_4 = 0.665$$
$$0.2942 x_1+ 0.5828 x_2 + 0.4561 x_3 + 0.4006 x_4 =0.47$$
$$7,969,147 x_1 +21,685 x_2+ 2,656,382 x_3 +7,083,686 x_4 = 1,328,191.2$$
I can vary the coefficients in my equations a little bit and I can vary the LHS of two of my equations (a little bit).
I had originally tried to treat this problem as a Linear Programming problem but was unable to find solutions for my given coefficients even while varying the LHS of the equations.
So my question is: How can I go about selecting coefficients from within a certain range without feeling like I am just stabbing in the dark? Is there a name for this type of problem? It would be a Linear Programming problem but I want to be able to vary the coefficients in my constraints until I find a solution and I also don't have an objective function.
Below is the current system I'm considering.
All of my coefficients must be positive.
I can make adjustments to the coefficients on line 2 by less than 0.5 each.
I can change coefficients in line 4 drastically (by millions).
I can make no adjustments to coefficients in lines 1 or 3.
$$x_1+ x_2 + x_3 + x_4 = 1$$
$$ 0.64 \geq 0.2895 x_1+1.2312 x_2 + 0.8360 x_3+ 0.5515 x_4 \leq 0.67$$
$$0.44 \geq 0.2942 x_1+ 0.5828 x_2 + 0.4561 x_3 + 0.4006 x_4 \leq 0.48$$
$$7,969,147 x_1 +21,685 x_2+ 2,656,382 x_3 +7,083,686 x_4 = 1,328,191.2$$

A: If we simply solve the initial system of four linear equations in four unknowns, its unique solution is this:
$$
x_1 = -10.1019 \\
x_2 = -10.3069 \\
x_3 = 15.7201 \\
x_4 =  5.6887 $$
This solutions is not nonnegative (forgive the use of a double negative!), and so is unsatisfactory.  There is a natural 3D geometric interpretation of the system, arising from the first equation that the sum of coefficients is one.  If all four variables are to have nonnegative values (yet sum to one), then these are  barycentric coordinates for the vector formed by the right-hand sides of the last three equations, in terms of the coefficents of the unknowns in the same three equations.
In other words, consider the four corners of a tetrahedron:
$$
P_1 := ( 0.2895, 0.2942, 7969147) \\
P_2 := ( 1.2312, 0.5828, 21685) \\
P_3 := ( 0.8360, 0.4561, 2656382) \\
P_4 := ( 0.5515, 0.4006, 7083686) $$
We were hoping to find that the point $Q := ( 0.665, 0.47, 1328191.2)$ belongs to the convex closure of those four corners. But it doesn't, as the solution of the linear system above tells us.
The issue then becomes whether the "little bit" of variation you are willing to allow will be sufficient to move the target point $Q$ inside the tetrahedron.
To avoid "stabbing in the dark" we can first ask about the distance the target $Q$ is from the closest point to it on the tetrahedron $P_1 P_2 P_3 P_4$.  Any adjustments to point coordinates should be made in a way that reduces this distance to zero.  What the problem statement permits (if I understand it correctly) is that the $x$ and $z$ coordinates can be adjusted to some extent, but not the $y$ coordinates.
I need to go run an errand, but when I get back I'll do the numeric experiment and tell you if the adjustments allow for that (and explain why or why not).


text:
Q: Create custom URL with different levels I am new to Wordpress and used to Drupal. In drupal I could put any url for any post. It is not bound to category or tags.
for example, pages in any category can have  any structure of different urls like below
1. /page/about/vision.html
2. /page/about/topics
3. /page/employee/motivation/artcle/1.html

But I noticed, in wordpress I can not modify the levels other than what I put in "Permalink Settings"'s custom structure section. After save the setting on it, i can not create more levels in page.
Any one worked in Drupal will understand the question easily.
What my question is, is there any plugins that can allow me create any URL or aliases with any levels to any post?

A: On a very basic level, sub-pages inherit the URL segment of their parent page.
A bit more complex, when creating custom taxonomies and custom post types you can define their slug for the WP rewrite engine. The documentation: http://codex.wordpress.org/Taxonomies#Custom_Taxonomies
Neither is exactly what you're looking for... Writing to .htaccess wouldn't be that hard.


text:
Q: Mulesoft - cloudhub runtime update issues - HTTP connector I am updating the runtime version of an application in cloudhub(anypoint platform - mulesoft).
In detail, updated the runtime 3.9.0 -2018 release to runtime 3.9.0 - 2019 latest version. I am able to successfully deploy the application and it is started without any issues.
Later, When I am trying to make HTTP request to application. It errors out as below ::
ERROR
********************************************************************************
Message: org.glassfish.grizzly.connectionpool.Endpoint.connect(Lorg/glassfish/grizzly/CompletionHandler;)Lorg/glassfish/grizzly/GrizzlyFuture; (java.lang.AbstractMethodError).
Element: /get:\/redacted:redacted-config/processors/0 @ redacted:redacted.xml:44 (HTTP)
--------------------------------------------------------------------------------
Exception stack is:
org.glassfish.grizzly.connectionpool.Endpoint.connect(Lorg/glassfish/grizzly/CompletionHandler;)Lorg/glassfish/grizzly/GrizzlyFuture; (java.lang.AbstractMethodError). (org.mule.api.MessagingException)
  org.glassfish.grizzly.connectionpool.SingleEndpointPool.connect(SingleEndpointPool.java:1158)
  org.glassfish.grizzly.connectionpool.SingleEndpointPool.take(SingleEndpointPool.java:790)
  org.glassfish.grizzly.connectionpool.MultiEndpointPool.take(MultiEndpointPool.java:592)
  com.ning.http.client.providers.grizzly.ConnectionManager.openAsync(ConnectionManager.java:143)
  com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider.execute(GrizzlyAsyncHttpProvider.java:174)
  com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:505)
  com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:527)
  org.mule.module.http.internal.request.grizzly.GrizzlyHttpClient.sendAndWait(GrizzlyHttpClient.java:360)
  org.mule.module.http.internal.request.grizzly.GrizzlyHttpClient.send(GrizzlyHttpClient.java:307)
  com.mulesoft.mule.http.request.grizzly.EEGrizzlyHttpClient.send(EEGrizzlyHttpClient.java:105)
  (191 more...)

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

A: Updating Mule 3.9.0 in CloudHub to the October 24 2019 release should resolve that issue.
Having said that, I usually recommend to also upgrade to the last version, 3.9.3, which includes many other fixes.


text:
Q: How do you display placeholder which is set as 'mm/dd/yyyy' instead of "1/1/0001" in date input fields when date is null? I have a column in my database, of type datetime which may or may not be null. The front-end form should display the date in database(if any) and if it is null it should display mm/dd/yyyy instead of 1/1/0001 which it does when there are null values in database. So basically if there's a date in the database, it should show the date and if it's null it should return the default datepicker with 'mm/dd/yyyy' or 'Select Date'.
My js file looks like:
    $scope.Changes = function (product, value) {
        var input =
            {
                ProductId: product.ProductId,
                isActive: value,
                graceEndDate: product.graceEndDate
            }

        AdService.updateProducts(input).then(function (response) {
            if (response && response.data && response.data.isSuccessful === true) {
                DealService.showSuccess('Update successful');
            } else {
                DealService.showError('error');
            }
            product.isUpdating = false;
            $scope.loadProducts();
        }, function (error) {
            product.isUpdating = false;
            $scope.loadProducts();
            DealService.showError(error);
        });
    }
};

My HTML looks like this:
<td ng-if="product.isActive === true">
  <quick-datepicker type="date" style="max-width: 175px"
                    placeholder="mm/dd/yyyy"
                    ng-model="product.EndDate"
                    disable-timepicker="true"
                    ng-change="saveChanges(product, true)">
  </quick-datepicker>
</td>

A: I don't think your problem is the placeholder. I'd be willing to bet that the data your front end is receiving has product.EndDate set to 1/1/0001 because of the DateTime type setting that as the default when null.
Depending on what your back end language is you can set the type to be nullable to fix this

A: If you used the nqQuickDate library you can easily use the placeHolder attribute to handle null values.
But double-check that your null value get from API is in the right format, sometimes null values came as string null ex: date:'null'


text:
Q: Destiny: Weekly crucible bounties I'm a Destiny veteran, but I just realized that I never completed crucible weekly bounties. I know that I have to go to lord Shax in the tower, but he doesn't give me the weekly bounty mission (as I saw on a video on youtube)...
How can I obtain crucible weekly bounties ?

A: According to this great GameZone article, you need to accomplish 8 steps in order to unlock the crucible weekly bounties :

1 – Crucible Forged
Defeat Guardians in a Control match with your team holding at least 2 Control zones – 8 kills.
2 – Crucible Combat
Complete the following things in the game:
No Guns Barred – Defeat opposing Guardians in the Clash playlist – 12 kills.
Not My Runner – Defeat opposing Guardians while your team has an active Runner in the Rift playlist – 5 kills.
Free For All – Defeat opposing Guardians in the Rumble playlist – 12 kills.
Small-Team Tactics – Defeat opposing Guardians in the Skirmish playlist – 8 kills.
Spelunking with Guns – Capture Relics in the Salvage playlist – secure 3 relics.
3 – Conquer the Day
Complete the following daily challenges :
Participation Point – Complete a match in the Daily Crucible playlist
Spoils to the Victor – Win a match in the Crucible Daily playlist
Making a Statement – Win multiple matches in the Crucible Daily playlist – a total of 4 wins
4 – Factions
This requires you to:
Note: You do not need to actually pledge to each of these factions for the wins. You simply need to talk to the faction leaders and they will give you the quest.
Meet with Dead Orbit – Visit the representative of Dead Orbit, Arach Jalaal, in the Tower Hangar
This is Dead Orbit Territory – Win matches in the Control playlist for Dead Orbit – a total of 2 wins
Dead Orbit Rifter – Win matches in the Rift playlist – a total of 2 wins
Return to Arach Jalaal – Return to Arach Jalaal in the Tower Hangar
The Future War Cult – Visit the representative of Future War Cult, Lakshmi-2, in the Tower Hangar
Clash for the Future – Win matches in the Clash playlist for the Future War Cult – a total of 2 wins
Future Rumble Cult – Finish as one of the top three competitors in the Rumble playlist – a total of 2 top 3 placements
Return to Lakshmi-2 – Return to Lakshmi-2 in the Tower Hangar
Meet with New Monarchy – Visit the representative of New Monarchy, Executor Hideo, at Tower North
New Monarchy Skimisher – Win matches in the Skirmish playlist for New Monarchy – a total of 2 wins
New Monarchy Relic Seeker – Win matches in the Salvage playlist for New Monarchy – a total of 2 wins
Return to Executor Hideo – Return to Executor Hideo in Tower North
5 – Trials Practice
Win a total of 5 matches in Elimination playlist.
6 – Break the Ceiling from Arcite 99-40
Win 5 crucible matches with a score of at least 1,200.
7 – Weapon Master from Banshee-44
Complete the following:
More Bullets – Win multiple matches in the Crucible with at least six Auto Rifle kills – a total of 3 wins
Burst of Bullets – Win multiple matches in the Crucible with at least six Pulse Rifle kills – a total of 3 wins
Nimble Bullets – Win multiple matches in the Crucible with at least six Scout Rifle kills – a total of 3 wins
Point and Shoot – Win multiple matches in the Crucible with at least six Hand Cannon kills – a total of 3 wins
8 – The Mountaintop
You need to earn a total of 9 points. Winning a Crucible match nets you 3 points; however, starting a new match costs 1 point.

When you complete The Mountaintop quest, you'll be rewarded with the Legendary Rocket Launcher, 'The Hothead'. You'll also be eligible for Lord Shaxx's weekly Crucible bounties, which refresh every week.


text:
Q: adding onClick event to JavaScript for loop What I am trying to do is to create an App in which there are 26 boxes with ids case0, case1, case2 and so on. When clicked, these should add class 'black' to respective item0, item1, item2 and so on. My current code looks like this:
let num = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
let guess = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
let i,x;
let arrayShuffle = function(arr){
    let newPos,temp;

    for (let i = arr.length-1; i > 0; i--) {
        newPos=Math.floor(Math.random()*i+1);
        temp=arr[i],
        arr[i]=arr[newPos];
        arr[newPos]=temp;
    }
    return arr;

    };
let numRandom = arrayShuffle(guess);
function suitCase(){
    for (x = 0; x < num.length; x++) {
    document.getElementById("casePanel").innerHTML+="
"+ num[x] + "
";
    document.getElementById('case'+numRandom[x]).onclick=function(){clickCase();}
    }
};

function clickCase(){
    for(x = 0; x < num.length; x++){
    document.getElementById('item'+[x]).classList.add('black');
    }
}

With this code I am having two problems. First class 'black' is applied to all items not single and only after I click the last box. Rest of the 25 boxes don't do anything when clicked. And secondly, only if I use variable numRandom[x], the whole array is visible but if I use simply [x] or num[x], just the first two elements of array that is 0 and 1 are visible.
Can someone please help me with this and suggest a better code?
Here is my html in case someone needs it for reference:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>The Suitcase</title>

    <link rel="stylesheet" href="style.css">

This is a sample title for this nice suitcase casino

            <?php
                $priceL = [".01","1","5","10","25","50","75","100","200","300","400","500","750"];

                for($i=0;$i<count($priceL);$i++){
                    echo "
$".$priceL[$i],"
";
                }
            ?>

            <?php
                $priceR = ["1000","5000","10,000","25,000","50,000","75,000","100,000","200,000","300,000","400,000","500,000","750,000","1,000,000"];
                $x = 13;
                for($i=0;$i<count($priceR);$i++){
                    echo "
$".$priceR[$i],"
";
                    $x++;
                }
            ?>

A: The onclick function should get the ID of the element that was clicked. Then replace case with item to get the corresponding item, and pass that as an argument to clickCase().
The reason only the last item is clickable is because you're rewriting document.getElementById("casePanel").innerHTML each time through the loop. This recreates all the elements, so all the previous elements no longer have their click handlers.
You can use insertAdjacentHTML() to add HTML to an element without reparsing what it already contains.

let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];
let guess = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];
let i, x;
let arrayShuffle = function(arr) {
  let newPos, temp;
  for (let i = arr.length - 1; i > 0; i--) {
    newPos = Math.floor(Math.random() * i + 1);
    temp = arr[i],
      arr[i] = arr[newPos];
    arr[newPos] = temp;
  }
  return arr;
};

let numRandom = arrayShuffle(guess);
suitCase();

function suitCase() {
  for (x = 0; x < num.length; x++) {
    document.getElementById("casePanel").insertAdjacentHTML('beforeend', "
" + num[x] + "
");
    document.getElementById('case' + numRandom[x]).onclick = function() {
      clickCase(this.id.replace('case', 'item'));
    }
  }
};

function clickCase(id) {
  document.getElementById(id).classList.add('black');
}
.black {
  background-color: blue;
}

This is a sample title for this nice suitcase casino

$.01

$1

$5

$10

$25

$50

$75

$100

$200

$300

$400

$500

$750

$1000

$5000

$10,000

$25,000

$50,000

$75,000

$100,000

$200,000

$300,000

$400,000

$500,000

$750,000

$1,000,000


text:
Q: Nodejs And Google spreadsheet Integration ( Cannot read property 'length' of undefined ) I have started using nodejs ( and have a beginner level understanding of javascript ) .
Currently following google Spreadsheet API guide to building a small application.
https://developers.google.com/sheets/api/quickstart/nodejs
While I was able to establish the connectivity with my google sheet and able to fetch the data I want to achieve it in a specific way as below.
Put the data fetching code in one file ( fetchdatafromgooglesheet.js getdata() function to fetch the data and return it to main function as rows  )
and later use the data in my main file ( start.js ) and then perform the actions based on the values.
However I m not able to achieve this sharing the code of both files. Please help .
start.js
const googlesheet = require('./fetchdatafromgooglesheet');

var rows=googlesheet.getData();

console.log(rows.length);

fetchdatafromgooglesheet
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
//var rows=null;

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
var rows;

const getData= ()=>
{

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Sheets API.
  authorize(JSON.parse(content), listMajors);
});
return rows;
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error while trying to retrieve access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Prints the names and majors of students in a sample spreadsheet:
 * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 */
function listMajors(auth) {
  const sheets = google.sheets({version: 'v4', auth});
  sheets.spreadsheets.values.get({
    spreadsheetId: '1MMx_OcwmQApgKJUVdU0ySC_lUx1FB6-81AfV3E',
    range: 'Sheet2!A2:F',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    var fetchedData = res.data.values;
  rows=fetchedData;
  });
}

module.exports={getData};

Getting below error while execution.
D:\study\nodejs\googlesheet\start.js:5
console.log(rows.length);
                 ^

TypeError: Cannot read property 'length' of undefined
    at Object.<anonymous> (D:\study\nodejs\googlesheet\start.js:5:18)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

After some research and following up with suggestions given by others I have modified the code as below it gets the job done but I think its not the right way of doing things. Please let me know (here is the modified code )
function fetchData () {

    var rows=googlesheet.getData();
    if (rows==undefined && rows==null) {
        setTimeout(fetchData, 300);
    } else {
      //setTimeout(fetchData, 300); // try again in 300 milliseconds
      console.log(rows.length);
    }
  }

fetchData();

A: Since rows is undefined, you can't access the length attribute. Better to do an undefined & null check before.
const googlesheet = require('./fetchdatafromgooglesheet');
rows=googlesheet.getData();
if(rows!==undefined && rows!==null) console.log(rows.length);

Update:

*

*Since getData() is an async method, you have to wait for it to fetch the result using await keyword.
rows = await googlesheet.getData();

*But since you can use await only inside async functions, you have to make use of Promise.then() method as async method always returns a Promise.
const googlesheet = require('./fetchdatafromgooglesheet');
googlesheet.getData()
       .then((rows) => { console.log(rows.length) });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


text: Q: Converting a SQLite flask app to a Postgres app for Heroku I built a Flask app with a SQLite database. Now, I want to actually upload the app for use. I uploaded to Github and connected the Github  repo to Heroku but realized that I can't use SQLite with Heroku because the database resets every hour. It seems like using the Heroku Postgres database is best, but I'm not sure how to convert my app. All of the tutorials for creating Postgres flask apps I could find are completely different from each other but equally confusing (either they assume I already have something built that I don't or a step is missing or a first step simply doesn't work). How should I even get started with this?


text:
Q: Storing data in Zend_Registry vs class properties I'm building a Zend Framework application wherein the Model layer is separated into Services and Models. Controller actions call service methods, which in turn call model methods.
For instance: LanguagesController::addAction() checks if a form is submitted and valid. If so, it passes the form data to Service_Language::add(), where some business logic is applied to the data before calling Model_Language::add(), which effectively adds the record to the database.
This means that most controller actions will need an instance of a service class, and most methods in the service class will need an instance of a model class.
I used to do it like this (example of a Service class)
class Service_Language
{
    public function add()
    {
        $languageModel = new Model_Language;

        // perform some business logic and add record
    }

    public function edit()
    {
        $languageModel = new Model_Language;

        // perform some business logic and edit record
    }

    public function delete()
    {
        $languageModel = new Model_Language;

        // perform some business logic and delete record
    }
}

Not only does it become cumbersome, in more complex applications where your controller actions call multiple Service methods, there's going to be multiple instances of the same Model class, which is just unnecessary.
A colleague told me to look into two options:

*

*keep a Model instance in a property of the Service

*keep a Model instance in Zend_Registry

I think the best solution would be the first option. The reason being that Zend_Registry acts as a global container. We don't want our Model instances to be available in our Controller actions, it's bad architecture. What are your opinions on this?
The first option could be implemented as follows:
class Service_Language
{

    protected $_model = null;

    function setModel()
    {
        $this->_model = new Model_Language();
    }

    function getModel()
    {
        if($this->_model == null)
        {
            $this->setModel();
        }

        return $this->_model;
    }
    public function add()
    {
        $languageModel = $this->getModel();

        // perform some business logic and add
    }
}

A: From your explanation it sounds like your services classes require tightly coupled models.
In which case I don't think public a public getter/setter for your model is necessary - would there ever realistically be a situation where you would need to set another model for the service?
In which case, assigning the model to a property makes sense - why not do this in the constructor?
class Service_Language
{
    protected $_model = null;

    public function __construct()
    {
        $this->_model = new Model_Language();
    }

    public function add()
    {
        // perform some business logic and add
        $this->_model->add($data);
    }

    public function edit()
    {
        // perform some business logic and add
        $this->_model->edit($data);
    }
}

A: The constructor would have been a good option, but not every method in the service layer needs to have a model instance to do its job, so I ended up doing it like this. I'm relatively new to OOP programming, so I'm wondering if this is a good solution. Any thoughts are more than welcome.
class Service_Language
{

    protected $_model = null;

    protected function setModel()
    {
        $this->_model = new Model_Language();
    }

    protected function getModel()
    {
        if($this->_model == null)
        {
            $this->setModel();
        }

        return $this->_model;
    }

    // Function where model is needed
    public function add($data)
    {
        // Perform some business logic

        $this->getModel()->add($data);

        // return something
    }

    // Function where no model is needed
    public function add($data)
    {
        // Perform some business logic

        // return something
    }
}


text:
Q: ckfinder unable to find image manipulation component Any help appreciated.
We have moved several sites from one server to another. They all work except one. When you goto a page and click the image button then the browse button you get the error 'Unable to find image manipulation component'. I have checked all the permissions agains the other sites as well as the user files directory. We are running CKFinder 2.0.2 on Windows IIS 7 using ASP.
The original developer is no longer available so we are working a little blind.

A: Please see: https://docs.cksource.com/CKFinder_2.x/Developers_Guide/ASP/Configuration/Images#Scaling. Most likely your server is missing some older ASP.NET. Please try installing it and setting the component to Asp.Net.


text:
Q: how to unescape special characters in django urlpatterns So, suppose I have a django app which needs to respond to a url like this: http://127.0.0.1:8000/food%20log/4/up/ .  The original parameter is "food log", but it needed to have the space replaced with %20 when it was included in the url.  Now the link has been clicked on, and it's coming back to urls.py.
urlpatterns = patterns('',
(r'^(?P<content_type>\w+)/(?P<object_id>\d+)/(?P<direction>up|down|clear)/$', process_vote),

...
)
So, it appears that it is not able to properly recognize the parameter .  This is functional code prior to wanting to use a content_type which has a space in it.  If we assume for the moment that I can't just remove the space from the name of that content_type throughout the rest of the system, how do I get the urlpatterns function to recognize that "food%20log" is actually "food log", so that it will recognize it as a valid ?
Basically I want to preprocess the string before it's acted on by urlpatterns, but I am not sure how/where to do that.  Thanks for any assistance.

A: According to the Python manual for the re module:

When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database.

So maybe include the space in the regular expression in addition to \w.
urlpatterns = patterns('',
(r'^(?P<content_type>[\w ]+)/(?P<object_id>\d+)/(?P<direction>up|down|clear)/$',     process_vote),


text:
Q: Carrying variables into new command prompt windows I want a batch file that opens and:

*

*Sets all items in list.txt to variable v one at a time.

*For each of the items in list.txt to open a command prompt and run starter.bat

*Carry variable v into starter.bat

My code
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=*" %%v in (C:\users\anhall\desktop\test\list.txt) DO START c:\users\anhall\desktop\test\starter.bat
ENDLOCAL & SET computer=%v%

this is just an example of what will be in there, when I get it all figured out there should be a couple hundred items in the list.  But I will probably break it down into smaller lists for ease of running.
list.txt
nhn-0073
nhn-0115
nhn-0846
This is what I end up with on the primary window:

I can see that its not working because it doesn't even carry to ENDLOCAL & SET computer=
My main concern is carrying the variable into each of the new windows.  I know this is possible but I can't get it to work.
Completed Code
My code
SETLOCAL
FOR /F "tokens=*" %%v in (C:\users\anhall\desktop\test\list.txt) DO START c:\users\anhall\desktop\test\starter.bat %%v

changes to starter.bat
changed variable to %1

A: Just pass it in on the command line:
for /F %%v in (YourFile.txt) do start c:\users\anhall\desktop\test\starter.bat %%v

Modify your starter.bat file to use %1 to receive the variable from the command line.
:: Starter.bat - replace echo with your actual command
@echo %1

(Doing it from the command line means you never change the computer environmental variable, so you can remove the & SET at the end of your first batch file.)


text:
Q: Zipping a Maybe and Single leads to no result being emitted I'm making an Android application. I've to zip results from two places: One from SharedPreferences as a Maybe and other from the Room Persistence library(basically SQLite) as a Flowable.
I'm using the following code:
repository.getMaybe()
    .subscribeOn(Schedulers.io)
    .toSingle()
    .zipWith(repository.getFlowable().single(DEFAULT VALUE), BiFunction { t1: DataType1, t2: DataType2 -> Pair(t1, t2) }
    .subscribe()

repository.getMaybe() is the Maybe source mentioned in the first paragraph. Likewise, repository.getFlowable() is the Flowable source.
I've tried using doOnEvent(to Log statements) on the Maybe source, the Flowable source and the zipped source. Only the Maybe source emits successfully. Others don't do anything at all.
The Flowable source is used in various other parts of my application and it is not at all an issue.
What am I doing wrong?

A: If your Maybe does not return a value then calling toSingle would result in an Single.error. This would mean it would reach the zipWith as an arrow and it would never bother evaluating the value, since there is no value to zip with.

A: Thanks to Akarnokd, I tried removing the single(DEFAULT ITEM) part. It worked. On looking up the documentation at http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html, I came across this:

single(T defaultItem)
Returns a Single that emits the single item
  emitted by the source Publisher, if that Publisher emits only a single
  item, or a default item if the source Publisher emits no items.

Basically, the Flowable should emit only once. So, I'm using firstOrError() in it's place.


text:
Q: Project's referenced DLL's path changes "by magic" when DLL is deleted Hereis the situation:
I have a folder that contains library DLLs, which are not built as part of my solution - lets say it is .\libs.
I add references to these DLLs.  I then build.  Everything is fine.
If I then delete the libs folder and rebuild my solution, the compilation still succeeds!  Weird - I would have expected compilation errors since the library dlls are not there!
But looking at the reference properties in Visual studio, I see that the reference path has been changed from .\libs\foo.dll to myproject\bin\Debug\foo.dll.  So it is picking up the referenced DLL from its old build output.
If I open myproject.csproj in a text editor, I see that the HintPath of the reference is still .\libs\foo.dll.  If I re-create the libs folder, visual studio still uses myproject\bin\Debug\foo.dll (it does not revert to the actual DLL I want!)
Is this expected behaviour?
Is there a way to stop this behaviour because it is causing me problems - especially when I want to rebuild myproject with different versions of the libs: half the time I find that I am using a different version than what I wanted.

A: This is not magic. Your DLL's Copy Local Property is probably set to true, that's all.
Setting it to false will get you the desired behaviour.


text:
Q: Concatenate different variables into a single variable in php I'm trying to bind the values of three input fields into a single variable and then I will store it in database... actually I have three value first is of day second is of month and third is of year
just like that

12 ---> day
09 ---> month
1990 ---> year

I want to store in database under single table like that
12-09-1996
here is my code
if(isset($_POST["reg-btn"])){
        $name=$_POST["name"];
        $lastname=$_POST["lastname"];
        $mail=$_POST["mail"];
        $pass=$_POST["pass"];
        $repass=$_POST["repass"];
        $country=$_POST["country"];
        $city=$_POST["city"];
        $day=$_POST["day"];
        $month=$_POST["month"];
        $year=$_POST["year"];
        $gender=$_POST["gender"];
        //echo '<script>alert("hello")</script>';
        $DOB+="$day."-".$month."-".$year";
        $arr= array($name,$lastname,$mail,password_hash($pass, PASSWORD_DEFAULT),$country,$city,$DOB,$gender);
        $SPS=$db->prepare("INSERT INTO signup (name,lastname,email,password,country,city,DOB,gender) VALUES (?,?,?,?,?,?,?,?)");
        $SPS->execute($arr);

A: instead $DOB+="$day."-".$month."-".$year";
should be $DOB = $day . '-' . $month . '-' . $year;

A:  $DOB = $day."-".$month."-".$year;

i hope it helps you.it must be working

A: if your DOB field is a varchar then your need to write it like
$DOB = $day . '-' . $month . '-' . $year;

If your DOB field is date type then you can't store like 12-09-1996
for that you need to write
    $DOB =  $year. '-' . $month . '-' . $day;

because MySql store's date in YYYY-MM-DD format.
Coming to your problem you wrote it wrong
$DOB+="$day."-".$month."-".$year"; // this is wrong

it should be $DOB = $day . '-' . $month . '-' . $year;

A: In your table if your data type is date then you can write like
$DOB = $year."-".$month."-".$day;
if datatype is varchar then:
$DOB = $day."-".$month."-".$year;


text:
Q: Which is faster inline function or MACRO I believe that preprocessor expands the Macro as a copy text in the code before compilation wherever is it called, while the compiler writes a copy of compiled function definition in each function call. So in both cases we avoided the overhead of regular function call, but in this case which is faster and has less overhead, inline function or MACRO?

A: The macro will only be 'faster' insofar as it is not left to compiler heuristics whether the macro will be inlined. Given the downsides of macros, it's typically better to leave this decision to the compiler. There are also issues with debugging levels and corresponding source code. Optimization levels, 'forced' inlining, e.g., __attribute__ ((__always_inline__)) (gcc/clang). More importantly, you avoid common pitfalls such as multiple expression expansion / evaluation within the macro.
I haven't done a S.O. question search (which you should get into the habit of doing), but I suspect this has been answered long before, in much greater detail!


text:
Q: How to differentiate by color even and odd rows in sublime text I've been using sublime text 2 just like every other day and thought about improving a bit the readability of my code.
I'm seriously looking for a simple solution.
I'm not very familiar with advanced sublime tools (I mean, I know how to install packages but I do not know how to write one).
What would be the simples way to make it so that every 2nd row has a background color like 10% darker/lighter than the 1st ones?
Is there some good package which already has this implemented or how hard would it be to make a sublime script which does this for me?

A: I've never seen anything like this in Sublime Text.
As a theme developer - I know we don't have even/odd selectors to change the colour.
You may be able to create a custom syntax with a package,but again I've never seen it.
As for readability - that is very important. I find these few settings to help with readability:
"line_padding_bottom": 1,
"line_padding_top": 1,
"highlight_line": true,
"highlight_modified_tabs": true,

As well spend some time finding the perfect programming font and a colour scheme


text:
Q: Socket.io second server should connect when first one reconnect_failed I got a scenario that i am implementing socket.io connectivity to push notifications to all clients,
    sockets = io.connect("http://localhost:3000");
       sockets.on("connection", function(socket){
            socket.on('connect',function(data){
             });
       socket.on('reconnect_failed',function(){
           console.log("reconnect_Failed");
               io.connect("http;//localhost:4000");
                 //Here i want to register a new socket when
                 // the first server is not able to reconnect
         });
      });

Please guide me to register when only first server is down. so that i can avoid the registering of second instance while running first server... Does this code helps. My Output is null not showing whether it is connected or not. First server is running fine.

A: You have a typo, http;//
That should do :
socket.on('reconnect_failed',function(){
           console.log("reconnect_Failed");
               io.connect("http://localhost:4000");
                 //Here i want to register a new socket when
                 // the first server is not able to reconnect
         });
      });


text:
Q: How to run schema-registry in master slave mode As of now I am running schema-registry as a single node.
To provide fault tolerance, I want to run schema-registry in master slave mode. One node for master and one node for slave.
Do we need to add any extra property to identify a node as master?
Please can any body share me the configurations(schema-registry.properties) for master and slave.
Any help is appreciated.

A: setting up multiple SchemaRegistry instances is pretty easy.
You can just startup several instances, but you have to ensure that all instances are pointing to the same zookeeper quorum.
This is property kafkastore.connection.url in file schema-registry.properties
The leader election will be managed by Zookeeper throughout all registered schema-registry instances. If you want to avoid particular schema-registry instances from becoming the leader (aka master), then set property master.eligibility=false in the properties file (default value is true).

A: I think what the original question is asking is really: How do I know which Schema Registry node is currently the master, and test that when one node fails another picks up?
As far as I can tell, this isn't explicitly documented anywhere, but I found that, at least for Confluent Platform v3.3.1, Zookeeper stores this information in the key /schema_registry/schema_registry_master. When I use Exhibitor as a UI to browse the state of Zookeeper, I see the following value for that key:
{"host":"172.31.59.89","port":8081,"master_eligibility":true,"version":1}

When I restarted the current master, this value updated instantly.


text:
Q: Unable to sign AAB file using 'r0adkll/sign-android-release@v1' in github action workflow I am getting the following error when signing the APK in Github workflow.
Below are some logs details from github workflow:

Run r0adkll/sign-android-release@v1 with:

releaseDirectory: app/release signingKeyBase64: ***

alias: ***

keyStorePassword: ***

keyPassword: ***

env: JAVA_HOME_8.0.275_x64:
/opt/hostedtoolcache/jdk/8.0.275/x64 JAVA_HOME:
/opt/hostedtoolcache/jdk/8.0.275/x64 JAVA_HOME_8_0_275_X64:
/opt/hostedtoolcache/jdk/8.0.275/x64 BUILD_TOOLS_VERSION: 30.0.2

Preparing to sign key @ app/release with signing key

**/opt/hostedtoolcache/jdk/8.0.275/x64/bin/jarsigner -keystore app/release/signingKey.jks -storepass *** -keypass ***
app/release/app-release.aab *****

This is the error part:
jarsigner: unable to sign jar:

java.util.zip.ZipException: invalid entry compressed size (expected
38206 but got 38984 bytes) Error: The process
'/opt/hostedtoolcache/jdk/8.0.275/x64/bin/jarsigner' failed with exit
code 1

I believe it's very specific to jar signer, ( I tried with the answer it fix the problem)
Update: This has happening to me as well.

A: You need to save your KeyStore, Alias, KeyStore Password and Key Password in the secret section inside GitHub settings.

*

*SIGNING_KEY — base64 text of your Keystore file

*ALIAS — your alias name

*KEY_STORE_PASSWORD — password of your Keystore

*KEY_PASSWORD — your key password

- name: Sign AAB
  id: sign
  uses: r0adkll/sign-android-release@v1
  with:
    releaseDirectory: app/build/outputs/bundle/release
    signingKeyBase64: ${{ secrets.SIGNING_KEY }}
    alias: ${{ secrets.ALIAS }}
    keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
    keyPassword: ${{ secrets.KEY_PASSWORD }}

r0adkll/sign-android-release


text:
Q: angularjs routing issue - appends index.html I have simple angularjs application and I believe I did not configure the routing the right way because in the browser the url looks weird. For example when I access my index.html page this is the url: http://localhost:8082/basic-web-app/app/index.html#/ and when I navigate to another pages within the app it appends the location after index.html#/: http://localhost:8082/basic-web-app/app/index.html#/login Every example I checked was without index.html and appending the location like http://localhost:8082/basic-web-app/app/ and http://localhost:8082/basic-web-app/app/login My routing:
    coursesApp.config(function($routeProvider, $httpProvider) {
    $routeProvider

    // route for the home page
    .when('/', {
        templateUrl: 'pages/home.html',
        controller: 'mainController',
        controllerAs: 'controller'
    })

    // route for the courses page
    .when('/courses', {
        templateUrl: 'pages/courses.html',
        controller: 'coursesController'
    })

    // route for the courses page
    .when('/login', {
        templateUrl: 'pages/login.html',
        controller: 'loginController',
        controllerAs: 'controller'
    })

    .when('/profile', {
        templateUrl: 'pages/profile.html',
        controller: 'profileController'
    });

    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
});

thank you!

A: The issue is your folder structure.
The index.html should be outside of the app folder.
The index.html lives at the root of front-end structure. The index.html file will primarily handle loading in all the libraries and Angular elements.
HEre is an example of folder structure,
app/
----- controllers/
---------- mainController.js
---------- otherController.js
----- directives/
---------- mainDirective.js
---------- otherDirective.js
----- services/
---------- userService.js
---------- itemService.js
----- js/
---------- bootstrap.js
---------- jquery.js
----- app.js

views/
----- mainView.html
----- otherView.html

index.html

Here are some links for your folder structure:
https://johnpapa.net/angular-growth-structure/
https://scotch.io/tutorials/angularjs-best-practices-directory-structure

A: If I got your question right, then:
There is nothing wrong in what you have done. Every Single Page Application framework (AngularJS being one of those) uses the hash - # - intelligently to keep the user on the same page. As long as your views are rendering the way you need, it looks alright.


text:
Q: Как сделать модальное окно processing во время обработки запроса сервером? Пока обрабатывается запрос сервером, хотелось бы вывести клиенту модальное окно, которое закрыло бы ему возможность продолжать кликать на кнопочки.
Как вообще такие механизмы реализуются, на чем они базируются? Как понять продолжительность отображения окна? Объясните, кто делал, пожалуйста.

A: С использованием primefaces все реализуется просто:

https://www.primefaces.org/showcase/ui/ajax/status.xhtml


text:
Q: module specifier in es6 import and export I'm confused about what the module specifier in these statements refer to:
export {bar} from "foo";

import {bar} from "foo";

What does "foo" refer to? It can't be a file since it would be something like "./foo". If it's not a file, I assume it's an ID. How is the ID defined?
I'm exporting from a js file, but the import would be part of an inline html script (type="module") in the firefox browser.
The browser version (and browser settings) have been verified to work with es6 modules.
Thanks in advance.

A: ES6 does not specify what the module specifier refers to.
It is indeed just that: an identifier. Nothing more.
It is left to the environment to resolve these identifiers to an actual module. A loader might interpret them as relative file paths, as global ids, as npm module names, as anything else.
In browsers, <script type="module"> took some time to specify, but it's here finally. A module specifier of "foo" is currently invalid, a browser will ignore that module as it doesn't know what to do with it. It will need something that resolves to an URL to load. Jake Archibald wrapped it up succinctly:

"Bare" import specifiers aren't currently supported. Valid module
  specifiers must match one of the following:

*

*A full non-relative URL. As in, it doesn't throw an error when put
  through new URL(moduleSpecifier).

*Starts with /.

*Starts with ./.

*Starts with ../.

  Other specifiers are reserved for future-use, such as importing built-in
  modules.


text:
Q: Is ther any Mac Images available in Azure? We are using stand alone mac server for our ios builds by configuring them as the Azuredevops agents. But looking for a way to enable high availability of mac machines if any mac image version is available in azure platform  to achieve this.

A: The list of supported agents you can find here: Software
or when you open build agent type on the classic pipeline.


text:
Q: Connect to localhost using public SSH key failure I have created a ansible code to create users and add respective ssh keys which is working successfully. But when trying to server access, it is asking for password.
Server is   127.0.0.1 or localhost
Ansible Script
tasks:
    - include_vars: users.yml
    - name: Create user
      user:
        name: "{{item.username}}"
      with_items: "{{ users }}"

    - name: Adding SSH key
      authorized_key:
        user: "{{ item.username }}"
        key: "{{ lookup ('file', 'keys/'+ item.username + '.key.pub') }}"
      with_items: "{{ users }}"

I am trying to connect through three ways :
1. ssh user@localhost - Asking for password
2. ssh -vvv user@localhost - Asking for password
3. ssh-copy-id user@localhost - Asking for password

If I go to ssh config file at set ask password flag to no than running anisble script next is giving permission issue which is valid case as that time public key for user will not be configured.
The solution which I am looking is once ssh key is set for user through ansible script, he must be able to login without password using ssh key.
NOTE :-  The server is localhost/127.0.01 not any remote server ( I am learning so not using remote server)

A: The issue is resolved by using ssh-add on basis of this link.


text:
Q: SCSS silent class output as helper class The extend normal class function will group the class name that i do not want.
So i use SCSS silent class.
%red {
  color: red;
}

.someclass {
  @extend %red;
}

but how can the silent class output as helper class for html late use?
.red {
  color: red;
}

red title

A: Do this:
favorite

The extend normal class function will group the class name that i do not want.
So i use SCSS silent class.
%red, .red {
  color: red;
}

.someclass {
  @extend %red;
}

And you can use the classname red on the HTML


text:
Q: How can I fix this code and add input inside the Elif statement? Please find the code below:
x = input("Enter your name: ")
y = input("Enter your field: ")
print("Hello %s,You have a very interesting Field" % x)
print("Here are the future options for all the careers related to %s:"% y)
if y == "commerce":
    print("A.Chartered accountant\nB.Civil Services\nC.Accountant\nD.company Secretary\nE.Financial Analyst\nF.Auditor")
elif y == "biology":
    print("A.Doctor\nB.pharmacist\nC.Chemist\nD.Scientist")
elif y == "engineering":
    z == input("Enter Stream: ")
    if z == "Mechanical":
        print("Mechanical Engineer")
    elif z == "computer science":
        print("A.Software Engineer\nB.Data Scientist\nC.Programmer")
else:
    print("I suppose you've entered Arts,YOu can opt for a career in\nA.IAS\nB.Music\nC.Political Science")

I do not understand the error in logic, I mean it makes perfect sense but some how it shows syntax error in the nesting code. Is there any way I can solve this without changing the method?

A: Your only error is, that:
elif y == "engineering":
z == input("Enter Stream: ")

should be:
elif y == "engineering":
z = input("Enter Stream: ")

== compares both values,
= assigns a value.


text:
Q: ASP.NET session alternative to pass object between pages I want to pass an object between pages of my website. I know I can use session object for this.
Personally, I don't want to use any session or application or caching for this.
Is there any other alternative?
Please help.
Thanks,
Mahesh

A: Another alternative would be to serialize the object into a hidden field and when you post to the other page deserialize the value back to an object instance. Or yet another possibility would be to persist the object to some data store and then use an id to fetch it back.


text:
Q: how to input data into KERAS python? In keras fit function
model.fit(X_train, y_train, nb_epoch=20, batch_size=16)

How should I input the data when i have more columns?
I want to input image, and detect object of class 1 on it. So the output is (x, y, width, height)
The input image should be 416 x 416 x 3 and output matrix should be 13x13x4 so i want to detect up to 169 objects.
Should the
X_train

variable be loaded set of images ( so it will be 4 dimensional array of N x 416 x 416 x 3 )
and
y_train

be 2D array of N x 4 , where 4 represents ( x ,y , width, height ) ?
If so what do i have to pass in validation_data arguments?
I am really confused.

A: The test (validation) data should have the same shape as the training data: the X must be "feedable" into the network and y must be "comparable" to the output of the network, no matter if it's for training or testing. So if
X_train.shape == (N, 416, 416, 3)
y_train.shape == (N, 169, 4)

... then the test data
X_test.shape == (M, 416, 416, 3)
y_test.shape == (M, 169, 4)

Here I assume you want to detect 169 objects at once per training instance. This number depends on the data you have, traditional datasets contain much fewer objects per image. Up to 10 objects would result in (N, 10, 4) output shape.
There's a nice tutorial on object detection with keras (here's the code), which can serve as an example.


text:
Q: I have the error in my code I try all the way but it doesn't work I use flutter downgrade command flutter clean etc /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_configuration.dart:161:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(AnimationConfiguration)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_limiter.dart:75:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(_AnimationLimiterProvider)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_simple_video_player-0.0.9/lib/flutter_simple_video_player.dart:124:33: Error: No named parameter with the name 'isInitialRoute'.
        settings: RouteSettings(isInitialRoute: false),
                                ^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/widgets/navigator.dart:520:9: Context: Found this candidate, but the arguments don't match.
  const RouteSettings({
        ^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_simple_video_player-0.0.9/lib/flutter_simple_video_player.dart:134:17: Error: No named parameter with the name 'resizeToAvoidBottomPadding'.
                resizeToAvoidBottomPadding: false,
                ^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/scaffold.dart:1451:9: Context: Found this candidate, but the arguments don't match.
  const Scaffold({
        ^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 21s
Exception: Gradle task assembleDebug failed with exit code 1


text:
Q: EKS - Restarting or Deleting a Pod of Go cobra/fasthttp helloworld for a K8s service kills service nodeport on worker group instance I have a simple k8s NodePort Service linked to a k8s deployment of a single pod hosting a hello world go program that basically uses cobra to spin up a fasthttp server. If the pod of that deployment restarts or get deleted (and a new one spins up), the whole service goes down and never comes back up. The pod reports healthy, the service reports healthy, but the load balancer is reporting no response. If I ssh onto the EC2 Node and try to call the nodeport of the service, i also get no response. Basically the entire port just dies and stops responding on the instance. Restarting the node doesn't fix it, deleting the instance and bringing up a new one doesn't fix it. I basically need to move the entire service to an entirely new port for it to start working again.
This with the k8s version of 1.24
Does anyone have any ideas why this might be the case, i've never encountered this issue hosting a container built in any other way.


text:
Q: Find all integers such that $2 < x < 2014$ and $2015|(x^2-x)$ Find all integers, $x$, such that $2 < x < 2014$ and $2015|(x^2-x)$.
I factored it and now I know that $x > 45$ and I have found one solution so far: $(156)(155)= (2015)(12)$. It's just that I don't think I'm approaching it the right way.
I'm new to this kind of stuff and I'm just doing this for fun so any help please?

A: You need a couple of pieces of information to complete this.
First of all, a property of prime numbers: If $p$ is a prime number such that $p ~|~ ab$, then $p~|~a$ or $p~|~b$. Also $2015=5 \cdot 13\cdot 31$.
Now, if $2015~|~N$, then $5~|~N$. Since $2015~|~x(x-1)$, $5~|~x$ or $5~|~(x-1)$; thus $x\equiv0\pmod5$ or $x\equiv1\pmod5$.
Continue with the other two factors: $13~|~x(x-1)$, so $x\equiv0\pmod{13}$ or $x\equiv1\pmod{13}$. There are now four possibilities for $x$:

*

*$x\equiv0\pmod5$ and $x\equiv0\pmod{13}$

*$x\equiv0\pmod5$ and $x\equiv1\pmod{13}$

*$x\equiv1\pmod5$ and $x\equiv0\pmod{13}$

*$x\equiv1\pmod5$ and $x\equiv1\pmod{13}$

When you continue with the 31 factor, you will get eight possibilities.
Here's the second piece of information you need: The Chinese Remainder Theorem: https://en.wikipedia.org/wiki/Chinese_remainder_theorem
Now, use the Chinese Remainder Theorem to find $x\mod (5\cdot13\cdot31)$ for each of the 8 cases, and find the solutions which are in the interval $[2,2013]$. (There are six of them, one of which is 156.)

A: $2015=31\cdot13\cdot5$
Now, you need each of the primes $31,13$ and $5$ to be a divisor of either $x$ or $x-1$. In other words you need the following: $x\equiv 1$ or $x\equiv 0 \bmod 5,13,31$
There are going to be $8$ possible solutions, each of them can be solved in an easy way, the only ones that are not possible are $x\equiv 0\bmod 5,13,31$ and $x\equiv1\bmod 5,13,31$ as they would give solutions $0$ and $1$ which are not permitted.
The other $6$ combinations will provide one working solution each.
I will work through one example, the others are analogous.
$x\equiv 0\bmod 5$
$x\equiv 1 \bmod 13$
$x\equiv 1\bmod 31$
write $x=5k$, now $5k\equiv 1\bmod 13$ and so $k\equiv 8\bmod 13$ (since $8$ is the inverse of $5\bmod 13$). From here $k=13j+8$ and so $x=5(13j+8)=65j+40$
Now write $65j+40\equiv 1 \bmod 31\implies 3j\equiv-39\bmod 32\implies 3j\equiv23\equiv -8\bmod 31$, multiplying by the inverse of $3\bmod 31$ which is $21\equiv-10$ yields $j\equiv80\equiv 18\bmod 31$. from here $j=31m+18$
and so $x=65(31m+18)+40=2015m+1210$.
So this combination gives $1210$ as an answer, only $5$ other combinations remain.

A: I think the following algorithm can be usefull:

*

*Observe that $x^2-x=x(x-1)$. Now $x$ and $x-1$ are coprime and then, if $2015=ab$, with $(a,b)=1$ you can suppose $a|x$ and $b|x-1$

*For every fixed couple $(a,b)$ of coprime divisors of 2015 solve by CRT the system af congruences:
$x \equiv 0 \mod a$     ^      $ x \equiv 1 \mod b$.
CRT gives a unique solution $\mod ab=2015$. We call its class $X$

*Now you have just to find the representant of the class of $X$ between $2$ and $2014$, if it exist, to find an $x$ that works.

So now you have just to apllie this algorithm to the 3 possible couple of coprime divisors of 2015, and for every couple there are only two cases to examinate...


text: Q: Fsck logs on the screen I just install Ubuntu 22.10 and first that I notice is fsck logs on the screen before splash screen. I don't want watch this. So I found fsck.mode=skip, but I don't want turn off checking, FRAMEBUFFER=y > /etc/initramfs-tools/conf.d/splash, but I don't know how it works, bu it works. Also I found article on Arch Wiki, but it Arch, Ubuntu haven't /etc/mkinitcpio.conf. Is it possible to adapt this article and the commands in it for Ubuntu?


text: Q: Is that possible to use query plan for dynamic SOQL queries? I know we can verify straightforward SOQL in query plan. Now, I am trying to find a way to use query planner for a dynamic SOQL queries. My SOQL query depends on several Ids (list of Ids) and binding variables which will be available only in the run time. Now, is that possible to verify a complex dynamic query in query planner? Please provide some guidance.


text:
Q: Adding categories to all blogs at once I am using WordPress mu 2.9.2 and have the same category structure on all my blogs. How do I add categories to all my blogs simultaneously? Is there a plugin that does this effectively?

A: You could write a script for that, here is something I wrote in Perl lately:

*

*first the sql statements to check if the term already exist and if not insert it:

the prepared statements:
my $wts    = $dbh->prepare(
"SELECT term_id FROM $tb_wp_terms WHERE name = ?")
or die "Couldn't prepare statement: " . dbh->errstr;

my $wti    = $dbh->prepare(
"INSERT INTO $tb_wp_terms
(name, slug) VALUES (?,?)")
or die "Couldn't prepare statement: " . dbh->errstr;

*

*then make the term taxonomy entry:

the prepared statements:
my $wtts    = $dbh->prepare(
"SELECT term_taxonomy_id FROM $tb_wp_term_taxonomy WHERE term_id = ?
 AND taxonomy = '".$config{'wordpress.taxonomy_type'}."'")
 or die "Couldn't prepare statement: " . dbh->errstr;

my $wtti    = $dbh->prepare(
"INSERT INTO $tb_wp_term_taxonomy
(term_id, taxonomy, count) VALUES (?,?,1)")
or die "Couldn't prepare statement: " . dbh->errstr;

my $wtts_count    = $dbh->prepare(
"SELECT count FROM $tb_wp_term_taxonomy WHERE term_taxonomy_id = ? AND taxonomy =
   '".$config{'wordpress.taxonomy_type'}."'")
or die "Couldn't prepare statement: " . dbh->errstr;

my $wtti_count    = $dbh->prepare(
"UPDATE $tb_wp_term_taxonomy
 SET count = ?
 WHERE term_taxonomy_id = ?
 ")
or die "Couldn't prepare statement: " . dbh->errstr;

And use the queries above with some code around it (you need to check for blogs that already have some of the categories).
For MU only the blogs > 1 get a blog id in their table name:
my $tb_blogid = "";
if ( $config{'wordpress.wp_mu_blog_id'} > 1 )
{
$tb_blogid = "_" . $config{'wordpress.wp_mu_blog_id'};
}
my $tb_posts                    = $config{'wordpress.prefix'} . $tb_blogid . "_posts";
my $tb_wp_terms                 = $config{'wordpress.prefix'} . $tb_blogid . "_terms";
my $tb_wp_term_taxonomy         = $config{'wordpress.prefix'} . $tb_blogid .
"_term_taxonomy";
my $tb_wp_terms_relationships   = $config{'wordpress.prefix'} . $tb_blogid .
"_term_relationships";

So just loop through them.


text:
Q: what is the file ORA_DUMMY_FILE.f in oracle? oracle version: 12.2.0.1
As you know, these are then unix processes for the  parallel servers in oracle:
ora_p000_ora12c
ora_p001_ora12c
....
ora_p???_ora12c

They can be seen also with the view: gv$px_process.
The spid for each parallel server can be obtained from there.
Then  I look for the open files associated with te parallel server here:
ls -l /proc/<spid>/fd

And I'm obtaining around 500-10000 file descriptors  for several parallel servers equal to this one:
991 -> /u01/app/oracle/admin/ora12c/dpdump/676185682F2D4EA0E0530100007FFF5E/ORA_DUMMY_FILE.f (deleted)

I've deleted them using:(actually I've create a small script for doing it because there are thousands of them)
gdb -p <spid>
    gdb> p close(<fd_id>)

But after some hours the file descriptors start being created again (hundreds every day)
If they are not deleted then eventually the linux limit is reached and any parallel query throws an error like this:
ORA-12801: error signaled in parallel query server P001
ORA-01116: error in opening database file 132
ORA-01110: data file 132: '/u02/oradata/ora12c/pdbname/tablespacenaname_ts_1.dbf'
ORA-27077: too many files open

Does anyone have any idea of how and why this file descriptors are being created, and how to avoid it?.
Edited: Added some more information that could be useful.
I've tested that when a new PDB is created a directory DATA_PUMP_DIR is created in it (select * from all_directories) that is pointing to:
/u01/app/oracle/admin/ora12c/dpdump/<xxxxxxxxxxxxx>

The linux directory is also created.
Also one file descriptor is created pointing to ORA_DUMMY_FILE.f in the new dpdump subdirectory like the ones described initially
lsof | grep "ORA_DUMMY_FILE.f (deleted)"

/u01/app/oracle/admin/ora12c/dpdump/<xxxxxxxxxxxxx>/ORA_DUMMY_FILE.f (deleted)

This may be ok, the problem I face is the continuos growing of the file descriptors pointing to ORA_DUMMY_FILE that reach the linux limits.


text:
Q: How to find Integration for a number of values in a column using array? 499183e+04   407257e+02   208773e+00      395     420
153463e+04   828733e+02   221093e+00      820     840
418161e+04   116941e+03   232724e+00      1160   1180
384500e+03   151044e+03   241853e+00      1500   1520
880331e+03   265567e+03   288564e+00      2645   2665
261537e+03   295819e+03   299508e+00      2945   2970
792049e+03   328865e+03   309009e+00      3275   3300
607461e+03   379468e+03   336309e+00      3780   3810
707934e+03   480620e+03   370690e+00      4790   4820

The above file is a text file that I am using.
I am trying to find the integration of a gausian function by reading columns using simpsons rule. Somewhere I am making a mistake and that's why I am not getting correct result.
The array's values (f[j] and g[j]) are not correct at the first place.
Any suggestions would be appreciated.`

#include <stdio.h>
#include<math.h>
#include <stdlib.h>
#define Max 9

      fclose(fptr);

    return 0;

}

A: As you mentioned, the values are incorrect after calculating the gaussian.  Your gaussian function itself looks correct, but I'm suspecting your input data is not.
Using the coefficients you have provided, then f[0] = a[0] * exp(-840510.774820);.  exp(-840510...) is a very small number (~6.4e-365030 according to Wolfram Alpha) which simply is too small to be represented by a 32-bit float (or 64-bit double for that matter), so it gets rounded down to 0.0.  This makes f[0] zero as well.
If the input data is actually what you want to calculate, then you will need to restructure your calculations so they can be calculated using the 32-bit floats you are using.  This could mean storing log(f) as an intermediate value instead of f directly, as a[0] * 840510.77 can most likely be represented in 32-bit float without problems.  But then you would need to modify the rest of the algorithm accordingly.
Another solution would be to use an arbitrary precision library to do your calculations.


text:
Q: Please explain the physics of a Cloud Chamber A friend of mine was telling me about building a cloud chamber while he was in graduate school.  As I understand it, this allows you to "see" interactions caused by high energy particles going through the cloud chamber.  This has fascinated me, and I would like to build one with my daughter, but I want to make sure I am able to explain it to her when the eventual questions come.  Can someone help me out please?  How would I explain a cloud chamber to someone who is a freshman in high school?

A: Feynman used to say - if you can't explain something in simple words, such that a child could understand, then you don't understand it either. So here's my take:
A cloud chamber is nothing more than a box where mist is about to form, but not quite yet. There's vapors of stuff (either alcohol, or water, or something else) in it, and the temperature is such that the vapors are almost about to produce mist (or "clouds"). Imagine wetlands or marshes on a cold autumn morning, it's kind of like that - fill a box with that kind of "cold wet air".
Now a charged particle (such as Alpha radiation from a chunk of radioactive ore) zips through the chamber at high speed. It bumps into water (or alcohol) molecules and ionizes them - it creates a trail of ionized molecules marking its path.
Now, the vapors are such that they really want to produce mist; any tiny disturbance is enough to push them over the edge. The trail of ionized molecules is enough to do that - the ions attract a bunch of molecules, the resulting clumps attract even more, and before you know it a droplet of water is formed, then another, and another. Voila, a trail of mist follows the particle.
I could try to describe the construction, but this Instructables page will do it much better:
http://www.instructables.com/id/Make-a-Cloud-Chamber-using-Peltier-Coolers/
Basically, you evaporate some alcohol and let it run over a very cold area (cooled by the Peltier elements). Like breath coming out of your mouth in the cold air of winter, the alcohol vapors will tend to produce mist, so some vapors will turn to mist anyway. But the process happens a lot faster when a charged particle zips through the chamber - so, if you place a tiny bit of radioactive material nearby, tiny white trails will seem to come from it and traverse the chamber, because mist tends to form that much better around the ionized trails left by the radiation in its wake.
More designs:
http://www.lns.cornell.edu/~adf4/cloud.html
http://www.nothinglabs.com/cloudchamber/
http://www.bizarrelabs.com/cloud.htm

A: The cloud chamber works by producing a super-saturated vapor, as explained by florin. When a charged particle passes by, it ionizes the molecules of the liquid, and these ions become centers for droplets, which condense around the ionization trail. But why are ions such good seeds for droplet condensation?
The reason is just electrostatic-dipole interaction, the cloud-chamber fluids are all dipoles. Choosing unit of energy eV, unit of length 1A, and unit of charge 1e, the Coulomb constant k is 14.4 (eV A/e). The dipole moment of water and alcohol (two common vapors for a cloud chamber) are both about .4 eV A.  That means that you have to go out a distance of 13 Angstroms before the thermal energy is comparable to the maximum dipole energy.
Within this region, the statistical equilibrium requires that the first dipole that enters sits on top of the ion, because the potential well is essentially infinitely deep. The ion plus polar molecule will attract another ion, and so on, until a droplet is formed.
Ignoring interaction between the dipoles, the radius of a droplet stabilizes electrostatically approximately when the energy gain from being on the surface of the droplet is equal to about 6kT, the factor of 6 is the approximate entropy gain of being in gas vs. liquid. This happens relatively quickly, so you get a microscopic droplet. But in a supersaturated liquid, there are strong forces already between dipoles which mean that there is very little cost to forming bigger drops. The energy gain just from the inter-molecular forces already balances the entropy loss from leaving the gas phase. The only thing that doesn't balance is the surface tension cost.
The radius of the drop is then approximately determined by the place where the average energy gain for a dipole on the surface is equal to the free energy difference between surface and bulk fluid. When this radius exceeds the critical droplet size for the supersaturated liquid, you get nucleation. Since it is going to be about 10 A, it is already pretty big. There is no chance of producing a 10A drop, containing hundred of molecules, by thermal fluctuations.