text:
Q: Service not registered: org.OpenUDID.OpenUDID_manager@2b038438 I have an application published in Google play and some time ago i received two error reports in my developer console which looks just like this:
java.lang.IllegalArgumentException: Service not registered: org.OpenUDID.OpenUDID_manager@2b038438
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:891)
at android.app.ContextImpl.unbindService(ContextImpl.java:921)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:352)
at org.OpenUDID.OpenUDID_manager.onServiceConnected(OpenUDID_manager.java:68)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)

and second:
java.lang.IllegalArgumentException: Service not registered: org.OpenUDID.OpenUDID_manager@40590d88
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:934)
at android.app.ContextImpl.unbindService(ContextImpl.java:952)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:352)
at org.OpenUDID.OpenUDID_manager.onServiceConnected(OpenUDID_manager.java:68)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1107)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1124)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4293)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

Can somebody explain me what is all this about? Non of the specified packages in stack trace are from my app.
Some of the libraries which i use are adcolony and appbooster. (I suppose that this libs might be the cause of problem).

A: Have a great new year 2014.if the answer is feasible than raise the answer and points :)
Hi i think i got the this problem please have a look.
Make sur you are using correct context.
one of these days
mService.unbindService(mConnection);

is obviously nonsense, calling unbind in the wrong context. It should be
unbindService(mConnection);

Additional mistake in the posted coding is the missing of
 @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()

        return false;
    }


text:
Q: Indicate minimum Blackberry version How can I indicate the minimum compiled version that I will allow my application to run on? Say OS 5.0 as minimum requirements.
I am using Java with the Eclipse tools.

A: As Remy says, the minimal supported OS version of your application is determined by the Blackberry SDK version you're using for development.
If you're planning to offer your application through Blackberry App World, the platform allows you to select the OS Version, carrier and even specific models that are allowed to download your product.

A: The minimum OS version is dictated by the version of the BlackBerry JRE that you compile with. If you have multiple JRE versions installed, you can select a particular version in the project's properties, in this case the 5.0 JRE.

A: Actually, the minimum OS version you can install your app is determined by the tag fileset in your .alx file. Example:
<fileset Java="1.54" _blackberryVersion="[4.5.0)">

The important info here is the Java attribute, the _blackberryVersion is only generated by newer plugin versions.
So you can compile a .cod file for let's say 5.0, and install it on 4.5 tweaking that element in the alx file. The alx is only used for BES and cable installs. You can also use JavaLoader and install the cod without caring about OS versions (no alx or jad file needed).
WARNING: The fact that you can install a "wrong" cod on a BlackBerry OS version it is not intended for doesn't mean you can run it without exceptions. If your app uses an API not present in your OS, it will crash.
Of course, the BB plugin generates the correct alx for the selected target OS, but you can bypass it by manually editing the alx if you wish. For OTA installs, the jad file doesn't contain any minimum version info AFAIK, but if it did, you could edit it as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails: wrong number of arguments (1 for 0) In my rails application I have this method in the job model that return the job of a company from job show page
  def same_company
    Job.approved.where(company: self.company).where.not(job: self.job)
  end

but this doesn't work and give me this error

wrong number of arguments (1 for 0)

Why I'm getting this error? and how can I resolve this
Update
This the error that I found in my log file
Rendered jobs/show.html.erb within layouts/application (352.9ms)
Completed 500 Internal Server Error in 1155ms

ActionView::Template::Error (wrong number of arguments (1 for 0)):
    154:

    155:

    156:

    157:             <% @job.same_company(6).each do |same_company_job| %>
    158:

    159:

    160:                     <%= link_to job_path(same_company_job), class: "_5q6s _8o _8t lfloat _ohe" do %>
  app/models/job.rb:65:in `same_company'
  app/views/jobs/show.html.erb:157:in `_app_views_jobs_show_html_erb__849384532_94102470'
  app/controllers/jobs_controller.rb:59:in `show'
  app/controllers/application_controller.rb:61:in `user_time_zone'

This is my job model
 #company
    belongs_to :company

  #User
  belongs_to :user

  def same_company
    Job.approved.where(company: self.company).where.not(job: self.job)
  end

A: Yes, fix is :
<% @job.same_company[0...6].each do |same_company_job| %>

As per the method definition same_company, it don't accept any argument, but you are sending same_company(6). I think you want first 6 rows, so  the above code is what you need.


text:
Q: How to display an aggregation of an object that is connected to another object? I've set up these 2 objects:

*

*Book

*Author
A book has an author field.
I have one action:

*

*Read
I have 2 aggregations:

*

*Recently read books

*Favorite authors

The Favorite authors aggregation is set up to show author objects on the read action.
I posted a story to my Timeline: Felipe read "some book", but it only shows the Recently read books aggregation and not the Favorite authors.
How am I suppose to set up the aggregation for Favorite authors?

A: If the aggregation is setup correctly (you can test this by adding sample objects and actions in the aggregation configuration) then it will show up when there is enough data to build the aggregation.
As not all aggregations show on Timeline for all people, you can see how it appears for you by looking at your app timeline view. You can find this at https://www.facebook.com/YOUR_USERNAME/app_YOUR_APP_NAMESPACE


text:
Q: How to get total amount after applying coupon in Stripe payment gateway I'm using stripe to process payments in my app.
I have created a plan and I have some coupons.
I am creating a subscription using following code.
customer.subscriptions.create(plan=PLAN_type,coupon=PROMO_CODE)
but I want to know the amount the customer going to charged if he appy coupon, so that I can display it to him on a webpage.
I am able get the amount of a plan and discount offered by a coupon. But now I want the total amount after applying the coupon.
I can do this by manually applying discount to the amount , but I want to know is there a way from API to do this

A: I don't think there would be a way to know the amount your customer is going to be charged upfront. If you want to display this to your customer before creating the subscription you have to calculate this on your end.
If you just want to confirm the total charged after the subscription has been created, you would retrieve the invoices for that customer with the List Customer Invoices API.
The invoice you're looking for should be the first one since it was the latest created, but to be safe you should check the corresponding subscription to make sure it corresponds to the subscription you just created. You would then be able to retrieve the total from that invoice to know how much you charged your customer.


text:
Q: Python decorator to automatically define __init__ variables I've got fed up of continually typing the same, repetitive commands over and over again in my __init__ function. I was wondering if I could write a decorator to do the work for me. Here's an example of my question:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

Is there some way in which I can automatically have all arguments passed into the function become instance variables with the same names? For example:
class Point:
    @instance_variables
    def __init__(self, x, y):
        pass

Where @instance_variables would automatically set self.x = x and self.y = y. How could I do this?
Thanks!
EDIT: I should mention that I use CPython 2.7.

A: Here is my first try at the decorator:
[EDIT second try: I added handling defaults for variables and checking for valid keywords. Thanks ivan_pozdeev ]
[EDIT 3: Added check for defaults is not None]
def instanceVariables(func):
    def returnFunc(*args, **kwargs):
        selfVar = args[0]

        argSpec = inspect.getargspec(func)
        argumentNames = argSpec[0][1:]
        defaults = argSpec[3]
        if defaults is not None:
            defaultArgDict = dict(zip(reversed(argumentNames), reversed(defaults)))
            selfVar.__dict__.update(defaultArgDict)

        argDict = dict(zip(argumentNames, args[1:]))
        selfVar.__dict__.update(argDict)

        validKeywords = set(kwargs) & set(argumentNames)
        kwargDict = {k: kwargs[k] for k in validKeywords}
        selfVar.__dict__.update(kwargDict)

        func(*args, **kwargs)

    return returnFunc

Here is a example:
class Test():

    @instanceVariables
    def __init__(self, x, y=100, z=200):
        pass

    def printStr(self):
        print(self.x, self.y, self.z)

a = Test(1, z=2)

a.printStr()

>>> 1 100 2

A: For those who might find this post, but are interested in a Python 3.7+ solution (and as Python 2 End Of Life is the Jan 1, 2020 ;-), you can use the Python standard lib dataclasses.
from dataclasses import dataclass

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

Will add, among other things, a __init__() that looks like:
def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

A: You could do this:
def __init__(self, x, y):
    self.__dict__.update(locals())
    del self.self   # redundant (and a circular reference)

But this is probably not a real improvement, readability-wise.

A: I disagree that this is useful. I find that forcing developers (including myself) to type out the painful boilerplate of member variable initiation is a good way to deter people from having __init__ methods that accept a ridiculous number of arguments, which are turned into a ridiculous number of member variables.
This happens a lot when someone wants to extend the features available in a class through the use of extra arguments, feature flags, and boolean switch variables that control customized instantiation. I consider all of those to be deficient ways to handle the need for accommodating new or optional extended complexity.
Being required to type out this particular kind of boilerplate is like a tax on class bloatedness. If you find yourself accepting so many args in __init__ that you need this feature, it's usually a good indicator that you should refactor your design with smaller, compartmentalized classes, maybe a MixIn design.
Nonetheless, here is one way to do it without the misdirection of the decorator. I didn't make an attempt to handle *args but then again in this particular case you would have to define special logic for what unnamed positional arguments meant anyway.
def init_from_map(obj, map):
    for k,v in map.iteritems():
        if k not in ["self", "kwargs"]:
            setattr(obj, k, v)
        elif k == "kwargs":
            for kk, vv in v.iteritems():
                setattr(obj, kk, vv)

class Foo(object):
    def __init__(self, x, y, **kwargs):
        init_from_map(self, locals())

f = Foo(1, 2, z=3)
print f.x, f.y, f.z
print f.__dict__

Prints:
1 2 3
{'x': 1, 'y': 2, 'z': 3}

A: You can either use reflection to reduce code duplication
self.__dict__.update(v,locals()[v] for v in 'x','y')

(or almost equivalent (v must not be a meta-variable name))
for v in 'x','y': setattr(self,v,locals()[v])

Or use CPython's implementation details to retrieve argument names from runtime as per Getting method parameter names in python
cur_fr = sys._getframe().f_code
self.__dict__.update(v,locals()[v] for v in cur_fr.co_varnames[1:cur_fr.co_argcount])  # cur_fr.f_locals is the same as locals()

The 2nd approach appears more "automated" but, as I've said, it turns out to be rather inflexible. If your argument list is longer than 3-4, you probably only need to handle some of the arguments this way, in which case, you have no other options but to construct their list by hand.

A: For Python 3.3+:
from functools import wraps
from inspect import Parameter, signature

def instance_variables(f):
    sig = signature(f)
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        values = sig.bind(self, *args, **kwargs)
        for k, p in sig.parameters.items():
            if k != 'self':
                if k in values.arguments:
                    val = values.arguments[k]
                    if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
                        setattr(self, k, val)
                    elif p.kind == Parameter.VAR_KEYWORD:
                        for k, v in values.arguments[k].items():
                            setattr(self, k, v)
                else:
                    setattr(self, k, p.default)
    return wrapper

class Point(object):
    @instance_variables
    def __init__(self, x, y, z=1, *, m='meh', **kwargs):
        pass

Demo:
>>> p = Point('foo', 'bar', r=100, u=200)
>>> p.x, p.y, p.z, p.m, p.r, p.u
('foo', 'bar', 1, 'meh', 100, 200)

A non-decorator approach for both Python 2 and 3 using frames:
import inspect

def populate_self(self):
    frame = inspect.getouterframes(inspect.currentframe())[1][0]
    for k, v in frame.f_locals.items():
        if k != 'self':
            setattr(self, k, v)

class Point(object):
    def __init__(self, x, y):
        populate_self(self)

Demo:
>>> p = Point('foo', 'bar')
>>> p.x
'foo'
>>> p.y
'bar'

A: I am searching for an autoinit decorator and come across this thread.
I couldn't find any @autoinit in the web that handles variable arguments, variable keywords and the keyword-only arguments.  Inspired by the other solutions, I wrote my own version that support everything.
I did some testing, it seems to work fine in all scenarios, but I haven't exhaustively test the code.  Let me know if it has a bug.   Thanks.
def autoinit(func):
"""
This decorator function auto initialize class variables from __init__() arguments
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
    if func.__name__ != '__init__':
        return func(*args, **kwargs)

    self = args[0]
    func_spec = inspect.getfullargspec(func)

    # initialize default values
    nargs = dict()
    if func_spec.kwonlydefaults is not None:
        for k,v in func_spec.kwonlydefaults.items():
            nargs[k] = v
    if func_spec.defaults is not None:
        for k,v in zip(reversed(func_spec.args), reversed(func_spec.defaults)):
            nargs[k] = v
    if func_spec.varargs is not None:
        nargs[func_spec.varargs] = []
    if func_spec.varkw is not None:
        nargs[func_spec.varkw] = {}
    # fill in positional arguments
    for index, v in enumerate(args[1:]):
        if index+1 < len(func_spec.args):
            nargs[func_spec.args[index+1]] = v
        elif func_spec.varargs is not None:
            # variable argument
            nargs[func_spec.varargs].append(v)
    # fill in keyword arguments
    for k,v in kwargs.items():
        if k in itertools.chain(func_spec.args, func_spec.kwonlyargs):
            nargs[k] = v
        elif func_spec.varkw is not None:
            # variable keywords
            nargs[func_spec.varkw][k] = v

    # set values to instance attributes
    for k,v in nargs.items():
        setattr(self, k, v)
    return func(*args, **kwargs)
return wrapper


text:
Q: Explanation of function from Gleez project Gleez project written in Kohana framework I am using it to learn.
I have some questions about how works the following code.
It is used to generate tree from given information and then recursive function is using this generated tree to create the structure.
I give a query result $tree to a function which contains
parent id = pid
The loop runs through each item checking if pid is set (using isset) and if so then adds empty array $d['children'] to the current item. Reference is used to change item's value in foreach loop.

*

*My question is why reference is used, because even if isset is false empty array $d['children'] is added? I guess i just don't understand the use of this function.
2.why my simplifyed function without reference still does add $item['children'] where pid = Null
private function generate_tree($tree)
{
$menu = array();
$ref  = array();

foreach($tree as $d)
{
    $d['children'] = array();

    if(isset($ref[$d['plid']]))
    {
        // we have a reference on its parent
        $ref[ $d['plid'] ]['children'][ $d['mlid'] ] = $d;
        $ref[ $d['mlid'] ] =& $ref[ $d['plid'] ]['children'][ $d['mlid'] ];
    }
    else
    {
        // we don't have a reference on its parent => put it a root level
                    $menu[$d['mlid']] = $d;
        $ref[$d['mlid']] =& $menu[$d['mlid']]; // both pointing to the mlid
    }
}

return $menu;

}
I simplifyed the function to just add $item['children']; to result $tree if parent id is set.
I give generate_tree function these parameters.
    array(4){
         [0]=> array(2)
             {
             ["id"]=> string(1) "2"
             ["pid"]=> NULL
             }
         [1]=> array(2)
             {
             ["id"]=> string(1) "3"
             ["pid"]=> NULL
             }
         [2]=> array(2)
             {
             ["id"]=> string(1) "6"
             ["pid"]=> string(1) "2"
             }
         [3]=> array(2)
             {
             ["id"]=> string(1) "8"
             ["pid"]=> string(1) "3"
             }
    }

    private function generate_tree($menu) {

    $tree = array();

    foreach ($menu as $item) {

        $item['children'] = array();

        if (isset($tree[$item['pid']])){
            $tree[$item['pid']['children']] = $item;
        }
        else{

            $tree[$item['pid']] = $item;
        }
    }
    return $tree;
}

the output of $tree. As you can see ["pid"]=> Null, but still $item['children'] was added.
    array(3) {
        [""]=> array(3)
             {
             ["id"]=> string(1) "3"
             ["pid"]=> NULL
             ["children"]=> array(0) { }
             }
        [2]=> array(3)
            {
            ["id"]=> string(1) "6"
            ["pid"]=> string(1) "2"
            ["children"]=> array(0) { }
            }
        [3]=> array(3)
        {
        ["id"]=> string(1) "8"
        ["pid"]=> string(1) "3"
        ["children"]=> array(0) { }
        }
    }

Thank you in advance!

A: When you perform operations by reference you are using same variable, anything you do to it will be parsed to any other referenced variable.
When you do not perform operations by reference you are creating a copy of the variable and anything you do to the copy will not be parsed to any other copied variables.
Then why is the code wrote this way? It's done like this so the programmer doesn't have to worry about updating the array all the way down the tree when a match is found.


text:
Q: File Translator to Export Animated 3D Character from Autodesk Maya as Quake MD2 I'm wondering if anyone knows of a way to export geometry/textures for a rigged, animated character as Quake MD2? I'm developing an app for mobile devices, and I've found that MD2 works great for lightweight OpenGL rendering. I have several animated characters, and I'd like to export them as MD2 from Maya. Here are some of the things I have tried:

*

*Exporting FBX to 3D Studio Max and using the QTip plugin
-- this works, but only if I convert my animation to point cache (pc2) and bring that into Max. When I do that, QTip plugin doesn't honor the point cache node, and all I get is the model, no animation

*Exporting OBJ Sequence to Blender, exporting MD2 from there
-- I can't seem to get blender to compile the imported obj sequence into a single animated object

*Exporting FBX to Milkshape
-- the maya rig gets corrupted in the process

*Bake point cache for animation, export to FBX, import to Milkshape
-- again, Milkshape doesn't honor the geometry cache, so all that appears is a static character.

I'm currently writing a plugin for Maya using the blender MD2 export script as reference (but re-writing using the C++ Maya API), but I'm just wondering if anyone has done this before or has any suggestions of how to do this.
Also, if anyone has other suggestions for the best format to render a single animated character on an OpenGL ES (Android or iPhone) device, I would be very grateful! I'm open to trying anything to get these animations rendering on device
Thanks!

A: If anyone is interested, I ended up solving this problem by just writing my own plugin for the Maya API that exports Quake MD2 files. I've released it as open source on github:
http://github.com/arifken/MD2Export


text:
Q: Add display property to accordion onload depending on resolution I'm using the W3C accordion on my website, and only want the accordion to be active when the page is under 768px. So far, I have the script adjusted so that the "panel" div's will toggle, but they initially are displayed, rather than hidden. Is there a line I can add to the code to initially hide the panel div's when the resolution is under 768px? I've tried adding display:none to the element in the css sheet, but the toggle script won't override it.
Hope this makes sense!

A: I have a feeling you can manage this in CSS..
@media only screen and (max-width: 768px) {
    .filterAccordion {
        display: none;
    }
}

As for the accordian and mentioned by Quentin.. W3Schools is probably not the best source of information.. For general modules like this perhaps Bootstrap(3/4) might be a more ideal framework if you are open to use one at all.
Edit : MediaQueries

A: Here's a working solution. Please note that I have commented out some code to demonstrate it in desktop view. Please uncomment that and your code should work in "mobile only" scenario.

document.querySelector('.accordion').addEventListener('click', function (e) {
  /*if (screen.width < 768) {*/
  var currentTarget = e.target;
  if (e.target.classList.contains('accordion-title')) {
    var allDesc = Array.prototype.slice.call(document.querySelectorAll('.accordion-description'));
    allDesc.forEach(function (el) {
      el.classList.add('hidden-xs');
    });
    e.target.nextElementSibling.classList.remove('hidden-xs');
  }
  /*}*/
});
/*@media only screen and (max-width: 767px) {
  .hidden-xs {
    display: none;
  }
}*/

/* Comment below code and uncomment above */

/* For demo purpose only */
.hidden-xs {
  display: none;
}

.accordion-title,
.accordion-description {
  padding: 20px;
  margin-bottom: 10px;
}

.accordion-title {
  background-color: #ccc;
  border-radius: 3px;
  border: 1px solid;
}

Title 1

Some description

Title 2

Some description


text:
Q: SQL Server XML field - using TSQL variable as XML node sequence indicator Why does this work?
SELECT
  XDocument
    .value('(/Book/Chapter[@verse="allo"])[2]',
      nvarchar(max)')
FROM XBiblos
WHERE Version = 666

But WHY does this not work? Where the only diff is that [2] is replaced by [sql:variable("@i")]
Which results in error msg
'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'
DECLARE @i int;
SET @i = 2;

SELECT
  XDocument
    .value('(/Book/Chapter[@verse="allo"])[sql:variable("@i")]',
      nvarchar(max)')
FROM XBiblos
WHERE Version = 666

Doc structure example ...
<XDocument name="DraXQueLah">
  <Book name="Worldymort">
    <Chapter verse="Forgot">Forgot so loved the world</Chapter >
    <Chapter verse="Icecream">That we were eternally creamed</Chapter >
    <Chapter verse="blah">blah blah</Chapter >
    <Chapter verse="blah">blah blah</Chapter >
    <Chapter verse="blah">blah blah</Chapter >
    <Chapter verse="blah blah">blah blah blah</Chapter >
  </Book>
</XDocument>

A: Just add [1] to enforce a singleton. The engine knows, that [2] (which is the position), will - for sure! - have only one (or none) result. But the engine is not able to predict, that your expression will result in one single result:
DECLARE @i int;
SET @i = 2;

SELECT
  XDocument
    .value('(/Book/Chapter[@verse="allo"])[sql:variable("@i")][1]', --<--Here
      nvarchar(max)')
FROM XBiblos
WHERE Version = 666


text:
Q: It is possible to render a mobius strip with a raytracer? In my raytracer all surfaces are centered at the origin and oriented on Y axis.
Displacement, rotations and resizing are obtained through transformation matrix applied on rays.
I recently rendered a torus in my ray-tracing using its Cartesian equation:

(x^2 + y^2 + z^2)^2 - 2 * (r1^2 + r2^2) * (x^2 + y^2 + z^2) + 4 * r1^2 * y^2 + (r1^2 - r2^2)^2

to which I replaced every point with the ray equation:

ex: X = Ray.ori.x + T * Ray.dir.x;

With the ray components replaced in the equation, I got the 5 coefficients of my quartic function which can be used to find the equation roots (the T intersections) with a 4th degree polynomial solver algorithm.
I was wondering if a mobius strip can be rendered the same way.
My research did not bring up much, I found some Raytracing codes using cubic equations but copying the 4 coefficients led me to incomprehensible forms and artifacts.
Could you help me to render it? Also advice to render it with another method is welcome.
Thanks!

A: Yes it is possible to render a mobius strip with a raytracer.

A: I took the (Cartesian) cubic equation of the mobius from: mathworld
then I replaced the x,y and z of mobius with the ray equation.
However the result is this one:

Here is the code to calculate the mobius coefficients.
double x = ray.ori.x;
double y = ray.ori.y;
double z = ray.ori.z;
double i = ray.dir.x;
double j = ray.dir.y;
double k = ray.dir.z;
double c[4];
double R = 1.;
int solutions;

c[3] = (i * i) * j - 2. * (i * i) * k + (j * j * j) - 2. * (j * j) * k + j * (k * k);
c[2] = (i * i) * y - 2. * (i * i) * z + 2 * i * j * x - 2. * i * k * R - 4. * i * k * x + 3. * (j * j) * y - 2. * (j * j) * z - 4. * j * k * y + 2. * j * k * z + (k * k) * y;
c[1] = - 2. * i * R * z + 2 * i * x * y - 4. * i * x * z - j * (R * R) + j * (x * x) + 3. * j * (y * y) - 4. * j * y * z + j * (z * z) - 2. * k * R * x - 2 * k * (x * x) - 2. * k * (y * y) + 2. * k * y * z;
c[0] = - (R * R) * y - 2. * R * x * z + (x * x) * y - 2. * (x * x) * z + (y * y * y) - 2. * (y * y) * z + y * (z * z);

Maybe I'm rendering the entire surface that extends to infinity?
How to get the mobius strip in this case?

A: Your last post is right. You are indeed rendering the good 3d shape.
To get your Möbius strip, you only need to select the right portion.
You may want to add up in a 3d grapher tool your cartesian equation with the parametric one that you can found on Wikipedia.
You will then see where it is ;)
(It's center is the origin and has a radius of 1.5)


text:
Q: Looking for 90's Action Movie with Robotic antagonist I remember this movie being on HBO or Showtime and from what little I remember, a bunch of bad guys were led by a cyborg-like villain with vision similar to the T800 and one of the bad guys was killed by a female protagonist by being electrocuted when she pulled on the switch to the cable he grabbed after falling in water.
The last scene involved the heroes leaving via helicopter and the main villain being stomped on after attempting to grab the rope ladder by the main protagonist, this causing him to lose his grip and subsequently fall to his death while the main hero says the line, "Ladies and gentlemen.... Elvis has left the building!!!!!" Anyone have a clue to what this movie is?

A: Sci-fi thriller Night Siege (AKA Shadowchaser 2 AKA Armed and Deadly AKA etc. etc., it has lots of names) from 1994.

Terrorists led by an android take over a nuclear plant and threaten to launch a missile at Washington. While the authorities desperately attempt to negotiate, the terrorists persue their real goal. A plant worker, her son and a tough-guy repair man have other ideas, and attempt to stop the terrorists from inside the plant.

The guy electrocuted, the Terminator-like villain's helicopter death after  falling off the rope ladder, Elvis Leaving the Building, it's all there. Here's the trailer:


text:
Q: sql server how to distinct data from multiple column but not all column I have a problem, I need to show unique data from some table, sql server based,  ihave the query but I have a error if not all column I select is not contain in the GROUP BY.
Table source:
+------+------+----------+-------+
| code | name | process  | time  |
+------+------+----------+-------+
| a    | qq   | write    | 10:10 |
| b    | qq   | read     | 11:10 |
| c    | qq   | read     | 12:11 |
| a    | qq   | write    | 09:40 |
| b    | yy   | write    | 08:50 |
| a    | yy   | read     | 11:10 |
| b    | yy   | write    | 09:40 |
+------+------+----------+-------+

Table I need:
+------+------+----------+-------+
| code | name | process  | time  |
+------+------+----------+-------+
| a    | qq   | write    | 10:10 |
| b    | qq   | read     | 11:10 |
| b    | yy   | write    | 09:40 |
| c    | qq   | read     | 12:11 |
| a    | yy   | read     | 11:10 |
+------+------+----------+-------+

Code I use:
select code, name, process, time
from tablesource
group by code, name, process;

But this query result in error:

[42000] [Microsoft][SQL Server Native Client 10.0][SQL Server]Column
  'time' is invalid in the select list because it is not contained in
  either an aggregate function or the GROUP BY clause. (8120),

But if  column time I insert in group by, the result is just same as the table source. Please help me.

A: You need to modify query to add aggregate function for time.
select code, name, process, max(time) from tablesource
group by code, name, process;


text:
Q: How to set the input shape of keras LSTM I often hit the proglem as
ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [10 ,3]
I googled around  and found out that
LSTM layer expects inputs to have shape of (batch_size, timesteps, input_dim)
OK, but honestly I am still confused a bit.
So for example,I have training data like this
x_train (100,3) #it consists of like `[[1,2,3],[3,4,5],[5,6,7]]`
y_train (100,3) #answers

I want to use 10 set of 3 pair of numbers and predict next 3pair ex [7,8,9].
like guessing from x_train[1~10] to y_train[11]`
The code below works but , I am still not clear
At the place input_shape=(3,1) What the meaning of 1??. it should be 3 (the dimension I want to get finally)
And batch_size is the first argument of LSTM requests.
So,,,when I want to predict one from past 10 items, is it correct to set here 10???
x_train = np.array(x).reshape(100, 3,1)
y_train = np.array(x).reshape(100, 3,1)

model.add(LSTM(512, activation=None, input_shape=(3, 1), return_sequences=True))

model.add(Dense(1, activation="linear"))

opt = Adam(lr=0.001)

model.compile(loss='mse', optimizer=opt)
model.summary()
history = model.fit(x_train, y_train, epochs=epoch, batch_size=10) // how to set batch size???

A: Try this code:
import tensorflow as tf
import numpy as np
x = np.random.uniform(0, 10, [101, 3])

x_train = np.array(x[:-1]).reshape(-1, 5, 3) # your data comprise of 20 sequences
y_train = np.array(x[1:]).reshape(-1, 5, 3)

model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(512, activation=None, input_shape=(None, 3), return_sequences=True))

model.add(tf.keras.layers.Dense(1, activation="linear"))

opt = tf.keras.optimizers.Adam(lr=0.001)

model.compile(loss='mse', optimizer=opt)
model.summary()
history = model.fit(x_train, y_train, epochs=10, batch_size=10) # here you can set a batch size (your 20 sequences will be splitted into two batches)


text:
Q: Javascript alternative to document.write not innerHTML I modified a little js script which compares a date to today and calculates the difference. (I'm a novice)
However, it uses document.write, which I've been told is bad.
I don't know why it's bad, people just say it's bad and never explain why.
Anyway, I'm looking for an alternative. innerHTML doesn't seem to work, and other questions answered on this site just point to DOM manipulation references without really answering the question.
Here's my script:
    //Set the two dates
    var iquit =new Date(2013, 1, 15);
    today=new Date();
    //Get 1 day in milliseconds
    var one_day=1000*60*60*24;
    var day_numeric=Math.ceil((today.getTime()-iquit.getTime())/(one_day));
    //Calculate difference btw the two dates, and convert to days
    document.write("
"+day_numeric+
            " days have gone by since you quit smoking!
"+
            "
You have saved "+ day_numeric*7+" pounds
");

If anyone can tell me a better way to write this, it'd be amazing.

A: The problem with document.write() is that if you call it after the DOM is ready, it will overwrite the existing DOM. This SO answer has a more extensive explanation to why document.write() rarely is the best choice.
Using .innerHTML should work fine, but you need to select the element you want to add the content do. So something like this:
document.getElementById("idOfSomeElement").innerHTML = "your content";

Live example
What method to use to get the proper element depends on what you have to select on, but if possible, the easiest way is probably to attach an ID to the element you want to add content to, and use the above method.

A: If you're using pure JavaScript, one of best ways to get this may be:
var paragraph1 = document.createElement("p");
paragraph1.appendChild(document.createTextNode(day_numeric+" days have gone by since you quit smoking!"));

var paragraph2 = document.createElement("p");
paragraph1.appendChild(document.createTextNode("You have saved "+ day_numeric*7+" pounds"));

document.body.appendChild(paragraph1);
document.body.appendChild(paragraph2);

100% standard DOM.
About document.write: good or evil...
I guess some consider document.write as a bad practice because it's the lower-level way of output raw content to the (X)HTML document.
Since (X)HTML is basically a dialect of XML (or at least, based on XML and SGML), the right and expected way of writing a document is creating nodes and appending them to the whole document.
document.write writes the content after the last written element and you lose a lot of control when you want to decide where to place the newly-created element in the document.
For example, would you output a paragraph from a JavaScript function loaded in the from the  element? It would be hard as it'll not be rendered in the body necessarily. That's too bad.
It's better to create DOM elements/nodes and append them to the document using appendChild(...).

A: Check this link for reasons why it is considered bad practice: Why is document.write considered a "bad practice"?
And how are you using innerHTML?
Have you tryed something like

This requires an element with the container-id id somewhere in the page, like:


text:
Q: hive indexes error on partitioned table I was trying to test an example of hive indexes. I am not able to create indexes on a partitioned column but works on all other columns. Most of the sites gave examples on partitioned column but for some reason I am not able to get it worked. I am using hive 14 and the example was taken from Programming in hive. Can some one let me know if something is wrong in the below code?
CREATE TABLE employees (
name STRING,
salary FLOAT,
subordinates ARRAY<STRING>,
deductions MAP<STRING, FLOAT>,
address STRUCT<street:STRING, city:STRING, state:STRING, zip:INT>
)
PARTITIONED BY (country STRING, state STRING);

CREATE INDEX employees_index
ON TABLE employees (country)
AS 'org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler'
WITH DEFERRED REBUILD
IDXPROPERTIES ('creator = 'me', 'created_at' = 'some_time')
IN TABLE employees_index_table
PARTITIONED BY (country, name)
COMMENT 'Employees indexed by country and name.';

Error :
FAILED: ParseException line 7:0 missing EOF at 'PARTITIONED' near 'employees_index_table'
org.apache.hadoop.hive.ql.parse.ParseException: line 7:0 missing EOF at 'PARTITIONED' near 'employees_index_table'


text:
Q: Named multi_match query I need a hand here. I have a cross_fields multi_match query and I need to use named queries for each field. I can rewrite it into a bool/should match but then I dont know how to reproduce the cross_fields condition. Any idea? Thanks!
Multimatch query: Relevance OK, but no named queries
GET test_index/_search
{
  "query": {
    "multi_match": {
      "query": "example_query",
      "fields": ["name","lastname"],
      "type": "cross_fields"
    }
  }
}

Bool query: Named queries OK but bad relevance
GET test_index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": {
              "query": "example query",
              "_name": "name_match"
            }
          }
        },
        {
          "match": {
            "latname": {
              "query": "example query",
              "_name": "latname_match"
            }
          }
        }
      ]
    }
  }
}

A: How does using dismax with tie_breaker: 1.0 work for your ES index?
Something like this:
GET vehicle/_search
{
  "query": {
    "dis_max": {
      "tie_breaker": 1.0,
      "queries": [
        {
          "match": {
            "make": {
              "query": "Lamborghini",
              "_name": "make"
            }
          }
        },
        {
          "match": {
            "model": {
              "query": "Diablo",
              "_name": "model"
            }
          }
        }
      ]
    }
  }
}

The Dismax query is very similar to the multi_match query in that it compares scores across sub clauses/queries. The tie_breaker parameter controls how much losing/non-max fields contributed to the final summation of clause scores, any losing fields scores are multiplied by the tie_breaker. The default tie_breaker: 0.0, which is most similar to type: best_fields in multi_match.


text:
Q: How to create form_tag for sign up form which will save form data in two different tables in rails As it is basic question but I am confused as I have to create one sign up form which will have to save data in two different tables like
1) salon 2) users
I have salons data like business name adress url these all fields should save in salon table
and email and password and adress should save in users table.
how to do this in good way
my view source code is something like this
<%= form_tag users_path(@users), :method => :post do |f| %>

<%= devise_error_messages! %>

<%=  label_tag :business_name %>

  <%= text_field_tag :business_name %></div

<%=  label_tag :website_url %>

  https://<%= text_field_tag :website %>

<%=  label_tag :business_adress %>

  <%= text_field_tag :business_adress %>

<%=  label_tag :owners_name %>

  <%= text_field_tag :name %>

<%=  label_tag :phone_number %>

  <%= text_field_tag :phone_number %>

<%=  label_tag :email %>

  <%= email_field_tag :email %>

<%= label_tag :password %>

  <%= password_field_tag :password %>

<%= label_tag :password_confirmation %>

  <%= password_field_tag :password_confirmation %>

<%= submit_tag "Sign up" %>

<% end %>

Also I want to know how controller side code would be managed and saved the fields data in different table

A: In controller Users_controller will be look like this:-
rails 4 with strong parameters
class UsersController < ApplicationController
 def create
   @user = User.create!(user_params)
   @user.salons.create!(salon_params)
 end

private
 def user_params
    params.require(:user).permit!(:name,:phone,:email, :password) #permit those parameters which you required
 end
 def salon_params
   params.permit!(:business_name, :website, :business_adress)
 end
end

In Model
class User < ActiveRecord::Base
     has_many :salons
  end

Thanks Hope it will be helpfull

A: First you need to create association between the two models, check this link to know about rails associations.
Once you created association between the models, checkout this link to know about nested attributes, which allow you to save attributes on associated records through the parent.
Example,

class User < ActiveRecord::Base
  has_many :salons, :dependent =>:destroy

  accepts_nested_attributes_for :salons

end
class Salon < ActiveRecord::Base
belongs_to :user
end

then in your UserController's new action you need to build salon like this,

@user = User.new
@user.salons.build

then in your user form you can get value for salon from user like this

<%= form_for @user do |f| %>
  ...

  <%= f.fields_for :salons do |builder| %>
    <%= f.text_field :business_name %>
    ...
  <% end %>
  <%= f.submit "Submit" %>
<% end %>

A: Assuming you are using devise as authentication solution, and you already have the relationship between them set up, you might want to have a look at this question to which the accepted answer essentially is:

*

*run rails generate devise:views inside your rails app's directory to extract the devise signup form and insert your form with the modifications below into it.

*modify the extracted form (app/views/devise/registrations/new.html.erb) to create an empty salon beforehand (resource.build_salon)

*instead of placing your salon model's form fields inside the main surrounding form_for block create a nested block using fields_for :salon do |s|

*and place all form fields which belong to your salon model into that block so it ends up looking like this
<%= form_tag users_path(@users), :method => :post do |f| %>

<%= devise_error_messages! %>

 <%= f.fields_for :salon do |s| %>

<%= s.label :business_name %>

   <%= s.text_field :business_name %></div

<%= s.label :website_url %>

   https://<%= s.text_field :website %>

 <% end %>

<%=  label_tag :email %>

 <%= email_field_tag :email %>

<%= label_tag :password %>

 <%= password_field_tag :password %>

<%= label_tag :password_confirmation %>

 <%= password_field_tag :password_confirmation %>

<%= submit_tag "Sign up" %>

<% end %>

Hope this helps


text:
Q: How to save an array of strings with SharedPreferences? I have an array of Strings, I need to save this array with SharedPreferences, and then read and display them on a ListView.
For now, I use this algorithm:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

//To save the strings
public void saveStrings(String[] str){
    int a = 0;
    int lenght = str.length;
    while (a<lenght){
        sp.edit().putString(Integer.toString(a), Integer.toString(str[a])).apply();
        a=a+1;
    }
}

//To read the strings
public String[] getStrings(){
    String[] str = new String [8];
    int a = 0;
    int lenght = 8; //To read 8 strings
    while (a<lenght){
        str[a] = sp.getString(Integer.toString(a),"Null");
        a=a+1;
    }
return str;
}

Is there a way to save and read the entire array, rather than a string at a time?
For this project I'm using API level 19 (Android 4.4.2 KitKat)

A: Well, you could use putStringSet(), but (a) it's only from API level 11 onwards, and (b) as its name says, it's for sets (which means that you will lose the original ordering and any duplicates present in the array).
We solved this problem by "encoding" collections into a string and using putString() and decoding them afterwards on getString(), with this pair of methods (for ArrayList, but should be easily convertible into array versions):
public String encodeStringList(List<String> list, char separator)
{
    StringBuilder sb = new StringBuilder(list.size() * 50);

    for (String item : list)
    {
        if (sb.length() != 0)
            sb.append(separator);

        // Escape the separator character.
        sb.append(item.replace(Character.toString(separator), "\\" + separator));
    }

    return sb.toString();
}

public List<String> decodeStringList(String encoded, char separator)
{
    ArrayList<String> items = new ArrayList<String>();

    if (encoded != null && encoded.length() != 0)
    {
        // Use negative look-behind with backslash, because it's used for escaping the separator.
        // Expression is "(?<!\)s" with doubling because of escaping in regex, and again because of escaping in Java).
        String splitter = "(?<!\\\\)" + separator; //$NON-NLS-1$
        String[] parts = encoded.split(splitter);

        // While converting to list, take out the escape characters used to escape the now-removed separator.
        for (int i = 0; i < parts.length; i++)
            items.add(parts[i].replace("\\" + separator, Character.toString(separator)));
    }

    return items;
}

A: Set<String> set =list.getStringSet("key", null);
Set<String> set = new HashSet<String>();
set.addAll(list of the string list u have);
editor.putStringSet("key", set);
editor.commit();
Please refer to this thread for further details Save ArrayList to SharedPreferences

A: //while storing
str is string array
String fin="";
for(i=0;i<n;i++){
    fin=fin+str[i]+",";
}
fin=fin.substring(0,fin.length()-1);

//while retrieving
List<String> items = Arrays.asList(fin.split("\\s*,\\s*"));


text:
Q: Avoiding well-definition of a morphism Let's take in account for example the groups case (but we should take any other algebraic structure which admits quotient). Let's take $H,H'$ (additive) groups. Let's suppose the first one is a quotient $H=G/K$, for some $G$ group and $K\lhd G$ be some normal subgroup of $G$.
Our problem is, given $\phi:H\to H'$, to show that it is a group isomorphism.
My first thought is to show that $\phi$ is well defined, that is, it does NOT depend on the representative (i.e. if $g_1,g_2$ are two distinct element of $G$ such that $h_1=h_2$ where $h_1:=g_1+K$ and $h_2:=g_2+K$ then $\phi(h_1)=\phi(h_2)$).
This situation is not always simple to treat.
So we can take another path: searching some $\xi:H'\to H$ and showing that it is a group isomorphism which inverts $\phi$. Dealing with $\xi$ we wouldn't have no more problem with good definition and maybe this latter question could be simpler to solve (even I suspect that the problem of good definition of $\phi$ will turn -in some way- into injectivity of $\xi$).
My question is the following: am I right? Can I avoid the problem of good definition of $\phi$ by working with $\xi$? Can I prove that $\phi$ is an isomorphism "simply" by searching a function, proving it is an isomorphism which inverts $\phi$?
Many thanks

A: In principle, you could try to solve a problem this way. The issue here is that it is often very difficult to construct a map $\xi:H'\to H$, whereas the map $\phi:H=G/K\to H'$ might be obvious. Additionally, this approach is not going to be helpful if $H'$ is also a quotient group. (For example, the 3rd isomorphism theorem is proved by constructing an isomorphism $H/H\cap N\to HN/N$. Giving a map $HN/N\to H/H\cap N$ is not so easy and, anyway, you still need to check that the map is well-defined.)
A better way to avoid checking if a map $G/K\to H'$ is well defined is to take advantage of some machinery.
Theorem: (First Isomorphism Theorem) Suppose
$$\phi:G\to H'$$
is a surjective homomorphism and $K=\ker\phi$. Then, there is an isomorphism $\overline{\phi}:G/K\to H'$.
One of the wonderful features of this theorem is that it checks that the map $\overline{\phi}$ is well-defined for you. In fact, this is how the 3rd isomorphism theorem is proved:
The map $H\to HN/N$ given by $h\mapsto hN$ is clearly a homomorphism, and there is no need to check that it is well-defined. The map is surjective since $hnN=hN$ for every $h\in H$ and $n\in N$, and the kernel of this map is obviously $H\cap N$. Invoking the first isomorphism theorem yields the result.


text:
Q: AngularJS: Is it possible for the following URL to be used in a form? In a form for an AngularJS page, is it possible to use the following URL to be set for a method?
https://example.com/transaction-address/id3

I've tried doing this, but the email id I've set is not being passed. The form is being handled in the injected script and the problem (or maybe a mistake) is in the line that injects the 'id3' method.
In the script for the ng-app, I've set the 'id3' method:
angular.module('app', [])
    .factory('Account', function($q, $u, $sce) {
        $q.all([
            ['$http',
            {'id1': 1,
            'id2': 2,
            'id3': 3,
            'id4': 4,}
        ]).then(function (response) {
            var sl = 'id3';
            $sce.trustAsResource('id3', sl);
            response.end();
        });
    });

A: You don't need to automatize the id3 string here. Just assign it to a variable:
angular.module('app', [])
    .factory('Account', function($q, $u, $sce) {
        $q.all([
            ['$http',
            {'id1': 1,
            'id2': 2,
            'id3': 3,
            'id4': 4,}
        ]).then(function (response) {
            var sl = 'id3';
            response.sendValue(sl);
            })
    });


text: Q: I want to implement a server side timer in firebase I want to put a timer in firebase and should decrement itself without any action from app side and when it expire should send a notification. For example, if I set one hour it should start and after one hour should send notification to a token id. I dont want any cloud function, can you help me with a good logic?


text:
Q: How to calculate the nth term of a sequence which has repeating, determined differences? I've covered quadratics and linear sequences and I've already got my feet into deep water with them, but I've never encountered this kind of sequence:
3, 15, 33, 39, 51, 69
The sequence evidently goes up by +12, +18, +6, +12, +18 and goes on and on...
I'd like to know how to find out its nth term and what the name of that kind of sequence is.
All help would be appreciated, thank you.

A: We can see
$$a_{3m+1}=39+36(m-1)=36m+3,$$
$$a_{3m-1}=15+36(m-1)=36m-21,$$
$$a_{3m}=33+36(m-1)=36m-3.$$
Hence, we get
$$a_n=\begin{cases}12n-9\ \ \ \text{if $n\not\equiv 0\pmod3$}\\12n-3\ \ \ \text{if $n\equiv 0\pmod3$}\end{cases}$$
So, noting that
$$\left\lceil\frac{n+3}{3}\div\left\lfloor\frac{n+3}{3}\right\rfloor-1\right\rceil=\begin{cases}1\ \ \ \text{if $n\not\equiv 0\pmod3$}\\0\ \ \ \text{if $n\equiv 0\pmod3$}\end{cases}$$
we get
$$a_n=12n-9+6\left(1-\left\lceil\frac{n+3}{3}\div\left\lfloor\frac{n+3}{3}\right\rfloor-1\right\rceil\right)\ \ \ (n=1,2,\cdots).$$

A: Hint: look at every third element of the sequence.

A: Given my really poor latex skills, this is the best form i could come up with:
given $n \in \mathbb{N^*}$
if: $\ \ \ \ \ \ n\ \ mod\ \ 3 = 0\ \ $  then:
$$
S_n = n*(12+18+6) + 3
$$
if: $\ \ \ \ \ \ n\ \ mod\ \ 3 = 1\ \ $  then:
$$
S_n = n*(12+18+6) - 21
$$
if: $\ \ \ \ \ \ n\ \ mod\ \ 3 = 2\ \ $  then:
$$
S_n = n*(12+18+6) - 39
$$


text:
Q: Autoit doesn't recognize _StringBetween function My code crashes, stating that _StringBetween is not a recognized function, even though I defined the correct #include that is needed.  It doesn't crash on the first _StringBetween, but it crashes on the next one.  Both _StringBetween's appear in Blue font, on the editor, confirming correct spelling, and correct number of parameters....  I'm puzzled...
See code below.  Stack Exchange forces me to add more description, so you can jump to the code section now.
CODE:
#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.14.5
 Author:         myName

 Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

;"C:\install\AutoIt3.exe" "C:\ArgsTest.au3" /argumentOne:MyFirstValue /argumentTwo:MySecondValue
#include <MsgBoxConstants.au3>
#include <IE.au3>
#include <Array.au3>
#include <Date.au3>
#include <String.au3>
#include <Excel.au3>
#include <WinAPIFiles.au3>

$BOL = 'HLCUEUR1810BCLY1'
$Tankno = '6001505'

$Link = "https://www.hapag-lloyd.com/en/online-business/tracing/tracing-by-booking.html"
$Link = $Link & "?blno=" & $BOL

;MsgBox($MB_ICONINFORMATION, "Tutorial", $BOL)

$file = fileopen(@scriptdir & "\HL3.txt", 10)
$IE = _IECreate($Link, 0, 1)

Sleep (200)
$source = _IEDocReadHTML($IE)
FileWrite($file, $source)

;extracting the value needed
$target_source = _StringBetween($source, $Tankno, '
')
$year = _StringBetween(target_source[0],$Tankno, "-")
$year = StringRight($year,4)
$month = _StringBetween($target_source[0],$year & '-', '-')
$day = _StringBetween($target_source[0],$year & "-" & $month & "-","<")
$day = StringLeft($day,2)
$ETA = $year & $month & $day

MsgBox($MB_ICONINFORMATION, "Tutorial", $ETA)

;$target_source2 = _StringBetween($target_source[0], '')
;$target_source3 = _StringBetween($target_source2[0], '>', '<')

;$USDEUR = $target_source3[0]

A: It's not the cleanest approach, but it's a solution to get the year-month-day value for that you're looking for:
Improved code:
#include-once
#include <Array.au3>
#include <Date.au3>
#include <Excel.au3>
#include <IE.au3>
#include <MsgBoxConstants.au3>
#include <String.au3>
#include <WinAPIFiles.au3>

$BOL    = 'HLCUEUR1810BCLY1'
$Tankno = '6001505'
$Link   = "https://www.hapag-lloyd.com/en/online-business/tracing/tracing-by-booking.html"
$Link   = $Link & "?blno=" & $BOL

$file   = fileopen(@ScriptDir & "\HL3.txt", 2 + 8)
$IE     = _IECreate($Link, 0, 1, 1, 1)

Sleep(2000)

$source = _IEDocReadHTML($IE)
FileWrite($file, $source)

$target_source = _StringBetween($source, $Tankno, '
')
$aETA          = StringRegExp($target_source[0], '(\d{4})-(\d{2})-(\d{2})', 3)
_ArrayDisplay($aETA) ; this is optional (see array content)
$ETA           = $aETA[0] & $aETA[1] & $aETA[2]

MsgBox($MB_ICONINFORMATION, "Tutorial", $ETA)

Please notice:
Your line $year = _StringBetween(target_source[0],$Tankno, "-") was not correct. You forgot the $ as variable indicator for $target_source. So the _StringBetween() function wasn't the problem. I decided to filter the $target_source with a RegEx expression instead of using _StringBetween() again for the year-month-day value.


text:
Q: bash read file line by line and use lines as arguments I have a file 'list' with a list of archives that I want to unpack. My script is:
#!/bin/bash
while read line
do
   echo 'string has been read'
   grep -e '**.zip' | xargs -d '\n' unzip -o
done < 'list'

But it works only for first zip-archive in a list and ignores other strings in list. If I comment out the 'grep -e '**.zip' | xargs -d '\n' unzip -o' script reads all lines.
I can't understand why it works this way, and how to fix it.

A: Could be done even without a loop, I think.
grep '\.zip$' < yourfile.txt | xargs -n1 unzip -o

or, from stdin:
grep '\.zip$' | xargs -n1 unzip -o

The -n1 tells xargs to use 1 command line per argument

A: You're not refering to $line in your loop. Hence it wont work the way you want.
What about:
#!/bin/bash
while read line; do
    if [[ "$line" =~ "\.zip$" ]]; then
        unzip -o $line
    fi
done < list


text:
Q: Angular 4 comma not working on tablet android keyboard In our Angular app when browsing on a tablet one of our number input fields I cannot use comma when typing. I can use the dot, +, numbers but I can't input comma and I cant figure out why.

As you can see, when I tap on input field "Vrijednost" (croatian for 'value'), google keyboard GBoard opens up. I can type in dots (as seen in picture), but I can't use commas.
I tried doing this on desktop using Chrome browser and I can type in commas using phyisical keyboard, I even tried with Windows on-screen keyboard and it also works. Any suggestions why it wouldn't work on tablet using GBoard?
Grid code in component.html:
                        <ng-template ngFor let-c [ngForOf]="grid.columns" let-y="index">
                        <input class="form-control" type="number"  min="0" step="1" inputmode="numeric"  pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="value1-{{i}}" name="value1-{{i}}" (keyup)="changeItem(item, $event, i)" [required]="item.remark != null ? true : false" [readonly]="typeID == 0 ? true : false" />
                        <input class="form-control" type="text" pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="value1-{{i}}" name="value1-{{i}}" (keyup)="changeItem(item, $event, i)" [required]="item.remark != null ? true : false" />
                        <input class="form-control" type="number"  min="0" step="1" inputmode="numeric"  pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="value2-{{i}}" name="value2-{{i}}" (keyup)="changeItem(item, $event, i)" [required]="item.value1 != null && typeId == 4 ? true : false" />
                        <input class="form-control" type="number"  min="0" step="1" inputmode="numeric"  pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="value2-{{i}}" name="value2-{{i}}" (keyup)="changeItem(item, $event, i)" />
                        <input class="form-control" type="number"  min="0" step="1" inputmode="numeric" pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="value3-{{i}}" name="value3-{{i}}" (keyup)="changeItem(item, $event, i)" />
                        <input class="form-control" type="text" pInputText [(ngModel)]="item[grid.columns[y].dataKey]" id="remark-{{i}}" name="remark-{{i}}" (keyup)="changeItem(item, $event, i)" [readonly]="typeID == 0 ? true : false" />
                        {{item[grid.columns[y].dataKey]}}
                    </ng-template>


text:
Q: Degraded game performance after format So I had sent my PC to a repair shop for a format, and when I have it back I noticed that some of the games I usually play are running slower than usual. For example, pre-format, my PC was able to handle Left 4 Dead at full detail, and now even at the lowest detail settings it lags and skips like crazy. I've made sure that the drivers are up-to-date (version 275.33), I've got DX 9c installed, I made sure that the anti-virus didn't get in the way by uninstalling it completely before playing, and I even went into the Nvidia Control Panel and set it to emphasize "performance" over "quality", and nothing seems to be working. I'd hate to have to take this back to the shop, is there anything else I can check or do?
Additional specs here
Specs:
Intel Pentium D 2.66ghz
1 GB RAM
nvidia 9400 GT (1 GB)
250 GB HD

UPDATE:
So I took the time to run fraps to get an idea of just how bad things are playing, here are the results, I played HL2 for a good 15 minutes, the "Our Benefactors" chapter @ 1024 x 768 resolution and low detail for everything, and no sound.
Frames   Time (ms)   Min     Max     Avg
13853    1042360     0       45      13.29

Another test run in another section of the game:
Frames   Time (ms)   Min     Max     Avg
6507     898140      0       31      7.245

It's like my video card doesn't even exist
I know my specs are on the low end of things here but I honestly think something's wrong.
UPDATE 2:
Reformatted the entire computer again, reinstalled the necessary drivers and tried again, still no change in performance. I'm tempted at this point to think that my GFX card might've failed in some way but it still works as far as the Windows desktop is concerned, I can still surf the web and edit documents, and do other non-gaming related activities.
UPDATE 3:
Solved! As per the advice in the answers and comments below I used Speccy and Speedfan to monitor the system temp and saw that it was holding steady at 91 C, so I took it apart and inspected the HSF and saw that the thermal paste was old and cracked and stuff and sure enough when I put it back together and powered up the system wouldn't even stay on, so I replaced the thermal compound and now I'm getting temps of 67-68 C average and Fraps reports the following -
Frames, Time (ms), Min, Max, Avg
8892,    279468,   0,   81,  31.818

And I suspect that the rest of my stuff will work fine now.

A: First things first; try running DXDiag and see what it says in the Disaply tab. Does it say Enabled in each of the three acceleration fields in the DirectX Features section? If you've got buttons next to the fields, click them and see what the test results are. Also check the Notes field to see if there are any problems. See screenshots below.
From your description, it sounds like they were only fixing your software, and thus should not have opened the system, but it may be worth a look inside to make sure that everything is as it should be. In fact, you may want to try an inventory app like Speccy to take stock of your system. I don't know if you have details about your system before it went to the shop, but you should check to see if for example, the RAM is slower than what you used to have.
Check to see if your hardware is what it used to be and that there are no loose connections. Your card does not seem to have a separate power connector, but if it does, make sure that it is connected.

Broken DirectX or hardware-acceleration not available:

DirectX okay, hardware acceleration available, Test buttons avilable:

A: You can use Speccy or SpeedFan to show the temperatures of all your computer components. I would pay close attention to the video card temperature (GPU). Both programs have options to graph the temperatures over a period of time. Open the graph, play a game, and then check the graph to see how hot it got. If your video card is overheating... it can do exactly what you are describing.
Make sure your heatsinks are clear of dust and make sure all fans spin.

A: Maybe this is nonsense, but what country / repair shop are we talking about? I'd be hesitant to let some stores in the USA fiddle with my PC, let alone one in the old country. "Swap GTX for GTZ, is good as new, in fact is 2 better!".

A: Check your BIOS. Are all the settings relating to performance set properly? In particular, is SpeedStep active, or is your processor speed being limited to the lowest denominator?

A: Nvidia has now released the 280 family of drivers.
You might try to update and see if there is any improvement.
EDIT
A hardware note : If the repair shop changed the PSU, they might have changed it to one that is too weak to support the video card running at high speed. Or it might be that the PSU has weakened down because of some other operation badly done at the shop.


text:
Q: Swift - Troubles with API calls / CompletionHandler / URLSessions I have this long function here which makes a bunch of API calls, parses through data and returns two arrays representing a bunch of sight-seeing locations (one array holds the latitudes, one holds the latitudes). The issue I am having is determining when the two arrays are finished being populated. Ideally, I would like to be able to place
print("ArrayCount = \(self.latArray.count)")

somewhere in my code and receive a single print statement in the console reading ArrayCount = 123. However everywhere I place the print statement I get either an array count of 0 or a loop of values being printed out as they are added (1..2..3.. ... ..123). Thanks in advance!
func someFunction()
{
    let url:URL = URL(string: "...")

    let task = URLSession.shared.dataTask(with: URLRequest(url: url))
    {
        data, response, error in

        if error != nil
        {
            print("ERROR IN API REQUEST: \(error!.localizedDescription)")
        }

        else
        {
            do
            {
                if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
                {
                    if let layerOne = parsedData["one"] as? [String: Any]
                    {
                        if let layerTwo = layerOne["two"] as? [[String: Any]]
                        {
                            for layerThree in layerTwo
                            {
                                if let variableName = layerThree["value"] as? String
                                {
                                    let innerUrl:URL = URL(string: "...")!

                                    let innerTask = URLSession.shared.dataTask(with: URLRequest(url: innerUrl))
                                    {
                                        data, response, error in

                                        if error != nil
                                        {
                                            print("ERROR IN API REQUEST: \(error!.localizedDescription)")
                                        }

                                        else
                                        {
                                            do
                                            {
                                                if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
                                                {
                                                    if let layerA = parsedData["A"] as? [String: Any]
                                                    {
                                                        if let lat = layerA["Latitude"] as? String, let long = layerA["Longitude"] as? String
                                                        {
                                                            self.latArray.append(lat)
                                                            self.longArray.append(lon)
                                                        }
                                                    }
                                                }
                                            }

                                            catch
                                            {
                                                print("ERROR IN JSON SERIALIZATION")
                                            }
                                        }
                                    }
                                    innerTask.resume()
                                }
                            }
                        }
                    }
                }
            }

            catch
            {
                print("ERROR IN JSON SERIALIZATION")
            }
        }
    }

    task.resume()
}

A: I'm not sure exactly what you're trying to do, but once I thinned out your incredibly verbose code and tried to understand it, I think the conclusion is that you'll only want to record the array counts after the last iteration of your inner loop. For example:
Instead of doing this: for layerThree in layerTwo
do this: for (index, layerThree) in layerTwo.enumerated()
Then, after you append the lat/long values, add this check:
if index == layerTwo.count - 1 //if this is our last inner loop
{
    //print the array counts
    print("Lat count: \(latArray.count)")
    print("Long count: \(longArray.count)")
}

This should work in your case. However, I disagree entirely with the execution of this simply because of the lack of portability and reusability of your code. Additionally, there are quite a few good language constructs which are being ignored. The relentless nested if let blocks could be reduced significantly with a few good guard statements. Furthermore, considering you aren't handling your errors in any catch blocks anyway, might as well just remove them and opt for a try? instead. One much swiftier way of handling things would be to just include a completion handler in the function itself so that the array count printing logic could be handled elsewhere. I'll include some example code of how I would clean things up:
func someFunction(completion: (([String], [String]) -> Void)?)
{
    let url = URL(string: "...")!
    var latArray: [String] = []
    var longArray: [String] = []

    let task = URLSession.shared.dataTask(with: URLRequest(url: url),
        completionHandler: { (data, response, error) -> Void in
            guard error == nil else
            {
                print("ERROR IN API REQUEST: \(error?.localizedDescription)")
                return
            }

            guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments),
                let parsedDict = parsedData as? [String: Any],
                let layerOne = parsedDict["one"] as? [String: Any],
                let layerTwo = layerOne["two"] as? [[String: Any]] else
            {
                print("JSON OBJECT DOES NOT MATCH EXPECTED PATTERN")
                return
            }

            for (index, layerThree) in layerTwo.enumerated()
            {
                guard let _ = layerThree["value"] as? String else
                {
                    print("Skip this iteration (I guess?)")
                    continue
                }

                let innerUrl = URL(string: "...")!
                let innerTask = URLSession.shared.dataTask(with: URLRequest(url: innerUrl),
                    completionHandler: { (data, response, error) -> Void in
                        guard error == nil else
                        {
                            print("ERROR IN API REQUEST: \(error?.localizedDescription)")
                            return
                        }

                        guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments),
                            let parsedDict = parsedData as? [String: Any],
                            let layerA = parsedDict["A"] as? [String: Any],
                            let lat = layerA["Latitude"] as? String,
                            let long = layerA["Longitude"] as? String else
                        {
                            print("Something went wrong")
                            return
                        }

                        latArray.append(lat)
                        longArray.append(long)

                        if index == layerTwo.count - 1 //if this is our last inner loop
                        {
                            completion?(latArray, longArray)
                        }
                    }
                )
                innerTask.resume()
            }
        }
    )

    task.resume()
}

someFunction(completion: { (latArray, longArray) -> Void in
    //print the array counts
    print("Lat count: \(latArray.count)")
    print("Long count: \(longArray.count)")
})

This could still be improved much further, though based on your question I don't see that I personally should be putting more time into constructing this for you. It would be best if you come up with a few methods of your own to build an application with more readable and reusable code.


text:
Q: How to change git checkout to original I cloned a software with git clone.
git clone https://github.com/BinPro/CONCOCT.git

And then
cd CONCOCT
git fetch
git checkout SpeedUp_Mp

Then I got this message.
Branch 'SpeedUp_Mp' set up to track remote branch 'SpeedUp_Mp' from 'origin'.
Switched to a new branch 'SpeedUp_Mp

Then I put
sudo python ./setup.py install

Now I want to make it into 'origin' as before.
So I put
git fetch
git checkout origin

Then I get an error message
error: Your local changes to the following files would be overwritten by checkout:
concoct/cluster.py
Please commit your changes or stash them before you switch branches.
Aborting

What can I do? How do I commit changes?

A: If you want to get the original version of the branch,
checkout to a new branch, delete branch with the problem in local
git branch -d SpeedUp_Mp
git fetch --all
git checkout SpeedUp_Mp

else, you could checkout all the changes you did
git checkout .


text:
Q: What is the meaning of "producing negative zeroes" in a system that doesn't support it? C17 6.2.6.2/4 says:

If the implementation does not support negative zeros, the behavior of the &, |, ^, ~, <<,
  and >> operators with operands that would produce such a value is undefined.

If I have a 2's complement system, it does not support negative zeroes. And it always utilizes all possible combinations of a binary number to express a value. Therefore it is impossible to ever produce a negative zero, no matter which bitwise operation that is used. So what is the meaning of this text?
My take is that this part refers to systems with 1's complement or signed magnitude that does not support negative zeroes, but instead use a padding bit or trap representation. Is this correct?

A: Yes, I think your interpretation is correct. In two's complement, that are no operations that could generate a negative zero, because the concept here doesn't exist: any value that has the sign bit set is necessarily less than 0.
BTW: It is very likely that the exotic sign representations will be removed from C2x, so all of this will disappear.

A: Your interpretation is correct.
Going up to paragraph 2 of 6.2.6.2:

For signed  integer  types,  the  bits  of  the  object
  representation  shall  be  divided  into  three groups:  value  bits,
  padding  bits,  and  the  sign  bit.  There  need  not  be  any
  padding  bits; signed char shall  not  have  any  padding  bits.
  There  shall  be  exactly  one  sign  bit. Each  bit  that  is  a
  value  bit  shall  have  the  same  value  as  the  same  bit  in  the
  object representation of the corresponding unsigned type (if there are
  M value bits in the signed type and N in the unsigned type, then M ≤ N
  ).  If the sign bit is zero, it shall not affect the  resulting
  value.   If  the  sign  bit  is  one,  the  value  shall  be  modified
  in  one  of  the following ways:

*

*the corresponding value with sign bit 0 is negated ( sign and magnitude );

*the sign bit has the value − (2M)( two's complement );

*the sign bit has the value − (2M − 1) ( ones' complement ).

  Which of these applies is implementation-defined, as is whether the
  value with sign bit 1 and  all  value  bits  zero  (for  the  first
  two),  or  with  sign  bit  and  all  value  bits  1  (for  ones'
  complement),  is  a  trap  representation  or  a  normal  value.   In
  the  case  of  sign  and magnitude  and  ones'  complement,  if  this
  representation  is  a  normal  value  it  is  called  a negative zero.

This means an implementation using either one's complement or sign and magnitude has, for a given size integer type, a specific representation which must be either negative zero or a trap representation.  It's then up to the implementation to choose which one of those applies.
As an example, suppose a system has sign and magnitude representation and a 32 bit int with no padding.  Then the representation that would be negative zero, if it is supported, is 0x80000000.
Now suppose the following operations are performed:
 int x = 0x7fffffff;
 x = ~x;

If the implementation supports negative zero, the ~ operator will generate -0 as the result and store it in x.  If it does not, it creates a trap representation and invokes undefined behavior as per paragraph 4.


text:
Q: Find a sinusoidal regression equation for some given data. I have some data which is sinusoidal when graphed. I want to find a regression equation for these data of the form: $$f_{(x)}=A\sin \left[\frac{2\pi}{B} (x-C)\right]+D$$
I estimated all the constants $A,B,C$ and $D$ from the graph and found a reasonable sinusoidal regression curve for these data, happy days.
But I am wondering whether or not there is some way of plotting my data in a linear form such that the slope and intercept etc. will give me a more accurate estimate for the constants. Is there such a method? What would be the simplest way to go about it?
I am not referring to any specific data sample but would like to know how to go about this in general.
Here are some data though that we can work with.
$$x=(1,2,3,4,5,6)$$ $$y=(3.42,0.73,0.12,2.16,4.97,5.97)$$
My work: $$A=\frac{5.97-0.12}{2}=2.925$$ $$D=0.12+2.925=3.045$$ $$C=\frac{6+3}{2}=4.5$$ $$B=2(6-3)=6$$ $$f_{(x)}=2.925\sin[\frac{\pi}{3}(x-4.5)]+3.045$$
I could only base my constants on the min and max data available. This method isn't much use if you don't have good extremity data and also if the data don't even cover one full oscillation.
What would be a more accurate way of going about this?

A: Assuming that the data cover a large range and do not contain much noise and using as a model $$f(x)=a\sin \left(\frac{2\pi}{b} (x-c)\right)+d$$ we can get some estimates using $$f(0)=d-a \sin \left(\frac{2 \pi  c}{b}\right)$$ which gives an estimate of $d$.
For the point $x_1$ where $f(x_1)=0$ we have $$x_1=c-\frac{b \sin ^{-1}\left(\frac{d}{a}\right)}{2 \pi }$$  which gives an estimate of $c$.
For the point $x_2$ where $f'(x_2)=0$ we have $$x_2=\frac{b}{4}+c$$  which gives an estimate of $b$ and $f(x_2)=a+d$  gives an estimate of $a$.
So, basically looking at the plot of the data, we have, in principle, at least consistent estimates of all parameters. and we can safely start the full nonlinear regression.
However, this would imply solving a tedious equation for $a$. But using the above, we can reduce in a first step to the fit of a single parameter $a$, parameters $b,c,d$ being expressed as functions of $a$ using the above relations. When the optimum $a$ has been found (this can be done using a plot of the sum of squares computed for a few discret values of $a$ until a minumum value is detected),  we can safely start the full nonlinear regression with consistent estimates.
Edit
Thinking more about the problem, I suppose that I should write the model as
$$f(x)=a \sin(\alpha x+\beta)+d\qquad \text{with}\qquad \alpha=\frac {2\pi}b\qquad \text{and}\qquad \beta=-\frac {2\pi c}b$$ Expanding the sine $$f(x)=a \cos (\beta ) \sin (\alpha  x)+a \sin (\beta ) \cos (\alpha  x)+d=A\sin (\alpha  x)+B\cos(\alpha  x)+d $$ which is linear if $\alpha$ is given a specific value.
For this value of $\alpha$, use a linear regression to get the best values of parameters $A( \alpha)$,  $B( \alpha)$, $d( \alpha)$ and compute the sum of square of residuals. You will find, by trial and error, a zone where $SSQ( \alpha)$ is minimum. Fo this value $\alpha_*$, go back $$A(\alpha_*)=a \cos(\beta)\qquad B(\alpha_*)=a \sin(\beta)\qquad \implies\qquad a\qquad \text{and} \qquad\beta$$ which themselves lead to $b$ and $c$.
For illustration purposes, I used the following (synthetic) data set
$$\left(
\begin{array}{cc}
 x & f(x) \\
 0.0 & -11.47 \\
 0.5 & -15.62 \\
 1.0 & -18.19 \\
 1.5 & -19.17 \\
 2.0 & -18.02 \\
 2.5 & -15.30 \\
 3.0 & -11.06 \\
 3.5 & -6.34 \\
 4.0 & -1.50 \\
 4.5 & +2.33 \\
 5.0 & +4.92 \\
 5.5 & +5.49 \\
 6.0 & +4.33
\end{array}
\right)$$
Below are reported the results of the linear regressions for different values of $\alpha$
$$\left(
\begin{array}{cc}
 \alpha & \\
 0.1 & \{145.375,\{A\to -7.60697,B\to -174.895,d\to 158.722\}\} \\
 0.2 & \{135.708,\{A\to -5.44567,B\to -48.7632,d\to 32.6894\}\} \\
 0.3 & \{119.635,\{A\to -5.52408,B\to -25.2303,d\to 9.34186\}\} \\
 0.4 & \{97.4249,\{A\to -6.2399,B\to -16.7424,d\to 1.16049\}\} \\
 0.5 & \{69.9893,\{A\to -7.29279,B\to -12.459,d\to -2.63686\}\} \\
 0.6 & \{39.7696,\{A\to -8.58334,B\to -9.62791,d\to -4.7105\}\} \\
 0.7 & \{12.4717,\{A\to -10.0273,B\to -7.20268,d\to -5.97143\}\} \\
 0.8 & \{\color{red}{0.0564199},\{A\to -11.4518,B\to -4.6306,d\to -6.79914\}\} \\
 0.9 & \{24.2511,\{A\to -12.4754,B\to -1.59026,d\to -7.37301\}\} \\
 1.0 & \{115.154,\{A\to -12.4273,B\to 1.90681,d\to -7.78404\}\}
\end{array}
\right)$$
Using $\alpha_*=0.8$, we get $a=12.3526$, $d=−6.79914$ and $\beta=-2.75734$ and then $b=7.85398$ and $c=3.44668$. Using these numbers, the reults of the nonlinear regression are
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 a & 12.346 & 0.0234427 & \{12.2919,12.4001\} \\
 b & 7.89158 & 0.0148157 & \{7.85741,7.92574\} \\
 c & 3.45132 & 0.003368 & \{3.44355,3.45909\} \\
 d & -6.77303 & 0.0209294 & \{-6.82129,-6.72477\} \\
\end{array}$$ As you can notice, the final parameters are quite close to the guesses. Comparing data and prediction
$$\left(
\begin{array}{ccc}
 x & f(x) & \text{prediction} \\
 0.0 & -11.47 & -11.509 \\
 0.5 & -15.62 & -15.558 \\
 1.0 & -18.19 & -18.234 \\
 1.5 & -19.17 & -19.117 \\
 2.0 & -18.02 & -18.070 \\
 2.5 & -15.30 & -15.255 \\
 3.0 & -11.06 & -11.115 \\
 3.5 & -6.34 & -6.2947 \\
 4.0 & -1.50 & -1.5496 \\
 4.5 & +2.33 & +2.3786 \\
 5.0 & +4.92 & +4.8754 \\
 5.5 & +5.49 & +5.5505 \\
 6.0 & +4.33 & +4.2982
\end{array}
\right)$$
Update
Using the data you posted in your edit
$$\left(
\begin{array}{cc}
 x & f(x) \\
 1 & 3.42 \\
 2 & 0.73 \\
 3 & 0.12 \\
 4 & 2.16 \\
 5 & 4.97 \\
 6 & 5.97
\end{array}
\right)$$ applying the procedure given in my edit, we obtain
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 a & 3.00141 & 0.00178404 & \{2.97874,3.02408\} \\
 b & 6.28596 & 0.00321329 & \{6.24513,6.32679\} \\
 c & 4.28388 & 0.00094226 & \{4.27190,4.29585\} \\
 d & 2.99993 & 0.00174274 & \{2.97779,3.02207\} \\
\end{array}$$
Comparing data and prediction
$$\left(
\begin{array}{ccc}
 x & f(x) & \text{prediction} \\
 1 & 3.42 &3.42124\\
 2 & 0.73 &0.72783\\
 3 & 0.12 &0.12170\\
 4 & 2.16 &2.15966\\
 5 & 4.97 &4.96954\\
 6 & 5.97 &5.97003
\end{array}
\right)$$ Your very simplified procedure leads to very different results.


text:
Q: I'm trying to create a signup and login system in python for some homework. It's not working as intended though     ExistingUser = input("Please enter either Y or N: ")

if (ExistingUser) == "N" or "n":
    newName = input("Please enter your name: ")
    with open("Userdata.txt", "a") as f:
        print(newName, file = f)
    newUserID = input("Please enter your desired username: ")
    with open("Userdata.txt", "a") as f:
        print(newUserID, file = f)
    newPassword = input("Please enter your desired password: ")
    with open("Userdata.txt", "a") as f:
        print(newPassword, file = f)
        f.close()

elif (ExistingUser) == "Y" or "y":
    existingUserID = input("Please enter your username: ")
    with open("Userdata.txt") as f:
        if (ExistingUserID) in f.read():
            print("True")

When I type in Y or y, it should trigger the login process. Instead, however it triggers the signup one.

A: if (ExistingUser) == "N" or "n": is same as if (ExistingUser) == "N" or True: so your if condition is always True
For more info - read Truth Value Testing
use if ExistingUser in ('N', 'n'):
or if ExistingUser.lower() == 'n':
Note that there is no need to use brackets around ExistingUser.

A: It looks to me that your If statements are not correct It seems to work if you you change them to this format
if (ExistingUser == "N" or ExistingUser == "n"):
elif (ExistingUser == "Y" or ExistingUser ==  "y"):
In this format:
if (ExistingUser) == "N" or "n":
the 'or "n"' evaluates to true all the time


text:
Q: How Can I Unregister Device Using GCM I've try to Unregister device by gcm using this Code :
 btn = (Button)findViewById(R.id.button1);

 btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         GCMRegistrar.unregister(MainActivity.this);
    }
});

with knowledge that i used this code in onCreate() Method ...
but when i try send a notification to the DeviceID the notification Arrives
that mean the Unregister process didn't success
My onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    txt = (TextView)findViewById(R.id.txt_nn);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals(""))
    {
      GCMRegistrar.register(this, "344XXXXXXX571");
    }
    else
    {
      Log.v("Info : ", "Already registered");
    }

     txt.setText(regId);

     btn = (Button)findViewById(R.id.button1);

     btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             GCMRegistrar.unregister(MainActivity.this);
        }
    });
}

My LogCat
12-25 17:16:31.290: E/Trace(18754): error opening trace file: No such file or directory (2)
12-25 17:16:31.425: V/Info :(18754): Already registered
12-25 17:16:31.485: D/libEGL(18754): loaded /system/lib/egl/libEGL_mali.so
12-25 17:16:31.490: D/libEGL(18754): loaded /system/lib/egl/libGLESv1_CM_mali.so
12-25 17:16:31.495: D/libEGL(18754): loaded /system/lib/egl/libGLESv2_mali.so
12-25 17:16:31.500: D/(18754): Device driver API match
12-25 17:16:31.500: D/(18754): Device driver API version: 10
12-25 17:16:31.500: D/(18754): User space API version: 10
12-25 17:16:31.500: D/(18754): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Wed Sep 12 17:53:53 KST 2012
12-25 17:16:31.540: D/OpenGLRenderer(18754): Enabling debug mode 0
12-25 17:16:43.015: D/GestureDetector(18754): [Surface Touch Event] mSweepDown False, mLRSDCnt : -1 mTouchCnt : 2 mFalseSizeCnt:0
12-25 17:16:43.020: D/GCMRegistrar(18754): resetting backoff for com.example.test09_gsm
12-25 17:16:43.020: V/GCMRegistrar(18754): Unregistering app com.example.test09_gsm
12-25 17:16:46.865: V/GCMBroadcastReceiver(18754): onReceive: com.google.android.c2dm.intent.REGISTRATION
12-25 17:16:46.865: V/GCMBroadcastReceiver(18754): GCM IntentService class: com.example.test09_gsm.GCMIntentService
12-25 17:16:46.870: V/GCMBaseIntentService(18754): Acquiring wakelock
12-25 17:16:46.895: V/GCMBaseIntentService(18754): Intent service name: GCMIntentService-IntentService-1
12-25 17:16:46.895: E/GCMRegistrar(18754): internal error: retry receiver class not set yet
12-25 17:16:46.895: V/GCMRegistrar(18754): Registering receiver
12-25 17:16:46.895: D/GCMBaseIntentService(18754): handleRegistration: registrationId = null, error = null, unregistered = com.example.test09_gsm
12-25 17:16:46.895: D/GCMRegistrar(18754): resetting backoff for com.example.test09_gsm
12-25 17:16:46.895: V/GCMRegistrar(18754): Saving regId on app version 1
12-25 17:16:46.940: D/onUnregistered(18754): APA91bFrB0pJOQqq7MxSe-so7fbqh70jLpX6bRrcRIdW6py1EuxletPfGr5ZlkytrenbdnJskdWXckjIcHWsvtKXppZ1PsMbhfkzIc9BmX26brIVDTCRSXPey7POA3UqP6EexMD4w_plFQkVy-9pacCqbBfV0k91dQ
12-25 17:16:46.940: V/GCMBaseIntentService(18754): Releasing wakelock

please can you help me to unregister the device on GCM
and don't receive the future notification
thanks in advance

A: Check if you are registering receiver to handle your GCM messages. Check mHandleMessageReceiver. I am assuming that you are using the same code as given in documentation.
But if you don't want to handle unregistered message
Goto GCMIntentService class and see onUnregistered method. Remove displayMessage() as I commented the line.
 @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        //displayMessage(context, getString(R.string.gcm_unregistered));
        if (GCMRegistrar.isRegisteredOnServer(context)) {
            ServerUtilities.unregister(context, registrationId);
        } else {
            // This callback results from the call to unregister made on
            // ServerUtilities when the registration to the server failed.
            Log.i(TAG, "Ignoring unregister callback");
        }
    }

This will do your task.
Happy coding :)


text:
Q: How to get the current location of a user in Dialogflow chatbot? I am trying to get the user location in Dialogflow, but so far I am not able to get it.
I have found information showing how to get the location in Dialogflow using Google assistance like this article. The thing is that I just want to do it with a chatbot and get the response there. I have tried as well the code below but still not working:
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const {Permission} = require('actions-on-google');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

   function requestPermission(agent) {
    agent.requestSource = agent.ACTIONS_ON_GOOGLE;
    let conv = agent.conv();
    console.log('conv '+conv);
    conv.ask(new Permission({
    context: 'to locate you',
    permissions: 'DEVICE_PRECISE_LOCATION',
    }));
    agent.add(conv); // Please add this

    }

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);

  intentMap.set('request_permission', requestPermission);

  agent.handleRequest(intentMap);
});

I added an intent call "request_permission". I will appreciate any help or recomendation.

A: There is no general solution in Dialogflow to get the location. Not all systems that work with Dialogflow have a way to transmit location automatically, and others use different means via messages.
The solution for Actions on Google just works with the Google Assistant.


text:
Q: Hooking to all control's click events using Jquery Currently I am calling a function in code behind once someone clicks on a button (using button's event) and using following ajax :
$('.toggleBtn').click(function(e) {
    $.ajax({
                        type: "POST",
                        url: "page.aspx/function",
                        data: "{'id': '" + id + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: false,

                        success: function (msg) {

Is it possible in jquery to hook to all of the controls events in current page and run only one $.ajax.
Say I have four controls, two textboxes and two comboboxes and want to update database accordingly. if i want to run the above I need to hook to their click events one by one and run separate function in code behind, which will not be ideal.
In another words want to populate my object once the user selects/inputs the control value.
Hope it makes sense.

A: I think you can use this logic:
var request = 0; //global flag

$('.toggleBtn').click(function(e) {
    if (!request) {
      $.ajax({
         ..
         success: function(){
           request = 1; //update the flag
         }
      });
    }
});

A: If I understand your question, you're asking how to fire the same code for the click event of a group of elements, but wish to pass the ID of the clicked element as a parameter in the data.  If so, this will do it for all elements with the class className...
$('.className').click(function(e) {
    $.ajax({
        type: "POST",
        url: "page.aspx/function",
        data: "{'id': '" + this.id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (msg) {
            ...
            ...
        }
    });
});


text:
Q: Snap SVG change line x,y coordinates using JavaScript I want to change the x and y coordinates of the svg line, but it keeps drawing multiple lines itself over and over again. Here is the result: http://prntscr.com/6tdexj
How do I draw only one line every 1 second ?
var paper = Snap('#one');

var timer = setInterval(function() {my_var()}, 1000);

function my_var() {
    x = Math.floor((Math.random() * 100) + 1);
    y = Math.floor((Math.random() * 100) + 1);

    console.log(x, y);

    // SVG LINE
    var line = paper.line(10, 10, x, y).attr({
        fill: 'f44',
        stroke: '#000'
    });
};

A: You're creating a new line in each interval. You should create a single line and change its properties instead:
var paper = Snap('#one');

var line = paper.line(10, 10, 10, 10)
  .attr({
  fill: 'f44',
  stroke: '#000'
})

setInterval(function() {
  var x = Math.floor((Math.random() * 100) + 1),
      y = Math.floor((Math.random() * 100) + 1);

  line.attr({ x2: x, y2: y })
}, 1000);

You could make the line transition smoothly by calling line.animate instead of line.attr:
line.animate({ x2: x, y2: y }, 500);

http://jsbin.com/josuyo/2/edit


text:
Q: Unidirectional ManyToOne: Why transient instance saved with CascadeType.ALL but not CascadeType.PERSIST I am getting org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: safu.Publisher exception when I try to run the following code:
public class SafuClient {
    public static void main(String[] args) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

            Publisher publisher = new Publisher("ABC", "ABC Co.");
            Book book = new Book("1-932394-88-5", "Safu", publisher);

            session.save(book);

            session.getTransaction().commit();

    }
}

I have a Many-to-One relationship from Book to Publisher. Book and Publisher entities follows:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String isbn;
    private String name;

    @ManyToOne(cascade={CascadeType.PERSIST})
    @JoinColumn(name="publisher_id")
    private Publisher publisher;

    public Book() {}
    public Book(String isbn, String name, Publisher publisher) {
        this.isbn = isbn;
        this.name = name;
        this.publisher = publisher;
    }

}

@Entity
public class Publisher {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String code;
    private String name;

    public Publisher() {}
    public Publisher(String code, String name) {
        this.code = code;
        this.name = name;
    }

}

If I replace @ManyToOne(cascade={CascadeType.PERSIST}) with @ManyToOne(cascade={CascadeType.ALL}) in the Book entity everything works just fine.
Could somebody explain why is it happening?

A: Try session.persist(book); this solves the problem instead of session.save(book);

A: The session.save(book) method works by removing the cascade attribute (cascade={CascadeType.PERSIST}) from @ManyToOne annotation in the Book entity and adding the @Cascade (value=CascadeType.SAVE_UPDATE) on the publisher field instead.
The @Cascade (value=CascadeType.SAVE_UPDATE) uses Hibernate's native annotations.

Follows the updated Book.java that worked:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String isbn;
    private String name;

    @ManyToOne
    @JoinColumn(name="publisher_id")
    @Cascade(value=CascadeType.SAVE_UPDATE)
    private Publisher publisher;

    public Book() {}
    public Book(String isbn, String name) {
        this.isbn = isbn;
        this.name = name;
    }
    public Book(String isbn, String name, Publisher publisher) {
        this.isbn = isbn;
        this.name = name;
        this.publisher = publisher;
    }
}