How to solve "Bitmap is not valid" error when I fetch image from online

Question: I am trying to make an app which shows images from online database. but I want to use palette API to get vibrant color from each image. But I think I don't know how to use Bitmap decodeResource method OR Palette. please guide me how to use Bitmap factory.decoderResource with Palette in online URL or URI image file.
here is the method which I used in activity class recylceview subclass error shows in line number 171 "Bitmap is not valid":
170    Bitmap photo = BitmapFactory.decodeResource(getResources(), mCursor.getPosition());
171    Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
                public void onGenerated(Palette palette) {
                    int bgColor = palette.getLightVibrantColor(getApplicationContext().getResources().getColor(android.R.color.black));
                    holder.placeNameHolder.setBackgroundColor(bgColor);
                }
            });

So here is the error:
10-29 17:39:42.067 31692-31750/com.example.xyzreader E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found
10-29 17:39:42.282 31692-31692/com.example.xyzreader E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.xyzreader, PID: 31692
                                                                       java.lang.IllegalArgumentException: Bitmap is not valid
                                                                           at android.support.v7.graphics.Palette$Builder.<init>(Palette.java:616)
                                                                           at android.support.v7.graphics.Palette.from(Palette.java:100)
                                                                           at android.support.v7.graphics.Palette.generateAsync(Palette.java:134)
                                                                           at com.example.xyzreader.ui.ArticleListActivity$Adapter.onBindViewHolder(ArticleListActivity.java:171)
                                                                           at com.example.xyzreader.ui.ArticleListActivity$Adapter.onBindViewHolder(ArticleListActivity.java:125)
                                                                           at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6062)
                                                                           at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6095)
                                                                           at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5277)
                                                                           at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5153)
                                                                           at android.support.v7.widget.LayoutState.next(LayoutState.java:100)
                                                                           at android.support.v7.widget.StaggeredGridLayoutManager.fill(StaggeredGridLayoutManager.java:1568)
                                                                           at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:678)
                                                                           at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:600)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3374)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3183)
                                                                           at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3627)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:630)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1142)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:836)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:850)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at com.android.internal.policy.DecorView.onLayout(DecorView.java:724)
                                                                           at android.view.View.layout(View.java:17519)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5612)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2342)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2069)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:683)
10-29 17:39:42.282 31692-31692/com.example.xyzreader E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

1- ArticleListActivity.class:
public class ArticleListActivity extends ActionBarActivity implements
        LoaderManager.LoaderCallbacks<Cursor> {

    private Toolbar mToolbar;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_list);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        ((CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout)).setTitle("XYZ Reader");

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        getLoaderManager().initLoader(0, null, this);

        if (savedInstanceState == null) {
            refresh();
        }

        //1---- I added setOnRefreshListener and then call refresh method in onRefresh()
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               refresh();
            }
        });
    }

    private void refresh() {
        startService(new Intent(this, UpdaterService.class));
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(mRefreshingReceiver,
                new IntentFilter(UpdaterService.BROADCAST_ACTION_STATE_CHANGE));
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mRefreshingReceiver);
    }

    private boolean mIsRefreshing = false;

    private BroadcastReceiver mRefreshingReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (UpdaterService.BROADCAST_ACTION_STATE_CHANGE.equals(intent.getAction())) {
                mIsRefreshing = intent.getBooleanExtra(UpdaterService.EXTRA_REFRESHING, false);
                updateRefreshingUI();
            }
        }
    };

    private void updateRefreshingUI() {
        mSwipeRefreshLayout.setRefreshing(mIsRefreshing);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return ArticleLoader.newAllArticlesInstance(this);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        Adapter adapter = new Adapter(cursor);
        adapter.setHasStableIds(true);
        mRecyclerView.setAdapter(adapter);
        int columnCount = getResources().getInteger(R.integer.list_column_count);
        StaggeredGridLayoutManager sglm =
                new StaggeredGridLayoutManager(columnCount, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(sglm);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mRecyclerView.setAdapter(null);
    }

    private class Adapter extends RecyclerView.Adapter<ViewHolder> {
        private Cursor mCursor;

        public Adapter(Cursor cursor) {
            mCursor = cursor;
        }

        @Override
        public long getItemId(int position) {
            mCursor.moveToPosition(position);
            return mCursor.getLong(ArticleLoader.Query._ID);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.list_item_article, parent, false);
            final ViewHolder vh = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            ItemsContract.Items.buildItemUri(getItemId(vh.getAdapterPosition()))));
                }
            });
            return vh;
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            mCursor.moveToPosition(position);
            holder.titleView.setText(mCursor.getString(ArticleLoader.Query.TITLE));
            holder.subtitleView.setText(
                    DateUtils.getRelativeTimeSpanString(
                            mCursor.getLong(ArticleLoader.Query.PUBLISHED_DATE),
                            System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS,
                            DateUtils.FORMAT_ABBREV_ALL).toString()
                            + " by "
                            + mCursor.getString(ArticleLoader.Query.AUTHOR));
            holder.thumbnailView.setImageUrl(
                    mCursor.getString(ArticleLoader.Query.THUMB_URL),
                    ImageLoaderHelper.getInstance(ArticleListActivity.this).getImageLoader());
            holder.thumbnailView.setAspectRatio(mCursor.getFloat(ArticleLoader.Query.ASPECT_RATIO));

            Bitmap photo = BitmapFactory.decodeResource(getResources(), mCursor.getPosition());
            Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
                public void onGenerated(Palette palette) {
                    int bgColor = palette.getLightVibrantColor(getApplicationContext().getResources().getColor(android.R.color.black));
                    holder.placeNameHolder.setBackgroundColor(bgColor);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mCursor.getCount();
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout placeNameHolder;
        public DynamicHeightNetworkImageView thumbnailView;
        public TextView titleView;
        public TextView subtitleView;

        public ViewHolder(View view) {
            super(view);
            placeNameHolder=(LinearLayout) view.findViewById(R.id.placeNameHolder);
            thumbnailView = (DynamicHeightNetworkImageView) view.findViewById(R.id.thumbnail);
            titleView = (TextView) view.findViewById(R.id.article_title);
            subtitleView = (TextView) view.findViewById(R.id.article_subtitle);
        }
    }
}

2- Xml file
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="112dp"
        android:background="?colorPrimary">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/collapsing_toolbar_layout"
        app:collapsedTitleTextAppearance="@style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
        app:expandedTitleMarginStart="72dp"
        app:contentScrim="?attr/colorPrimaryDark"
        app:expandedTitleTextAppearance="@style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            app:theme="@style/ThemeOverlay.AppCompat.Light"
            android:layout_marginLeft="@dimen/list_toolbar_side_margin"
            android:layout_marginRight="@dimen/list_toolbar_side_margin"
            app:contentInsetStart="72dp"
            app:layout_collapseMode="pin"
            >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/logo"
                app:layout_collapseMode="parallax"
                android:scaleType="centerCrop"
                android:contentDescription="@string/app_name" />

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:scrollbarStyle="outsideOverlay"
            android:paddingTop="116dp"
            android:paddingLeft="@dimen/list_side_margin"
            android:paddingRight="@dimen/list_side_margin"
            android:paddingBottom="28dp" />

    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.design.widget.CoordinatorLayout>

Answer:
Sorry for late reply,

I forgotten to answer this question after solving problem. So here is the answer :
I found Picasso API for Palette color and here is the code of Picasso API with Palette feature
Picasso.with(getActivity())
                    .load(mCursor.getString(ArticleLoader.Query.PHOTO_URL))
                    .into(Imagebar, new com.squareup.picasso.Callback() {
                        @Override
                        public void onSuccess() {
                            Bitmap bitmap = ((BitmapDrawable) Imagebar.getDrawable()).getBitmap();
                            if (bitmap != null) {
                                Palette.from(bitmap)
                                        .generate(new Palette.PaletteAsyncListener() {
                                            @Override
                                            public void onGenerated(Palette palette) {
                                                Palette.Swatch vibrantSwatch = palette.getDominantSwatch();
                                                if (vibrantSwatch != null) {
                                                    bylineView.setBackgroundColor(vibrantSwatch.getRgb());
                                                    bylineView.setTextColor(vibrantSwatch.getTitleTextColor());
                                                    coordinatorLayout.setBackgroundColor(vibrantSwatch.getPopulation());
                                                }
                                            }
                                        });
                            }
                        }

                        @Override
                        public void onError() {
                            Snackbar snackbar = Snackbar
                                    .make(coordinatorLayout, "Error on image load.", Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }
});


order topology is Hausdorff

Question: Is it appropriate to ask the community to check my proof?  I am rereading Munkres Topology and trying to do the HW.  This is my attempt for #10 on page 101.

Show that every order topology is Hausdorff.

Proof:
Suppose that $x_1, x_2$ are elements of $X$, and $x_1 < x_2$.
Case 1:
Suppose that $x_2$ is the next element after $x_1$, and suppose that $$x_0 < x_1 < x_2 < x_3.$$  Then $x_1$ is an element of $(x_0, x_2) = U_1$.  Then $x_2$ is an element of $(x_1, x_3) = U_2$.
$U_1$ and $U_2$ are disjoint.
Case 2:
Suppose that there might not be "next elements" in $X$ but $x_1 < x_2$.  Then there exists $$a < x_1 < b < x_2 < c.$$  Then $x_1$ is an element of $(a, b) = U_1$.  Then $x_2$ is an element of $(b, c) = U_2$.
$U_1$ and $U_2$ are disjoint.
Thus $X$ is Hausdorff.
Is this on the right track?
Comment: Note that actually it holds that order topology is hereditarily normal.
Answer: It's almost right: in Case $1$ you forgot to cover the cases in which $x_1$ or $x_2$ is an endpoint of the space. However, there's no need to treat these separately if you modify your proof a little. I'd arrange it like this:

Let $x,y\in X$, and assume without loss of generality that $x<y$. If there is a $z\in X$ such that $x<z<y$, let $U=(\leftarrow,z)$ and $V=(z,\to)$; then $x\in U$, $y\in V$, and $U\cap V=\varnothing$. If there is no such $z$, let $U=(\leftarrow,y)=(\leftarrow,x]$ and $V=(x,\to)=[y,\to)$; once again $x\in U$, $y\in V$, and $U\cap V=\varnothing$, and $X$ is therefore Hausdorff.

Here $(z,\to)=\{u\in X:u>z\}$, $(\leftarrow,z)=\{u\in X:u<z\}$, $[z,\rightarrow)=\{u\in X:u\ge z\}$, and so on.
Answer: Looks almost correct to me.
It might be a bit tighter to phrase you first case not in terms of "next elements," but in terms of whether a there exists an element $b$ such that $x_1 < b < x_2$.
Also, you don't cover cases where $x_1$ is minimal or $x_2$ is maximal. Those should be easy to do from the definition of the order topology, though.

order topology is Hausdorff


Predicting dichotomous outcome of temporal data set with covariates

Question: I have a set of data, with outcome and time-varying variables, for patients during the course of their respective stays in the hospital.  There is a dichotomous outcome on the last day. The length of stay may be different for each patient.  I am most interested in making a predictive model, in the same spirit as one might do with standard regression.
I believe that the patient may develop some "momentum" which would tend lead to one outcome or the other.
My previous attempts to model this data have been limited to logistic regression. I am beginning to think about lmer and friends, but I'm not sure if it would be suitable for the directionality in time. Also, I have considered some stochastic approaches, but I haven't made much progress with hitching this into a binary outcome or even considering the covariates.
Any suggestions would be most welcomed.
Fictional Data:
<code>Patient No. | Day of Stay | Outcome | Age | Gender | Blood Value | ...
         1  |           1 |       - |  70 |      M |       123.1 | ...
         1  |           2 |       - |  70 |      M |       134.2 | ...
         1  |         ... |     ... | ... |    ... |         ... | ...
         1  |          10 |       1 |  70 |      M |       148.3 | ...
           ...           ...       ...   ...      ...           ...
       100  |           1 |       - |  54 |      F |        98.3 | ...
       100  |           2 |       - |  54 |      F |        95.2 | ...
       100  |         ... |     ... | ... |    ... |         ... | ...
       100  |           6 |       0 |  54 |      F |        54.1 | ...
</code>
Comment: This would seem amenable to survival analysis which doesn't require that the outcomes be survival only that they be dichotomous and occur at a particular time. Time varying covariates are possible.
Comment: Do you have LOTS of data? Or a fairly small number of patients? And could you specify what sort of relationship you think exists between outcome and your time-series?
Comment: Well, both. We have a ton of retrospective data, seemingly infinite number of columns at our disposal. But I could image doing this on 100 or even a million.  I'm open to all suggestions: frequentist, Bayesian, etc.  It's hard to say what the relationship is, but in health care, I assume that the more one deviates from "normal" (up or down) the more unfortunate outcome is more likely to happen.
Answer: If you have a LARGE data set, there might be something in the machine learning literature to help you. View it as a classification problem. But since this is a medical example, I suspect the total number of patients is fairly small.
In that case, your best hope lies in being able to specify a model for the time-dependent stuff. For example, if a simple regression relates Day to Blood Value, you could compare the estimated slope parameter to outcome: 2 groups; simple t-test. If you have additional covariates, you could include them as well. You would then have a logistic regression with your slope parameter and covariates in the model. You could fit a more complex functional form if needed.
You might be able to model the blood value component in other ways: try a principal components analysis, and if most of the variation appear to be on the first component, replace the whole series of observations with the PC score. Then proceed as before with a logistic regression.
If you had the same number of "repeated observations" for each patient, you could try a discriminant analysis. This is similar to the PCA mentioned above, except that the components are chosen to best distinguish between the two dichotomous outcome of the last day.
Whatever you do, you can estimate your model from one portion of the data set and test it on the other part -- see how well you can actually predict the outcome.
Answer: I think a mixed effects model or a marginal model using generalized estimating equations (GEE) might work for you.  Using GEE you could specify a working correlation matrix that designates those observations later in the series as being more highly correlated with one another and you could add a variable into your model for the time component.  You could, of course do something similar with lmer and mixed effects (minus the working correlation matrix bit). The mixed effects approach has the added benefit that it isn't using a population averaged approach like GEE.
Taking this a step further, you may even be able to build several predictive models using classical statistical modelling techniques and machine learning techniques like boosted regression trees and then use a machine learning ensemble method to combine them into a single, more powerful predictor.  Using Stacking for example, you might build several models and then combined all of the models into one final prediction model.  These models generally outperform Bayesian model averaging approaches as well.


System dialog Angular Material

Question: I work for system of dialog (Angular Material).
I create dialog-service for controll and container dialog. Dialog-service has methods for open/show different dialoges.
And I create dialog-component for contain data for dialog (it is single component of dialog). It is universal component.
I add StackBlitz
I have problem with closing dialoges after callback.
How I can close dialog after callback? I try using [mat-dialog-close] - but I was not able to somehow parameterize - enable and disable the [mat-dialog-close] of different buttons.
And a have little problem. How I can add dynamicly mat-button to button element?
(I add class 'mat-button', but this don't full imitation mat-button)

 0 || getCloseButton()" mat-dialog-actions>
    <ng-container *ngFor="let button of getButtons()">
      <button [attr.class]="button.class"
        (click)="button.callback(button.callbackItem || dialogForm)">{{button.title}}</button>
    </ng-container>

Answer: In your dialog.html you must have something like this:
<button mat-stroked-button (click)="closeDialog()">Close</button>

and in your dialog.ts:
import { Component, OnInit, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
  selector: 'dialog',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {

  constructor(public dialogRef: MatDialogRef<DialogComponent>) { }

  ngOnInit() {
  }

  closeDialog() {
    this.dialogRef.close();
  }

}

Comment: Yep, this good idea, but I think HOW relation between dialog-service and dialog-component. How I formation button data for dialog-component that somethink buttons close dialog after callback function? Please, look at StackBlitz example.

System dialog Angular Material


Initial server response time for different cached pages

Question: I have been trying to speed up a Drupal site and measuring speed through page speed insight. What really has puzzled me for last few weeks of experiments is that node pages score an average of 170-200ms on 'initial server response time' while taxonomy pages (which are far more important from SEO speed point of time) take an average of 720-750ms in terms of initial page response time.
(Drupal 7, Nginx, Php-fpm, large site with over 100K nodes).
These are all cached pages (tried both Database and Memcache) using Page cache for anonymous users. Why is it taking 4 times more longer for Drupal to serve cached HTML of a term page versus cached HTML of a node page?
I am really stumped. Only time this changes is when I restart the Php-fpm. For a few minutes, term pages are close to 300ms before going back to 700+ms in few minutes.
Any ideas on what could be causing this? Could it be a php configuration issue?
Comment: The only way to know for sure is to profile.
Comment: Have you confirmed (by headers or stepping through the code) that the pages are definitely being served from cache?
Comment: Technically an answer to this question is "Upgrade to Drupal 10". Current releases have essentially solved this problem. In Drupal 7 I think you have to fiddle around with the Expire module.
Comment: Update - Changing Opcache to file cache has shaved 100ms off slow pages. I guess this explains why site feels faster after restarting php-fpm. Credit to this thread: https://forums.cpanel.net/threads/websites-works-fast-after-restarting-fpm.637557/
Comment: @Clive yes definitely going through Cache. Without Cache, those pages take over a second.
Comment: @cilefen How would you profile a Cache being delivered from database? Any help would be great!
Comment: @Clive sorry spoke too soon. It appears term pages aren't going through Cache at all. These are views pages. When I disabled Views caching, changes were showing without cache.
Comment: Now what's really happening here. Term pages are view based and views are cached. Now when some node updates and view needs to change, it expires the term page and anonymous users have the fresh page but logged in users still have old content. Is this the intended behaviour? I have minimum cache set to one hour and both page and block cache enabled.
Comment: @cilefen I agree - just too many legacy modules but we have to upgrade sooner or later I guess.
Answer: Finally got it to work.
Mistake I made was following.
While setting Cache for views, in the block setting page, I had selected 'Cache for every page'. This was generating and saving a copy of cache for lots of utm parameters/tracking variables and filled up Memcache instance.
Due to amount of views present on term pages, it was slowly them down.


Double explode an array

Question: The string:
user:hello,user2:world

Desired Output:
$string = array(
   1 => array( 1 => "user", 2 => "hello"),
   2 => array( 1 => "user2", 2 => "world")
);

What I've tried (that doesn't work):
$string = explode(',',$string);
$string = explode(':',$string);

The error I get: explode() expects parameter 2 to be string
How can I get from the string to the desired output? Thanks!
Comment: ................. Didn't expect this question, use explode then a foreach loop then explode again ...
Comment: loop over the output from the first explode and explode the second time on each value.
Comment: when you explode a string you obtain an array of strings not a string
Comment: [Here you go](http://viper-7.com/uDgaIq).
Answer: loop over the output from the first explode and explode the second time on each value.
$string = "user:hello,user2:world";
$array = explode(',', $string);

foreach($array as $k=>$v){
    $array[$k] = explode(':', $v);
}

Comment: @michi I just prefer not to use references with foreach loops, especially with really generic variable names like `$v` simply because I don't like leaving the open reference to `$v` when the loop is done. If a value later on assigns to `$v`, it will still have the reference to the last entry from the loop unless you explicitly `unset($v)`. I find setting the value in the array using the key to be more readable as well. Example: http://codepad.viper-7.com/tnIVSu If you leave out the possibility for the error of not unset'ing the reference, I feel it makes for better code.
Comment: just one little improvement: `foreach($array as &$v) $v = explode(':', $v);` see http://codepad.viper-7.com/5ExRH1
Comment: there is no need to make a reference out of $v, when he is reassigning the value through the key. either way works, to be honest
Comment: @JonathanKuhn: Right, this can be a problem.
Answer: <?php

$string = "user:hello,user2:world";

$array = array_map(function ($input) {
    return explode(':',$input);
}, explode(',', $string));

print_r($array);

Answer: Please try this:
$string = 'user:hello,user2:world';
$output = explode(',',$string);
foreach ($output as &$e) {
    $e = explode(':', $e);
}
print_r($output);

Comment: Don't forget to doing `unset($e);` after `foreach`. It may cause a new issue.
Answer: You can use example of user from manual.
function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo '
';
print_r($res);
echo '
';

Double explode an array


Criar Menu DropDown

Question: Alguém me poderia ajudar? Gostava de tornar este menu num menu dropdown, mas ainda não tenho conhecimentos para tal, e gostava de pedir ajuda.
// CSS
nav#mainnav ul {
    padding: 0;
    margin: 0;
    list-style: none;
}

nav#mainnav li {
    padding:0;
    border-bottom: 1px solid #99C581;
    border-top: 1px solid #6FAB4F;
}

nav#mainnav li.selected-item  {
    border-bottom:none;
}

nav#mainnav li.selected-item a,
nav#mainnav li.selected-item a:hover {
    color:#80B763;
    font-weight:bold;
    background: #fff;
}

nav#mainnav li a:hover {
    background:#669D48;
    color: #fff;
    text-decoration:none;
}

nav#mainnav li a {
    color: #f0f0f0;
    display: block;
    padding: 15px 17px;
    text-align: right;
    font-weight:  bold;
    text-decoration: none;
}

// HTML

Home

Exemplo 1

Exemplo 2

Exemplo 3

Exemplo 4

Comment: http://www.w3schools.com/css/css_dropdowns.asp
Comment: Veja no site [Dinamic Drive](http://dynamicdrive.com/). Lá possui muitas coisa pronta, e que é possível customizar.
Answer: Você pode começar alterando a estrutura HTML do seu menu, não que não seja possível fazer com essa estrutura, mas seria melhor trabalhar de forma diferente.
Este é só um exemplo e você precisa fazer as modificações de acordo com suas necessidades

#mainnav ul{
  list-style: none;
}

#mainnav ul li{
  padding:10px 15px;
  background:#000000;
}

.wrapper-menu{
  position:relative;
}

.dropdown{
  position:absolute;
  left:0;
  display:none;
}

.wrapper-dropdown:hover > .dropdown{
  display:block;
}

      Home

Exemplo 1

Exemplo 2

Exemplo 3

Exemplo 4

Esta estrutura HTML para dropdown pode abrigar vários dropdowns, com essa estrutura que você usa atualmente você só poderia colocar algumas poucas opções
Answer: @Renan voçê perguntou sobre o css??
Vou tentar explicar de uma forma detalhada:
Primeiro vc deve perceber que o seu codigo esta dentro de uma nav, ok vc disse para o navegador semanticamente que aqui dentro do nav será a sua sessão de navegação ok, logo em seguida vc colocou uma ul e dentro dessa ul, vc colocou 5 li(s);
Explicando como vc poderia estilizar isso no css;
Tenha em mente que vc começa a estilizar a ul pai,
ul.menu {
      list-style:none; //Repara, quero remover as bolinhas das li(s)
}

agora vc iriá estiliza os seus links;
/*Configura todos os links do menu*/
ul.menu a {
      text-decoration:none; //Quero remover o sublinhado da linha
      color: #fff; //cor do link
      display:block; //faz com que o elemento HTML seja renderizado como bloco, aqui acontece a magica;
}

/*Faz os
s ficarem na horizontal*/
 ul.menu > li {
       //Perceba que não quero estilizar todas as lis, somente as que são filhos direto da minha ul pai;
       //Quero que as li(s) ficam deitadas ex:Home Contact  AboutMe  etc
       float:left; //irão flutuar a esquerda
       position:relative; //A posição relativa ao pai
 }

Explicação sobre Posicionamento relativo e absoluto do css
/*Configurar os links do menu principal*/
ul.menu > li > a {
     position: relative;
     padding: 20px;
     margin: 0 5px;
}

/*Configurar o efeito ao clicar o mouse no link*/
ul.menu > li > a:active{
    top: 3px;
    left: 2px;
    box-shadow: 0px -2px 0px #009900;
    font-size: 12px;
    width: 150px;
    text-align: center;
}

/*Configurar o fundo do menu principal quando o mause passar em cima do meu link*/
ul.menu > li > a:hover{
    background: #009900;
}

Se tivesse dentro das suas li(s) outra ul:
/*Mostrar o submenu no evento do mouse hover*/
ul.menu > li:hover > ul.submenu{
    display: block;
}

O restante das configurações do sub-menu é parecido, ate aqui se vc entendeu o codigo, ficará facil de vc ter a logica de como construir um menu drop down, fica ligado que existe centenas maneiras de fazer isso, o interessante seria vc tentar entender o seletor, as propriedades, valores e a forma de se declarar os mesmos, como funciona a hierarquia do css não é facil no inicio ficar fera nisso, mas a pratica leva a perfeição.
Espero ter ajudado de alguma forma.
Answer: Olá,
o Bootstrap veio para facilitar de vez a nossa vida com o css. ele padroniza toda a estrutura css e tem nesse site tem uma documentação com tudo quase pronto! :)
Simplesmente associe um as três Tags no Head referenciando o css, a biblioteca jQuery e a versão compilada, os três nesta ordem:

<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Seu Site

Home

        Página 1

Página 1-1

Página 1-2

Página 1-3

Página 2

Página 3

Criar Menu DropDown


Quais as Dlls Preciso para criar um projeto com oracle no visual studio 2015?

Question: Ola pessoa tudo bem? atualmente estou tentando criar um novo projeto no visual studio 2015 com a nova versão do oracle RC1 update 2 eu gostaria de saber quais as Dlls do devart preciso para configurar meu projeto para criar conexão com o banco e tudo mais...
desde ja agradeço.
Answer: Você não mencionou se deseja trabalhar com ADO.NET ou Entity Framework.
Em todo caso, aconselho que trabalhe com EF6 Code First, para tal basta instalar o seguinte NuGet:
Official Oracle ODP.NET, Managed... 12.1.2400
Se preferir, pode faze-lo por linha de comando: PM> Install-Package Oracle.ManagedDataAccess.EntityFramework
Ele já tem como dependência o Oracle.ManagedDataAccess (Caso queira trabalhar com ADO.NET) e o EntityFramework.
lembrando que não deve utilizar o EF7 para trabalhar com Oracle, o mesmo ainda não tem suporte para o Oracle.
Lembrando que o Visual Studio permite criar o seu Modelo Code First de forma "automatizada", para tal adicione um item ao seu projeto ADO.NET Entity Data Model, então escolha Code First from Database.
Caso não tenha esta opção, talvez seja necessario instalar o Entity Framework 6 Tools for Visual Studio 2012 & 2013, mas como está à utilizar o VS 2015, acredito que não seja necessario.
Comment: Eu não entendi muito bem, pois sou iniciante TobyMosque, porem vou fazer o meu projetinho de estudos em query acredito que seja o ADO.NET que você esta falando.
Comment: @MarceloLopes, ADO.NET é a tecnologia que você usa para acessar qual quer banco de Dados, através dele você define objetos de conexão, comandos sql, leitura e modificação dos dados... Na internet você entra varios tutorias de como utilizar ele para acessar um Banco SqlServer, usando classes como SqlConnection, SqlCommand, SqlDataReader, tentre outras... Para Oracle você terá de instalar o `Oracle.ManagedDataAcess` (a forma mais simples é pelo `NuGet`), então utilize as classes OracleConnection, OracleCommand, OracleDataReader.
Comment: ja estou fazendo um projetinho com isso pra estudar obrigado.
Comment: @MarceloLopes, se aparecer qual quer duvida pelo caminho, é só fazer uma nova pergunta.
Comment: Ta certo obrigado


How to increase time resolution of a time series on specific days?

Question: Suppose I have a time series which has a frequency of 1 observation every 3 days.
I'd like to have a value for each day, that is increase the time resolution of the time series on specific days. Note: I don't need to do this for all the time series.
How can I do this? At first I thought I could somehow interpolate the time series but since it is not necessarily linear (nor quadratic or polynomial) with time this trick might not work.
Let's consider a time series which is a sum of sinusoidal and cosinusoidal terms as an example. Note that my original time series (which I can't share here) might not be that smooth... Suppose the observations are every 3 days and I'd like to find the value of the time series on the 10th day.
<code>t <- 1:30
tsv <- sin(t) + cos(2*t)
plot(t, tsv, type="l", ylab = "tsv", xlab="t")
points(tsv, pch="o", col="green")
</code>

Again, note that t is 3 days. That is, when t=10, it is the 30th day of observation.
The 10th day of observation should be between t=3 and t=4. What statistical method could be used to calculate the value of tsv for the 10th day?
Personally, as a first try I'd use:

Geometrical "interpolation" by taking the line that intersects the two values of tsv at t=3 and t=4. Very rough approximation that assumes linearity of the time series between 3 and 4 and then calculate the value on the 10th day.
Linear approximation of tsv by taking the numerical derivative of tsv in t=3 and then calculating $\Delta tsv = f'(t=3) \Delta t$

These methods do not seem very "statistical" based to me but they seem more on the math side of things. What statistical method could (or should I) use?
Answer: I would recommend that you fit an appropriate model for how your values depend on time and then interpolate. (This is actually what you have been doing.) An "appropriate" model will probably indeed involve periodic splines or harmonics to model seasonality, and potentially trends or other drivers, depending on your actual application.
A very simple model, e.g., using linear splines, may impose a lot of assumptions - but it may still work best, because it has low variance. More sophisticated models may look more elegant, but they will vary more.
Find which model is best by running cross-validation over a number of different ways to model your time series, using the values you already have. This will still only tell you how well your model performs in-sample. So if you have any way of actually obtaining some of the values you want to interpolate, these would be invaluable to check whether your interpolation makes sense. For all we know, the values you have never sampled are randomly drawn between 10,000 and 11,391.557, and all the interpolation is completely off the correct track.


Offline source control

Question: I'm about to start a project where programmers will be contributing from their homes (much like stackoverflow was built)
I want to use some centralized source control, but I don't want it to require the programmers to be online, and the server may come offline from time to time (as at first it'll probably be my desktop machine)
I think I remember Jeff talking about this in some podcast, but I don't remember which one.
Is there a source control tool that works perhaps asynchronically by e-mail?
Programmers could connect to download the latest version, and the checkin process would be sending files to an email account for example
Does such a thing exist?
EDIT: Sorry, I forgot to say that I'll be working with .NET (Visual Studio 2008)
It'd be great if it could be integrated into this environment... does GIT (suggested below) support that?
Comment: email is not a good way to move large files around.  If nothing else, there's too many places that are likely to limit transmission size or strip out attachments.  Use something better suited for this.
Answer: git is basically built with this scenario as one of the major requirements.
Others support it as well, they usually go under the name of "distributed version control system".
Comment: Agreed. I personally prefer Bazaar (http://bazaar-vcs.org/), but whichever you choose, it sounds like distributed version control is what you need.
Answer: You're looking for a Distributed Revision Control, system such as Git, Bazaar, or Mercurial.
I personally like Bazaar because it has good windows support.
I think Mercurial may be the best choice in your case, as it seems to have a Visual studio plugin.  It does have a web interface and ssh support, which are probably better options than email, but there is also an extension that allows patches via email.
Comment: Hmm, hadn't seen that... There goes one more difference... looks like they're all nearly identical at this point...
Comment: What about something that could be integrated in visual studio?
Comment: I think mercurial might be the only one with VS support... and I think that was a third party plugin
Comment: Bazaar has support for patches via email, but I'd use SFTP or similar.
How up to date is msysgit? How mature? I'm usually skeptical of Windows ports that require Cygwin (not because of any problems with cygwin, but because Windows is generally not a priority among products that rely on it)
Comment: Git and mercurial both have good windows support now, so most of the distinctions have gone away between the 3.
Answer: git and mercurial will both do this; they allow syncing via emailed patches.  Other distributed source control software will probably also work.
Answer: You could use git for this purpose. It doesn't require access to a centralized server, but you can set one up if you want to. Git differentiates between commit and push/pull, so working offline works great. The git website has great documentation.
Answer: Subversion is what Jeff was talking about in the podcast.  You can buy VisualSVN for Visual Studio integration.  svn works very well offline as you don't need to talk to the server unless you are checking stuff in, or getting stuff out.
Comment: The problem with SVN compared with real distributed version control systems is that you can't do local commits, compares, branches, merges. DVCS support all (or most) of those operations without access to a central repository.
Comment: Also look at AnkhSVN - Free for Visual Studio!
Comment: I love Git and saua is right about DVCS giving you more offline possibiliities. But for now, you'll get more utility from the integration of VisualSVN or AnkhSVN for working with Visual Studio.
Comment: Developers can always run local svn repositories and sync up the the server every so often to get most of the benefits of git. I did this on one project were VSS was the master source control system.   We used SVN locally and synced to VSS on a daily basis.
Answer: Sourcegear vault has an add on that allows this
Answer: There's also a free SmartSVN tool for Subversion, which integrates with Windows shell (adding fancy icons that let you distinguish locally modified files from pristine etc).
I've used Subversion and SmartSVN when working from home as well as in the office, and I can only recommend it. Check its features here.

Offline source control


Ruby: merging arrays or hashes

Question: I'm having trouble understanding how to solve this issue, essentially I have two arrays that look like:
First array:
days_to_report
#=> [{:date=>Fri, 01 Apr 2011},
#=>  {:date=>Sat, 02 Apr 2011},
#=>  {:date=>Sun, 03 Apr 2011},
#=>  {:date=>Mon, 04 Apr 2011}]

Second array:
tracks_by_day
#=> [{:date=>Mon, 04 Apr 2011, :count=>905, :percentage=>13.205895228367137},
#=>  {:date=>Sat, 02 Apr 2011, :count=>6745, :percentage=>98.4240478622501},
#=>  {:date=>Fri, 01 Apr 2011, :count=>6853, :percentage=>100.0}]

The dates being Date objects in this case.
So I want to like merge them so that for every item in the first array (days_to_report), has the data that the second array has too, like the ideal output would be: (notice the data for the date for Sun, 03 Apt 2011)
[{:date=>Mon, 04 Apr 2011, :count=>905,  :percentage=>13.205895228367137},
 {:date=>Sun, 03 Apr 2011, :count=>0,    :percentage=>0},
 {:date=>Sat, 02 Apr 2011, :count=>6745, :percentage=>98.4240478622501},
 {:date=>Fri, 01 Apr 2011, :count=>6853, :percentage=>100.0}]

Notice that the second item of the array has zero for the values because the :date wasn't in the hash for the tracks_by_day array... any thoughts on how to accomplish this? It seems like the functionality provided in zip or something, but I need to match up the keys to see if they exist and zero fill their values if they don't.
I hope I'm describing this correctly, thanks again guys! high five!
Answer: days = days_to_report.map{|d| d[:date] } - tracks_by_day.map{|d| d[:date]}
days.each{ |d| tracks_by_day << {:date => d, :count => 0, :percentage => 0} }

OR
days.inject(tracks_by_day){|a,d| a << {:date => d, :count => 0, :percentage => 0}}

Answer: This is how I would do it as long as there's not a huge number of items:
days_to_report.each do |day_hash|
  tracks = tracks_by_day.find {|h| h[:date] == day_hash[:date]}
  day_hash.merge!(tracks || {:count=>0, :percentage=>0})
end

If tracks_by_day is huge, you might want to convert it to a hash first that maps dates to their data.
Comment: In case anyone needs it: To convert it to a hash that maps dates to their data, you could just do `tracks_by_day.group_by {|track| track[:date]}`.
Answer: Try this:
idx = tracks_by_day.index_by {|r| r.first }
days_to_report.map do |r|
  data = (idx[r.first] || []).first || {:count=>0,    :percentage=>0}
  r.merge(data)
end

Answer: (days_to_report+tracks_by_day).group_by {|h| h[:date]}.
   map{|date, (h1, h2)| {:count => 0, :percentage => 0}.merge(h1).merge(h2 || {})}

Ruby: merging arrays or hashes


Determine the angle between the two lines $L₁$ and $L₂$

Question: Determine the angle between the two lines L₁ and L₂:
$$L₁: {(α+u(μ-α),β+u(ρ-β)),u∈(0,1)}$$
$$L₂:{(α₁+v(μ₁-α₁),β₁+v(ρ₁-β₁)),v∈(0,1)}$$
where $α,μ,β,ρ,α₁,μ₁,β₁,ρ₁$ are constants.
Comment: Hint: Draw a picture and use trigonometry. Also refer to [here](https://www.google.si/#q=angle+between+two+lines).
Answer: Hint:  If you are willing to assume they meet at all, just find a vector along each line.  To get a vector along $L_1$, take two values of $u$ and find the vector between the two points.  Now take the dot product of those two vectors and divide by the product of their magnitudes.  You are left with the cosine of the angle between the vectors.


How to animate a UIView while loading from top to bottom like shutter?

Question: I am trying to develop a iphone application. I know how to slide a view from left to right while pushing into navigation stack. But my requirement is to animate the view from top to bottom while pushing into navigation stack. So how to do that?
I am searching google but have not found any satisfying result.. If somebody knows it... Please tell me how to do that.
info = [[InfoView alloc] initWithNibName:@"InfoView" bundle:nil];
[self.navigationController pushViewController:info animated:YES];

Answer: You can try something like this while pushing your viewcontroller to the navigation stack:
       SecondViewController *VC2 = [[SecondViewController alloc]init];
       VC2.nameSupplied = self.nameField.text;
       CGPoint mycenter = VC2.view.center;
       CGPoint navCenter = self.navigationController.navigationBar.center;
       VC2.view.center = CGPointMake(mycenter.x , mycenter.y - VC2.view.frame.size.height);
       self.navigationController.navigationBar.center = CGPointMake(navCenter.x, navCenter.y - self.navigationController.navigationBar.frame.size.height);
      [self.navigationController pushViewController:VC2 animated:NO];
      [UIView animateWithDuration:0.5
                            delay:0
                          options: UIViewAnimationCurveEaseOut
                       animations:^{
                                  VC2.view.center = mycenter;
                                  self.navigationController.navigationBar.center = navCenter;
                 }
                 completion:^(BOOL finished){
                     NSLog(@"Animation Done!");
                 }];

However if you want to just show another view(moving top to bottom) in the same view controller , you can use tranform property of UIView like this :
self.secondView.transform = CGAffineTransformMakeTranslation(0, secondView.frame.size.height);

Comment: @user1523344: Your should accept the answer if it did help you.


Download File no asp net mvc

Question: Tenho arquivos que foram feitos upload na pasta wwwroot/arquivos/ do meu projeto. Quero fazer download desses arquivos mas quando clico no botão nada acontece.
public ActionResult DownloadFile(string arquivo)
    {

        if (arquivo == null)
            return Content("filename not present");

        var path = Path.Combine(
                       Directory.GetCurrentDirectory(),
                       "wwwroot", "arquivos", arquivo);
        var memory = new MemoryStream();

        var writer = new StreamWriter(memory);
        writer.Flush();
        memory.Position = 0;
        return File(memory, GetContentType(path), arquivo);
    }

html

Download:
    item.Arquivo)>

function downloadMaterial(e){
  var path = e.name;
  var arquivo = path.split("arquivos/")[1];
    $.ajax({
      url: '@Url.Action("DownloadFile")',
      type: "POST",
      cache: false,
      data: {'arquivo': arquivo},

    });
}

Answer: Nada acontece porque está tentando fazer o download via Ajax, uma outra forma de resolver isso seria abrindo uma nova janela em branco para o download, para isto basta alterar sua função JavaScript para o seguinte:

Download:
    item.Arquivo)>

Para o download você pode fazer assim:
public ActionResult DownloadFile(string arquivo)
{
    if (arquivo == null)
        return Content("filename not present");

    var path = Path.Combine(
                   Directory.GetCurrentDirectory(),
                   "wwwroot", "arquivos", arquivo);

    FileStream fileStream;

    try
    {
        fileStream = System.IO.File.OpenRead(path);
    }
    catch (DirectoryNotFoundException)
    {
        return new EmptyResult();
    }

    return File(fileStream, GetContentType(path), arquivo);
}

Comment: Deu certo! Obrigada
Comment: Obrigada, agora está baixando. Porém o arquivo está vindo vazio...qual pode ser o erro no meu controller? Não consigo ver na minha Action o momento em que pego o arquivo, só vejo pegando o caminho do arquivo..Ou isso é feito na parte do MemoryStream?
Comment: o Path está correto?
Comment: Sim, já conferi
Comment: Outra dúvida, é net core?
Comment: Isso mesmo!....
Comment: Editei com uma alternativa

Download File no asp net mvc


Can't define class in python

Question: CODE::
from tkinter import *
import tkinter.messagebox

class Library:

    def __init_(self, root):
        self.root = root
        self.root.title(" Library Management System ")
        self.root.geometry("1350x750+0+0")

        MTy = StringVar()
        Ref = StringVar()
        Title = StringVar()
        fna = StringVar()
        sna = StringVar()
        Adr1 = StringVar()
        Adr2 = StringVar()
        pcd = StringVar()
        MNo = StringVar()
        BkID = StringVar()
        Bkt = StringVar()
        BkT = StringVar()
        Atr = StringVar()
        DBo = StringVar()
        Ddu = StringVar()
        sPr = StringVar()
        Lrf = StringVar()
        Dod = StringVar()
        DonL = StringVar()

        #============================================FRAMES=================================================#

        MainFrame = Frame(self.root)
        MainFrame.grid()

        Title_Frame = Frame(MainFrame, bd=2, padx=40, pady=8, bg='cadet blue', relief=RIDGE)
        Title_Frame.grid(side=TOP)

        self.lblTitle = Label(Title_Frame, font=('arial', 46, 'bold'), text=" Library Management System ")
        self.lblTitle.grid(sticky=W)

        ButtonFrame = Frame(MainFrame, bd=2, width=1350, height=100, padx=20, pady=20, bg='Cadet Blue', relief=RIDGE)
        ButtonFrame.pack(side=BOTTOM)

        FrameDetail = Frame(MainFrame, bd=0, width=1350, height=50, padx=20, relief=RIDGE)
        FrameDetail.pack(side=BOTTOM)

        DataFrame = Frame(MainFrame, bd=1, width=1300, height=400, padx=20, pady=20, relief=RIDGE)
        DataFrame.pack(side=BOTTOM)

        DataFrameLEFT = LabelFrame(DataFrame, bd=1, width=800, height=300, padx=20, relief=RIDGE,
                                   font=('arial', 12, 'bold'), text=' Library Member Info ', bg='Cadet Blue')
        DataFrameLEFT.pack(side=LEFT)

        DataFrameRIGHT = LabelFrame(DataFrame, bd=1, width=450, height=300, padx=20, pady=3, relief=RIDGE,
                                    font=('arial', 12, 'bold'), text=' Book Details ', bg='Cadet Blue')
        DataFrameRIGHT.pack(side=RIGHT)

    if __name__ == '__main__':
        root = Tk()
        application = Library(root)
        root.mainloop()

Error::

Traceback (most recent call last):   File
"C:/Users/Jedi/PycharmProjects/LMS/main.py", line 5, in
class Library:   File "C:/Users/Jedi/PycharmProjects/LMS/main.py", line 62, in Library
application = Library(root) NameError: name 'Library' is not defined
Process finished with exit code 1
Comment: That is not the error. That is just saying where the error is. Post the rest of the traceback.
Comment: If you want an empty class, use `class Library: pass`
Comment: Post the full error code please
Comment: Traceback (most recent call last):
  File "C:/Users/Jedi/PycharmProjects/LMS/main.py", line 5, in
    class Library:
  File "C:/Users/Jedi/PycharmProjects/LMS/main.py", line 62, in Library
    application = Library(root)
NameError: name 'Library' is not defined

Process finished with exit code 1
Comment: So the error came from a line of code that you have not included in your question. Please [edit] your question to include a [mre].
Comment: if __name__ == '__main__':
        root = Tk()
        application = Library(root)
        root.mainloop()
Comment: I don't understand how the two snippets are connected. A class body can't be null - that's a syntax error. On the other hand, the erroring line is supposedly inside the class, but `if __name__ == '__main__':` by convention is at the top level. Again, you need to provide a [mre].
Comment: It looks like your `if __name__ == '__main__'` is indented. That is an error. It should not be indented.
Comment: No problem is not there in indentation
Comment: You're trying to call Library from inside the definition of Library. Not from inside a Library method. Not from outer scope. Either your indentation is wrong or your logic is.
Comment: After indentation, the error has changed to::

Traceback (most recent call last):
  File "C:/Users/Jedi/PycharmProjects/LMS/main.py", line 62, in
    application = LMS(root)
TypeError: LMS() takes no arguments
Comment: You sure your placing the `if` in the same indentation level as `class` ?
Comment: Yes, I have if in the same indentation level as class
Answer: Firstly, your indentation is wrong, you have to place the if on the same indentation level as class, like:
class Library:
   .....

if __name__ == '__main__':
  ....

Secondly, but most importantly, your def __init_() has a typo, it should be __init__() with two underscore trailing and leading init, but you gave just one(trailing).
class Library:
    def __init__(self, root):
        self.root = root
.....

But even after doing all this, you will get another error at Title_Frame.grid(side=TOP), because grid() has not option side, it is the option of pack(), so change that to:
Title_Frame.pack(side=TOP)

Can't define class in python


Extrapolate lowest/highest value from partial sample

Question: Given a partial sample of values from a set (known size), how to extrapolate the lowest/highest value in the entire set?
Comment: You need to know (or at least assume) a distribution.  Even then the uncertainty could be substantial especially if your distribution may have long tails. Try reading about the [German tank problem](http://en.wikipedia.org/wiki/German_tank_problem) for a simple example with a uniform distribution.
Answer: One way to go about it would be:

Hypothesise a model distribution for your population.  Your population can itself be seen as a sample from a hypothetical infinite population.
Using your actual sample, estimate the parameters of your model distribution, and perform diagnostic checks to see if the model remains plausible.
Simulate data of the size of your actual population, using the fitted model to simulate the data from the population that you haven't observed, and repeating your actual sample for the part of the population that you do have.  Do this say 500-1000 times to create confidence intervals for the maximum and minimum of the population.

Depending on your model, you could replace step 3 with a theory-based calculation of the confidence interval.  How to do that would depend on your model (ie what distribution you are hypothesising) however.  Which would depend on what sort of data you are looking at.
Comment: Peter, did you catch that the question is about a *finite* population of known size and that the sample (apparently) is without replacement?
Comment: @whuber - good point, will have an edit.


How do I define table columns in a base class and table names in a child class in SQLAlchemy?

Question: I need to have 2 separate tables with identical structures which seems like an inheritance scenario, but I don't want the base class to be associated with a table. The Base only exists to define the columns for the table(s) in the child class(es). The AbstractConcreteBase docs led me to implement it this way:
in status.py:
class Base(AbstractConcreteBase):
    id = Column('id', Integer, primary_key=True)
    date = Column('date', DateTime(), nullable=False)

class Status1(Base):
    __tablename__ = 'status1'
    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'concrete': True
    }

class Status2(Base):
    __tablename__ = 'status2'
    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'concrete': True
    }

in part.py:
class Part(declarative_base()):
    __tablename__ = 'parts'

    id = Column('id', Integer, primary_key=True)
    status1 = relationship('Status1', uselist=True, backref=backref('status1', order_by='Status1.date'))
    status2 = relationship('Status2', uselist=True, backref=backref('status2', order_by='Status2.date'))

When attempting this, I get the following error:
InvalidRequestError: When initializing mapper Mapper|Part|parts, expression 'Status1' failed to locate a name ("name 'Status1' is not defined"). If this is a class name, consider adding this relationship() to the <class 'package.Part'> class after both dependent classes have been defined.

Suggestions?
Answer: What you really want is a Mixin class. Your base class should not inherit from the SQLAlchemy declarative_base if dont want to associate the base class with a table. A mixin will define the columns/table structure like you want. Your child classes then inherit from both the mixin and the declarative_base.
The mixin would be defined as follows:
class StatusMixin(object):
    id = Column('id', Integer, primary_key=True)
    date = Column('date', DateTime(), nullable=False)

The child classes become much simpler:
Base = declarative_base()

class Status1(StatusMixin, Base):
    __tablename__ = 'status1'

class Status2(StatusMixin, Base):
    __tablename__ = 'status2'

Finally, your relationships defined for the Part class are not correctly defined. To use backrefs you need to have a foreign key defined in status1 and status2 that link them together:
class Status1(StatusMixin, Base):
    __tablename__ = 'status1'
    part_id = Column('part_id', Integer, ForeignKey('parts.id'))

The table defining the relationship that has a backref needs to have its own table name as the backref instead of the names of the child1 and child2 tables:
class Part(declarative_base()):
    __tablename__ = 'parts'
    id = Column('id', Integer, primary_key=True)
    status1 = relationship('Status1', uselist=True, backref=__tablename__)
    status2 = relationship('Status2', uselist=True, backref=__tablename__)


Expression> only valid inline and not through bound lambda in Moq's Setup()?

Question: The mocking library Moq has a Setup() method with the signature:
public ISetup<T, TResult> Setup<TResult>(Expression<Func<T, TResult>> expression)

So I can do something like this just fine (using the library's recursive mocking):
Mock<Thing> _thing = new Mock<Thing>();
_thing.Setup((Thing t) => t.PropA.SubPropB).Returns(string.Empty);

But this fails:
Expression<Func<Thing, object>> test = (Thing t) => t.PropA.SubPropB;
_thing.Setup(test).Returns(string.Empty);

with the error:
Expression is not a method invocation: t => (Object)t.PropA.SubPropB

What's the difference between the inlined lambda and the one assigned to a variable first? Aren't both expression trees and not yet compiled (Moq parses the tree)?
Edit - Looks like the issue is with the Func<Thing, object> typing. Why is, e.g., string acceptable, but object is not?
Comment: Because `System.String` is not covariant with `System.Object`?
Answer:
Why is, e.g., string acceptable, but object is not?

because function declaration in moq is not covariant by generic types. Try to Setup moq in next way
 _thing.Setup(test).Returns((object)string.Empty);

because you have next signature Expression<Func<Thing, object>> and it's not covariant with respect to object
Or change your signature to string like this (assume t.PropA.SubPropB returns string):
Expression<Func<Thing, string>> test = (Thing t) => t.PropA.SubPropB;
                        //^here should be string

Real-case
I have created a test project with Expression as local variable, it all works fine with string and object. Please check my configuration if I missed something. Moq - 4.0.10827v
[TestFixture]
public class Class1
{
    [Test]
    public void TestMethod()
    {
        Mock<Thing> _thing = new Mock<Thing>();

        Expression<Func<Thing, string>> setup = t => t.PropA.SubPropB;
//                               ^ works with string and object
        _thing.Setup(setup).Returns(string.Empty);

        Assert.IsEmpty(_thing.Object.PropA.SubPropB);

    }
}

public class Thing
{
    public virtual Thingy PropA { get; set; }
}

public class Thingy
{
    public virtual string SubPropB { get; set; }
}

Comment: I was trying to define some general type for something like: `List> things = ... { new Func(), new Func(), ... }`. The `(object)` cast in the `Returns()` had no effect with the `object` generic type; same error.
Comment: @wes I have updated my answer, please check it if any mistakes made


Can I connect an RDS instance to a software based VPN (an EC2 instance)

Question: To elaborate, I have an AWS EC2 instance running a SoftEther VPN server, an AWS RDS instance, and clients on the VPN.
What I need to be able to do is have my RDS instance(s) connect through the VPN to the clients and pull some subsets of our data. I've been looking around and it seems that I can have my RDS instance access information through a VPN; however, it looks like all the documentation is in regards to a hardware based VPN. I found very little in the AWS Docs about a software based VPN.
My biggest question is, is it possible to do this kind of configuration in AWS (using a software vpn instead of a hardware vpn). If so, can you provide some kind of documentation on how to do so?
Much appreciation in advance!
Comment: What do you mean by "have my RDS instance(s) connect through the VPN to the clients"? What does it mean.
Comment: Our setup is a little weird, but we have our main database (the one that we want to move to RDS) using dblink to aggregate information about other databases (clients) so we can have everything on the main database. We can't remove the functions to connect and aggregate the data because it's supporting a legacy setup. We just had a big scare where the DB server went down and the most recent backup was more than a week old.
Comment: My best guess based on a little experience with AWS VPN is that if a VPN is set up, and the routing is set up correctly, all requests including those from RDS will use that VPN. What I'm not sure about is if RDS includes the features you need to connect to other databases.
Answer: If you just want machines at the other end of the VPN to connect to RDS, you can do it -- you just need to NAT the connections to RDS to the IP address of the EC2 instance acting as the VPN endpoint, so RDS knows where to send the return packets.
However, if you want RDS to be actively soliciting to endpoints over the VPN, you're going to have a tricky time.  You can't influence RDS to route over the VPN through your EC2 instance (VPC routing tables are terrible), so RDS won't be able to connect.  You could fudge it with DNAT rules on the EC2 instance, though, if you were feeling adventurous, and just tell RDS to talk to the EC2 instance, and have it forward the traffic through the VPN.
BTW, if you haven't rummaged around in RDS yet, don't assume that you can do whatever you're trying to do.  A lot of the more esoteric features of the various RDS-supported database engines aren't available in RDS, so you might not be able to do whatever it is that you want to do.  You may have to jury-rig up something involving EC2 instances to pump data around.
(We don't "provide documentation" here, BTW; you're expected to know how to use a search engine)
Comment: What about if it's an AWS VPN, with a customer and virtual private gateway - is that more likely to work easily?
Comment: Are thinking of Direct Connect? If so you will have more options due to BGP but you will not be able to setup your RDS to do outbound calling. Start looking at configuring your own MySQL (replace with your DB) on an EC2 instance. Then you can use a LAN-to-LAN setup with OpenSwan or Windows Server.
Comment: *"You can't influence RDS to route over the VPN through your EC2 instance (VPC routing tables are terrible)*"  **This simply isn't correct.** I have a full-mesh of cross-region tunnels built from EC2 instances with OpenVPN and have no such problem with accessing RDS cross-region with native source and destination addresses, and no NAT whatsoever.  With source/dest check disabled on the VPN instance, you create a route in the RDS subnet's routing table for the destination subnet pointing to the instance ID or ENI of the VPN instance... and it just works.


Custom home page not recognized by system

Question: I have set up a Drupal 8 site with a custom home page using page--front.html.twig. The content displays at domain.com/front. When I go into Administration to change to the new home page, it says that the path is invalid. I've also tried leaving the field blank.

I also noticed that when I'm on /front, the browser tab displays "Page not found".
I've cleared the cache repeatedly (and every time it sends me to /user/1).
What am I missing here?
Answer: There are two separate issues at play here, which is where you are getting confused.
1) page--front.html.twig - this is a template suggestion for the page theme hook. This can be seen by the double-hyphens that follow page. The page theme hook is used to wrap the content of every page on the site, using the page.html.twig template. Drupal's theme layer allows for creating suggestions for templates that take precedence over the base template. In this case, when on the front page, the site looks for page--front.html.twig, and if it finds this file, it uses it. You have created this file. However, you'll notice I said this template wraps the current page content. That leads to:
2) Page content. 'Pages' on Drupal show content if a page has been assigned to the given path. However, if a user goes to a path that doesn't exist, they get the 'page not found' page. This page is wrapped by page.html.twig, just like any content page.
When you go to /front, you see page not found, because you have not created a page at that path yet. You've only created a template for the front page, whatever that may be (even if that ends up being page not found).
You can test this by creating a new node, and setting the path to be /front (note - you'll need appropriate permissions for this). Then set the site front page to /front, and your template will be picked up.
Comment: Ok, I get what you're saying. Thank you so much for clearing this up.
Answer: If you need a clear homepage, then you can use the Empty Page module. Just create a page with the module, add the URL to page in the Site Information settings and define a template in the theme.


Remover borda do botão

Question: Possuo um Jumbotron btn que não consigo tirar o hover do botão (o retangulo azul),
ja tentei desabilitar todos os styles no console do chrome porem não funciona.
<button type="submit" class="btn">Entrar</button>

.jumbotron
{
    text-align: center;
    border-radius: 25px;
    display: block;
    vertical-align: middle;
    background-color: #fefefe;
    width: 520,50 px;
    height: 687,50 px;
    font-size: 15px;
}

.jumbotron .btn
{
    padding: 0px 0px;
    font-size: 18px;
    height: 60px;
    background-color: #fefefe;
    background-image: url('images/bt_03.jpg');
    background-repeat: no-repeat;
    background-position: center;
    color: #bb4200;
    font-family: ubuntu;
    width: 120px;
    font-weight: normal;
    box-shadow: 0 0 0 0 rgba(0,0,0,0),0 0 0 0 rgba(0,0,0,0) !important;
    border-bottom: 0px;
     border:none!important;
    background-color: white!important;

}
quando clico.

alguma sugestão?
Answer: Cara, pode usar focus.
.jumbotron .btn:focus{
outline: thin dotted;
    outline: 0px auto -webkit-focus-ring-color;
    outline-offset: 0px;
}
.jumbotron:focus {
 outline: thin dotted;
    outline: 0px auto -webkit-focus-ring-color;
    outline-offset: 0px;
}

Comment: @GuilhermeLima vejo nas respostas alguns dizendo para você usar `!important`. Alerta: Se você precisa usar o `!important` é por que algo em seu `css` não está tão correto como deveria. São raros os casos em que realmente um `!important` é necessário. Atente-se a isso.
Comment: Clap Clap, funcionou perfeitamente. Agradeço a todos cada um ajudou um pouquinho.
Comment: Fico feliz por ter ajudado!
Answer: Tente isso:
.jumbotron:hover {
    border:none!important;
    background-color: white!important;
}

Ficaria mais fácil se disponibilizasse o código do botão...
Comment: Editei a pergunta com mas um problema.
Comment: Tente isso
.jumbotron::active {
    border:none!important;
    background-color: white!important;
}
.jumbotron::actived {
    border:none!important;
    background-color: white!important;
}
Comment: não funcionou..
Comment: Tente isso:
.jumbotron .btn:actived
{
 border:none!important;
 background-color: white!important;
}
Comment: nada ainda amigo, adicionei mais informações na pergunta.
Comment: Ponha isso:
.btn:active{
    border:none!important;
    background-color: white!important;
}
Answer: No meu caso funcionou isto:
.jumbotron:focus{
  outline-style: none;
}

Answer: o que tu pode fazer é sobreescrever a regra do hover com !important, algo do tipo:
#id:hover {border:none!important}

Comment: Editei a pergunta com mas um problema.
Comment: teria que ver a classe que fica o botão para te ajudar melhor... mas é só definir a classe e colocar o `border:none!important`
Comment: vou editar a pergunta novamente, mas a classe é btn
Comment: daí ou tu põe um id nele, e faz o link pelo id (#id), ou isso irá se aplicar a todos .btn
Comment: eu quero que aplique a todos,
Comment: então é só por `.btn {border:none!important}` tira a classe .jumbotron do seletor do css nessa parte
Comment: negativo, já tem esse codigo e não funciona
Comment: então manda o código aqui porque as informações não estão suficientes.
Comment: editei a pergunta chegou a ver?
Comment: teria que inspecionar quem é põe a borda e em qual elemento, pois se a borda estivesse no .btn, ela teria saído com a regra. (se ele for filho de .jumbotron como está no css)

Remover borda do botão


Djikstra's algorithm gives wrong result what is going on?

Question:
According to Djikstra's algorith the least distance between nodes A and D will be 6 which isnt really true since the path ABD has a distance of 4 so what is happening here?
EDIT
.Some of you requested(correctly my question was a bit sloppy) how I implemented Djikstra's algorithm.So here it goes:
Comment: Please edit your post to show how you got the incorrect result.
Comment: Wrong numbers. Or a bad implementation of the algorithm.
Answer: Dijkstra's algorithm considers all paths to a node, rather than taking the first one it finds for each node. When you found a path to D of length 6, why did you stop? You have considered all the successors of the node C, but not of the node B. Considering the path $A\to B\to D$ lets you decrease the tentative distance value of 6 to 4. It is then only because you have considered all possible edges to unvisited nodes that you can cross off D and conclude the shortest path is $A\to B\to D$.
The algorithm in its most general form is indifferent to the order in which these tentative distances are considered, but any implementation will have to use some ordering, such as alphabetical order.
Answer: In dijkstra's algorithm, at the last step you did, you should pick the node $B$ instead of the node $D$. That is because you pick the node with the minimal distance and the distance of $B$ is $3$ which is lower than the distance of $D$ (which is $6$). When you pick $B$, at the next step you will pick $D$ with the distance of $4$ (when its previous node will be $B$), which is the correct answer.


Imagem caber na célula

Question: Bom dia!
Estou utilizando o código abaixo, mas ele não coloca a imagem corretamente na célula mesclada e eu gostaria que a imagem ficasse do tamanho da célula mesclada
<code>        Public Sub Carregarfoto1()

       Dim photoNameAndPath As Variant
    Dim photo As Picture
    photoNameAndPath = Application.GetOpenFilename(Title:="")
    If photoNameAndPath = False Then Exit Sub
        Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath)
        With photo
           .Left = ThisWorkbook.Worksheets("Template").Range("C205").Left
           .Top = ThisWorkbook.Worksheets("Template").Range("C205").Top
           .Width = ThisWorkbook.Worksheets("Template").Range("C205").Width
           .Height = ThisWorkbook.Worksheets("Template").Range("C205").Height

           .Placement = 1

        End With

    End Sub
</code>
Comment: `Range("C205").Left`, assim como `Top`, `Width` e `Height`, não retornam as medidas da área inteira, e sim somente da célula C205, como se não estivesse mesclada. Para obter as medidas da célula mesclada por inteiro, você precisa pegar: `ThisWorkbook.Worksheets("Template").Range("C205").MergeArea.Left` (e também top, width e height).
Comment: Poxa me ajudou muito, obrigada! Mas a foto está saindo muito pra cima sabe como posso trazer ela mais pra baixo?
Comment: Mexa no top, assim: `.Top = ThisWorkbook.Worksheets("Template").Range("C205").Top + 10`. Aí em vez de +10, Você testa um número útil pra você.
Answer: Oi tudo bem? Use o código abaixo que vai resolver seu problema:
<code>Public Sub Carregarfoto1()
Dim photoNameAndPath As Variant
Dim photo As Picture
Dim CelulaFotoImagem As Range

photoNameAndPath = Application.GetOpenFilename(Title:="")

If photoNameAndPath = False Then Exit Sub

Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath)
Set CelulaFotoImagem = ThisWorkbook.Worksheets("Template").Range("C205")

With photo
    'Ajustar aqui a proporção da imagem
    .Left = CelulaFotoImagem.Left + 1
    .Top = CelulaFotoImagem.Top + 1

    'Seta Proporção para 100%
    .ShapeRange.LockAspectRatio = msoFalse
    .ShapeRange.ScaleHeight 1, msoTrue, msoScaleFromTopLeft
    .ShapeRange.ScaleWidth 1, msoTrue, msoScaleFromTopLeft
    .ShapeRange.LockAspectRatio = msoTrue

    'Reduz proporcionalmente até "caber" na celula
    .Width = CelulaFotoImagem.MergeArea.Width - 2
    Do While .Height > CelulaFotoImagem.MergeArea.Height - 2
        .Width = .Width - 1
    Loop

    'Ajusta imagem no centro da celula
    'Se quiser centralizar, descomente esses duas linha abaixo
    '.Left = CelulaFotoImagem.Left + 1 + ((CelulaFotoImagem.Width - .Width) / 2)
    '.Top = CelulaFotoImagem.Top + 1 + ((CelulaFotoImagem.Height - .Height) / 2)

    'Ajusta imagem na célula com crop
    .Left = CelulaFotoImagem.Left + 1
    .Top = CelulaFotoImagem.Top + 1
    .ShapeRange.PictureFormat.Crop.ShapeWidth = CelulaFotoImagem.MergeArea.Width - 2
    .ShapeRange.PictureFormat.Crop.ShapeHeight = CelulaFotoImagem.MergeArea.Height - 2
    .ShapeRange.PictureFormat.Crop.PictureOffsetX = 0
    .ShapeRange.PictureFormat.Crop.PictureOffsetY = 0

    .Placement = 1
End With
</code>
End Sub
Comment: Curioso como um código que funciona adequadamente para a questão receba tantos votos negativos. Se alguém quiser testar o código, renomeie uma aba para o nome "Template" (sem aspas) e mescle algumas células a partir da C205. Vocês verão que funciona. Obrigado para quem isso foi útil.

Imagem caber na célula


How to efficiently solve this question? Possibly using Max Mod Principle

Question: Let $f: {\mathbb{D}} \rightarrow {\mathbb{C}}$ be holomorphic and continuous on the closed unit disk $\bar {\mathbb{D}}$. Assume that
$|f(z)| \leq 1$ whenever $|z| = 1$ and $Im(z) > 0$; and
$|f(z)| \leq 9$ whenever  $|z| = 1$ and $Im(z) < 0$.
Show that $|f(0)| \leq 3$.
Is it possible to solve this using the Max Mod Principle?
Answer: Apply the maximum modulus principle to the function $g(z) = f(z) f(-z)$ which has $|g(z)| \le 9$ everywhere on the boundary.


Prime numbers and their products

Question: I've been reading a bit about prime numbers and their use in cryptography.
If i would create a table of primes and their products, would there be any way to point out the area where a given number x would be? (X will only be a product of two primes)
For example, number 15 is a product of prime number at position 3 and 4.(1,2,3,5)
Would a table of those numbers be small enough to fit in a computer memory?
Comment: There are more than $2^{120}$ primes below $2^{128}$ (using the formula from [this question](http://math.stackexchange.com/q/102291/34930)). Given that to store one number, you need $128$ bits = $16$ bytes, you'd need more than $2^{124}$ bytes to store all those numbers. With 1 TB = $2^{40}$ bytes, that means you'd need $2^{64}\approx 1.8\cdot 10^{19}$ Terabyte disks to store those numbers. So no, the list definitely would not be small enough to fit in memory.
Comment: The table might be small enough to fit in memory, but computing the values of the table would probably take too long...
Comment: There are an infinite amount of prime numbers, however large your computer memory, I'll always be able to find prime numbers that are not in it.
Comment: True, but cryptographic techniques involve primes smaller than a number n, where n would be 2^128
Comment: how about finding a range of primes that can be a factor of a number? It would be pointless to go through all of them to find the 2
Comment: @coolbartek, for RSA (say) N is at least 1024 bits (now days more like 2048). That means the primes are 512 bits (or 1024 bits). Current [factoring methods](http://en.wikipedia.org/wiki/Integer_factorization) will be much faster (yet still infeasible for secure RSA). I think there are a few factoring related question you might find interesting on [Crypto.SE](http://cryptography.stackexchange.com).
Answer: So say you are trying to defeat RSA-1024. Each of the 2 primes to generate the RSA keypair is approximately 512 bits.
According to the Prime Number Theorem, there are approximately $\frac{n}{\ln{n}}$ prime numbers less than $n$.
Say we assume that both primes are between 510 bits and 512 bits. There are approximately $2^{503}$ primes less than $2^{512}$. Subtract off all primes that are 509 bits and less (there are approximately $2^{500}$ such primes) and we are left with $2^{503} - 2^{500}\approx 2^{502}$.
Therefore, there are approximately $2^{502}$ primes you would have to store. There are approximately $2^{265}$ atoms in the known universe. So, even if each atom could store one prime number, you wouldn't be able to store all of the primes for the given range.
Comment: one more question, is there any way to estimate the range of primes, that can be the solution?
Comment: @coolbartek, It depends on the implementation. Some will allow any prime of say 512 bits or less. Others will force the most-significant-bit to be 1, thus forcing it to be only 512 bit numbers. It all depends.
Comment: ,What i meant was, for a number x that is a product of two primes, is there a way to estimate that the primes(a,b) are a number that c < a,b < d ?
Comment: @coolbartek, not that I know of. Might be a good question for here or crypto.SE. My guess is that there isn't because, for example you could have a 1000 bit prime multiplied by a 24 bit prime and still get a 1024 bit prime.
Comment: and there is at least one more prime for every other bit since there is at least one prime between n and 2n. Thanks for the answers

Prime numbers and their products


C++: Calculate using large numbers (>1 mrd.) and procentage

Question: I want to calculate a price for an element using the percentage of the current value. For example: An apple costs 4$ right now and for every apple you buy, the price increases by 7%. So the first apple would cost 4$, the next 4.28$ (price + 7% of 4$), the next 4.58$ (price + 7% of 4.28$) and so on.
My script is working somehow, but as the numbers grow larger, i struggle to find the right data type for this.
Since i have to round to the last 2 digits, i'm doing something like this:
int64_t c = 0;
double ergebnis = 0;
double komma1 = 0;

komma1 = komma1 + ((komma1 / 100) * 7);
c = komma1 * 100;
ergebnis = c / 100.0;

The problem is, that if i bought 50000 apples, the number would grow so large, that the result would just become a negative number. I'm using "Visual Studio 2017 Community Edition".
#include "stdafx.h"
#include "stdint.h"
#include "iostream"
#include "Windows.h"

using namespace std;

int main()
{
    cout.precision(40);
    int price = 4;
    long double cost = 0;
    long double b = 4;
    int d = 0;

    while (d != 50000)
    {
        cost = price + (price / 100 * 7);
        price = cost * 100.00;
        cost = price / 100.00;
        d = d++;
    }
    cout << "Number is: " << cost << endl;
    Sleep(5000);
    return 0;
}

This pretty much describes my problem.
I already used google and found the idea to use "int64_t" as integer, but i think the real problem is the double here, right?
So, tl;dr:

Any way to use pretty large numbers in C++?
Any way to solve my problem using another solution? like splitting the numbers up or something? Like:
if (number == 1.000.000)
{
million = million++;
number = 4;
}
Comment: "The obvious problem is here" What obvious problem? Don't see any. "-19974798308344 or something" There's no "or something" in the set of integers. Please post a [mcve]. This should include a buildable runnable program, any input it requires, desired output, and actual output.
Comment: Try to use `long double`, it has a pretty high precision. Also, you might want to look at a third party library like Boost for very high numbers.
Comment: `price = cost * 100.00; cost = price / 100.00;` This makes no sense. What should this fragment of code do? Why your `price` is an integer? `d = d++` doesn't do what you think it does. Use a `for` loop.
Comment: yeah, gsamaras already pointed that out. I'm just doing some terribly stupid mistakes here...
Well, the `cost*100` part should round the numbers, but i think i can just use "roundl", right?
Comment: Hello, please do not use greetings or thanks. Questions are hoped to be useful long after the day you are asking them, and at night, so you don't need to wish the reader a good day.
Comment: Read about [arbitrary precision arithmetic](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) then use [GMPlib](http://gmplib.org/)
Answer: In your edited code:
First, this:
d = d++;

may be undefined (you should get a compilation warning), like this:
warning: operation on 'd' may be undefined [-Wsequence-point]
         d = d++;
         ~~^~~~~

Replace this line of code with:
d++;

which is equivalent to:
d = d + 1;

price is an int. You then perform integer division price / 100, which will give an int as its result! So 4/100 in an integer division gives 0. Cast one operand to a floating point value, to get a division that will yield a floating point number as a result. E.g. (long double)price / 100.
However, what you describe as your algorithm doesn't match your expected results. You say that you want to charge from 4$, to 4.28$, then to 4.58$. The formula to achieve this is not the one you describe, but this:
cost = cost + cost * 7%

Moreover, these two lines of code make no sense:
price = cost * 100.00;
cost = price / 100.00;

just discard them.
Furthermore, since you know how many times you want the iteration to execute, use a for loop, instead of a while loop.
Putting everything together, you get:
 #include "iostream"

using namespace std;

int main()
{
    cout.precision(40);
    long double cost = 4;

    for(int i = 0; i < 50000; ++i)
    {
        cost = cost + ((long double)cost / 100 * 7);
    }
    cout << "Cost is: " << cost << endl;
    return 0;
}

Comment: I just noticed something: on another forum i read something about divison by 100 and multiplicate that again and stuff... but can't i just use "roundl" from math.h?
I just googled that, but i dont quite understand, how to define the numbers after the decimal point.

And thanks for the clarification with d++. I always wondered what that warning meant. Seems like VS just wanted to tell me to stop being stupid :P
Comment: Found the post: [link](https://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c)
Comment: Well, i'm not getting the number you got, i got "inf". I'm using the exact code you posted up there. But... why?
Comment: Because the compuer you use has smaller limits than mine's. Try it on wandbox.org and you will see!
Comment: whew, good to know. Thank you for this much help! i really appreciate that. And sorry for asking such foolish questions. Being a beginner sucks.... :D
Comment: @Couchuser don't be so harsh on yourself. Everyone was a beginner at some point of time! ;) For future questions, try to post a minimal example, like the one you edited in your question now, from the start! Glad I helped, cheers!
Answer: Your attempt to calculate compound interest went horribly wrong. The program doesn't do anything remotely similar to what your description says it should do.
Here's how your loop should look like:
 long double price = 4.0;
 for (int i = 0; i < 50000; ++i)
 {
    price = price * 1.07; // == (100.0 + 7.0)/100.0
 }

The regular double doesn't have a range to represent your price, but long double is OK. If you want to go bigger, you need a third party large numbers library. Note that the nearest integer to your answer has ~1500 decimal digits, so calculations with such numbers can be rather slow.
The same result can be obtained without looping:
  std::cout "The number is " << 4 * std::pow (1.07L, 50000) << "\n";

Comment: Oh my god, this is embarassing...
Well, thank you, this actually answered my question :D
Answer: Try long double instead of double. Difference between long double and double in C and C++.
Beware of the floating point precision and for conversion when performing calculations with variables that are sensitive to precision.

Any way to use pretty large numbers in C++?

Use a library, like Gnu Multiple Precision (GMP):
"a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface."
However, these libraries are for advanced usage. Make sure you really need to use that large numbers (large numbers are time consuming when being processed).
Comment: Thank you for this answer!
It seems that the **long double** is actually working a lot better, but i'm still getting a negative number. I added an example above, maybe this will clear things up :-)