text:
Q: ImageView not getting adjusted according to screen Android? I am working on android application. I have used Listview in one of activity which shows Two image views  and text views. The view should look as follows and in big screen looks fine but on small screen image takes most of space.
Nexus 4 Screen: But if you see images in following ss images are not aligned properly also if textview is bigger.

On Small Screen image acquires most of space. It looks bad as follows:

I want it to be consistent across in terms of layout.
Following is my layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="100" >

    <com.wallie.imagview.SquareImageView
        android:id="@+id/categoryimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="10" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="80"
        android:gravity="left"
        android:orientation="vertical"
        android:paddingLeft="10dp" >

        <TextView
            android:id="@+id/categorylistname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="#000000"
            android:textSize="20sp"
            android:typeface="sans" />

        <TextView
            android:id="@+id/categorylistcount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#777777"
            android:textSize="16sp"
            android:typeface="sans" />
    </LinearLayout>

    <ImageView
        android:id="@+id/categoryseeall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="10"
        android:src="@drawable/see_all" />

</LinearLayout>

SquareImageView is my custom class with following code:
public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }
}

Help will be really appreciated.
After making code changes looks like this in smaller screen

A: Try this way,hope this will help you to solve your problem.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <ImageView
        android:id="@+id/categoryimage"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.30"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitXY"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.60"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/categorylistname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="#ff0000"
            android:textSize="20sp"
            android:typeface="sans" />

        <TextView
            android:id="@+id/categorylistcount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#777777"
            android:textSize="16sp"
            android:typeface="sans" />
    </LinearLayout>

    <ImageView
        android:id="@+id/categoryseeall"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:layout_weight="0.10"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

A: If you want always layout-ed 10:80:10 by android:layout_weight attr,
set android:layout_width="0dp".
long expression:
layout_weight will use spaces without content width.
So if container is 800dp and layout_width are not 0dp, first ImageViews are layout-ed normally (like imageview 400dp, text 300dp...) and then
separate spaces with weight.
if left space is 100dp, split 10:80:10 those space then ImageView get 410dp. oh no!
yes, maybe this time, ImageView with wrap_content is too large and weight attr gets nothing split to space.
If you getting wrong aspect ImageView, change the ImageView like this:
    <com.wallie.imagview.SquareImageView
        android:id="@+id/categoryimage"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"       <---- this
        android:src="@drawable/dummy_avatar"
        android:layout_weight="10"/>

A: Change your onMeasure method to
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(heightMeasureSpec, heightMeasureSpec);
}

And set layout widths to 0dp when setting its weight:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="horizontal"
                  android:weightSum="100">

        <com.wallie.imagview.SquareImageView
            android:id="@+id/categoryimage"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/dummy_avatar"
            android:layout_weight="10"/>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="80"
            android:gravity="left"
            android:orientation="vertical"
            android:paddingLeft="10dp">

            <TextView
                android:id="@+id/categorylistname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="1"
                android:textColor="#000000"
                android:textSize="20sp"
                android:typeface="sans"/>

            <TextView
                android:id="@+id/categorylistcount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#777777"
                android:textSize="16sp"
                android:typeface="sans"/>
        </LinearLayout>

        <ImageView
            android:id="@+id/categoryseeall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="10"
            android:src="@drawable/see_all"/>

    </LinearLayout>


text:
Q: How can I set the attributes of an object to the value of another object's attribute (another class) in Python? In this project I have two classes:
class StockEntity:
    def __init__(self, ticker, exchange = 'NASDAQ'):
        self.ticker = ticker
        self.exchange = exchange

        # Get the history
        ticker = yf.Ticker(self.ticker)
        self.stock_hist = ticker.history(period = "max")

class Curve(StockEntity):
    def __init__(self, ticker, startdate, type_of_curve, hierarchy_order):
        self.ticker = StockEntity.ticker
        self.startdate = startdate
        self.type_of_curve = type_of_curve
        self.hierarchy_order = hierarchy_order
        self.stock_hist = StockEntity.stock_hist

The concept here is that each instance of StockEntity has a ticker symbol, and a history of stock trading data.
So I would say AAPL = StockEntity('AAPL'). That works fine. If I want to make a chart of the trading data, i can simply use the values in AAPL.stock_hist which gives me a dataframe to work with.
Now, for each stock, i also want to be able to do create curves based on calculations.
So i created the other class Curve, where i pass a StockEntity object as a property, the idea being, that, while I need the object of the class Curve for 'AAPL' to be an (instance of an) object by itself, it would make sense to make use of the same data that sits in the AAPL object.
However, when I do:
AAPL = StockEntity('AAPL')
and then do
AAPL_curve = Curve(AAPL, '2020-01-01', 'S', 1) i get an error saying "AttributeError: type object 'Stock_entity' has no attribute 'ticker'"
HUH?
If I type 'AAPL.ticker' it returns 'AAPL' as expected! So there is no doubt the attribute is there.
What am i missing here? Am I doing this all wrong?

A: class Curve():
    def __init__(self, stock, startdate, type_of_curve, hierarchy_order):
        self.ticker = stock.ticker
        self.startdate = startdate
        self.type_of_curve = type_of_curve
        self.hierarchy_order = hierarchy_order
        self.stock_hist = stock.stock_hist

Try just passing the stock entity as an attribute maybe?

redpajama_set_name: RedPajamaStackExchange


text:
Q: my function in bash I wrote this bash script. also l wrote my function with param.
function is called with no parameters normally. the parameters sampled several ways, but nothing of them has been successful
#!/bin/bash
   RESULT_DIR="./imgR"
   rm -r $RESULT_DIR
   mkdir $RESULT_DIR
   widthOrigin=0
   heightOrigin=0
   widthR=0
   heightR=0
   for i in ~/img/{*.jpg,*.jpeg,*.png,*.JPG,*.JPEG,*.PNG}
   do
   echo  "file" $i
   if [ -f $i ]
   then
   echo "file1"
   widthOrigin=`identify -format "%w" $i`
   #$checkTwo
   widthR=$(checkTwo $widthOrigin)
   heightOrigin=`identify -format "%h" $i`
   #heightR=$(checkTwo $heightOrigin)

   echo "width origin" $widthOrigin " width power 2" $widthR
   echo "height origin" $heightOrigin "wicth power 2" $heightR

   #convert -resize $widthR $heightR $i $RESULT_DIR/$(basename "$i")
   fi
   done
   exit 0

and my function
   checkTwo(){
   echo "checkTwo"
   param=$1
   echo "param" $param
   if [ param -ge "1024"]
   then
   return 1024
   else

   if [param -ge "512"]
   then
   return "512"
   else

   if [param -ge "256"]
   then
   return "256"
   else

   if [param -ge "64"]
   then
   return "64"
   else

   if [param -ge "32"]
   then
   return "32"
   else

   if [param -ge "16"]
   then
   return "16"

   else
   if [param -ge "4"]
   return "4"
   else
   return "2"

   fi fi fi fi fi  fi  fi
   }
   }
   #end

but in  line  "   widthR=$(checkTwo $widthOrigin)" l have error "function widthOrigin not found"

A: It should be:
if [ "$param" -ge "1024" ]

You need a dollar sign before the variable name for it to be expanded. And you need spaces around [ and ]. The quotes around $param are needed to avoid a problem if the parameter is empty or contains whitespace.
Another problem: The function should use echo, not return, since you're using it in $(...), which substitutes the stdout of the function.
You also don't need all those nested ifs, with a zillion fis at the end, if you use elif between the cases instead of else if.
if ...
then ...
elif ...
then ...
elif ...
then ...
else ...
fi

I can't explain why you're getting the specific error you're getting, since there's no reference to a function widthOrigin.
Actually I'd implement that whole function as a loop:
x=1024
while [ "$param" -lt $x ] && [ $x -gt 2 ]
do
    x=((x>>1))
done
echo $x


text:
Q: About black holes paradox About the information paradox in the black holes, isn't it possible in principle, that the "singularity" itself doesn't really exists, and its just the horizon plane, where the particles that falls into it gets stucked, and the hawking radiation, instead of being the creation of the 2 virtual particles, it would creates only the one that goes out of it, and that be entangled with a correspondent one stuck in the horizon, with that way we could retrieve the information, I'm sure that is some problems with that view, but, since we proved we can describe all the black hole just with the horizon itself, doesn't it shows that there isn't nothing more than the horizon?
I mean, for me its a much smaller leap, than what physics is doing to assume that since the black hole can be described by the horizon, our hole universe can be described in one less dimension.


text:
Q: insertMapObject Function Android Returning 23 code Cartotype Firstly, Cartotype provides API for providing the Map in Android,iOS and other platforms  as per my knowledge .
from the docs i found a function that meets my need
native int com.cartotype.Framework.insertMapObject  (   int     aMapHandle,
int     aMapObjectType,
String  aLayerName,
Geometry    aGeometry,
String  aStringAttributes,
int     aIntAttribute,
long    aId,
boolean     aReplace
)

But the parameters they refer to i couldn't be successful in getting those and finally got as
// Second or continuing measurement, add to arrays
// and draw line
iDistanceMeasurementX = extendArray(
iDistanceMeasurementX, thisPoint[0]);
iDistanceMeasurementY = extendArray(
iDistanceMeasurementY, thisPoint[1]);

// _thread.iFramework.deleteMapObjects(0,
// ID_MEASUREMENT_TOOL, ID_MEASUREMENT_TOOL, null);
// _thread.iFramework.addLineOrPolygonObject(
// "measurementtool", iDistanceMeasurementX,
// iDistanceMeasurementY,
// Framework.DEGREE_COORDS, null, 0,
// ID_MEASUREMENT_TOOL, false);

//Drawing line geometry
Geometry geometry = new Geometry(Framework.DEGREE_COORDS);
geometry.appendPoint(thisPoint[0],thisPoint[1]);
geometry.beginContour();

 try {
                                int abc = _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        ID_MEASUREMENT_TOOL, false);
                                Toast.makeText(getContext(),abc,Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//Drawing line with coordinates
// _thread.iFramework.insertPointMapObject(0,"measurementtool", iDistanceMeasurementX[0],iDistanceMeasurementY[0] ,MapObject.LINE_TYPE, "", 0,
// ID_MEASUREMENT_TOOL, false);
//Toast.makeText(getContext(),"Draw Line ",Toast.LENGTH_SHORT).show();
getMapAndDraw(); // Inefficient, we are drawing

Those 'abc' int returns a value 23 and needs to be 0,if success according to the docs.
MY NEED IS DRAW A LINE b\w 2 Coordinates
Any help will be appreciated

A: Thanks @Graham
geometry = new Geometry(Framework.DEGREE_COORDS);

   iDistanceMeasurementX = extendArray(
                                    iDistanceMeasurementX, thisPoint[0]);
                            iDistanceMeasurementY = extendArray(
                                    iDistanceMeasurementY, thisPoint[1]);
geometry.appendPoint(iDistanceMeasurementX[iDistanceMeasurementX.length-1], iDistanceMeasurementY[iDistanceMeasurementY.length-1]);

                            //Drawing line geometry

                                _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        0, false);

A: At first glance it seems that only one point is being added to the Geometry object. You need two points to draw a line. Also, the call to beginContour is not needed.
But you mentioned that you're getting the 'duplicate object' error (23). That's because more than one object has been inserted with the id ID_MEASUREMENT_TOOL. By the way, you can get a reference to the CartoType error code constants for Android here:
http://www.cartotype.com/assets/android_api_doc/classcom_1_1cartotype_1_1_error.html


text:
Q: connect woo rest api to a live server wp multisite I'm new to this, i want to configure the woo custom dashboad and was following https://www.cloudways.com/blog/custom-dashboard-using-woocommerce-php-rest-api/.
following the basic setup,
i'm on ftp testing this but i get is a blank page,how will i do to connect to the rest api and another thing my intention is to use this for a wp multisite, will work for me?
   <?php

  $woocommerce = new Client('https://myscustom.com/',
                     'ck_testclient numbers',
                     'cs_testid1',
                     [
                     'wp_api' => true, 'version' => 'wc/v3',
  ]);

 var_dump($woocommerce);
 ?>

A: as far the api connection on a life server i had to many issues with composer by it self so i did it without it, now is connecting. make sure to get the right path
this was found at https://github.com/woocommerce/wc-api-php/issues/146
<?php

   require_once(__DIR__.'/src/WooCommerce/Client.php');
     require_once(__DIR__.'/src/WooCommerce/HttpClient/BasicAuth.php');
       require_once(__DIR__.'/src/WooCommerce/HttpClient/HttpClient.php');
    require_once(__DIR__.'/src/WooCommerce/HttpClient/HttpClientException.php');
    require_once(__DIR__.'/src/WooCommerce/HttpClient/OAuth.php');
  require_once(__DIR__.'/src/WooCommerce/HttpClient/Options.php');
   require_once(__DIR__.'/src/WooCommerce/HttpClient/Request.php');
  require_once(__DIR__.'/src/WooCommerce/HttpClient/Response.php');

  use Automattic\WooCommerce\Client;
  use Automattic\WooCommerce\HttpClient\HttpClientException;

     $woocommerce = new Client('https://ursite.com/',
                     'ck_xxxxxxxxxxxxxxxxxxxxxx',
                    'cs_xxxxxxxxxxxxxxxxxxxxxx',

      [
        'wp_api' => true, 'version' => 'wc/v3',

      ]);
  ?>


text:
Q: Error on heroku after deploying my app on heroku,when i try to sign up on the app,i get this page from heroku
We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

my log file is this
-----> Using set buildpack heroku/ruby

-----> Ruby app detected

-----> Compiling Ruby/Rails

-----> Using Ruby version: ruby-2.0.0

###### WARNING:

       Removing `Gemfile.lock` because it was generated on Windows.

       Bundler will do a full resolve so native gems are handled properly.

       This may result in unexpected gem versions being used in your app.

       In rare occasions Bundler may not be able to resolve your dependencies at all.

       https://devcenter.heroku.com/articles/bundler-windows-gemfile
-----> Installing dependencies using bundler 1.9.7

       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4

       Fetching gem metadata from https://rubygems.org/...........

       Fetching version metadata from https://rubygems.org/...

       Fetching dependency metadata from https://rubygems.org/..

       Resolving dependencies...

       Rubygems 2.0.14.1 is not threadsafe, so your gems must be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.

       Installing rake 10.4.2

       Installing i18n 0.7.0

       Installing json 1.8.3

       Installing minitest 5.8.3

       Installing thread_safe 0.3.5

       Installing tzinfo 1.2.2

       Installing activesupport 4.2.4

       Installing builder 3.2.2

       Installing erubis 2.7.0

       Installing mini_portile2 2.0.0

       Installing nokogiri 1.6.7.1

       Installing rails-deprecated_sanitizer 1.0.3

       Installing rails-dom-testing 1.0.7

       Installing loofah 2.0.3

       Installing rails-html-sanitizer 1.0.2

       Installing actionview 4.2.4

       Installing rack 1.6.4

       Installing rack-test 0.6.3

       Installing actionpack 4.2.4

       Installing globalid 0.3.6

       Installing activejob 4.2.4

       Installing mime-types 2.99

       Installing mail 2.6.3

       Installing actionmailer 4.2.4

       Installing activemodel 4.2.4

       Installing arel 6.0.3

       Installing activerecord 4.2.4

       Installing pg 0.18.4

       Installing activerecord-postgresql-adapter 0.0.1

       Installing execjs 2.6.0

       Installing autoprefixer-rails 6.2.1

       Installing bcrypt 3.1.10

       Installing sass 3.4.20

       Installing bootstrap-sass 3.2.0.2

       Using bundler 1.9.7

       Installing coffee-script-source 1.10.0

       Installing coffee-script 2.4.1

       Installing thor 0.19.1

       Installing railties 4.2.4

       Installing coffee-rails 4.1.1

       Installing concurrent-ruby 1.0.0

       Installing orm_adapter 0.5.0

       Installing responders 2.1.1

       Installing warden 1.2.4

       Installing devise 3.5.3

       Installing multi_json 1.11.2

       Installing jbuilder 2.3.2

       Installing jquery-rails 4.0.5

       Installing password_strength 1.1.1

       Installing sprockets 3.5.2

       Installing sprockets-rails 3.0.0

       Installing rails 4.2.4

       Installing rails_serve_static_assets 0.0.4

       Installing rails_stdout_logging 0.0.4

       Installing rails_12factor 0.0.3

       Installing tilt 2.0.1

       Installing sass-rails 5.0.4

       Installing simple_form 3.2.1

       Installing turbolinks 2.5.3

       Installing uglifier 2.7.2

       Installing will_paginate 3.0.7

       Installing will_paginate-bootstrap 1.0.1

       Bundle complete! 20 Gemfile dependencies, 62 gems now installed.

       Gems in the groups development and test were not installed.

       Bundled gems are installed into ./vendor/bundle.

       Bundle completed (52.05s)

       Cleaning up the bundler cache.

-----> Preparing app for Rails asset pipeline

       Running: rake assets:precompile

       I, [2015-12-24T11:22:04.534075 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/futo-e4861dc21d4f262c7d71f5a7485df89a9766ef9010d301950b49070a0a3bb67e.jpg

       I, [2015-12-24T11:22:04.536994 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/header-212dcd3c416ad94c32cdd01d58ed1c613374c139de20215783e057c54f93af64.jpg

       I, [2015-12-24T11:22:06.814030 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/application-7ec857240036347e31e43de6607d10195206514a27809edbabaac2cbb7e33a2c.js

       I, [2015-12-24T11:22:06.814357 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/application-7ec857240036347e31e43de6607d10195206514a27809edbabaac2cbb7e33a2c.js.gz

       I, [2015-12-24T11:22:13.868142 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/application-2976e5261a35a755c4b539f86ad52435d2609ef6b8f7dfa41759505bca725188.css

       I, [2015-12-24T11:22:13.868470 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/application-2976e5261a35a755c4b539f86ad52435d2609ef6b8f7dfa41759505bca725188.css.gz

       I, [2015-12-24T11:22:13.869235 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/bootstrap/glyphicons-halflings-regular-f495f34e4f177cf0115af995bbbfeb3fcabc88502876e76fc51a4ab439bc8431.eot

       I, [2015-12-24T11:22:13.870405 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/bootstrap/glyphicons-halflings-regular-fc969dc1c6ff531abcf368089dcbaf5775133b0626ff56b52301a059fc0f9e1e.woff

       I, [2015-12-24T11:22:13.871564 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/bootstrap/glyphicons-halflings-regular-bd18efd3efd70fec8ad09611a20cdbf99440b2c1d40085c29be036f891d65358.ttf

       I, [2015-12-24T11:22:13.872573 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/bootstrap/glyphicons-halflings-regular-d168d50a88c730b4e6830dc0da2a2b51dae4658a77d9619943c27b8ecfc19d1a.svg

       I, [2015-12-24T11:22:13.873371 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/bootstrap/glyphicons-halflings-regular-d168d50a88c730b4e6830dc0da2a2b51dae4658a77d9619943c27b8ecfc19d1a.svg.gz

       I, [2015-12-24T11:22:13.947930 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/index-fa812812183a74cbeb7cead19cf81fd3f19c2ef9737e0795ca6e292e9880fc67.css

       I, [2015-12-24T11:22:13.948537 #1003]  INFO -- : Writing /tmp/build_5a632118a67ee197ead18c935b980da8/public/assets/index-fa812812183a74cbeb7cead19cf81fd3f19c2ef9737e0795ca6e292e9880fc67.css.gz

       Asset precompilation completed (11.27s)

       Cleaning assets

       Running: rake assets:clean
###### WARNING:

       Include 'rails_12factor' gem to enable all platform features

       See https://devcenter.heroku.com/articles/rails-integration-gems for more information.
###### WARNING:

       You have not declared a Ruby version in your Gemfile.

       To set your Ruby version add this line to your Gemfile:

       ruby '2.0.0'

       # See https://devcenter.heroku.com/articles/ruby-versions for more information.
###### WARNING:

       Removing `Gemfile.lock` because it was generated on Windows.

       Bundler will do a full resolve so native gems are handled properly.

       This may result in unexpected gem versions being used in your app.

       In rare occasions Bundler may not be able to resolve your dependencies at all.

       https://devcenter.heroku.com/articles/bundler-windows-gemfile
###### WARNING:

       No Procfile detected, using the default web server (webrick)

       https://devcenter.heroku.com/articles/ruby-default-web-server
-----> Discovering process types

       Procfile declares types     -> (none)

       Default types for buildpack -> console, rake, web, worker
-----> Compressing... done, 30.0MB

-----> Launching... done, v12

       https://limitless-eyrie-2483.herokuapp.com/ deployed to Heroku

A: May be You have to change better Heroku using plan. (Not sandbox!)
With this errors I moved to AmazonWS... :)
UPDATE:
This is an accurate answer to the question. Some time ago I had exactly the same problem. Heroku free only as sandbox. If You try use free Heroku from public internet, You will see message as ChrisGeek wrote. So one solution -- move to other Cloud, for example AmazonWS EC2. When I move my project WITHOUT ANY CHANGING to AWS --- it work properly. On HEROKU minimal plan for using from public internet -- 7$ per month, but all they's ad. say -- "we are free".


text:
Q: Android A cast to int has gone wrong. Please contact the mp4parser discussion group (3292244048) Error Log:
java.lang.RuntimeException: A cast to int has gone wrong. Please contact the mp4parser discussion group (3292244048)
Fatal Exception: java.lang.RuntimeException on MovieCreator.build()
I need help
Movie movieA = null;
try {
    movieA = MovieCreator.build(firstFile.getAbsolutePath());
} catch (IOException e) {
    e.printStackTrace();
}
final Movie finalMovie = new Movie();
List<Track> audioTracks = new ArrayList<>();
ArrayList<Movie> movilist=new ArrayList<>();
for(int i=0;i<value;i++){
    movilist.add(movieA);
}

for (Movie movie : movilist) {
    for (Track track : movie.getTracks()) {
        if (track.getHandler().equals("soun")) {
            audioTracks.add(track);
        }
    }
}
try {
    finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
} catch (IOException e) {
    e.printStackTrace();
}

final Container container = new DefaultMp4Builder().build(finalMovie);
File mergedFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.PROJECT_FOLDER + "/Sounds/newsound123" + ".mp3");
try {
    final FileOutputStream fos = new FileOutputStream(mergedFile);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
FileChannel fc = null;
try {
    fc = new RandomAccessFile(mergedFile, "rw").getChannel();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
try {
    container.writeContainer(fc);
} catch (IOException e) {
    e.printStackTrace();
}
try {
    fc.close();
} catch (IOException e) {
    e.printStackTrace();
}
return mergedFile.getAbsolutePath();


text:
Q: It spells vs it is spelt Why do we use the active form of verbs rather than using the passive form of it.
For example,

*

*it spells as "W.O.R.k"

*it is spelt as "W.O.R.K"

And

*

*the oranges sell at $2 Lb

*the oranges are sold at $2 Lb

My question is in which cases can we use the active form where at the same time we can use the passive form?
I want to know if the orange can sell itself or the word can spell itself! Or the word is spelt by someone and the oranges are sold by someone
I hope you can understand my point to answer.

A: When you inform someone of how something is spelled, you say:
It is spelled or spelt w-o-r-k. [you are providing information on spelling]
If you say: w-o-r-k spells work, that usually is a metaphorical use, it means: is.
For example: That boy spells trouble. [spells=is].
Generally, one would not say: spelled or spelt as unless you are comparing two spellings of something. As used in some place or publication. "But, Mary, they are spelling it as "c-o-l-o-u-r".
The oranges usually sell for $2 a pound but today are selling for $2.60 a pound.
The oranges are sold for 2$ a pound most of the time.
You can say either. One is active and the other is passive. There is no difference in meaning and you do not need to say by whom.
Sell at is ok, too. Sell at is used for the stock market, for example.
Words cannot spell themselves.
The words are spelled or spelt by someone or something [a computer]. You do not always need the agent.
Oranges are sold by the pound [by grocery stores].

A: Regarding spelling:

*

*it is spelt as W.O.R.K
If there are differences you can say

*

*I spell it C-O-L-O-U-R and he spells it C-O-L-O-R

On the telephone it is common for service companies to ask how to spell your name or address details like this:

*

*My name is Thomson. How are you spelling that?


text:
Q: How to return a record when the sum reached a certain threshold I am using SQL and I have a table with three colums: account, transaction_date, Points.
Each account will have multiple transaction_dates and Points earned for each transaction.
How do I return the transaction_date when each account reached a certain threshold (i.e. accumulatee 100 Points).  Say the first account has 2000 transactions and the first five have each 21 Points.  I would like the query to return transaction # 5 because that is when the account reached 100.
Can anybody help?
Thanks!
Cat

A: select min(a.transaction_date), a.account from

(select sum(t1.points) as thesum, t2.transaction_date, t2.account
from table t1
inner join table t2 on t1.account = t2.account and t1.transaction_date <= t2.transaction_date
group by t2.transaction_date, t2.account
having thesum >= 100) a

group by a.account

A: Use a triangular join:
In T-SQL:
SELECT account, MIN(dt), MIN(points)
FROM
(
    SELECT t1.account, t1.date, sum(t2.points) AS points
    FROM table t1
      INNER JOIN table t2 ON t1.account = t2.account AND t1.dt >= t2.dt
    GROUP BY t1.account, t1.date
    HAVING SUM(t2.points) > 100
) iq
GROUP BY account

A: This should get you what you're after.
SELECT account_id, MIN(transaction_date) FROM table t1 WHERE (SELECT SUM(points) FROM table t2 WHERE t2.transaction_date < t1.transaction_date) <= 100 GROUP BY account_id

A: You could do this using a cursor in a stored procedure. Then you could just step through the records for the account and accumulate the points. As soon as you pass the threshold you return the current record.
But this will probably be quite slow if you have a large dataset, so if you know the threshold(s) you are after before running the query you could add an extra table where you tag the records where you cross the thresholds you are after. Updating this extra table could be done in a trigger on the transactions table.


text:
Q: JOIN Table request to retrieve all rooms that are not already booked in the time period requested I have a rails app with a room model that has_many bookings.
My booking table has a room_id, a start_date, a end_date.
In my form, I ask my user for the time period he wishes to book the room for : params[:from], params[:to]
I need to retrieve all the rooms from the db that are not booked for the time period requested. I think that this request can be represented by the intersection of two groups :
A)  All rooms that dont have a booking with a start_date between params[:from] and params[:to]
B) All rooms that dont have a booking with a end_datebetween params[:from] and params[:to]
C) All rooms that dont have a booking with a start_date prior to params[:from] and after params[:to]
I came up with this
Room.joins(:bookings).where("bookings.start_date >= ? AND <= ?", params[:from], params[:to])

but this is only answering partially the problem. How can I write an AR request (SQL or AR) that will retrieve all rooms that are not booked in the time period requested.


text:
Q: Binary Tree Top View Segmentation Fault I am trying to solve a problem about binary tree, but I got something wrong with build a tree, maybe. It seems wired to me, why I got segmentation fault when I try to print out the data of a node:
//      3
//    /   \
//   5     2
//  / \   / \
// 1   4 6   7
//  \       /
//   9     8

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

void top_view(struct node * root) {

    int array[100] = {0};
    int count = 0;
    struct node * temp;

    if (root) {
        if (root->left) {
            temp = root;
            while (temp->left) {
                printf("%d ", temp->left->data);
                // array[count] = temp->left->data;
                count++;
                temp = temp->left;
            }
        }
        array[count] = root->data;
        printf("%d\n", array[count]);

        if (root->right != NULL) {
            printf("right %d\n", root->right->data);
            temp = root;
            printf("%p\n", temp->right->right);
            printf("%d\n", temp->right->right->data);
        }

        // for (int i = 0; i < 100; i++) {
        //     printf("%d ", array[i]);
        // }

    } else {
        return ;
    }

}

int main(int argc, char const *argv[])
{
    // struct node *nine = (struct node*)malloc(sizeof(struct node*));
    // nine->data = 9;
    // nine->left = NULL;
    // nine->right = NULL;

    // struct node *ten = (struct node*)malloc(sizeof(struct node*));
    // ten->data = 10;
    // ten->left = NULL;
    // ten->right = NULL;

    // struct node *one = (struct node*)malloc(sizeof(struct node*));
    // one->data = 1;
    // one->left = ten;
    // one->right = nine;

    // struct node *four = (struct node*)malloc(sizeof(struct node*));
    // four->data = 4;
    // four->left = NULL;
    // four->right = NULL;

    // struct node *five = (struct node*)malloc(sizeof(struct node*));
    // five->data = 5;
    // five->left = one;
    // five->right = four;

    struct node *eight = (struct node*)malloc(sizeof(struct node*));
    eight->data = 8;
    eight->left = NULL;
    eight->right = NULL;

    struct node *six = (struct node*)malloc(sizeof(struct node*));
    six->data = 6;
    six->left = NULL;
    six->right = NULL;

    struct node *seven = (struct node*)malloc(sizeof(struct node*));
    seven->data = 7;
    seven->left = eight;
    seven->right = NULL;

    struct node *two = (struct node*)malloc(sizeof(struct node*));
    two->data = 2;
    two->left = six;
    two->right = seven;

    struct node *three = (struct node*)malloc(sizeof(struct node*));
    three->data = 3;
    three->left = NULL;
    three->right = two;

    top_view(three);

    return 0;
}

the output is this way:
3
right 2
0x7fc800000003
[1]    2091 segmentation fault  ./a.out

where I went wrong with it?

A: Your printf is trying to print a data attached to a NULL pointer. Like @Johnny said, temp->right->right might be null so temp->right->right->data segfault
You should add a stop hook. Before :
printf(temp->right->right->data);

After:
if (temp->right->right)
    printf(temp->right->right->data);

A: I just made an edit at the code and it compiles and doesn't give any error. I changed the way you use malloc to init a new node and deleted the cast. You also must check if root->right->right exists. Here it is with the three you show at the top of the code.
    /*      3
 *    /   \
 *   5     2
 *  / \   / \
 * 1   4 6   7
 *  \       /
 *   9     8
 */
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

void top_view(struct node *root) {

    int array[100] = {0};
    int count = 0;
    struct node *temp;

    if (root) {
        if (root->left) {
            temp = root;
            while (temp->left) {
                printf("%d ", temp->left->data);
                // array[count] = temp->left->data;
                count++;
                temp = temp->left;
            }
        }
        array[count] = root->data;
        printf("%d\n", array[count]);

        if (root->right != NULL) {
            printf("right %d\n", root->right->data);
            temp = root;
            /*You must check it*/
            if(root->right->right != NULL){
                printf("%p\n", temp->right->right);
                printf("%d\n", temp->right->right->data);
            }
        }

            /*for (int i = 0; i < 100; i++) {
             printf("%d ", array[i]);
         }*/

    } else {
        return ;
    }

}

int main(int argc, char const *argv[])
{
    struct node *nine = malloc(sizeof(struct node));
    nine->data = 9;
    nine->left = NULL;
    nine->right = NULL;

   /* struct node *ten = (struct node*)malloc(sizeof(struct node*));
    ten->data = 10;
    ten->left = NULL;
    ten->right = NULL;*/

    struct node *one = malloc(sizeof(struct node));
    one->data = 1;
    one->left = NULL;
    one->right = nine;

    struct node *four = malloc(sizeof(struct node));
    four->data = 4;
    four->left = NULL;
    four->right = NULL;

     struct node *five = malloc(sizeof(struct node));
     five->data = 5;
     five->left = one;
     five->right = four;
    /*You should cast the result of a malloc just if you need it*/
    struct node *eight = malloc(sizeof(struct node));
    eight->data = 8;
    eight->left = NULL;
    eight->right = NULL;

    struct node *six = malloc(sizeof(struct node));
    six->data = 6;
    six->left = NULL;
    six->right = NULL;

    struct node *seven = malloc(sizeof(struct node));
    seven->data = 7;
    seven->left = eight;
    seven->right = NULL;

    struct node *two = malloc(sizeof(struct node));
    two->data = 2;
    two->left = six;
    two->right = seven;

    struct node *three = malloc(sizeof(struct node));
    three->data = 3;
    three->left = five;
    three->right = two;

    top_view(three);

    return 0;
}


text:
Q: Alternative to blur() for setting window focus? I am using a little bit of Javascript to set the focus of a window to the background.  I am asking a user if they want to take a survey.  If so, the survey window should fall behind the active window so they can continue to surf the site unabated.  The JS works fine, except for in Chrome (and probably Safari).
Here's the JS:
window.onload = function()
{
  self.blur();
};

Is there a better way to do this that has better browser acceptance?

A: To my knowledge, there is no standard or reliable way to force the window manager to position a popup window below its parent on all platforms.
If you're into unobtrusive surveys, you might want to consider implementing something like StackOverflow's notification bar, and opening your popup window in the foreground only if the user interacts with that element.

A: Looks like you have the survey window in front of another window, and want it to go behind that window if user elects to take the survey.
Try this:
<BODY onLoad="self.blur()">


text:
Q: Importing and Packages I'm not quite sure what I'm doing wrong, here. I have two files in a directory, let's call them FileA.java and FileB.java.
FileA.java has a definition along the lines of:
package com.domain.package;

import stuff;
import package.FileB;

public class FileA extends Blah implements Listener {
    /* global vars */
    /* methods */
}

FileB.java is my data object class, which I'd like to reference from FileA.java thusly:
Map<Object, FileB> varname;

to be used along the lines of:
varname = new HashMap<Object, FileB>();

FileB.java, on the other hand, is defined as such:
package com.domain.package;

import stuff;

public class FileB {
    /* global vars */
    public FileB() {
         /* stuff */
    }
}

Why am I getting:
FileA.java:20: package package does not exist
import package.FileB;

? Rather, how do I make it work?

A: Because both files are in the same package (com.domain.package), you should not need to import FileB at all.  You should be able to reference it directly.
Additionally, please ensure that both FileA and FileB are placed in their package folder: com/domain/package.

A: The package of FileB is com.domain.package. You are trying to use package.FileB instead.

A: package is a reserved word, don't use it as part of a package name. If you try to add a package with "package" as part of it in Eclipse, you will get an error message:
Invalid package name. 'package' is not a valid Java identifier

Rename the package, then remove the import statement. You don't need to import a file that's in the same package as the one it's referenced in.

A: @rgettman has the correct solution. Compiling both files using javac FileA.java FileB.javasolves this issue. You can also use his suggestion: javac *.java


text:
Q: MS-BI-SSRS,Passing Cascaded parameters to Drill Through report I am trying to develop a report from cube,and it has one drill through report.when i click on sales amount field on main report,then it open the drill through report with details.Here i passed the (category,subcat,product)parameters(Cascaded) to drill through report in action part of main report.In my main report i have two columns .
columns are Level  and              Salesamount.   Values are like
[-]category 100
[-]subcat 50
product 30
when i click on 100, parameters are passed & it open the detail report correctly, but when i click on 50,the values for subcat parameter is not getting values in detail report and same as the product also.
Here i used the expressions in parameter values
pCategory----iif(inscope(category),!fields.category.value,split(join(Parameters!category.value,","),","))
psubcat----iif(inscope(subcat),!fields.subcat.value,split(join(Parameters!subcat.value,","),","))
pproduct----iif(inscope(product),!fields.product.value,split(join(Parameters!product.value,","),","))
can any one plz reply me.Thanks in Advance

A: After Struggled 2 days , finally i made this. I just changed the expressions for the parameters, it worked fine.
pCategory= iif(inscope(category),!fields.category.value,split(join(Parameters!category.value,","),","))
psubcat= iif(inscope(subcat),!fields.subcat.value, lookupset(Fields!Category_ID.Value,Fields!Subcat_ID.Value,Fields!Subcat.Value,"dsMain")
pproduct= iif(inscope(product),!fields.product.value, lookupset(Fields!Subcat_ID.Value,Fields!Product_ID.Value,Fields!Product.Value,"dsMain")


text:
Q: In a key: value object, what is the difference between outputting the value by the key and by an array? Consider the following cases:
console.log({a: 1}.a);
console.log({a: 1}['a']);

They both output 1, what is the difference between them? Which one should be used when outputting the value 1?

A: With the second syntax you can have spaces, operators, variables and operations like:

const keyPrefix = 'a';
console.log({'a+ 1': 1}[keyPrefix + '+ ' + (3 - 2)]);

That's not possible with the first syntax. "Which one should be used when outputting the value 1?" You have to use the second syntax if the first is not possible. In all other cases it's opinion based. They have same behavior. {a: 1}.a is syntax sugar for {a: 1}['a'].


text:
Q: How to find the session id of running jobs Trying to get the session id of executing jobs
;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on j.job_id = jd.Job_Id

but it throws the following error

Msg 8169, Level 16, State 2, Line 47 Conversion failed when converting
  from a character string to uniqueidentifier.

I tried to cast the job_id to varbinary but it produces no result
;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on cast(j.job_id as varbinary) = jd.Job_Id

but when I copy paste a job_id from cte like this
select job_id, name
    from msdb..sysjobs
    where job_id = 0x128A47A31EAB8F4DA1AD852093D815F5

it works. Any idea how to fix this query

A: I used CONVERT to convert the msdb.dbo.sysjob.job_id to BINARY(16) and then used CONVERT (and a style) to convert that to a varchar(max) which could be compared to what comes out of your cte.  You can read more about CONVERT and styles by reviewing the documentation for CONVERT. This worked in my testing.
Try this:
;
WITH JobDetails
AS (
    SELECT DISTINCT Job_Id = left(intr1, charindex(':', intr1) - 1)
        ,Step = substring(intr1, charindex(':', intr1) + 1, charindex(')', intr1) - charindex(':', intr1) - 1)
        ,SessionId = spid
    FROM master.dbo.sysprocesses x
    CROSS APPLY (
        SELECT replace(x.program_name, 'SQLAgent - TSQL JobStep (Job ', '')
        ) cs(intr1)
    WHERE spid > 50
        AND x.program_name LIKE 'SQLAgent - TSQL JobStep (Job %'
    )
SELECT *
FROM msdb.dbo.sysjobs j
INNER JOIN JobDetails jd ON jd.Job_Id = convert(VARCHAR(max), convert(BINARY (16), j.job_id), 1)


text:
Q: CDI + JPA Multiple @OneToMany - LAZY/EAGER - LazyInitializationException OR Cannot instantiate multiple bags I am developing an application using Jboss AS 7, CDI, JPA, and some other resources bundled.
My question is: When I create a project in Eclipse using the maven-jboss-webapp-archetype it generates some files, which I have been extensively studying and trying to get along with. The problem is that sometimes I see myself a little bit confused whether I am using Hibernate resources or JPA resources.
Second question: When I use multiple @OneToMany relationships in the same Entity I notice two behaviors:
a) Without specifying EAGER type for Fetch, it deploys the application but when I try to use the list it gives me the LazyInitializationException error so vastly discussed here.
b) When I specify Eager for the FetchType on the @*ToMany relationship it just doesnt deploys the application. It gives me the error: Cannot instantiate multiple bags.
Here is the problematic piece of code:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "teamUser" , fetch = FetchType.EAGER)
private Collection<Users> usersCollection;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "teamRanking" , fetch = FetchType.LAZY)
private Collection<Ranking> rankingCollection;

@NotNull
@OneToMany(cascade = CascadeType.ALL, mappedBy = "teamModality" , fetch = FetchType.LAZY)
private Collection<Modality> modalitiesCollection;

public Teams() {

}

public Teams(Long id_team , String name) {
    this.id = id_team;
    this.name = name;
}

I have been reading about this and people told me that JPA does not support FetchType.EAGER for multiple realtionships in the same Entity. But I need to use multiple relationships in this entity in specific. I don't know what to do anymore, because I have tried several approaches, Lazy fetching, and all of them present some kind of issue. For example, if I leave only one FetchType.EAGER in the class then it deploys my app but it doesn't runs properly because when I try to fetch a List from the database it gives me the error: LazyInitializationException, and when I try to put all of them using the FetchType.EAGER it just doesnt deploy because it gives the error: Cannot instantiate multiple bags.
So my issues here are related to:
1) Maven-jboss-webapp-archetype uses hibernate or jpa or both?
2) How can I attack this problem of using multiple @OneToMany relationships in an Entity? And although I know that fetching eagerly the Collections in the model is not the best approach because when the system grows I will probably have performance issues right? So how can I properly work with Lazy loading?

A: First of all, Hibernate is an implementation of the JPA pecification, and is the default one in JBoss. So you're using JPA, with Hibernate as the implementation.
Second, You get a LazyInitialization exception because you access a lazy-loaded collection, after having closed the session, without having initialized this collection while the session was still open. If you have two lazy collections and you know that the client code needs both initialized, initialize them before returning the entity and closing the session (i.e. while you're still inside the transactional service method):
SomeEntity e = em.find(SomeEntity.class, someId);
e.getFirstCollection().size(); // initialize the first collection
e.getSecondCollection().size(); // initialize the second collection
return e;

You can fetch multiple toMany associations at once, but only one of them can be a bag (i.e. a Collection or a List). I wouldn't advise eager collections generally. But if you really want them, make them Sets instead of Collections.


text:
Q: Docker exit code 0 issue Here is my logs after trying to dockerizing a fastapi script:
$ docker-compose logs -f
Attaching to docker-name
docker-name exited with code 0

Here is my docker compose file:
version: '3'

services:
  observatory-service:
    build: ./observatory
    volumes:
      - ./observatory:/usr/src/app
    ports:
      - 8000:8000

docker file:
FROM python:3.9

COPY requirements.txt /usr/src/app/
RUN pip install -r /usr/src/app/requirements.txt

COPY . /usr/src/app

CMD ["python", "/usr/src/app/api.py"]

api.py:
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return { "Lux app": "Welcome to Lux app" }

@app.post("/extract_text")
def ali():
    return {"Hello": "World"}

I am sure it goes through api.py but it exits out of it without error. I am running this on Windows docker.

A: The problem is that you're directly calling the fastAPI server script with python and not wrapped with a ASGI web server such as Uvicorn. This is explained in the debugging page of fastAPI.
I tested with latest versions of fastapi/uvicorn and it works just fine. I suggest you make these two changes:
1 - Add this line to your requirements.txt file:
uvicorn

2- Then add the first line and the two last lines to the end of your api.py file:
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return { "Lux app": "Welcome to Lux app" }

@app.post("/extract_text")
def ali():
    return {"Hello": "World"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Result of GET /
{"Lux app":"Welcome to Lux app"}

Finally, another alternative would be following the docker guide provided by fastAPI which solves this easily by calling your fastapi module directly with uvicorn. This will achieve the same as above.
Example of Dockerfile:
FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]


text:
Q: Using multiple dots (.) in file names Are there reasons not to use multiple . in website file names (images, css files, js files...) like in logo.french.png?

A: No.
The only reason I can think of to not use multiple .'s in a filename is that a very poorly written file-extension checker might get confused.

A: Too bad that answers cannot be so short: No.
Update:
Mmh ok let me think (you wanted that!):

*

*URLs don't restrict the uses of periods in the path.

*The normal file naming restrictions of the OS your server is running on apply.
If you run Linux or UNIX then you should be pretty free in naming your files (regarding periods). Windows, not so sure ;)

Update 2:
There might be some special configurations of your web server (like Apache's content negotiation) that also uses several periods in the filename to distinguish content. But that should not interfere with naming your files this way.

A: Yes.
I had a file on my website named ads.atx.ps.960.jpg, referenced inside an img src tag...   that spot came up blank in both Chromium and Firefox on Linux when I retrieved the page.   When I finally out of desperation changed the name to ads_atx_ps_960.jpg, it worked fine.
I don't know if the problem was with the browser or the web server, just know it didn't work with the dots, in either browser.   My query for the server type returned "Apache/2"
Note that I do also have a bunch of html files with multiple dots in the names, things like yocto.file.copy.html, etc... these are referenced in href tags and all work fine, the first time I saw the problem was with the JPG in an img src tag.

A: We do use webpack.config.js file name in our javascript projects to configure webpack.
So, it is not a general scenario.


text:
Q: Django-filters , display min price and max price in the placeholder I have a model field price and using class base views, I have added 'django_filters' to settings as well, this is what I have in my project:
model.py
class Product(models.Model):
    price = models.IntegerField(default=0)

setting.py
    'django_filters',

views.py
class ProductListView(generic.ListView):
    template_name = "product/product_list.html"
    queryset = Product.objects.all()
    filter_set = ProductFilter

filters.py
class ProductFilter(django_filters.FilterSet):
    min_price = django_filters.NumberFilter(field_name="price",
    lookup_expr='gt',widget=RangeWidget(attrs={'placeholder': 'min_price'}))
    max_price = django_filters.NumberFilter(field_name="price",
    lookup_expr='lt',widget=RangeWidget(attrs={'placeholder': 'max_price'}))

class Meta:
    model = Product
    fields = { 'min_price', 'max_price'
    }

everything is working perfectly when using price only in fields without 'min_price', 'max_price',
but what I want is to have min_price and max_price show in my placeholder. When I run the code above, I get this error:
"TypeError: 'Meta.fields' must not contain non-model field names: min_price, max_price"


text:
Q: max value for same minute over multiple days from csv with unix timestamps I have a CSV with a unix timestamp column that was collected over multiple days having a data row for every 5 minutes (output log of my photo voltaik roof power plant).
I'd like to create a plot for 24 hours that shows the maximum value for every single (fifth) minute  over all days.
Can this be done with gnuplots own capabilities or do I have to do the processing outside gnuplot via scrips?

You don't show how your exact data structure looks like, - theozh

This files are rather large. I placed an example here:
http://www.filedropper.com/log-pv-20190607-20190811 (300kB)
I'm specially interested in column 4 (DC1 P) and 9 (DC2 P).
Column 1 (Zeit) holds the unix timestamp.
The final goal is separate graphs (colors) for DC1 P  and  DC2 P, but that's a different question... ;o)

A: Update/Revision:
After revisiting this answer, I guess it is time for a clean up and simpler and extended solution. After some iterations and clarifications and after OP provided some data (although, the link is not valid anymore), I came up with some suggestions, which can be improved.
You can do all in gnuplot, no need for external tools!
The original request to plot the maximum values from several days is easy if you use the plotting style with boxes. But this is basically only a graphical solution. In that case is was apparently sufficient. However, if you are interested in the maximum values as numbers it is a little bit more effort.
gnuplot has the option smooth unique and smooth frequency (check help smooth). With this you can easily get the average and sum, respectively, but there is no smooth max or smooth min. As @meuh suggested, you can get maximum or mimimum with arrays, which are available since gnuplot 5.2.0
Script: (Requires gnuplot>=5.2.0)
### plot time data modulo 24h avg/sum/min/max
reset session

FILE = 'log-pv-20190607-20190811.csv'

set datafile separator comma
HeaderCount = 7
myTimeFmt   = "%Y-%m-%d %H:%M:%S"

StartTime = ''
EndTime   = ''
# if you don't define start/end time it will be taken automatically
if (StartTime eq '' || EndTime eq '') {
    stats FILE u 1 skip HeaderCount nooutput
    StartTime = (StartTime eq '' ? STATS_min : strptime(myTimeFmt,StartTime))
    EndTime   = (EndTime   eq '' ? STATS_max : strptime(myTimeFmt,EndTime))
}

Modulo24Hours(t) = (t>=StartTime && t<=EndTime) ? (int(t)%86400) : NaN
set key noautotitle

set multiplot layout 3,2

    set title "All data" offset 0,-0.5
    set format x "%d.%m." timedate
    set grid x,y
    set yrange [0:]
    myHeight = 1./3*1.1
    set size 1.0,myHeight
    plot FILE u 1:4:(tm_mday($1)) skip HeaderCount w l lc var
    set multiplot next

    set title "Data per 24 hours"
    set format x "%H:%M" timedate
    set xtics 3600*6
    set size 0.5,myHeight
    plot FILE u (Modulo24Hours($1)):4:(tm_mday($1)) skip HeaderCount w l lc var

    set title "Average"
    set size 0.5,myHeight
    plot FILE u (int(Modulo24Hours($1))):4 skip HeaderCount smooth unique w l lc "web-green"

    set title "Sum"
    set size 0.5,myHeight
    plot FILE u (int(Modulo24Hours($1))):4 skip HeaderCount smooth freq w l

    set title "Min/Max"
    set size 0.5,myHeight
    N = 24*60/5
    SecPerDay = 3600*24
    array Min[N]
    array Max[N]
    do for [i=1:N] { Min[i]=NaN; Max[i]=0 }  # initialize arrays
    stats FILE u (idx=(int($1)%SecPerDay)/300+1, $4>Max[idx] ? Max[idx]=$4:0, \
          Min[idx]!=Min[idx] ? Min[idx]=$4 : $4<Min[idx] ? Min[idx]=$4:0 ) skip HeaderCount nooutput

    plot Min u ($1*300):2 w l lc "web-blue", \
         Max u ($1*300):2 w l lc "red"

unset multiplot
### end of script

Result:

A: From gnuplot 5.2 you could use the new array datatype to calculate a maximum value for each 5 minute slot.  I am not a gnuplot expert, so the following example needs more work, but shows the potential.
Assume data is similar to these lines, where there is a date in the format
yyyy.mm.dd.HH:MM, a comma and a y value:
2018.02.03.18:23,4
2018.02.03.19:23,7
2018.02.04.18:23,8
2018.02.05.19:23,11

Instead of using gnuplot's built-in time parsing, since we want to ignore the date, we create a function fsecs to use substr(stringcolumn(...),12,16) to get just the hours and minutes from data column 1, and strptime("%H:%M",...) to convert this to seconds:
set datafile separator ","
fsecs(v) = strptime("%H:%M",substr(stringcolumn(v),12,16))

We create an array Max indexed by "5 minute slot", of which there are 24*60/5 per day. It is initialised to NaN, not-a-number.
Nitems = int(24*60/5)+1
array Max[Nitems]
do for [i=1:Nitems] {
    Max[i] = NaN
}

We then "plot" the data file data.csv into a dummy table, rather than generating any output. As we go through the data we index Max by the data x value (column 1) converted to seconds by fsecs(1) and then to slot by findex(). This is Max[findex(fsecs(1))].
We call our function fmax() to return the new maximum to set in the array.
findex(x) = int(((x)/60)/5)
fmax(a,b) = ((a>=b)?a:b)
set table $Dummy
  plot 'data.csv' using \
    (Max[findex(fsecs(1))] = fmax(Max[findex(fsecs(1))],$2)):2
unset table

Finally, we plot the array, which is the slot number against the value held in that slot number.
plot Max using 1:(Max[$1]) with points lw 2 title "max day"

This works for me on 5.2. You still need to label the x axes with HH:MM, and change the date parsing to fit your needs.

A: For time formating, please see Gnuplot date/time in x axis
If you do not care about format as time, you may use the every command, see gnuplot docu, but that does not take a maximum or something.
For the maximum value over a given time interval I suggest an awk script, see e.g. https://unix.stackexchange.com/a/207287/297901


text:
Q: Strange output from variable to hidden form field Below is a function that outputs a form with existing users from a database, with checkboxes and a submit button. The user choose one or several users to be removed and submits the form. What i'm working on right now is to implement a confirmation box in js ("Are you sure you want to remove..."), which shall contain the users that the user wants to remove.
By that reason I'm putting in the usernames in a hidden field that the js function will retrieve the username(s) from. The problem is that not only the usernames are put into the hidden input fields value attribute, but also several input fields as well (!?). If I hard code in for example 'username1,username2' in the attribute it works as it should, but not if I use the variable $users.
    public function ShowUsers($userArray) {

        $userIdArray = $userArray[0];
        $userNameArray = $userArray[1];
        $users = implode(",", $userNameArray);

        echo $users;        // username1,username2...

        $nrOfUsers = count($userIdArray);

        for ($i = 0; $i < $nrOfUsers; $i++) {
            $users .= "
                        $userNameArray[$i]
                        <input type='checkbox' name='$this->_checkBox' value='$userIdArray[$i]' />

                        ";
        }

        $userList = "

                    <form id='form3' method='post' action=''>
                        <fieldset>

Existing users

                            $users
                            <input type='hidden' value='$users' />
                            <input type='submit' id='$this->_submitRemove' name='$this->_submitRemove' Value='Ta bort' />
                        </fieldset>
                    </form>

";

        return $userList;
    }

The output is the following:
<input type='hidden' value='username1,username2
                        username1
                        <input type='checkbox' name='check[]' value='47' />

                        username2
                        <input type='checkbox' name='check[]' value='50' />

                        ' />

I just don't get it why this happens? The content of $users (in this case 'username1' and 'username2') is there as expected, but why is the input and label tags put into the value attribute?

A: The problem is in your for loop. There you're appending all that HTML to the variable $users which already is $users == username1,username2. If you do echo $users; or even var_dump($users); just after you've finished the for loop, you'll see.
What are you trying to achieve in the for loop indeed? Did you rather mean
for ($i = 0; $i < $nrOfUsers; $i++) {
    echo "
                $userNameArray[$i]
                <input type='checkbox' name='$this->_checkBox' value='$userIdArray[$i]' />

          ";
}


text:
Q: Is it safe to terminate the thread that emits a queued signal before the signal has been processed? In my code I have a worker that runs in a separate std::jthread:
// Worker.h:
#pragma once
#include <QWidget>
class Worker : public QObject {
    Q_OBJECT
public:
    Worker();
signals:
    void sendMessage(QString msg);
private:
    void threadFunction();
    std::jthread m_thread;
};

and a widget that runs in the main thread:
// Widget.h
#pragma once
#include <QWidget>
class Widget : public QWidget {
    Q_OBJECT
public:
    Widget();
public slots:
    void getMessage(QString msg);
};

I create a queued connection between the sendMessage signal and getMessage slot:
#include <QApplication>
#include <chrono>
#include "Widget.h"
#include "Worker.h"

int main(int argc, char* argv[])
{
    QApplication a(argc, argv);
    Widget widget;
    {
        Worker worker;
        QObject::connect(&worker, &Worker::sendMessage, &widget, &Widget::getMessage,
                         Qt::ConnectionType::QueuedConnection);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    } // worker deleted and thread terminated
    widget.show();
    return a.exec();
}

Q1: Is it safe to terminate the thread that emits the signal before the signal has been processed?
 // Worker.cpp:
 #include "Worker.h"
 #include <chrono>
 Worker::Worker() {
    m_thread = std::jthread(&Worker::threadFunction, this);
 }
 void Worker::threadFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    emit sendMessage("finished");
 }

and
// Widget.cpp:
#include "Widget.h"
#include <iostream>

Widget::Widget() : QWidget() {}

void Widget::getMessage(QString msg) {
    std::cerr << msg.toStdString() << "\n";
}

The emit of sendMessage invokes the method:
// moc_Worker.cpp:
void Worker::sendMessage(QString _t1)
{
    void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) };
    QMetaObject::activate(this, &staticMetaObject, 0, _a);
}

QMetaObject::activate() is defined in qobject.cpp.
Reading about how Qt signals and slots are implemented I find that this method looks up the zeroth element (first and only signal) of a SignalVector of the Worker object. This element is a doubly linked list of QObjectPrivate::Connection objects. In my case this list only have 1 element which is a connection to the getMessage method.
It also calls
QThreadData *td = connection->receiverThreadData.loadRelaxed();
bool receiverInSameThread = currentThreadId == td->threadId.loadRelaxed();

on this connection to determine if the receiver is in the same thread as the sender.
The receiverThreadData is being set when the connection is made:
// qobject.cpp:
QObjectPrivate::Connection *QMetaObjectPrivate::connect(...,QObject *receiver,...) {
   ...
   QThreadData *td = receiver->threadData;
   connection->receiverThreadData.storeRelaxed(td);
   ...
}

Since I am using a QueuedConnection the method:
void QObject::queued_activate(QObject *sender, int signal, QObjectPrivate::Connection *c, void **argv);

is called which in turn calls:
void QCoreApplication::postEvent(QObject *receiver, QEvent *event);

with a QMetaCallEvent:
struct QMetaCallEvent {
   // the signal:
   QObject *sender;
   uint signal_index;

   // the slot:
   QObject *receiver;
   ushort method_offset;

   // the data:
   int nargs_;
   int* types_;
   void** args_;
};

Q2: Is it safe to delete the sender object before the event has been processed?
Reading about QObject *QObject::sender():
"Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns nullptr. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.
The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal."
Invalid pointer = may crash?

A: It should be safe to process a signal after the emitting thread is terminated and/or the sending object is destroyed.
Queued connections are meant to provide easy, non-blocking and thread-safe communication between threads. Although not explicitly documented, this mechanism would become useless if it is not safe to shut down a thread before all emitted signals are processed in another thread, as the emitting thread/object is not aware of when the slot is processed.
Off course,

*

*You should ensure that the passed objects are not destructed (in case of (smart) pointer types are passed).

*You do not access any object that was destructed in the other thread (i.e. QObject::sender()).


text:
Q: How can I stop IISExpress from dumping every detail of every request into the Visual Studio Output window? My VS 2013 output window is full of this:
iisexpress.exe Information: 0 : Request, Method=GET, Url=http://localhost:51741/api/Clients/?$filter=UniqueName eq '6269', Message='http://localhost:51741/api/Clients/?$filter=UniqueName eq '6269''
iisexpress.exe Information: 0 : Message='Clients', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='MyProj.Controllers.ClientsController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='MyProj.Controllers.ClientsController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'GetClients()'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Operation=HttpActionBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Operation=QueryableAttribute.ActionExecuting
iisexpress.exe Information: 0 : Message='Action returned 'System.Collections.Generic.List`1[MyProj.Models.ClientDto]'', Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Operation=QueryableAttribute.ActionExecuted, Status=200 (OK)
iisexpress.exe Information: 0 : Operation=ClientsController.ExecuteAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=GET, Url=http://localhost:51741/api/Clients/?$filter=UniqueName eq '6269', Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=ClientsController.Dispose

How do I turn all that off?  All I want to see are my calls to Trace.TraceInformation, Trace.TraceError, Trace.TraceWarning, etc.

A: In App_Start\WebApiConfig.cs, remove config.EnableSystemDiagnosticsTracing();
Simple as that :facepalm:

A: First off all, when you use code like
Trace.TraceInformation("My Custom Info Message.");

for tracing (not matter from what place - page, controller or some other class from separate .dll) and then run your application under IIS Express the MS VS Output window would show something like
iisexpress.exe Information: 0 : My Custom Info Message.

How could you recognize what messages is "yours" and what is "not yours"?
Maybe you should add additional marker for each your messages? But as I could see the Output windows still does not support the message filtering by the custom tags or text, but it's support the text Search (Ctrl+F), so...
I had the same issue with IIS Express spamming to the output windows with messages like this
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-130838650006648508): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

I had solved that by going to the MS VS (2013) main menu
-> DEBUG -> Options & Settings... -> Debugging -> Output Window
and turning Off unneeded output messages types

A: Does adding this work?
<location path="YouSiteName">
    <system.webServer>
        <httpLogging dontLog="true" />
    </system.webServer>
</location>

Found at: http://forums.iis.net/post/1992357.aspx


text:
Q: Showing an image from LocalStore in HTML on PhoneGap/Cordovia on Windows Phone 7 What is required to show an image from LocalStorage in HTML markup on PhoneGap running on Windows Phone 7?

*

*an image is downloaded from the Internet and stored on the phone (on Windows Phone 7 it can be stored only in LocalStorege of the application's domain);

*this image is to be shown using PhoneGap \ Cordova HTML markup with  element;

*using  ain't working;

A: The solution was quite different from Android version.
Following steps are necessary:

*

*load the image from localstore as binary data;

*place it in the "src" attribute of the img element encoded;
Code:
var fileName = 'myappname/test.png';

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFail);

function onFileSystemSuccess (fileSystem) {
  fileSystem.root.getFile(fileName, null, gotFileEntry, onFail);
}

function gotFileEntry(fileEntry) {
  fileEntry.file(onGotFile, onFail);
}

function gotFile(onGotFile) {
  var reader = new FileReader();
  reader.onloadend = function (evt) {
    $('#outerDiv').html('');
  };
  reader.readAsDataURL(file);
}

function onFail(evt) {
  console.log('error: ' + evt.target.error.code);
}


text:
Q: Pandas.to_datetime giving an error when given 15-Jan-0001 is there a way around this? I've got a dataset which goes back to 15-Jan-0001 (yes that is 1 CE!), it was originally 0 CE but since that year doesn't exist I cut those 12 months out of the data.
I am trying to get pandas to convert to date-time string in my datasdf.datetime=pd.to_datetime(df.datetime) to an internal datetime object.
I tried:
import pandas as pd
df = pd.load_csv(file)
df.datetime = pd.to_dtaetime(df.datetime)

and got:
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-15 00:00:00

the first two lines of the csv file are:
datenum,year,month,day,datetime,data_mean_global,data_mean_nh,data_mean_sh
381,1,1,15,15-Jan-0001 00:00:00,277.876675965034,278.555895908363,277.197456021705

A: One way is convert this problematic values to NaTs:
df.datetime = pd.to_dtaetime(df.datetime, errors='coerce')


text:
Q: Class not found exception in a route of slim framework I'm starting with Slim+eloquent+twig  (using this presentation http://slides.com/revul/slimframework )  and getting this error:
 Type: Error
 Message: Class 'Localizacao' not found
 File: /Users/Bigua/Sites/salas/src/routes.php
 Line: 19

I'm trying to list all from a table and pass it to my view. The command "composer update" don't returned any problem.
here my code:
Composer.json:
{
"name": "slim/slim-skeleton",
"description": "A Slim Framework skeleton application for rapid development",
"keywords": ["microframework", "rest", "router", "psr7"],
"homepage": "http://github.com/slimphp/Slim-Skeleton",
"license": "MIT",
"authors": [{
    "name": "Josh Lockhart",
    "email": "info@joshlockhart.com",
    "homepage": "http://www.joshlockhart.com/"
}],
"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.1"
},
"autoload": {
    "psr-4": {
        "App/Models\\": "app/models"
    }
}

Route
$app->get('/sala/add', function ($request, $response, $args) {
    $this->logger->info("Slim-Skeleton '/salas/add' route");
    // Render index view
    $args['locais'] = Localizacao::all();
    $this->logger->info("locais" . $args);
    return $this->renderer->render($response, 'add_sala.html.twig', $args);
})->setName('sala_add');

Model
<?php
  namespace App\Models;

  use Illuminate\Database\Eloquent\Model as Eloquent;

  class Localizacao extends Eloquent {
    protected $table = 'localizacao';

    protected $primaryKey = 'id_local';
    public $timestamps    = false;
  }

I had read many similar topics here and seems to me that is a problem with namespaces, but I just don't get it where its wrong. Sorry if this is a noob question.
[SOLVED]
The solution its following the two answers, from @marcin-nabiałek and @geggleto  :
Fixed the psr-4:
"psr-4": {
    "App\\Models\\": "app/models"
}

And using namespace correctly:
  \App\Models\Localizacao::all()

Tnx a lot !!!

A: Your composer entry for PSR-4 autoloading is incorrect
"psr-4": {
    "App/Models\\": "app/models"
}

Should be
"psr-4": {
    "App\\Models\\": "app/models"
}

A: The problem is that Localizacao is in App\Models namespace and in routes.php you use:
Localizacao::all()

without any namespace so it's assumed it's from global namespace.
You can replace it into:
\App\Models\Localizacao::all()

or use it like before but at the top of file add:
use App\Models\Localizacao;

A: Let Make things Clear here, the reason why this error is because the name you use for your psr-4 is not the same with the name you declare in your controller class: for example:
 "autoload-dev": {
        "psr-4": {
            "{name you will like to use for your name space here, that will represent your application name e.g any name here (App) for instance}\\": "the directory you will like to load your asset,library, routes,middle-ware etc e.g like app or src/"
        }
    }


text:
Q: UIimage Detect Landscape Image with Swift I want to read a photo from Library
in this function
 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

now I want to know is that landscape photo or not I try to tie this code
if(pickedImage?.size.width > pickedImage?.size.height)

But I received this error Binary operator '>' cannot be applied to two 'CGFloat?' operands how can I resolve this Problem

A: Try this
 if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

   {
      if pickedImage.size.width > pickedImage.size.height
      {
         /// landscape mode
      }

   }

}

A: The problem here that you try to work with Optional values, instead of unwrapped. To unwrap value you can use guard:
guard let pickedImage = pickedImage else {
    // false logic here
    return
}

if pickedImage.size.height > pickedImage.size.height {

} else {

}

By the way, are you sure that you want to compare pickedImage's height to itself? Looks weird.

A: I find the solution with this code ? -> !
if(pickedImage!.size.width > pickedImage!.size.height)

A: Another possible solution could be to use switch pattern matching:
switch image?.size {
case .some(let size) where size.height > size.width:
  // do something
default:
  break
}


text:
Q: Intersection of two convex functions such that their derivatives are also the same at the intersections I have two functions $T_1(x)$ and $T_2(x)$ defined on the interval $[0,1]$ such that $T_1(0) = T_2(0) = 0$ and $T_1(1) = T_2(1) = 1$. Furthermore, both of these are strictly monotone functions and are convex in the given interval. Also, they are  differentiable at least twice.  My aim is to prove these two functions are exactly equal. I have the following additional constraints on them.

*

*$T_1'(0) = T_2'(0)$ and  $T_1'(1) = T_2'(1)$

*They intersect at $2$ points in (0,1).

Intuitively, I think that the functions should be the same given the constraints and I think only the first condition is sufficient to prove this. However, I am not able to get a proof for the same even with both these conditions. I tried a variety of things but they did not lead me anywhere. Any help on this would be highly appreciated. Thanks!

A: This is not true. Set $T_1(x) = x^2$, consider a smooth function $g$ which has compact support in $(0,1)$ and set $T_2(x) := T_1(x) + \epsilon \, g(x)$ for $\epsilon$ small enough.

A: Here is a rather tedious counterexample.
Define $f(x) = {1 \over 3} x$ for $x \in [0, { 1\over 3}]$, and
$f(x) = 3x-2$ for $x \in [{8 \over 9}, 1]$.
Note that $f({1 \over 3}) = {1 \over 9}$, $f'({1 \over 3}) = {1 \over 3}$, $f''({1 \over 3}) = 0$, and
$f({8 \over 9}) = {2 \over 3}$, $f'({8 \over 9}) =  3$, $f''({8 \over 9}) = 0$.
In particular, if we let $a={1 \over 3}, b={8 \over 9}$, then we have
$f'(a) < f'(b), f''(a) = f''(b) = 0$.
We can construct many convex functions $\phi$ on $[a,b]$ such that
$\phi(a) = f(a), \phi(b) = f(b) $, $\phi'(a) = f'(a), \phi'(b) = f'(b) $, $\phi''(a) = \phi''(b) = 0$. Then if we define $f(x) = \phi(x)$ for
$x \in [a,b]$ we have many functions that satisfy the criteria.
To show one such construction, it will be easier to work in terms of $g=\phi'$. Then the constraints are $g(a)=f'(a), g(b)=f'(b)$, $g'(a)=g'(b) = 0$, $g'(x) \ge 0$ for $x \in [a,b]$ and $\int_a^b g(t)dt = f(b)-f(a)$.
To see one way of doing this, choose $t_t,t_2$ such that $a < t_1 < t_2 < b$ and define $g(x) = f'(a)$ for $x \in [a,t_1]$, $g(x) = f'(b)$ for $x \in [t_2,b]$ and
$g(x) = {f'(a)+f'(b) \over 2} + {f'(a) -f'(b) \over 2} \cos ({x - t_2 \over t_2-t_1}\pi)$ for $x \in [t_1,t_2]$. It is easy to confirm that all of the constraints except the integral one are satisfied.
To show that there are multiple values of $(t_1,t_2)$ that satisfy the integral constraint, note that
$\int_a^b g(t)dt= f'(a) ({t_1+t_2 \over 2} -a) + f'(b) (b-{t_1+t_2 \over 2})$.
Since $f'(a)(b-a) < {f(b)-f(a)} < f'(b)(b-a)$, we see that we can choose a
value of ${t_1+t_2 \over 2}$ such that the integral constraint is satisfied.
Now we can choose $t_1-\delta,t_2+\delta$ for small $\delta$ to get different functions.


text:
Q: Weird behavior of jquery click event handler with setInterval Hi everybody,
I am building an application which includes a fast interval along with a scrollTop modification. I have an overflowed div and each interval cycle update's the scrollTop position of that div. I run into a very weird behavior of the click event handler which does not fire.
HTML:

CSS:
* {border:0px; margin:0px; padding:0px;}
#wrapper {width:350px; height:100px; overflow:hidden;}
#wrapper .cube {width:350px; height:100px; float:left;}

.red {background-color:#f00;}
.gray {background-color:#454545;}
.blue {background-color:#1d5ef3;}
.green {background-color:#0c0;}
.orange {background-color:#f60;}

Javascript:
var myInterval;
var i = 1;
var el = $('#wrapper');
var cubeNum = ('.cube').length;

el.click(function(){
    clearInterval(myInterval);
});

myInterval = setInterval(function(){
    el.scrollTop(i * 100);
    i++;
    if(i >= cubeNum)
        i = 0;
},16.6);

You can see here a simple example of the bug:
http://jsfiddle.net/rMN55/
You can notice that the click handler is not fired from the first click.
If you raise the interval to 300ms than everything works fine.
Another thing that I noticed is that if I changes the handler to mousedown (With the same 16.6 ms interval) than everything works as it should.
Javascript:
var myInterval;
var i = 1;
var el = $('#wrapper');
var cubeNum = ('.cube').length;

el.mousedown(function(){
    clearInterval(myInterval);
});

myInterval = setInterval(function(){
    el.scrollTop(i * 100);
    i++;
    if(i >= cubeNum)
        i = 0;
},16.6);

Check out the same example with a mousedown handler attached:
http://jsfiddle.net/rMN55/1/
Is this a bug in the way that jQuery handles clicks?
Should i open a ticket in the bug report system?


text:
Q: NGROK, can't assign port on URL I was wondering if there's a way to assign a specific port using TCP to the URL that ngrok generates.
i tried with config.yml file, it has this code but it doesn't work
tunnels:
  blueiris:
    remote_port: 5666
    proto: tcp
    addr: 123

it generates this URL: Forwarding                    tcp://0.tcp.ngrok.io:18777 -> localhost:123
the port of the localhost pretty much it doesn't matter. I wan't to assign the port 5666 to the URL 0.tcp.ngrok.io so it can be: 0.tcp.ngrok.io:5666
Thanks.


text:
Q: How to change the default size of a font file? Is it possible to change the default size of a font file.
I'm talking about ttf files.
On my kindle paperwhite, I installed a couple of new fonts. Some of them works great, while some other appears too small, but enlarge it in the kindle menu results in a much larger font that is not good for read.
I'm wondering whether I could tweak the font file so that the default size will be bigger.
I work under the linux environment.

A: I've googled a way using the free software fontforge. Fontforge change font size
After installation, open the font file you want to change.
The detailed steps are as follow:

*

*go to: Edit>Select>SelectAll (all characters should be selected)

*go to: Element>Tansformations>Transform

*On the transform menu, I have chosen to increase by 20%...make sure all boxes below are checked.

*Click ok

*It should now render them 20% larger (or whatever you choose)

*go to: File>Generate Fonts
make sure you change filename to keep the original clean and de-select validate - otherwise you will get about 200 warnings

*Click ok...there will be a couple of warnings that appear, but I have not found any visible font issues or errors-you can ignore them - hat is it. When you close Font Forge, it will ask you about saving changes...if you do, it creates another file type, but I have never paid attention to it.


text:
Q: Why proxy class is required for Spring AOP? What is the responsibity of the proxy class in AOP? What is the role of that?

A: Dynamic proxies are used to execute additional code before/after methods of your beans. The most trivial example is transaction handling:

*

*spring creates a proxy around your beans that need transactions

*if a method is declared transactiona (e.g. annotated with @Transactional) the proxy starts a new transaction and delegates to the real method

*the real method executes and returns

*the proxy now commits (or rollbacks) the transaction

Thus your code becomes transaction-agnostic. And when a transactional bean is injected into another one, it is actually the proxy that gets injected (which is of the same type as your bean)
And proxies are dynamic, because spring does not know at compile time the types of all your beans, so it has to create the proxies at runtime.


text:
Q: Como selecionar ultimo registro da tabela MySQL com last ou outro comando? Como selecionar ultimo registro da tabela MySQL com last ou outro comando
Por exemplo:
select last registro from tabela where coluna = 23;

Já tentei com este código mas não funcionou.

A: Se a tabela possuir um campo auto incremento faça a ordenação decrescente e limite o resultado em 1 linha.
SELECT registro FROM tabela WHERE coluna = 23 ORDER BY id DESC limit 1;

A: Já faz muito tempo essa pergunta, mas segue a resposta.
SELECT MAX(id) as maxId FROM table

A: SELECT MAX(id) as maxId FROM table

Acho que este tipo de consulta traz o maior valor e não o último!


text:
Q: Map a SignalProducer that contains an error to return a NoError I am working with ReactiveSwift 3.x in an iOS project and have been unable to map over an error provided by one SignalProducer into a different one.
My NoError SignalProducer is:
func foo() -> SignalProducer<Void, NoError>

The function being called within foo() that I want to map is:
func bar() -> SignalProducer<Data, MyError>

I currently have the following:
func foo() -> SignalProducer<Void, NoError> {
    // Stuff happens here...
    return bar()
        .map({ _ -> Void in
            return ()
        })
        .mapError({ error -> NoError in
            print(error.localizedDescription)
            // I do not want to handle this error
            return NoError
        })
}

But I am getting the error:

'mapError' produces 'SignalProducer< Void, F >', not the expected
   contextual result type 'SignalProducer< Void, NoError >'

Ultimately, I just want to print out the error, and then return.

A: Quack.
I had attempted some flatMapError work earlier, but got it to work with the following:
.flatMapError({ error -> SignalProducer<Void, NoError> in
    return SignalProducer.empty
    })


text:
Q: How can I reference column aliases from a projection inside the projection? Calculations on the projection (select) values are  useful and common. Yet column aliases declared in the projection can't be used there.
select sellprice as x, cost as y, x/y as markup
from mytable

gives an error.
I can accomplish this with
select sellprice as x, cost as y, sellprice/cost as markup
from mytable

But that is a simple example: We usually declare column aliases names with as for complex cases. For example, instead of cost, I might have some  function built from average etc,  that I declare as a column alias.
How can I use these aliases inside the projection clause?

A: The usual way to cope with that is to use a derived table (aka sub-query):
select x, y, x/y as markup
from (
  select sellprice as x, cost as y
  from mytable
) as t;


text:
Q: OAuth2 Configuration Issues: AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: Trying to get Oauth2.0 to work with APIM in my Azure space.
I have imported and setup an 2.0 Open API as the backend.  I am using the APIM developer portal as the client to call this backend API.  I have the dev portal App ID as the Client ID and using its Client Secret.  I tried using the provided redirect_uri for authorization code as the reply url and also tried using app.com/auth with same issue
When I  make a call to the API from the Developer Console, I prompted to sign in. I then sign in and get the following error:
AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.
Any help would be greatly appreciated

A: Do follow this document to protect your API by using OAuth 2.0 with Azure Active Directory.
Note: This document applies to App registrations(Legacy). If you used App registrations, there will be something different from the document.

It seems that the reply url configured for your client app is not correct.
Click OAuth2.0->click your oauth2 service->you will find the redirect_uri.

Go you your client app and replace the reply url with this redirect_uri.


text:
Q: xlsxwriter modifying worksheet font I need assistance modifying the font and size of excel spreadsheet from default to 'Arial' 9.  I'm able to modify the header row, but unable to get the body of the spreadsheet to do the same.  I'm using xlsxwriter, I'm sure it's something simple just not that familiar with xlsxwriter.   See code below, any assistance greatly appreciated.
Pipeline_details.to_excel(writer1,
                          sheet_name ='Pipeline_Details',
                          startrow=1,
                          startcol=0,
                          header=False,
                          index=False)

workbook = writer1.book
worksheet = writer1.sheets['Pipeline Details']
(max_row, max_col) = Pipeline_details.shape
worksheet.autofilter(0,0,max_row, max_col - 1)
worksheer.hide_gridlines(2)

header_format = workbook_add.format({
    'font_name': 'Arial',
    'font_size': 9,
    'bold': False,
    'text_wrap': True})

for col_num, value in enumerate(Pipeline_details.columns.values):
    worksheet.write(0, col_num, value, header_format)

cell_format = workbook.add_format({'font_name': 'Arial', 'font_size': 9})

writer1.save()

A: The docs for formatting while using pandas with xlsxwriter state the following:

XlsxWriter and Pandas provide very little support for formatting the output data from a dataframe apart from default formatting such as the header and index cells and any cells that contain dates or datetimes. In addition it isn't possible to format any cells that already have a default format applied.

If you require very controlled formatting of the dataframe output then you would probably be better off using Xlsxwriter directly with raw data taken from Pandas.

That being said

It is possible to format any other, non date/datetime column data using set_column()

For an example using A notation, you'd execute this after writing your data to the worksheet:
worksheet.set_column('A:Z', None, format)

I'd try that first to see if you get anywhere with it. Otherwise I'd suggest writing your rows yourself and adding your format that way.


text:
Q: php-curl зависает, как изменить версию пакета? На моем сервере установлена php-curl 7.68.0
По неизвестной причине, часть запросов с этой библиотекой "зависают" - скрипты перестают реагировать и спустя время убиваются ядром. Проблема непостоянна и уловить ее причину не удалось.
Когда-то сталкивался с подобным и решил ее сменой версии curl. Сейчас не могу найти, как изменить версию php-curl на сервере?
Ubuntu 20.04


text:
Q: VB.NET - Accessing My.MySettings.Default changes Thread.CurrentPrincipal? It appears that when you access My.Settings.Default in VB.NET, your thread's CurrentPrincipal changes. Consider the following code.
            Dim name = "admin"
            Dim user = Membership.GetUser(name)
            Dim identity = New GenericIdentity(user.UserName)
            Dim principal = New RolePrincipal(identity)

            System.Threading.Thread.CurrentPrincipal = principal
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)
            Dim x = My.MySettings.Default
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)

The output of this code is

admin
MyDomain\MyUserName

Is this expected? Is it documented anywhere? I couldn't find any references to it.
It also seems to only do this the first time My.MySettings.Default is accessed, which means that a workaround might be to touch the property to initialize it before attempting to set the thread's CurrentPrincipal. Would there be any undesirable side effects to doing that?

A: I believe that this is because the default instance is created using a thread-safe operation:
    Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)

Since the default instance is only created the first time you access MySettings, I think the easiest solution is to access it once prior to changing your user identity.


text:
Q: Smoothing algorithm using integer arithmetic The following code was taken from an Arduino tutorial on smoothing:
int smooth(int data, float filterVal, float smoothedVal) {

  if (filterVal > 1) {
    filterVal = .99;
  }
  else if (filterVal <= 0) {
    filterVal = 0;
  }

  smoothedVal = (data * (1 - filterVal)) + (smoothedVal  *  filterVal);

  return (int)smoothedVal;
}

The following statement, took from the same tutorial, got me thinking:

This function can easily be rewritten with all-integer math, if you need more speed or want to avoid floats.

Fact is I do want to avoid floats and increase speed, but I wonder: how to convert this to integer arithmetic? Bit-banging solutions are a bonus ;o)

A: A simple technique is scaling up by multiplying the input value with for example 10000 and putting that result in an int, do the calculations in int, and then scale the output back into a float by dividing with the same factor.
In your function you then also need scale up everything with that same factor.
The choice of factor depends on the possible ranges of the values; you want to avoid overflow at the high end, and inaccuracy at the low end.  If you think about it, the factor determines where you put the decimal point: fixed point, instead of floating point.
The factor can be anything, it does not have to be 100, 1000, and so on, but 627 is fine too.
If you go down this route, you want to convert as much of your code to int, because the conversions described above of course also take time.
To illustrate my point, the following could be it:
#define FACTOR 10000  // Example value.
int smooth(int data, int filterVal, int smoothedVal)
{
    if (filterVal > FACTOR)
    {
        filterVal = FACTOR - 100;
    }
    else if (filterVal <= 0)
    {
        filterVal = 0;
    }

    smoothedVal = (data * (FACTOR - filterVal)) + (smoothedVal * filterVal);

    return smoothedVal;
}

You may need/want to check for overflow, ...

A: //  ------------------------------------------------------------------
//  SMOOTHING WITH INTEGER VARIABLES  (CSHARP)
//  ------------------------------------------------------------------
Int32 Storage;
Int32 SmoothingINT(Int32 NewValue, Int32 Divisor)
{
    Int32 AvgValue;
    //  ------------------------- Compute the output averaged value
    AvgValue = Storage / Divisor;
    //  ------------------------- Add to storage the delta (New - Old)
    Storage += NewValue - AvgValue;
    //  -------------------------
    return AvgValue;
}

Or
' -------------------------------------------------------------------
' SMOOTHING WITH INTEGER VARIABLES  (VbNet)
' -------------------------------------------------------------------
Function SmoothingINT(ByVal NewValue As Int32, ByVal Divisor Int32) As Int32
    Dim AvgValue As Int32
    Static Storage As Int32
    ' -------------------------- Compute the output averaged value
    AvgValue = Storage \ Divisor
    ' -------------------------- Add to storage the delta (New - Old)
    Storage += NewValue - AvgValue
    ' --------------------------
    Return AvgValue
End Function


text:
Q: mysql auto increment - use 1st available blank instead of the last number Instead of automatically adding the ID number after the last highest ID number, how can I:
Automatically add the next available blank in sequence.
ie
I have a table with the following ID's that are taken
1,2,5,9
Instead of auto incrementing so the next one is 10, I'd like to know if possible I can automatically make the next ID 3.
I have many ID's that need filling before I start adding more to the end.


text:
Q: Need to Fetch Row which have count 2 i have table A such as
       TABLE1
  =======================
  | id | product_id | filter_id | category_id |
  | 16 | 33         | 6         | Null        |
  | 23 | 40         | 16        | 76          |
  | 48 | 20         | 6         | 45          |
  | 69 | 10         | 6         | 87          |
  | 70 | 10         | 9         | 67          |

Now i have to find product_id 10 which have filter_id 6 and 9

A: You could just use having
select
    product_id, count(product_id)
from
    teble1
group by
    product_id
having
    count(product_id) = 2;

A: use one of this samples
SELECT *
FROM TABLE1
WHERE products_id = 10
AND filter_id IN (6,9);

OR
SELECT *
FROM TABLE1
WHERE products_id = 10
AND (filter_id = 6 OR filter_id = 9);