text:
Q: How to use the dimension of a python matrix in a loop I am working with a matrix, lets call it X, in python.
I know how to get the dimension of the matrix using X.shape but I am interested specially on using the number of rows of the matrix in a for loop, and I dont know how to get this value in a datatype suitable for a loop.
For example, imagine tihs simple situation:
a = np.matrix([[1,2,3],[4,5,6]])
for i in 1:(number of rows of a)
     print i

How can I get automatically that "number of rows of a"?

A: X.shape[0] == number of rows in X

A: A superficial search on numpy will lead you to shape. It returns a tuple of array dimensions.
In your case, the first dimension (axe) concerns the columns. You can access it as you access a tuple's element:
import numpy as np

a = np.matrix([[1,2,3],[4,5,6]])
# a. shape[1]: columns
for i in range(0,a.shape[1]):
   print 'column '+format(i)

# a. shape[0]: rows
for i in range(0, a.shape[0]):
   print 'row '+format(i)

This will print:
column 0
column 1
column 2
row 0
row 1


text:
Q: Filter list and its children in jquery This is my html code:
<input class="form-control" id="myInput" type="text" placeholder="Search..">

b - B

backbiting

Loreum Ipsum

This is the jquery I am using:
$("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myList h3").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
});

I want search/filter to work on li > h3 element and the above code is working but I am not able to hide cards under every list. How should I do that ?

A: I think you are you are getting problem in hiding the li also along with h3.
Here, you have select only #myList h3 so only that segment will be hide on filter. To hide li along with that you have to select both the elements i.e., parent of that element. So, instead of select #myList h3 select #myList li and in filter use $(this).find('h3').text() for filter like below...
$("#myInput").keyup(function() {
        var value = $(this).val().toLowerCase();
        $("#myList li").filter(function() {
            $(this).toggle($(this).find('h3').text().toLowerCase().indexOf(value) > -1)
        });
    });

I think this should solve your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select multiple dates on android calender view     val calendar: Calendar = Calendar.getInstance()
    calendar.set(2022, 5, 10)
    val dateSelected = calendar.timeInMillis

    val calender2 = Calendar.getInstance()
    calender2.set(2022, 5, 11)
    val dateSelected2 = calender2.timeInMillis

    binding?.calenderView?.setDate(dateSelected, true, true)
    binding?.calenderView?.setDate(dateSelected2, true, true)

I've tried to select two dates as shown above, but it doesn't work? Any help?

A: If you just want to select range of date, try material date picker material date picker doc
 MaterialDatePicker.Builder.dateRangePicker().build().show(supportFragmentManager, "")

A:             val dateRangePicker =
            MaterialDatePicker.Builder
                .dateRangePicker()
                .setTheme(R.style.ThemeOverlay_MaterialComponents_MaterialCalendar)
                .setTitleText("Title")
                .setSelection(
                    Pair(
                        MaterialDatePicker.thisMonthInUtcMilliseconds(),
                        MaterialDatePicker.todayInUtcMilliseconds()
                    )
                )
                .build()

        dateRangePicker.show(childFragmentManager, "tag")
        dateRangePicker.addOnPositiveButtonClickListener {
            println(it.first)
            println(it.second)

        }


text:
Q: Create a dictionary of the list I want to create a dictionary whose values are lists. For example:
"data": {"1": {"id": 1,
               "name": test1,
               "description":yyyyy},
         "2": {"id": 2,
               "name": test2,
               "description":xxxxx}}

When I do this, it just creates in the list - [] but I want to get all the values in the list as dictionary - {}:
data = []
for x in Test.objects.filter(act=True):
    data.append({"%s" % x.id:{"id":"%s" % x.id, "name": "%s" % x.name, "description": "%s" % x.description})
ins = {}
ins['instance'] = data

Result:
"data": [{"1": {"id": 1,
                "name": test1,
                "description":yyyyy}},
         {"2": {"id": 2,
                "name": test2,
                "description":xxxxx}}]

A: In your example, there are no lists. There is a dictionary with nested dictionaries. Try...
data = {}
for x in Test.objects.filter(act=True):
    data["%s" % x.id] = {"id":"%s" % x.id, "name": "%s" % x.name, "description": "%s" % x.description}

ins = {}
ins['instance'] = data

or
data = {}
for x in Test.objects.filter(act=True):
    data[str(x.id)] = {"id":str(x.id), "name": str(x.name), "description": str(x.description)}

ins = {}
ins['instance'] = data

A: First, you don't show any lists in your question. What you have there in your desired example is a dictionary whose values are also a dictionary. Brackets [] denote lists. Braces {} denote dictionaries. Lists are an ordered array of items. Dictionaries store values in key:value pairs.
Second, there's really no point to making a dictionary with keys numbered serially like that.You could simply have a list of dictionaries and refer to each item by the list index instead.
You should also name your variables for what they are rather than just x or test1 or yyyyy.
So as for your question, it sounds like you have some values like [1,test1,yyyyy] or say [x.id,x.name,x.description] where each item corresponds in order to: id,name, and description I believe the way you want to sort this data is as such:
data=[
    {"id":1,"name":test1,"description":yyyyy},
    {"id":2,"name":test2,"description":xxxxx}
]

So your code might look something like
data=[]
for x in Test.objects.filter(act=True):
    data.append({"id":x.id,"name":x.name,"description":x.description})

#Or as a list comprehension:
#data=[{"id":x.id,"name":x.name,"description":x.description} for x in Test.objects.filter(act=True)]

Then you can access your data like such
for item in data:
    print("""\
ITEM ID: {}
ITEM NAME: {}
ITEM DESCRIPTION: {}
---------------------""".format(item["id"],item["name"],item["description"]))

If you REALLY wanted to format your data exactly how you described in your post:
the_dict={}
for index, x in enumerate(Test.objects.filter(act=True)): #assuming this is a list of objects
    the_dict[str(index+1)]={"id":x.id,"name":x.name,"description":x.description}
    #the +1 to start keys at 1 as in your example, instead of 0

Edit: Actually, after re-reading your example, it sounds like you want the ID to be the key in the dictionary, not just numbered arbitrarily from 1-n...
In that case, as long as you're sure there's no duplicate IDs (dict keys must be unique) :
the_dict={}
for x in Test.objects.filter(act=True):
    the_dict[str(x.id)]={"id":x.id,"name":x.name,"description":x.description}


text:
Q: Why is it recommended to declare functions as "friends" in operator overloading I have read this at many places which recommend of using "friend" while overload operators but no body explained it clearly as to why it is really needed? Why can not we declare them as plain member function? Any shortcoming?
Googled this but did not get any clear answer.

A: Sometimes you can't declare operator overload as a member function, like in IO operator<< and operator>>. The first parameter of these functions has to be ostream or istream, which are library classes and you can't extend them, declaring such functions as friend gives them access to private variables of your class.

A: Using friend means it's a nonmember friend function.
For improving encapsulation by minimizing dependencies, it's better to declare nonmember nonfriend functions. If it need to access the private/protected member of the class, make it friend. At last, make it a member function.
Here's an algorithm to determine whether a function should be a member and/or friend, from [C++ Coding Standards: 101 Rules, Guidelines, and Best Practices By Herb Sutter, Andrei Alexandrescu](Item 44. Prefer writing nonmember nonfriend functions):
// If you have no choice then you have no choice; make it a member if it must be:

If the function is one of the operators =, ->, [], or (), which must be members:

    Make it a member.

// If it can be a nonmember nonfriend, or benefits from being a nonmember friend, do it:

Else if: a) the function needs a different type as its left-hand argument (as do operators >> or <<, for example); or b) it needs type conversions on its leftmost argument; or c) it can be implemented using the class's public interface alone:

    Make it a nonmember (and friend if needed in cases a) and b) ).

    If it needs to behave virtually:

        Add a virtual member function to provide the virtual behavior, and implement the nonmember in terms of that.

Else: Make it a member.

In some case, such as above-mentioned a) and b), you can't achieve them by member function, you have to declare them as nonmember function, and make them friend if need to access the private/protected member of the class.

A: There are a few reasons people use friend:

*

*sometimes granting friendship is actually reasonable, as the public API shouldn't expose some members than need to be compared

*it's convenient for a lazy programmer to grant access to all the private and protected data members, ensuring you can write the operator implementation without needing to go back to grant access later or use a less obvious/direct public function (that's NOT a good reason, just a lazy one)

*you can define the operator function inside the class, where any template parameters, typedefs, constants etc. don't need to be explicitly qualified as they would in the surrounding [namespace] scope.  That's considerably simpler for those new to C++.
e.g.:
    template <typename T>
    struct X
    {
        friend bool operator==(const X& lhs, const X& rhs) { ... }
    };

...vs...
       ...struct X as above without ==...
    template <typename T>
    bool operator==(const X<T>& lhs, const X<T>& rhs) { ... }

*

*in a two-birds-with-one-stone scoop, it makes the function nominally inline, avoiding One Definition Rule complications

Only the first reason above is a compelling functional reason for making the operator a friend, rather than making it a non-member function, given the lesser encapsulation and correspondingly higher maintenance burden involved.
There are excellent reasons though to prefer either a friend or non-friend non-member function to a member function, as an implicit constructor can then kick in to allow the operator to work with one instance of the class and another value from which a second instance can be constructed:
struct X { X(int); };
bool operator==(const X& lhs, const X& rhs);

x == 3;   // ok for member or non-member operator==
3 == x;   // only works for non-member operator== after implicit X(3) for lhs

A: You are listing two options only for overloaded operator, while actually there are three:

*

*global function, not friend

*member function

*global function, friend of the class

You did not list the first one, and yet it is the recommended one. If you can define an operator in terms of existing class public interface, define it as global function outside the class. In this way you do not extend the class public interface without need, minimizing the number of functions with access to the class private members.
What to do if the operator needs to access the class private members? Then you have two options - member function or a friend global function. From those two member function is preferable because it is cleaner. However, in some cases it is not possible to define an overloaded operator as the member function. If the object of your class is right-hand argument to two-argument operator, then global function is the only choice.

A: I assume that we are comparing global-scope friends that are defined in class and non-friends.
The reasons that the former is sometimes preferred are that such functions...

*

*... need access to the data members for the operation to be performed. This can also be done by loosening encapsulation by providing the data through public getters, but that's not always desired.

*... shall only be found via ADL to avoid pollution of some namespaces and overload candidate sets. (Only friend functions that are defined in the class they are a friend of satisfy this!)
Moreover, a minor goodie is that for class templates, it's easier to define a global function that operates on specializations  inside them since we avoid making the function a template. Also the function is implicitly inline. All this shortens the code, but is no primary reason.

A: If your implementation followed proper data encapsulation then you might not exposed your data variables to outside world and all data members will be declared as private.
But using operator overloading most of the times you will be accessing the data members , please note it here you will be accessing the data members outside your class. So to provide access to the data members  outside your class it is advised to declare the operator overloaded function as friend.
But this might not be required for unary operators , as it will operate on the data members of the particular class in which it is called.
Let me know if you need any examples for your understanding.

A: There are serious advantages to non-member functions when dealing with operators.
Most operators are binary (take two arguments) and somewhat symmetrical, and with a member operator they only work if *this is the left-hand side argument.  So you need to use a non-member operator.
The friend pattern both gives the operator full access to the class (and, operators are usually intimate enough that this isn't harmful), and it makes it invisible outside of ADL.  In addition, there are significant advantages if it is a template class.
Invisible outside of ADL lets you do crazy stuff like this:
struct bob {
  template<class Lhs, class Rhs>
  friend bob operator+( Lhs&&, Rhs&& ) { /* implementation */ }
}

here our operator+ is a template that seemingly matches anything.  Except because it can only be found via ADL on bob, it will only be matched if it is used on at least one bob object.  This technique can let you pick up on rvalue/lvalue overloads, do SFINAE testing on properties of types, etc.
Another advantage with template types is that the operator ends up not being a template function.  look here:
template<class T>
struct X {};

template<class T>
bool operator==( X<T>, X<T> ) { return true; }

template<class T>
struct Y {
  friend bool operator==( Y, Y ) { return true; }
};

struct A {
  template<class T>
  operator X<T>() const { return {}; }
};

struct B {
  template<class T>
  operator Y<T>() const { return {}; }
};

int main() {
  A a;
  X<int> x;
  B b;
  Y<int> y;
  b == y; // <-- works!
  a == x; // <-- fails to compile!
}

X<T> has a template operator==, while Y<T> has a friend operator==.  The template version must pattern-match both arguments to be a X<T>, or it fails.  So when I pass in an X<T> and a type convertible to X<T>, it fails to compile, as pattern matching does not do user defined conversions.
On the other hand, Y<T>'s operator== is not a template function.  So when b == y is called, it is found (via ADL on y), then b is tested to see if it can convert to a y (it can be), and the call succeeds.
template operators with pattern matching are fragile.  You can see this problem in the standard library in a few points where an operator is overloaded in ways that prevent conversion from working.  Had the operator been declared a friend operator instead of a public free template operator, this problem can be avoided.


text:
Q: Not able to connect with MySQL server to Spring Application in Docker? i'm new to Docker, as a part of dockerization of spring mvc application , i'm  not able to connect my application to MySQL server

Dockerfile :this is Spring mvc application so need to copy my war to

 tomcat container
    FROM tomcat:8.0.20-jre8
    COPY /target/CTH.war /usr/local/tomcat/webapps/

docker-compose.yml

  version: '3'
services:
  mysql-standalone:
    image: 'mysql:5.7'
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    volumes:
      - ./docker/provision/mysql/init:/docker-entrypoint-initdb.d
    environment:
      - MYSQL_ROOT_PASSWORD= root
      - MYSQL_USER= root
      - MYSQL_PASSWORD= root
      - MYSQL_DATABASE= CTH
      - MYSQL_DATABASE= CTH_CHAT
    ports:
      - "3307:3306"
  cth-docker-container:
    image: cth-docker-container
    ports:
      - "8082:8082"
    environment:
      CTH_DATASOURCE_DATABASE: CTH
      CTH_DATASOURCE_SERVERNAME: mysql-standalone
      CTH_DATASOURCE_USERNAME: root
      CTH_DATASOURCE_PASSWORD: root
      CTH_DATASOURCE_PORT: 3307

      CTH_CHAT_DATASOURCE_DATABASE: CTH_CHAT
      CTH_CHAT_DATASOURCE_SERVERNAME: mysql-standalone
      CTH_CHAT_DATASOURCE_USERNAME: root
      CTH_CHAT_DATASOURCE_PASSWORD: root
      CTH_CHAT_DATASOURCE_PORT: 3307

    build:
      context: "./"
      dockerfile: "Dockerfile"
    depends_on:
      - mysql-standalone

application.properties :this is spring mvc application and application uses MySQL db with two databases

1st db
dbuser.local=${CTH_DATASOURCE_USERNAME:root}
dbpassword.local=${CTH_DATASOURCE_PASSWORD:root}
dbdatabaseName.local=${CTH_DATASOURCE_DATABASE:CTH}
dbserverName.local=${CTH_DATASOURCE_SERVERNAME:localhost}
dbportNumber.local=${CTH_DATASOURCE_PORT:3306}

2nd db
dbuser.cth.chat.local=${CTH_CHAT_DATASOURCE_USERNAME:root}
dbpassword.cth.chat.local=${CTH_CHAT_DATASOURCE_PASSWORD:root}
dbdatabaseName.cth.chat.local=${CTH_CHAT_DATASOURCE_USERNAME:CTH_CHAT}
dbserverName.cth.chat.local=${CTH_CHAT_DATASOURCE_SERVERNAME:localhost}
dbportNumber.cth.chat.local=${CTH_CHAT_DATASOURCE_PORT:3306}

i read articles from which i created dockerfile and docker-compose file https://medium.com/@asce4s/dockerize-spring-mvc-application-a9ffbd11eadb https://github.com/abagayev/docker-bootstrap-collection/tree/master/mysql-few-databases/docker/provision/mysql/init

but i'm getting following erros when i execute
docker-compose -f docker-compose.yml up

Caused by: com.mysql.cj.core.exceptions.CJCommunicationsException: Communications link failure
cth-docker-container_1  |
cth-docker-container_1  | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
cth-docker-container_1  |       at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
cth-docker-container_1  |       at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
cth-docker-container_1  |       at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
cth-docker-container_1  |       at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
cth-docker-container_1  |       at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
cth-docker-container_1  |       at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:93)
cth-docker-container_1  |       at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:133)
cth-docker-container_1  |       at com.mysql.cj.core.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:149)
cth-docker-container_1  |       at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:83)
cth-docker-container_1  |       at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:122)
cth-docker-container_1  |       at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1754)
cth-docker-container_1  |       at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1624)
cth-docker-container_1  |       ... 125 common frames omitted
cth-docker-container_1  | Caused by: java.net.UnknownHostException: mysql-standalone
cth-docker-container_1  |       at java.base/java.net.InetAddress$CachedAddresses.get(InetAddress.java:797)
cth-docker-container_1  |       at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1505)
cth-docker-container_1  |       at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1364)
cth-docker-container_1  |       at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1298)
cth-docker-container_1  |       at com.mysql.cj.core.io.StandardSocketFactory.connect(StandardSocketFactory.java:179)
cth-docker-container_1  |       at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:57)
cth-docker-container_1  |       ... 128 common frames omitted

i'm stuck and not getting if i have set wrong environment or my way is not correct your any suggestion i'll definitely help me
thanks!

A: After reading lots of articles, I got success to up my application with MySQL db in a docker container and access in Mysql workbench.
here is my docker-compose file
version: '3'

services:
  app:
    container_name: cth-app
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - '8080:8080'
    environment:
      ##db1
      CTH_DATASOURCE_DATABASE: CTH
      CTH_DATASOURCE_HOST: mysqldb
      CTH_DATASOURCE_USERNAME: cth
      CTH_DATASOURCE_PASSWORD: root
      CTH_DATASOURCE_PORT: 3306

      ##db2
      CTH_CHAT_DATASOURCE_DATABASENAME: CTH_CHAT
      CTH_CHAT_DATASOURCE_HOST: mysqldb
      CTH_CHAT_DATASOURCE_USERNAME: cth
      CTH_CHAT_DATASOURCE_PASSWORD: root
      CTH_CHAT_DATASOURCE_PORT: 3306
    depends_on:
      - mysqldb

  mysqldb:
    image: mysql/mysql-server:5.7
    container_name: mysqldb
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    ##here i am able to access dump file which I'll create two databases
      with user created for me.
    volumes:
      - ./docker/provision/mysql/init:/docker-entrypoint-initdb.d
    ports:
      - '3308:3306'
    environment:
        MYSQL_ROOT_PASSWORD: root
        MYSQL_USER: cth
        MYSQL_PASSWORD: root

you need to create a dump file refer the article [ https://github.com/abagayev/docker-bootstrap-collection/tree/master/mysql-few-databases]

when you'll  docker-compose up -d --build
your application is up running on port 8080, with MySQL DB running inside a host machine
Thanks!


text:
Q: My selenium browser won't close in Python I'm trying to create a class that will have methods to test http proxies one by one until I have a working one that I can add to to a selenium webdriver instance.
I have a raw_input to verify that the proxy is working in the webdriver, if it isn't working it should test another proxy and ask for confirmation from me and then either close the driver or stay open. (I removed the if statement that uses the test method because I was getting an error)
When I enter 'n' in terminal when I get asked for confirmation it closes the browser and opens another one with another proxy but when I enter 'n' a second time the browser stays open.
class Driver:

    def test(self):
        try:
            urllib.urlopen(
                "https://www.google.com",
                proxies={'http': proxy}
            )
            return True
        except IOError:
            print "Connection error! (Check proxy)"
        else:
            return False

    def get_driver(self):
        proxies = []
        with open('working_proxies.txt', 'rb') as working_proxies:
            for proxy in working_proxies:
                proxy.rstrip()
                proxies.append(proxy.decode('ascii'))
        for i in proxies:
            try:
                myproxy = proxies.pop()
                proxy   = Proxy({
                              'proxyType': ProxyType.MANUAL,
                              'httpProxy': myproxy,
                              'ftpProxy': myproxy,
                              'sslProxy': myproxy,
                              'noProxy': '' # set this value as desired
                              })
                driver = webdriver.Firefox(proxy=proxy)
                is_working = raw_input('Is your proxy working? [y/n]: ')
                if is_working == 'y' or is_working == 'Y':
                    return driver
                if is_working == 'n' or is_working == 'N':
                    driver.close()
                    continue
                if not is_working == 'y' or is_working == 'Y' or is_working == 'n' or is_working == 'N':
                    print 'Invallid'
            except:
                continue

driver = Driver()
driver = driver.get_driver()
driver.get("https://www.google.com")

A: You can try driver.quit() instead of driver.close()


text:
Q: create table that has a date item in sqlite3 database in python I'm making a database for a website and it needs to take the users input of a date but I think I can do that bit. The part I'm struggling to do is create a table with the date item. What do I need to tell it to do when creating the table I've gotcreate table Results (GameID integer,Date ???????, primary key(GameID)
I just need to to know what I set date to as its not an integer real or text.
I'm using python 3.2

A: SQLite does not have a built-in date type.
SQLite can store dates as a string or a number.


text:
Q: Download android-ndk-r9-linux-x86 I am trying to find somewhere link to download android-ndk-r9-linux-x86 but unfortunately all my tries failed.
Can someone provide me a working link, so I can Download Android NDK R9 for linux x86.

A: The link from here seems to work:
http://dl.google.com/android/ndk/android-ndk-r9c-linux-x86.tar.bz2
You can then set up with the instructions here. You may also find this of help.

A: The specific version you requested, r9 without a letter suffix, although not linked on the download page, currently appears to be able to be obtained by taking one of the current-version links and simply editing it to change the version number to the one you want.  However, it's not a given that this will continue to be the case - the android downloads seem to move around a fair amount.
http://dl.google.com/android/ndk/android-ndk-r9-linux-x86.tar.bz2
Of course if you don't need that exact version you can simply follow the link to a current version on the download page.


text:
Q: Lambda for getter and setter of property In C# 6.0 I can write:
public int Prop => 777;

But I want to use getter and setter.
Is there a way to do something kind of the next?
public int Prop {
   get => propVar;
   set => propVar = value;
}

A: C# 7 brings support for setters, amongst other members:

More expression bodied members
Expression bodied methods, properties etc. are a big hit in C# 6.0,
  but we didn't allow them in all kinds of members. C# 7.0 adds
  accessors, constructors and finalizers to the list of things that can
  have expression bodies:
class Person
{
    private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
    private int id = GetId();

    public Person(string name) => names.TryAdd(id, name); // constructors
    ~Person() => names.TryRemove(id, out _);              // finalizers
    public string Name
    {
        get => names[id];                                 // getters
        set => names[id] = value;                         // setters
    }
}

A: First of all, that is not lambda, although syntax is similar.
It is called "expression-bodied members". They are similar to lambdas, but still fundamentally different. Obviously they can't capture local variables like lambdas do. Also, unlike lambdas, they are accessible via their name:) You will probably understand this better if you try to pass an expression-bodied property as a delegate.
There is no such syntax for setters in C# 6.0, but C# 7.0 introduces it.
private int _x;
public int X
{
    get => _x;
    set => _x = value;
}

A: There is no such syntax, but the older syntax is pretty similar:
    private int propVar;
    public int Prop
    {
        get { return propVar; }
        set { propVar = value; }
    }

Or
public int Prop { get; set; }


text:
Q: Video is not playing using mediaplayer and surfaceview public  class PlayVideoActivity extends Activity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);
        Intent intent=getIntent();
        int no=intent.getIntExtra("index",0);
        Toast.makeText(getBaseContext(),"Hello",Toast.LENGTH_SHORT).show();
        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setFixedSize(176, 144);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDisplay(surfaceHolder);

        try {
            mediaPlayer.setDataSource(MainActivity.musicPath[no]);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mediaPlayer.start();
    }

I'm trying to play video using mediaplayer and surface view, but it is not playing,i writing my code here .please tell me the what is the problem in my code? thanks in advance
.......................................................................................................................................................................................


text:
Q: wiki site doesn't appear in tfs Just now I've set up a new wiki page in our TFS, but it doesn't show up by another computer/colleague. What could be the reason?

A: I would bet it's security within SharePoint. Whenever adding users to a TFS project, they must be added to not only TFS, but also the SharePoint site and SQL reporting.

A: It could be that your changes aren't checked in yet.  Click on "Team Wiki" then select "Home" and see if an option to "Check In" is available.


text:
Q: Story where telekinesis is used to stop nuclear bombs Does anyone remember the name of a story and the author where the USA uses telepaths/telekinesis to prevent Russian nuclear bomb from detonating?

A: Another one is the novel Psychic Warrior by Bob Mayer and Robert Doherty. Published in 2000
Both US and Soviet use psychic warriors. The title matches the book, it is the primary theme of the book. Bombs are "launched" via psi as well as stopped via psi battle.

A: This happens in Robert Heinlein's 1953 short story Project Nightmare.  The bombs are not dropped, but are smuggled into the US and hidden in various places.  A team of psychics is used to locate the bombs and prevent them from exploding.
Spoiler:

 they don't get them all

A: Could this be Kurt Vonnegut's "The Report on the Barnhouse Effect"?
It features a professor who discovers telekinesis and becomes the first "weapon with a conscience", choosing to disable all weapons as soon as they're exposed. The story is told from the viewpoint of an ex-student who follows in his footsteps.

"Gentlemen," I read aloud, "As the first superweapon with a conscience, I am removing myself from your national defense stockpile. Setting a new precedent in the behavior of ordnance, I have humane reasons for going off. A. Barnhouse."


text:
Q: Gradle multi-poject build api(project(..)) dependencies stoped working So I got this project in kotlin that consists of multiple sub projects. All of them are link with single settings.gradle file. It was all working fine until after a week of coding another part I noticed that i get a lot of compilation errors from one of the modules. So I started digging and found out that Intellij couldn't import classes from another sub project even though it is dependent on it via api project(':lib:content:model'). I couldn't figure out the reason why it stopped working and tried to build the project without intellij, just with graddlew. Then i got strange error:
command: ./gradlew :lib:game:model:build
FAILURE: Build failed with an exception.

* What went wrong:
Circular dependency between the following tasks:
:lib:game:model:classes
\--- :lib:game:model:compileJava
     +--- :lib:game:model:compileKotlin
     |    +--- :lib:game:model:jar
     |    |    +--- :lib:game:model:classes (*)
     |    |    +--- :lib:game:model:compileJava (*)
     |    |    +--- :lib:game:model:compileKotlin (*)
     |    |    \--- :lib:game:model:kaptKotlin
     |    |         +--- :lib:game:model:jar (*)
     |    |         \--- :lib:game:model:kaptGenerateStubsKotlin
     |    |              \--- :lib:game:model:jar (*)
     |    \--- :lib:game:model:kaptKotlin (*)
     \--- :lib:game:model:jar (*)

(*) - details omitted (listed previously)

I tried to google my way out of it but none of the suggestions from the internet worked for me. The strangest thing is that it USED to work when i was writing it previously. Then i just switched to another module and when i came back it was all like this, broken =(
I tried to isolate bugged code into test and ended up with lib module containing two sub modules content and game. Another one is project-types module where I store gradle plugins to overcome configuration duplication. content project just have one subproject called model and game project has three: api, impl, and also 'model`.
lib->game->model project depends on lib->content->model
lib->game->impl project depends in lib->game->api
So another really strange thing is that lib->game->impl WORKD just fine and compiles even when he is dependent on lib->game->api. But the same thing doesn't work for 'lib->game->model' which uses THE SAME mechanism to depend on 'lib->content->model'
So I'm lost and don't know what to do. There is a good reason I need all of them to be different projects but I don't want to put myself through the hell of publishing new artifact to local repo every time I change code in one of them. Can someone please help me fix it T-T
My ./gradlew -q projects output:
------------------------------------------------------------
Root project 'test'
------------------------------------------------------------

Root project 'test'
\--- Project ':lib'
     +--- Project ':lib:content'
     |    \--- Project ':lib:content:model'
     \--- Project ':lib:game'
          +--- Project ':lib:game:api'
          +--- Project ':lib:game:impl'
          \--- Project ':lib:game:model'

Included builds
\--- Included build ':project-types'

project-types contains common and kotlin-project sub projects.
common build.gradle:
plugins {
    id 'groovy-gradle-plugin'
}
repositories {
    mavenCentral()
}

and commons.gradle file inside src:
plugins {
    id 'java'
}

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    implementation 'com.fasterxml.jackson.core:jackson-core:2.13.4'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.4'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.4'
    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.4'
    implementation 'com.fasterxml.jackson.module:jackson-module-paranamer:2.13.4'

    implementation 'org.slf4j:slf4j-api:1.7.36'
    implementation 'ch.qos.logback:logback-classic:1.2.11'

    implementation 'commons-io:commons-io:2.11.0'
    implementation 'org.apache.commons:commons-lang3:3.12.0'
    implementation 'commons-codec:commons-codec:1.15'
}

kotlin-project build.gradle file:
dependencyResolutionManagement {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
        google()
    }
}

rootProject.name = 'project-types'

include 'commons'
include 'kotlin-project'

and it's kotlin-project.gradle file inside src:
plugins {
    id 'commons'
    id 'org.jetbrains.kotlin.jvm'
    id 'org.jetbrains.kotlin.kapt'
}

dependencies {
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    implementation 'org.jetbrains.kotlin:kotlin-reflect'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.6.4'

    implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
    testImplementation 'org.mockito:mockito-junit-jupiter:4.8.1'
    testImplementation 'org.mockito.kotlin:mockito-kotlin:4.0.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.1'

}

test {
    useJUnitPlatform()
}

compileKotlin {
    kotlinOptions.jvmTarget = '17'
    kotlinOptions.freeCompilerArgs = ['-Xjsr305=strict', '-Xemit-jvm-type-annotations']
}

compileTestKotlin {
    kotlinOptions.jvmTarget = '17'
    kotlinOptions.freeCompilerArgs = ['-Xjsr305=strict', '-Xemit-jvm-type-annotations']
}

kapt {
    correctErrorTypes = true
}

So my main projects structure is:
My ./setting.gradle file content:
rootProject.name = 'test'

includeBuild 'project-types'

include 'lib:game'
include 'lib:game:model'
include 'lib:game:api'
include 'lib:game:impl'

include 'lib:content'
include 'lib:content:model'

./build.gradle file content
plugins {
    id 'org.jetbrains.kotlin.jvm' version "1.7.21" apply false
    id 'org.jetbrains.kotlin.kapt' version "1.7.21" apply false
}
repositories {
    mavenCentral()
}

./lib/content/model/build.gradle file content:
plugins {
    id 'kotlin-project'
}

group 'cvazer.test'
version '1.0.0'

dependencies {

}

./lib/game/api/build.gradle file content:
plugins {
    id 'kotlin-project'
}

group 'cvazer.test'
version '1.0.0'

dependencies {

}

./lib/game/impl/build.gradle file content:
plugins {
    id 'kotlin-project'
}

group 'cvazer.test'
version '1.0.0'

dependencies {
    api project(':lib:game:api')
}

./lib/game/model/build.gradle file content: (The one with the problem)
plugins {
    id 'kotlin-project'
}

group 'cvazer.test'
version '1.0.0'

dependencies {
    api project(':lib:content:model')
}

A: Gradle has issues resolving dependencies when two subproject names are the same, even if the paths are different.

*

*https://github.com/gradle/gradle/issues/847

*Gradle multiprojects with same name, different paths

*https://discuss.gradle.org/t/dependency-substitution-wrong-with-more-than-one-sub-project-with-same-name/7253
You have two subprojects, both called 'model'

*

*:lib:game:model

*:lib:content:model
Gradle can't distinguish between them.
I would recommend renaming your subprojects to flatter, without nesting, and making the names of each subproject unique.
└── lib/
    ├── game
    ├── game-model
    ├── game-api
    ├── game-impl
    ├── content
    └── content-model


text:
Q: Lift inner div out of its parent with negative margin I'm trying to lift an inner div outside of its parent with the negative margin.
Supposing the following structure:

* {
  margin: 0;
  padding: 0;
}

.grand-parent {
 height: 300px;
 width: 100%;
 background: pink;
}

.parent {
  height: 150px;
}

.grey {
  background-color: grey;
}

.child {
  height: 50px;
}

.required {
  width: 70%;
  background-color: yellow;
}

Neighboring parent

          Required Heading

          Other Heading

I would like to lift the "Required heading" as well as all the consequent tags up, outside the parent element by applying the negative margin, so that the parent's background/margins are not affected. I am able to achieve this behavior when there is another child element coming before the "Required heading", like that:

* {
  margin: 0;
  padding: 0;
}

.grand-parent {
 height: 300px;
 width: 100%;
 background: pink;
}

.parent {
  height: 150px;
}

.grey {
  background-color: grey;
}

.child {
  height: 50px;
}

.first {
  background-color: lightgrey;
}

.required {
  width: 70%;
  background-color: yellow;
  margin-top: -120px;
}

Neighboring parent

With another child

          Required Heading

          Other Heading

But without the "first child" the "Required header" actually lifts the parent fully, like so:

* {
  margin: 0;
  padding: 0;
}

.grand-parent {
 height: 300px;
 width: 100%;
 background: pink;
}

.parent {
  height: 150px;
}

.grey {
  background-color: grey;
}

.child {
  height: 50px;
}

.first {
  background-color: lightgrey;
}

.required {
  width: 70%;
  background-color: yellow;
  margin-top: -120px;
}

Neighboring parent

          Required Heading

          Other Heading

Can this be achieved without introducing another element?


text:
Q: Невозможно преобразовать значение типа '[ArrayImages]' в ожидаемый тип аргумента '[UIImage?]' Получаю ошибку

Cannot convert value of type '[ArrayImages]' to expected argument type '[UIImage?]'

struct ArrayImages: Hashable {
var asset: PHAsset
var image: UIImage
}

@State var imagePost: [ArrayImages] = []

и далее передаю в
uploadImages (images: **imagePost** , itemId: save.id) {(imageLinkArray) в // <- ошибка тут

save.imagePost = imageLinkArray

сама функция такая
let storage = Storage.storage ()

func uploadImages (images: [UIImage?], itemId: String, завершение: @escaping (_ imagePost: [String]) -> Void) {

    var uploadedImagesCount = 0
      var imageLinkArray: [String] = []
      var nameSuffix = 0

      for image in images {
          let fileName = "ItemImages/" + itemId + "/" + "\(nameSuffix)" + ".jpg"
        let imageData = image!.jpegData(compressionQuality: 0.8)

          saveImageInFirebase(imageData: imageData!, fileName: fileName) { (imagePost) in

              if imagePost != nil {
                  imageLinkArray.append(imagePost!)
                 uploadedImagesCount += 1

                  if uploadedImagesCount == images.count {
                      completion(imageLinkArray)
                  }
              }
          }
          nameSuffix += 1
      }
}

A: вы передаете в метод uploadImages [ArrayImages] вместо [UIImage?], вам нужно либо изменить параметр на images: [ArrayImages], либо сначала сформировать массив [UIImage?]


text:
Q: How to convert V24 drawables to something lower that is compatible with older APIs I have noticed that some of my drawables say v24 (some are JPGs and some are PNGs). This wasn't an issue until I started testing on older APIs. My lowest compatibility I'm shooting for is API 23, but v24 isn't supported and my app keeps crashing.

A: Viewing the project as "Android" will hide drawable v24 folder. View the project as "Project Files" and you can navigate to both drawable and drawable v24 folders. From here click and drag your drawables to drawable folder.


text:
Q: How to keep the FAB toolbar open after clicking a button inside it? I am using angular material for my ionic app. I came across the fab tool bar and I have included it in my app.
Here is a demo provided in the angular material guide.
FAB toolbar demo.
This is my code:
<md-fab-toolbar md-open=true md-direction='left'>
<md-fab-trigger class="align-with-text">
  <md-button aria-label="menu" class="md-fab md-primary">
    <md-icon md-svg-src="img/icons/menu.svg"></md-icon>
  </md-button>
</md-fab-trigger>
<md-toolbar>
  <md-fab-actions class="md-toolbar-tools">
    <md-button aria-label="comment" class="md-icon-button">
      <md-icon md-svg-src="img/icons/ic_comment_24px.svg"></md-icon>
    </md-button>
    <md-button aria-label="label" class="md-icon-button">
      <md-icon md-svg-src="img/icons/ic_label_24px.svg"></md-icon>
    </md-button>
    <md-button aria-label="photo" class="md-icon-button">
      <md-icon md-svg-src="img/icons/ic_photo_24px.svg"></md-icon>
    </md-button>
  </md-fab-actions>
</md-toolbar>

The fab tool bar keeps getting closed whenever we press any button inside its content. Is there any way to keep the FAB toolbar open even after clicking a button inside it?

A: This looks like an open issue:
https://github.com/angular/material/issues/4973

A: As mentioned by lj-wizard, there is an open issue on github.
https://github.com/angular/material/issues/5124
You can try using md-fab-speed-dial as the issue does not occur.
https://material.angularjs.org/latest/api/directive/mdFabSpeedDial
If you do not set the animation, the buttons will be permanently visible.


text:
Q: Azure Data Lake Store Access Thru Proxy Using Java SDK I could not see a way to set proxy in Azure Data Lake Store Client SDK. I am working in a corporate network and I have to set proxy while using Azure and ResourceManager classes (.withProxy(..)) to be able to access Azure. Am I missing something or isn't that really available?
Thanks
Edit:
I saw that setting proxy properties did not help. However, I found out that when while creating DataLakeStoreAccountManagementClientImpl, I could use the constructor accepting RestClient. While creating RestClient using "usingProxyAuthenticator" and/or "usingProxy" methods according to needs and passing to client constructor, solved the problem.

A: The SDK itself can't have any proxy settings. You might need to check settings of the IDE (Visual Studio for example) you are using. Another easier way would be to use tools such as Proxifier.


text:
Q: Meaning of "Render onto Caesar the things which are Caesar's"
Render onto Caesar the things which are Caesar's

What does this sentence mean?

A: The quote is "Render unto Caesar the things which are Ceasar's..." and comes from the Bible, Mark 12:17
Since this is a forum for discussion of language rather than exigesis, I will refrain from discussing the possible deeper contextual implications of the phrase, and instead clarify the semantic meaning.
Please be aware that the quote you have referenced comes from the King James Bible, a  translation of biblical scripture that was carried out some centuries ago and therefore using language that can be mystifying to the modern reader. A more up-to-date translation in common use is the New International Version, which renders the quote thus:

"Give to Caesar what is Caesar's and to God what is God's."

This was in response to a question about whether Jews should pay taxes (or instead resist Roman authority.) Please refer to one of the many biblical study guides or websites for a scriptural analysis, or this Wikipedia article for a good primer (thanks J. M. and Scott Mitchell :-)
This particular biblical quote is used in different contexts to mean any one of a number of different things, but in my experience it is most commonly an exhortation to keep the affairs of religion and politics separate.

A: Jesus' words, "render unto Caesar the things which are Caesar's," (Mt. 22, Mk. 12, Lk. 20 https://www.biblegateway.com/quicksearch/?quicksearch=give+to+Caesar&qs_version=NLT) means exactly what the words say. They manifestly do not mean "pay Caesar's tax," nor do they mean give him YOUR coins with his image on them. His words are a clear and simple statement of how one is to treat the property of others in accordance with the Decalogue. (Exodus 20) It means, "if you have something belonging to Caesar, give it back to him;" and by obvious, undeniable inference, "if not, give Caesar nothing of your own, for he will only use it to support his violent, evil regime of murder, rapine and enslavement."
The question, "Should we pay it (viz., Caesar's tax), or should we not?" (Mark 12) Was asked, as the Gospel of Luke makes abundantly clear, "to trap him in his words so as to hand him over to the power and authority of the governor." (Luke 20) The governor was Pilate, who was responsible for collecting Rome's taxes in Judea. He was ready and able to snuff out the life of anyone who resisted or led others to resist paying Rome's taxes.
Jesus' response was truly brilliant on several accounts. In essence, he told his antagonists exactly what they hoped he would say, but in such a way that his answer completely befuddled them and left them shaking their heads in amazement.  In effect, he walked right into their trap, took the bait, and walked out unscathed, while his trappers looked on dumbfounded by his honesty and their own deceit.
His answer also subtly pointed out the fact that whatever Caesar might claim as his was not lawfully his in accordance with God's law forbidding stealing. (Exodus 20) Everything Caesar "owned" had been acquired unlawfully by force, through conquest, plunder, taxation or enslavement, in other words stolen.
And of course his listeners who were familiar with sacred Jewish Scripture, which would include most Jews of his day, knew that the Hebrew Bible states in at least six places, as in Psalm 24 verse 1, "The Earth is the Lord's and everything in it," which leaves nothing for poor old Caesar.
Finally, when they asked their insidious question, Jesus had them produce the coin used to pay the tax, a Roman denarius with Tiberius Caesar's "graven image" on it (see, Exodus 20), and an inscription referring to him as the "son of the divine Augustus," in competition with Jesus for that title. Since the incident occurred in the Temple precincts where the use of such coins was strictly forbidden by Jewish law, Jesus in effected showed one and all that his questioner who produced the coin was guilty of blasphemy by virtue of having the offending coin on his person.
Jesus knew he was soon to die at the hands of the Roman Empire's agent, Pontius Pilate, but he was not about to allow his death on the cross to be the result of being bamboozled by a venal trick of the chief priests, who, according to Luke, sent "spies" to ask him the entrapping question. When the spies returned to their handlers, no doubt the priests chastised them, "You fools, don't you realize you had him? His words can only mean "don't pay!"
Unable to outwit Jesus, his enemies next sent their henchmen to take him by force and at night as he prayed in the Garden of Gethsemane. The next day they led him off to Caesar and accused him of promoting resistance to Rome's taxes: "This man has been leading our people astray by telling them not to pay their taxes to the Roman government...he is causing riots by his teaching wherever he goes—all over Judea, from Galilee to Jerusalem!" (Luke 23:2-5) https://www.biblegateway.com/passage/?search=Luke+23&version=NLT
Since Pilate left no memoir, it is impossible to know what motivated him to crucify Jesus. The Gospels imply Pilate crucified Jesus on the basis of the false accusation that he had called himself a king, whereas logic dictates he was crucified for his very public opposition to Caesar's tax. Since none of the Evangelists nor any of their informers would have attended Jesus' trail, the accounts of the trial in all four Gospels could only be based on the authors' pure speculation.


text:
Q: Facebook Custom Story Link Not Working in Android but Does in iOS and Web I am posting a custom story onto my Facebook timeline. This is fine and appears the way I expect.
The issue I am having is when I click on the story whilst using the Android Facebook application, the link opens in the browser but then comes up with the message "The page you requested was not found".
I am using the Android FacebookDialog to publish my OpenGraphObject and Action.
These links work fine when I click on the custom story using the iOS Facebook application and on the web version on Facebook.
Anyone else notice this?


text:
Q: c++ accelerate Eigen least squares solver with approximation I'm solving least squares problems using Eigen.
here https://eigen.tuxfamily.org/dox/group__DenseDecompositionBenchmark.html is a good comparison of different solvers to solve for A*x=y in a least squares sense.
I have a lot of very similar problems where the solutions differ only slightly. Can I accelerate some (or all?) of these solvers by initializing them somehow with the close result I already have?
If so, how?


text:
Q: HABTM through Checkboxes Issue Rails 3 I've been having a problem HABTM. I'm following tutorials as I see them but no luck. Here's my code:
class Country < ActiveRecord::Base
  has_and_belongs_to_many :videos
end

class Video < ActiveRecord::Base
  has_and_belongs_to_many :countries
end

Edit View:
<% for country in Country.find(:all) %>
  <%= check_box_tag "video[country_ids][]", country.id, @video.countries.include?(country.id) %>
  <%= label_tag "video[country_ids][]", country.name, :for => "video[country_ids][]" %>

<% end %>

Show View:
  <% for country in @video.countries %>
    <%= country.name %>

  <% end %>

Video Controller:
  def update
    @video = Video.find(params[:id])
    if @video.update_attributes(params[:video])
      flash[:notice] = "Successfully updated video."
      redirect_to video_url
    else
      render :action => 'edit'
    end
  end

And the error in the log:
Started POST "/videos/2" for 127.0.0.1 at Tue Feb 08 15:01:33 -0600 2011
  Processing by VideosController#update as HTML
  Parameters: {"commit"=>"Update Video", "authenticity_token"=>"6y01pmKxB+TEG0pbU6ujDsfwzqQW9eqiXBJfPHQW5+w=", "utf8"=>"✓", "id"=>"2", "video"=>{"name"=>"Video number 1", "vimeo_id"=>"12341234", "country_ids"=>["2", "3", "4", "11", "12", "13"]}}
  [1m[36mVideo Load (0.4ms)[0m  [1mSELECT "videos".* FROM "videos" WHERE ("videos"."id" = 2) LIMIT 1[0m
  [1m[35mCountry Load (0.4ms)[0m  SELECT "countries".* FROM "countries" WHERE ("countries"."id" IN (2, 3, 4, 11, 12, 13))
Completed   in 35ms

ActiveRecord::StatementInvalid (Could not find table 'countries_videos'):
  app/controllers/videos_controller.rb:31:in `update'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (10.6ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.1ms)

The Videos table and the Countries table are not joining thru the HABTM. It says it can't find the countries_videos table. What am I missing?

A: Woops. Ok so I didn't realize that I need to actually create those tables. Got it all working now.
Thanks!


text:
Q: add positive and negative floating point values in c I know, another topic on floating point arithmetic!
I've been trying to wrap my head around this and can't seem to come up with why adding negative floating point values isn't working for me.
If they're both positive values everything is working as expected (returns numbers that aren't wildly out of what was expected, since this is floating point after all).
I'm using the 32bit version, incase it wasn't obvious ;)
I've already read through this: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
And have found various, and great, explanations of floating point arithmetic online – however, I still can't seem to figure out how to add mixed positive and negative values (or case 2, 3, and 4 in the code below).
Here's my code thus far:
int flt32_get_sign (flt32 x) {

    /** shift sign bit right; 0 = pos, 1 = neg */
    return ((x & 0x80000000) >> 31);
}

int flt32_get_exp (flt32 x) {

    /** get biaseed exponent value */
    return ((x & 0x7F800000) >> 23);
}

int flt32_get_val (flt32 x) {

    /** mask off mantissa
    *   make sure implicit one set
    */
    return ((x & 0x7FFFFF) ^ 0x800000);
}

int flt32_left_most_1 (int bits) {

    int position = -1;

    /** make sure working with abs value */
    if (flt32_get_sign(bits) != 0){
        bits = flt32_negate(bits);
    }

    while(bits != 0){
        position++, bits >>=1;
    }

    return position;
}

int flt32_right_most_1 (int bits) {

    int position = -1;

    /** make sure working with abs value */
    if (flt32_get_sign(bits) != 0){
        bits = flt32_negate(bits);
    }

    while (!(bits & 1)){
       position++, bits >>=1;
    }

    return position;
}

flt32 flt32_abs (flt32 x) {

    return (x & 0x7FFFFFFF);
}

flt32 flt32_negate (flt32 x) {

    if (flt32_get_sign(x) == 0){
        /** is possitive */
        return (x ^ 0x80000000);
    }
    /** else is negative */
    return (x & 0x7FFFFFFF);
}

flt32 flt32_add (flt32 x, flt32 y) {

    /**
    *   Possible casses:
    *   1: +x +y; 2: +x -y; 3: -x +y; 4: -x -y
    */

    flt32 sum, x_val, y_val;
    int shift;

    /** Case 1 */
    if (flt32_get_sign(x) == 0 && flt32_get_sign(y) == 0){
        if (flt32_get_exp(x) == flt32_get_exp(y)){
            /** no shifting neccesary
            *   add mantissa's then mask to make sure
            *   we don't get overflow into the exponent bits
            *   then add exponent back to new value
            */
            sum = (x & 0x7F800000) + ((flt32_get_val(x) + flt32_get_val(y)) & 0x7FFFFF);

        } else if (flt32_get_exp(x) > flt32_get_exp(y)){
            /** exponent of x is larger than y
            *   need to right shift y and set its exponent = exponent of x
            */
            shift = (flt32_get_exp(x) - flt32_get_exp(y));
            y_val = flt32_get_exp(x) + (flt32_get_val(y) >> shift);

            sum = x + y_val;

        } else {
            /** exponent x is smaller than y
            *   need to right shift x and set its exponent = exponent of y
            */
            shift = (flt32_get_exp(y) - flt32_get_exp(x));
            x_val = flt32_get_exp(y) + (flt32_get_val(x) >> shift);

            sum = x_val + y;
        }
    }

    /** Case 2 */
    if (flt32_get_sign(x) == 0 && flt32_get_sign(y) == 1){
        if (flt32_get_exp(x) == flt32_get_exp(y)){
            /** no shifting neccesary
            *   add mantissa's then mask to make sure
            *   we don't get overflow into the exponent bits
            *   then add exponent back to new value
            */
            x_val = ((x & 0xFF800000) + flt32_get_val(x));
            y_val = ((y & 0xFF800000) + flt32_get_val(y));

            sum = x_val + flt32_negate(y_val);

        } else if (flt32_get_exp(x) > flt32_get_exp(y)){
            /** exponent of x is larger than y
            *   need to right shift y and set its exponent = exponent of x
            */
            shift = (flt32_get_exp(x) - flt32_get_exp(y));
            y_val = flt32_get_exp(x) + (flt32_get_val(y) >> shift);

            sum = x + flt32_negate(y_val);

        } else {
            /** exponent x is smaller than y
            *   need to right shift x and set its exponent = exponent of y
            */
            shift = (flt32_get_exp(y) - flt32_get_exp(x));
            x_val = flt32_get_exp(y) + (flt32_get_val(x) >> shift);

            sum = x_val + flt32_negate(y);
        }
    }

    return sum;
}

Aside: just an observation that I made while wrapping my head around all of this; it seems that it's great, and even necessary, to understand floating points – but almost every article I've come across, even text books, say to avoid it when possible! :)

A: Case 2 considerations
After  sum = x + flt32_negate(y_val), should sum <  0x800000, you need to normalize answer:  Left shift until not so, decrementing exponent as you go.  Watch for sum == 0 first and return specially formed 0.  You will not check for underflow when decrementing bias exponent once you fix flt32_get_val().
Further difference issue:  Subtraction (+ case 2) must be done such that any bits shifted out as part of shift are brought back in due to the sum <  0x800000 issue.  If any bit remains shifted out, rounding must be assessed and handled.
Consider handing + and - though common routines and vectoring off to adding/subtracting magnitudes.  + cases 1,2,3,4 are  like - case 1,4,3,2.  + case 1,4 are the same, just different sign.  + case 2,3 are negations of each other once you find which is greater in magnitude first.
Consider handling +0, -0 as special cases at first.
You are doing nothing about INF and NAN.  Recommend to save for later, put in stubs for now.

Case 1 considerations
If sum > 0xFFFFFF, you need to right sift and increment exponent, test for exponent overflow and the returning INF.
If you right shift, OP needs to decide on rounding mode and potentially increment answer, again testing for increment exponent, test for exponent overflow and the returning INF.

After making sum, answer reconstitution must be careful to deal with hidden MSBit.
OP is mixing up use of | vs. ^.
OP has a long way to go, I'd estimate OP is 10% done with the add case.


text:
Q: EMF of an ideal cell I know it's a very stupid question but I am confused a little bit right now.
An ideal cell has constant EMF of 7V. When connected in a circuit, the voltage across the cell decreases to 5V.
Can i say that the new EMF of the cell is 5V?
please consider the cell as a non-ideal cell

A: In an ideal cell the internal resistance is zero.  According to the equation
$V=E-Ir$  the $I*r$ term is always zero for an ideal cell.  So, there can not be any voltage drop across the cell after connecting to a circuit that means $V$ is always equal to EMF.


text:
Q: Osculating conics in normal sections of a surface: how to generalize Euler's equation? Well known background: Consider a differentiable surface in $\mathbb{R}^3$ and a point $p$; a normal plane at $p$ is a plane containing the normal vector. It is a classical result that the curvature of the intersection of a normal plane in $p$ and the surface (the normal section) has a curvature in $p$ depending on the normal plane and that maximum and minimum value of this curvature (known as principal curvatures $k_1$ and $k_2$) occur at perpendicular directions of the normal plane.
The dependence of the curvature in the normal section on the angle of the normal plane is given by $k(\alpha) = k_1 \cos^2 \alpha + k_2 \sin^2 \alpha$ with $\alpha$ being the angle with respect to the direction where the principal curvature $k_1$ occurs. Sometimes this equation is called Euler's equation (one of many).
Now we consider in the normal section the osculating conic at $p$ (in the sense of question Osculating conics and cubics and beyond).
Thus we don't have any more an osculating circle defining the curvature $k(\alpha)$ in each normal section, but an osculating conic with in general two focal points, semi-axis and eccentricity.
Some questions seem to be very natural, but I couldn't find any results:

*

*What is the surface built by the set of the osculating conics at a point $p$ (if we vary the normal section)? It does not seem to be an osculating quadric at point $p$ for the reason that the osculating conic in the normal section does not need to be symmetric with respect to the normal vector in $p$, whereas normal sections of an osculating quadric are (or am I mistaken here?).

*How do the characteristic parameters (take e.g. the eccentricity) of
the osculating conics depend on the normal plane, is there an analogous equation to the one of Euler for the curvature (of the osculating circle)?

*Is there an explicit description of this surface in terms of the
partial derivations of $f$, if the surface is given as a graph $f(x,y)$ (let's assume wlog $f_{x}= f_{y} =0$).

*If all the osculating conics in the normal sections are parabolic (in
the sense of the above mentioned question), what does this mean for the original surface at point $p$?


text:
Q: Agrupacion por meses Quiero armar un select con todos los meses con los que se registro algun registro. Para luego crear consultas de esto.
Es decir. Por ejemplo
Se crean registros en el mes de enero-20 , febrero-20, abril-20... Por lo que unicamente en el select tienen que aparecer

*

*enero-20

*febrero-20

*abril-20

Por lo cual estoy haciendo el siguiente scope
public function scopeMonthRecords()
{
    $months = $this->groupBy('date_new')->get();

    return $months;
}

Esto me esta agrupando la consulta por días. Ya probe utilizar de agregar ->format('YY-mm') pero me arroja el siguiente error

BadMethodCallException
  Call to undefined method Illuminate\Database\Eloquent\Builder::format()
  http://intranic.test/reports/panel

Como puedo agruparlo por mes ?

A: Estuve investigando y utilice DB::RAW, para lo que cree el siguiente scope
public function scopeMonthRecords()
{
    $months = $this->orderBy('date_new')->groupBy(DB::raw("MONTH(date_new)"))->get();

    return $months;
}

Con esto ya puedo generar un listado de unicamente los meses donde se crearon registros agrupado por meses.


text:
Q: Python: Convert a Letter Grade to its corresponding integer value I am attempting to troubleshoot the errors in this code.
The program is supposed to handle as many students as the user indicates are in the class. Receive a letter grade: A, B, C, D, F for each student. Finally it will calculate and display the class average.
My code so far:
students = int(input('How many students: '))
total_sum = 0
for n in range(students):
    Letter = input('Enter grades: ')
    Letter_int = Letter
if Letter == "A":
    Letter_int == int(80)
elif Letter == "B":
    Letter_int == int(70)
elif Letter == "C":
    Letter_int == int(60)
elif Letter == "D":
    Letter_int == int(50)
elif Letter == "F":
    Letter_int == int(40)
    total_sum += Letter_int
avg = total_sum/students
print('Average of this/these', students, 'student(s) is:', avg)

The code isn't adding the integer value of the letter grades, the sum always returns as 0 or TypeError: unsupported operand type(s) for +=: 'int' and 'str'. I am a python novice and I could use some assistance.

A: Here is your code improved and made work. Use it, but please read the comments I provided and analyze what parts I have changed. Also, it would be good to revise Python documentation as others mentioned. Especially indentation and it's meaning in Python.
students = int(input('How many students: '))
total_sum = 0
for n in range(students):
    Letter = input('Enter grades: ')
    Letter_int = 0 # here you better initialize with integer not string
    if Letter == "A": # this condition needs to be indented - you want it to be executed
                      # in every iteration of for loop
        Letter_int = 80 # the assignment in Python is done by "=" not "==" (that would be comparison)
    elif Letter == "B":
        Letter_int = 70 # you do not need to do int(70), 70 is already an integer
    elif Letter == "C":
        Letter_int = 60
    elif Letter == "D":
        Letter_int = 50
    elif Letter == "F":
        Letter_int = 40
    total_sum += Letter_int # this cannot happen inside elif clause - this way it would only be
                            # executed when F grade is provided
    avg = total_sum/students
    print('Average of this/these', students, 'student(s) is:', avg)


text:
Q: undefined reference to `pthread_cancel' I have written the following T class with pthread. When i compile this class using g++ -lpthread then it's working fine. But if i extend this class from another class A and compile all together it's returns an error; "undefined reference to pthread_cancel"
Code:
class T{
private:
    pthread_t thread;
public:
    void start(){
        pthread_create(&thread,NULL,&run,this);
    }
    void destroy_thread(){
        pthread_cancel(thread);
    }
    static void* run(void*){}
    ~Thread(){
        destroy_thread();
    }
};

Next class:
class A:T{
    A(){
      start();
    }
}

Main
int main(){
  A a;
  return 0;
}

Compile:
g++ -c T.cpp A.cpp Main.cpp -lpthread
g++ -o out *.o

Error:
undefined reference to `pthread_cancel'

A: Do this instead:
g++ -pthread -c T.cpp A.cpp Main.cpp
g++ -pthread -o out *.o

-lpthread is a linker flag, it's used only when linking, not compiling, so where you have it isn't correct - the linking part happens in the second step.
And generally don't use -lpthread anyway. Use -pthread both for compiling and linking.
From the GCC manual:

Adds support for multithreading with the pthreads library.  This option sets flags for both the preprocessor and linker.


text:
Q: How to implement Login in Dialogflow chatbot i want to add login to my chatbot with webhook.I want to take username and password from user and send it to the webhook.

A: I know you didn't get much search results for that
there are following approaches

*

*If you use only Google Assistant for chatbot then use built in "Sign-in" required option and then open link https://console.actions.google.com/project/your-project-name/accountlinking/ and in that provide your required settings like
"Do you want signup ?" or "Login Only"
select type of Oauth and Implicit
Enter the endpoint url
and bingo you will get button in Google Assistant for login

*If you wanna add login for web-demo use Detect Intent API
then go for Account linking OAuth2 using either code flow or implicit flow but I would suggest to go for implicit flow first.
there are various resourses out here for each language.
Integrating API you need a service account keys add that to your enviornment for Authentication to google apis
then use detectIntent function to get response  and IMPORTANT use Unique session id
hope you got it ;-)


text:
Q: How to prove that medians were swapped? I have two independed samples: df and df8. The first sample df includes points at the data1 and at the data2. These points were earned in an experimental group (n1=20). The second sample df8 includes points at the data1 and at the data2. But these points are correspond to a control group (n2=21).
From boxplot  we can see that median1< median2, at the data1 and
vice versa at the data2: median1> median2.
)
I would like to prove this fact with the Brown-Mood median test (First sample is not normal.
The null hypothesis: median1= median2. I have tested the null hypothesis at the data2 and at the data1. In both cases the null hypothesis was rejected:
data1: p-value = 0.9211>0.05
data2: p-value = 0.1378>0.05
It means that median1 < median2 twice, at the data1 and data2.
Could someone please correct me and give an idea how to statistically prove that median1< median2 (at the data1) and vice versa median1> median2 (at the data2)?
library(coin)
df <- data.frame(points1 = c(113,   145,    137,    73, 131,    137,    130,    45, 133,    119,
                             115,   127,    156,    141,    95, 119,    121,    120,    163,    134),
                 points2 = c(173,   216,    188,    0,  195,    215,    209,    62, 186,    206,
                             194,   216,    207,    193,    244,    228,    217,    203,    204,    207)
    ))

    df8 <- data.frame(points1 = c(182,  123,    150,    97, 154,    155,    118,    144,    129,    121,                              153,  104,    153,    125,    151,    162,    170,    133,    126,    127, 165),
                      points2 = c(239,  198,    188,    218,    196,    177,    191,    167,    174,    187,
                                  195,  180,    168,    205,    211,    208,    185,    189,    180,    144,    233))

boxplot(df$points1, df8$points1, df$points2, df8$points2, ylab ="Points",
col = c("red", "green", "red", "green"), names = c("exp","con", "exp","con"))

> # Brown-Mood median test
tmp1 <- data.frame(p1 = c(df$points1,df8$points1),
g = factor(rep( c("exp", "con"), c(20, 21))))
(mt1 <- median_test(p1 ~ g, data = tmp1, alternative = "less", distribution = "exact"))

#        Exact Two-Sample Brown-Mood Median Test

#data:  p1 by g (con, exp)
#Z = 1.0842, p-value = 0.9211>0.05
#alternative hypothesis: true mu is less than 0

 tmp2 <- data.frame(p2 = c(df$points2,df8$points2),
g = factor(rep( c("exp", "con"), c(20, 21))))

(mt1 <- median_test(p2 ~ g, data = tmp2, alternative = "less", distribution = "exact"))

#        Exact Two-Sample Brown-Mood Median Test

#data:  p2 by g (con, exp)
#Z = -1.3854, p-value = 0.1378>0.05
#alternative hypothesis: true mu is less than 0

A: *

*Did you notice that your code fails on the first line?

*You should not be rejecting a null hypothesis of equality of population medians ("The null hypothesis: median1= median2") when p-values are larger than your significance level, but rather when they are smaller than it.

*You seem to be trying to do a one tailed test based on the direction of observed difference (which is a complete no-no -- if you didn't specify the direction for the alternative before collecting the data, your test is two tailed), but then in any case it looks like you got the direction wrong on the second test. (Your explanation of what you're doing is very unclear throughout. We can't read your mind. You seem to use "period1" and "data1" to mean the same thing for example, and "con" and "df8" to mean the same thing. This is, to put it plainly, awful practice -- it's very hard to keep things straight if you're not consistent.)

*Your title suggests you're looking for a swap in direction, but your body text suggests the opposite (you test the same direction both times). You should make the actual question of interest more clear. Your whole discussion is very vague.
Here I do a straight randomization test of of no difference in population medians against a two tailed alternative, where the difference in sample medians is the test statistic; it should give somewhat similar results to a permutation test based on the Mood median test (and have equally poor power!).

At the 5% level, we would reject the null in the first instance but not the second.
(If instead of taking the absolute difference in medians as the test statistic we were to double the one-tailed p-value we'd get slightly different p-values but the conclusions at the same significance level would be the same)
Unless you're strongly wedded to the median as a measure of location I'd be more inclined to just use a straight Wilcoxon-Mann-Whitney


text:
Q: PHP ImageMagick getImageType returns array... how to associate with type? The PHP ImageMagick function getImageType returns an array number, but I can't find any documentation as to how to actually associate this with a type.
I need to know if it's a png, jpg, gif, etc...
$image = new Imagick("test.png");
$ext = $image->getImageType();

// prints 6
echo $ext

A: I suggest this way which works fine for me
    $image = new Imagick('image.gif');
    $image->getImageFormat();
    echo $image; // output GIF

A: You could use getimagesizeto get the image size and type. Image type is return at index pos 2.
1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.
Php doc for getimagesize() - http://php.net/manual/en/function.getimagesize.php
Example usage:
list($width, $height, $type) = getimagesize('herp-derp.png');
echo $type;

Edit: Useful comment from phpdoc notes....
In addition to thomporter's quick-reference of the output array, here's what PHP 4.4.0 does:

Array[0] = Width
Array[1] = Height
Array[2] = Image Type Flag
Array[3] = width="xxx" height="xxx"
Array[bits] = bits
Array[channels] = channels
Array[mime] = mime-type

Edit: getImageType returns one of IMAGICK_TYPE_* constants (http://www.phpf1.com/manual/imagick-getimagetype.html). You can find the list of constants here - http://php.net/manual/en/imagick.constants.php .
IMGTYPE constants
imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)

A: A good and quick way to validate images is:
$ identify -format %m image.jpg
JPEG

in PHP:
<?php
// If its not a valid image, returns an empty string.
$image_type = exec('identify -format %m image.jpg');
?>

More about using -format: imagemagick formats

A: getImageType() returns an array if it's successful as per this page.
http://php.net/manual/en/function.imagick-getimagetype.php
maybe try a vardump or a print_r  of $ext?

A: this is the best I could do for you this will give you the extension and you can use that first before you load image
$path_parts  = pathinfo("test.png");
echo $path_parts ['extension'];


text:
Q: C++0x thread interruption According to the C++0x final draft, there's no way to request a thread to terminate. That said, if required we need to implement a do-it-yourself solution.
On the other hand boost::thread provides a mechanism to interrupt a thread in a safe manner.
In your opinion, what's the best solution? Designing your own cooperative 'interruption mechanism' or going native?

A: Here is my humble implementation of a thread canceller (for C++0x).
I hope it will be useful.
// Class cancellation_point
#include <mutex>
#include <condition_variable>

struct cancelled_error {};

class cancellation_point
{
public:
    cancellation_point(): stop_(false) {}

    void cancel() {
        std::unique_lock<std::mutex> lock(mutex_);
        stop_ = true;
        cond_.notify_all();
    }

    template <typename P>
    void wait(const P& period) {
        std::unique_lock<std::mutex> lock(mutex_);
        if (stop_ || cond_.wait_for(lock, period) == std::cv_status::no_timeout) {
            stop_ = false;
            throw cancelled_error();
        }
    }
private:
    bool stop_;
    std::mutex mutex_;
    std::condition_variable cond_;
};

// Usage example
#include <thread>
#include <iostream>

class ThreadExample
{
public:
    void start() {
        thread_ = std::unique_ptr<std::thread>(
            new std::thread(std::bind(&ThreadExample::run, this)));
    }
    void stop() {
        cpoint_.cancel();
        thread_->join();
    }
private:
    void run() {
        std::cout << "thread started\n";
        try {
            while (true) {
                cpoint_.wait(std::chrono::seconds(1));
            }
        } catch (const cancelled_error&) {
            std::cout << "thread cancelled\n";
        }
    }
    std::unique_ptr<std::thread> thread_;
    cancellation_point cpoint_;
};

int main() {
    ThreadExample ex;
    ex.start();
    ex.stop();
    return 0;
}

A: It is unsafe to terminate a thread preemptively because the state of the entire process becomes indeterminate after that point. The thread might have acquired a critical section prior to being terminated. That critical section will now never be released. The heap could become permanently locked, and so on.
The boost::thread::interrupt solution works by asking nicely. It will only interrupt a thread doing something thats interruptible, like waiting on a Boost.Thread condition variable, or if the thread does one of these things after interrupt is called. Even then, the thread isn't unceremoniously put through the meat grinder as, say, Win32's TerminateThread function does, it simply induces an exception, which, if you've been a well-behaved coder and used RAII everywhere, will clean up after itself and gracefully exit the thread.

A: Implementing a do-it-yourself solution makes the most sense, and it really should not be that hard to do. You will need a shared variable that you read/write synchronously, indicating whether the thread is being asked to terminate, and your thread periodically reads from this variable when it is in a state where it can safely be interrupted. When you want to interrupt a thread, you simply write synchronously to this variable, and then you join the thread. Assuming it cooperates appropriately, it should notice that that the variable has been written and shut down, resulting in the join function no longer blocking.
If you were to go native, you would not gain anything by it; you would simply throw out all the benefits of a standard and cross-platform OOP threading mechanism. In order for your code to be correct, the thread would need to shut down cooperatively, which implies the communication described above.

A: Its unsafe to terminate a thread, since you would have no control over the state of any data-structures is was working on at that moment.
If you want to interrupt a running thread, you have to implement your own mechanism. IMHO if you need that, your design is not prepared for multiple threads.
If you just want to wait for a thread to finish, use join() or a future.

A: My implementation of threads uses the pimpl idiom, and in the Impl class I have one version for each OS I support and also one that uses boost, so I can decide which one to use when building the project.
I decided to make two classes: one is Thread, which has only the basic, OS-provided, services; and the other is SafeThread, which inherits from Thread and has method for collaborative interruption.
Thread has a terminate() method that does an intrusive termination. It is a virtual method which is overloaded in SafeThread, where it signals an event object. There's a (static) yeld() method which the running thread should call from time to time; this methods checks if the event object is signaled and, if yes, throws an exception caught at the caller of the thread entry point, thereby terminating the thread. When it does so it signals a second event object so the caller of terminate() can know that the thread was safely stopped.
For cases in which there's a risk of deadlock, SafeThread::terminate() can accept a timeout parameter. If the timeout expires, it calls Thread::terminate(), thus killing intrusively the thread. This is a last-resource when you have something you can't control (like a third-party API) or in situations in which a deadlock does more damage than resource leaks and the like.
Hope this'll be useful for your decision and will give you a clear enough picture about my design choices. If not, I can post code fragments to clarify if you want.

A: I agree with this decision. For example, .NET allows to abort any worker thread, and I never use this feature and don't recommend to do this to any professional programmer. I want to decide myself, when a worker thread may be interrupted, and what is the way to do this. It is different for hardware, I/O, UI and other threads. If thread may be stopped at any place, this may cause undefined program behavior with resource management, transactions etc.

A: All the language specification says that the support isn't built into the language.
boost::thread::interrupt needs some support from the thread function, too:
When the interrupted thread next executes one of the specified interruption points (or if it is currently blocked whilst executing one)
i.e. when the thread function doesn't give the caller a chance to interrupt, you are still stuck.
I'm not sure what you mean with "going native" - there is no native support, unless you are spellbound to boost:threads.
Still, I'd use an explicit mechanism. You have to think about having enough interruption points anyway, why not make them explicit? The extra code is usually marginal in my experience, though you may need to change some waits from single-object to multiple-objects, which - depending on your library - may look uglier.

One could also pull the "don't use exceptions for control flow", but compared to messing around with threads, this is just a guideline.

A: Using native handle to cancel a thread is a bad option in C++ as you need to destroy all the stack allocated objects. This was the main reason they don't included a cancel operation.
Boost.Thread provides an interrupt mechanism, that needs to pool on any waiting primitive.  As this can be expensive as a general mechanism, the standard has not included it.
You will need to implement it by yourself. See my answer here to a similar question on how to implement this by yourself. To complete the solution an interruption should be throw when interrupted is true and the thread should catch this interruption and finish.


text:
Q: Symlinks and Cross-Origin Resource Sharing I have a main site forexample.com, and then I have a second site, forinstance.com.
Both use the same Magento system, but forinstance.com is pointing to all the files in forexample.com using symlinks. This is using Magento for a multi-site.
For forinstance.com, I wanted to add fonts to the font folder (which I thought was shared) and link to it. Unfortunately, with Magento, it seems that if you want to link to something in Magento, you have to link from the main site, not the site you want to use. If I want to use the images folder for forinstance.com, I have to link http://forexample.com/images instead ( I must have it setup wrong). Otherwise, I get a 404 if I link to the images folder using http://forinstance.com
From the CSS I can link to forexample.com just fine. However with fonts, I try to link to http://forexample.com/fonts/font.ttf and i get this error:

Redirect at origin 'http://forexample.com' has been blocked from
  loading by Cross-Origin Resource Sharing policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://forinstance.com' is therefore not allowed
  access.

I can understand that since its not the same URL the browser wouldn't want you to steal from another site, but they're using the same CMS. What can I do?

A: Well, this probably won't work for everything (like dynamic image folders where product images are added), but I simply added a fonts folder to the add-on domain's folder in the server (duh). This way, the fonts are directly in the folder of the domain and there's no need for symlinks.
So instead of trying to reference fonts from the main site through symlinks, I added a folder:
/forinstance.com/
    /admin
    /images
    /forexample.com/ (addon domain)
        /fonts (new folder inside)
    /resources
        /logs
        /svgs
    /fonts (main folder)

Hope that some how makes sense.


text:
Q: Check for separator after every 2 characters Is there a way to check if there is a separator after every 2 characters in a string.
For example:
x = '32-21-44-33':
  # if there is '-' after every 2 digits, return True

# so if x = '231-21-21-21' it would return as False

A: I would phrase your requirement using the regex pattern:
^\d{2}(?:-\d{2})*$

Sample script:
inp = '32-21-44-33'
if re.search(r'^\d{2}(?:-\d{2})*$', inp):
    print("MATCH")   # prints MATCH

A: One way is to slice string and check using all().
If you just want to check that - is at every 3 position in your string, then you can simply do:
>>> my_str = '32-21-44-33'
>>> all(x=='-' for x in my_str[2::3])
True

And if you want to ensure that "-" is present at only at third position and not any where else, then you can use itertools.groupby() as:
>>> from itertools import groupby

>>> all(list(j)[0] == '-' if i else len(list(j))==2 for i, j in groupby(my_str, key=lambda x: x=='-'))
True

However, if you want to ensure that your string is strictly following the pattern of two numbers followed by "-", then you can achieve that by additionally using zip() with sliced strings as:
>>> all(z=='-' and (x + y).isdigit() for x, y, z in zip(my_str[::3], my_str[1::3], my_str[2::3]))
True

A: the best and easiest way is
z = x.split("-")
for j in z:
    if len(j)!=2 :
        print("false")

A: You can use split() with - as a delimiter to break up the words, then use all() to ensure that all have the desired length or other properties:
>>> x = '32-21-44-33'
>>> all(len(s) == 2 for s in x.split('-'))
True
>>> x = '231-21-21-21'
>>> all(len(s) == 2 for s in x.split('-'))
False

If you want to ensure that they are all numeric too:
>>> x = '32-21-44-33'
>>> all(len(s) == 2 and s.isdigit() for s in x.split('-'))
True
>>> x = '32-ab-44-33'
>>> all(len(s) == 2 and s.isdigit() for s in x.split('-'))
False

A: Check every 3rd character to see if it is equal to a dash.  If it isn't, immediately return false.  If you reach the end of the string, return true.
x = 2
while x < len(mystring):
    if mystring[x] != '-':
        return False
    x += 3
return True

A: If you don't know the delimiter there's a easy "comprehensible" way to do it
x = '32-21-45-33'

# split list with the third char of the string, then sort the list by element length

sorted_list = sorted(x.split(x[2]), key=len)

# if your first element length is equal to your last element length all element are the same length

if len(sorted_list[0]) == len(sorted_list[len(sorted_list) - 1]):
   print("ok")
else
    print("nok")

A: Here you get a oneliner returning the bolean + the unknown delimiter
def check_every_n(x,n):
    return (len(list(set([x[i] for i in range(n,len(x)-n) if (i+1) % (n+1) == 0]))) == 1), x[n]

x = '32-21-44-33'

n = 2

print (check_every_n(x,n))

You take your string x, your test n, you use list comprehension to build a list of elements every n in the string, you remove duplicates, if len() = 1 means there is the same element every n, and so you return the bolean check + the delimiter at position n index n - 1.
Output:
(True, '-') # n = 2
(False, '2') # n = 3

Worthless to say, if the boolean is False, the delimiter is meaningless.
With this you can check for any kind of delimiter every n. So you don't need to mention it. Plus you can loop to find any delimiter at any n if you like.
Let say, return bolean and delimiter, if any, with spacing from 2 to len(x)//3 (to allow repeats):
x = '2403-0132-1321-3123'

for n in range(2,len(x)//3):

    print (n,check_every_n(x,n))

Output:
2 (False, '0')
3 (True, '3')
4 (True, '-')
5 (False, '0')


text:
Q: OpenAI Gym environment cannot be loaded in Google Colab I'm trying to train a DQN in google colab so that I can test the performance of the TPU. Unfortunately, I get the following error:
import gym
env = gym.make('LunarLander-v2')

AttributeError: module 'gym.envs.box2d' has no attribute 'LunarLander'

I know this is a common error, and I had this before on my local machine. I was able to fix it with commands like:
!pip install box2d box2d-kengz
!pip install Box2D
!pip install -e '.[box2d]'

While this worked on my local machine, on google colab is it not. I can't get rid of the error. Does anyone have a solution?

A: On a fresh colab, I simply installed box2d-py via
!pip3 install box2d-py

and it worked.
Try it on a new colab it should work.

A: You need to execute at the beginning a cell with the code:
!sudo apt-get install swig build-essential python-dev python3-dev

This should solve your problem and you will be able to install this library in google colab


text:
Q: Remove contour gaps from object Is there any method OpenCV provides or any other methods to smooth the contours:

Here what I want is the smaller gaps in the edge pixels i.e contours need to overlap and the shape of the detected object should come smoothly.
Here is another contour of an object detected; here I reduced the noise but still the contour is not smooth.  Why I'm trying to get smooth edges is so that after this can be divided into lines and curves.
The main thing I want is to jump the smaller gaps in edges.


text:
Q: Random Path generation in a game I want to make a 2D game that generates a frequent random paths between two points on the 2D screen. I have read into the A* algorithm + random obstacle generation to create paths but that algorithm seems a bit time-consuming to learn.
My question is "What are the other types of random path generation algorithms that are appropriate for my situation?" ( Generating random paths between 2 fixed points)

A: Simplest solution I can think of is to generate waypoint nodes that know which other nodes they're connected to, and then randomly choose a connection to follow (possibly with some heuristic to head towards your goal)
eg,
using System.Linq;
public class Waypoint : MonoBehaviour{
    public Waypoint[] Connections;

    public Waypoint Next( Waypoint previous, Waypoint finalDestination) {

        if (this == finalDestination) return null; // You have arrived

        var possibleNext = Connections.Where(m => m != previous && CheckHeuristic(m, finalDestination)); // Dont go backwards, and apply heuristic

        if (possibleNext.Count() == 0) throw new System.ApplicationException("No exitable paths from Waypoint"); // Error if no paths available

        possibleNext = possibleNext.OrderBy( m => Random.Range(0f, 1f)); // 'shuffle'

        return possibleNext.First(); // Grab first 'random' possible path
    }

    private bool CheckHeuristic(Waypoint candidate, Waypoint finalDestination) {
        // Basic 'is not farther' check
        return Vector3.Distance(candidate.transform.position, finalDestination.transform.position) <= Vector3.Distance(this.transform.position, finalDestination.transform.position);
    }
}

Also, "there's no such thing as a free lunch" applies here.  There's always a cost to building stuff like this.  You'll either spend the time learning A*, or you'll spend the time manually creating paths...


text:
Q: Googleway R Alternative routes I'm using the google_directions() function to generate driving routes between two coordinates which are generated on clicking at different points in a leaflet map.I would like to show a few possible routes, instead of just one. Setting alternatives = TRUE does not seem to do the job for me. I've tried multiple coordinates.
    key <- "my_key"
    #lat1,lon1 generated on first click. lat2,lon2 generated on second click.
    df <- google_directions(origin = c(lat1,lon1),
                            destination = c(lat2,lon2),
                            key = key,
                            mode = "driving",
                            simplify = TRUE,
                            alternatives = TRUE)
    pl <- decode_pl(direction_polyline(df))
    leaflet() %>% addTiles() %>% addPolylines(data = pl, lng = ~lon, lat = ~lat,group = "route")

A: I found the issue and have uploaded a fix
In brief, the alternatives argument wasn't correctly being used, as you found out.
If you install the latest development version this should work for you
devtools::install_github("SymbolixAU/googleway")

To show it working, this example will generate two routes
library(googleway)

set_key("api_key")

df <- google_directions(origin = "Melbourne Airport, Australia",
                        destination = "Portsea, Melbourne, Australia",
                        mode = "driving",
                        alternatives = TRUE)

df_routes <- data.frame(polyline = direction_polyline(df))

set_key("map_key", api = "map")

google_map() %>%
  add_polylines(data = df_routes, polyline = "polyline")


text:
Q: How to scrape the link of all links from a webpage and scroll down I am extracting news items from a certain category page of a website in which there is no load-more button; instead, the links to news stories are produced as I scroll down. I created a function that accepts category page url and limit page (the number of times I want to scroll down) as inputs and returns all the links to the news items shown on that page. It was running properly earlier recently I found in each page each news links are in different class which is making very difficult to retirve them back all together. Maybe I'm wrong and I do believe there would be a simpler method.
Category page link = https://www.scmp.com/topics/currencies
This was my try!
def get_article_links(url, limit_loading):

    options = webdriver.ChromeOptions()

    lists = ['disable-popup-blocking']

    caps = DesiredCapabilities().CHROME
    caps["pageLoadStrategy"] = "normal"

    options.add_argument("--window-size=1920,1080")
    options.add_argument("--disable-extensions")
    options.add_argument("--disable-notifications")
    options.add_argument("--disable-Advertisement")
    options.add_argument("--disable-popup-blocking")

    driver = webdriver.Chrome(executable_path= r"E:\chromedriver\chromedriver.exe", options=options) #add your chrome path

    driver.get(url)
    last_height = driver.execute_script("return document.body.scrollHeight")

    loading = 0
    end_div = driver.find_element('class name','topic-content__load-more-anchor')
    while loading < limit_loading:
        loading += 1
        print(f'scrolling to page {loading}...')
        end_div.location_once_scrolled_into_view
        time.sleep(2)

    article_links = []
    bsObj = BeautifulSoup(driver.page_source, 'html.parser')
    for i in bsObj.find('div', {'class': 'content-box'}).find('div', {'class': 'topic-article-container'}).find_all('h2', {'class': 'article__title'}):
        article_links.append(i.a['href'])

    return article_links

Assuming I want to scroll 3 times in this category page and get back all the links on those pages.
get_article_links('https://www.scmp.com/topics/currencies', 3)

But it is neither scrolling nor getting me back the links as the problem faced by me. Any help with this will be really appreciated. Thanks~~

A: This one took a while to solve!
Apparently there is no way of scrolling to the bottom of the page if you don't click it first. And it's also much easier to just send the END key.
I got the idea of sending keys from here.
After scrolling, look for the div that contains all articles, its class is 'css-1279nek ef7usvb8'.
Then use regex to match all href, including only the webpage address. Lastly use set() to get rid of duplicates.
    driver.get(url)
    elem = driver.find_element_by_xpath("//body")
    for i in range(limit_loading):
        action = ActionChains(driver)
        action.click().perform()
        elem.send_keys(Keys.END)
        time.sleep(5)

    bsObj = BeautifulSoup(driver.page_source, 'html.parser')
    article_div = bsObj.find('div', {'class': "css-1279nek ef7usvb8"})
    article_links = list(set(re.findall('href="([\/A-z0-9.-]+)', str(article_div))))