text:
Q: Text not wrapping in ListViewItem The ListViewItems are getting their width from the TextBlock element. I want the ListViewItem to fit to the ListView. I have seen in other posts that making HorizontalContentAlignment="Stretch" will fix the issue, but my problem persists. The second TextBlock element in the ItemTemplate is set to WrapWithOverflow.
Sources:
http://www.teixeira-soft.com/bluescreen/2016/03/21/c-how-to-make-a-panel-within-a-datatemplate-fill-the-entire-width-of-a-listview-or-itenscontrol-derivative/
Code:
<UserControl x:Class="XXXX.Views.XXXXView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:cal="http://www.caliburnproject.org"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="{StaticResource BlackBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20*"/>
            <ColumnDefinition Width="32*"/>
            <ColumnDefinition Width="6*"/>
            <ColumnDefinition Width="32*"/>
        </Grid.ColumnDefinitions>
        <DockPanel Grid.Column="1">
            <ListView Grid.Column="1"
                      x:Name="UniqueShortDescriptions"
                      VerticalAlignment="Stretch"
                      ItemsSource="{Binding UniqueShortDescriptions}"
                      SelectedItem="{Binding SelectedUniqueShortDescriptions}"
                      cal:Message.Attach="[Event SelectionChanged] = [Action SelectionChanged($this, $eventArgs)]">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Border BorderBrush="Navy"
                                BorderThickness="3"
                                Margin="3"
                                Padding="2">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <TextBlock Grid.RowSpan="3"
                                           Grid.Column="0"
                                           Text="{Binding Path=Date}"
                                           Foreground="Black"
                                           VerticalAlignment="Center"
                                           TextBlock.FontWeight="ExtraBold"/>
                                <TextBlock Grid.Row="0"
                                           Grid.Column="1"
                                           Text="{Binding Path=LongDescription}" Foreground="{StaticResource BlackBrush}"
                                               TextWrapping="WrapWithOverflow"/>
                                <!--<TextBlock Text="{Binding Path=ShortExpenseDescription}" Foreground="{StaticResource BlackBrush}"/>-->
                                <TextBlock Grid.Row="1"
                                           Grid.Column="1"
                                           Text="{Binding Path=Cost}" Foreground="{StaticResource BlackBrush}"/>
                                <TextBlock Grid.Row="2"
                                           Grid.Column="1"
                                           Text="{Binding Path=Source}" Foreground="{StaticResource BlackBrush}"/>
                            </Grid>
                        </Border>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </DockPanel>
    </Grid>
</UserControl>

A: I got the code you posted to work by simply disabling horizontal scrolling of the ListView.
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled" ...


text:
Q: Access columns after pandas merge gave them suffixes I have two dataframes:
d1 = {'id': [1, 1, 2], 'date': [pd.Timestamp('2020-10-16'), pd.Timestamp('2020-10-18'), pd.Timestamp('2020-12-4')], 'var1': [1, 2, 2]}
df1 = pd.DataFrame(data=d1)

d2 = {'id': [1, 1, 2, 2], 'date': [pd.Timestamp('2020-10-11'), pd.Timestamp('2020-10-18'), pd.Timestamp('2020-12-3'), pd.Timestamp('2020-12-13')], 'var2': [1, 2, 2, 5]}
df2 = pd.DataFrame(data=d2)

After performing an outer merge on id, the resulting df looks like this:
df_merged = pd.merge(df1, df2,on='id', how='outer', suffixes=['_x','_y']).fillna(pd.NA)
>> df_merged
df_merged
   id      date_x  var1      date_y  var2
0   1  2020-10-16     1  2020-10-11     1
1   1  2020-10-16     1  2020-10-18     2
2   1  2020-10-18     2  2020-10-11     1
3   1  2020-10-18     2  2020-10-18     2
4   2  2020-12-04     2   2020-12-3     2
5   2  2020-12-04     2  2020-12-13     5

I want to perform operations on the two date columns. However, I am unsure on how to access them since their name changed due to the merge (i.e., pandas added the _x and _y suffixes).
Of course I could manually add the _x and _y suffixes to the end of my column names before performing the operations, but this does not cover the cases where the two date column names have names which differ from each other (e.g. 'date1' and 'date2'), therefore the _x and _y  suffixes wouldn't have been added.
The operation I want to perform looks like this:
df_merged['time_difference'] = abs((df_merged[date1_column_name] - df_merged[date2_column_name]).dt.days)

How can I cover both the case that pandas added the suffixes and that no suffixes were added, therefore the date columns kept their original names?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find all the ordered pairs $(x,y)$ such that $x^y=y^x$
Find all the ordered pairs $(x,y)$ such that $x^y=y^x$.

So the only ones that i find are when $x=y$ such as $(1,1)$ because $1^1=1^1$.
However, I'm not very familiar with ordered pairs?
Any help?


text:
Q: Вывод курсора из процедуры По аналогии с выводом результата функции:
SELECT * FROM TABLE(пакет.функция(параметры));

А что если у нас есть не функция, а процедура, где первый параметр - out sys_refcursor?
procedure My_proc
 (
  out_refcur  OUT SYS_REFCURSOR,
  другие In параметры
 )

Как получить так же выборку прямо в окне SQL Window, как в случае функции?

A: В SQL Window нельзя напрямую вызвать процедуру. Перейдите в Command Window и попробуйте, например:
set autoprint on
col dummy for a10
variable rcur refcursor
declare
    procedure getCursor (rcur out sys_refcursor) is
    begin
        open rcur for select dummy from dual;
    end;
begin
    getCursor (:rcur);
end;
/

Вывод:
PL/SQL procedure successfully completed.

DUMMY
----------
X

Если мешает сообщение о выполнении - Как убрать фразу "PL/SQL procedure successfully completed."

A: В 12с у пакета dbms_sql появилась функция return_result.
Вам нужно указать в своей процедуре dbms_sql.return_result(_cur_name), т.е.
    create or replace My_proc(
      out_refcur in OUT SYS_REFCURSOR,
      другие In параметры
      )
    is
    begin
    ....
    dbms_sql.return_result(out_refcur);
    end;

В итоге при вызове в sqlplus вам покажется содержимое курсора.
В 11g и ранние версии нужно создавать функцию.


text:
Q: com.google.android.gms.vision.ica not found com.google.android.gms.vision.ica not found.
W/DynamiteModule: Local module descriptor class for com.google.android.gms.vision.ica not found.
I/DynamiteModule: Considering local module com.google.android.gms.vision.ica:0 and remote module com.google.android.gms.vision.ica:0
AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vt.shoppet">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".ShopPetApp"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ui.MainActivity"
            android:exported="true"
            android:theme="@style/SplashTheme"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="MainActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_pet" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/menu_item_chat" />

        <meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="ica" />

        <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="ica"/>

        <meta-data
            android:name="firebase_performance_logcat_enabled"
            android:value="true" />

        <service
            android:name=".MessagingService"
            android:exported="false"
            android:permission="android.permission.INTERNET">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

Build in Project
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath(kotlin("gradle-plugin", "1.5.30"))
        classpath("com.android.tools.build:gradle:7.0.2")
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5")
        classpath("com.google.dagger:hilt-android-gradle-plugin:2.38.1")
        classpath("com.google.gms:google-services:4.3.10")
        classpath("com.google.firebase:firebase-crashlytics-gradle:2.7.1")
        classpath("com.google.firebase:perf-plugin:1.4.0")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

tasks {
    register("clean", Delete::class) {
        delete(rootProject.buildDir)
    }
}

built in app
plugins {
    id("com.android.application")
    kotlin("android")
    kotlin("kapt")
    id("com.google.gms.google-services")
    id("com.google.firebase.crashlytics")
    id("com.google.firebase.firebase-perf")
    id("dagger.hilt.android.plugin")
    id("androidx.navigation.safeargs.kotlin")
}

android {
    compileSdk = 31
    buildToolsVersion = "31.0.0"
    ndkVersion = "23.0.75998587"

    defaultConfig {
        applicationId = "com.vt.shoppet"
        minSdk = 23
        targetSdk = 31
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }

    compileOptions {
        isCoreLibraryDesugaringEnabled = true
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_11.toString()
        freeCompilerArgs = listOf("-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi")
    }

    buildFeatures {
        viewBinding = true
    }

    lint {
        isCheckDependencies = true
        isCheckGeneratedSources = true
    }

    splits {
        abi {
            isEnable = true
            isUniversalApk = true
        }
    }
}

dependencies {
    // Kotlin / Java
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.5.2")

    // Android Architecture Components
    implementation("androidx.activity:activity-ktx:1.4.0")
    implementation("androidx.appcompat:appcompat:1.4.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.2")
    implementation("androidx.coordinatorlayout:coordinatorlayout:1.1.0")
    implementation("androidx.drawerlayout:drawerlayout:1.1.1")
    implementation("androidx.core:core-ktx:1.7.0")
    implementation("androidx.fragment:fragment-ktx:1.4.0")
    implementation("androidx.preference:preference-ktx:1.1.1")
    implementation("androidx.recyclerview:recyclerview:1.2.1")
    kapt("androidx.hilt:hilt-compiler:1.0.0")

    // CameraX
    val cameraVersion = "1.0.1"
    implementation("androidx.camera:camera-camera2:$cameraVersion")
    implementation("androidx.camera:camera-core:$cameraVersion")
    implementation("androidx.camera:camera-lifecycle:$cameraVersion")
    implementation("androidx.camera:camera-view:1.0.0-alpha31")

    // Firebase
    implementation(platform("com.google.firebase:firebase-bom:28.4.1"))
    implementation("com.google.firebase:firebase-analytics-ktx")
    implementation("com.google.firebase:firebase-auth-ktx")
    implementation("com.google.firebase:firebase-core")
    implementation("com.google.firebase:firebase-crashlytics-ktx")
    implementation("com.google.firebase:firebase-firestore-ktx")
    implementation("com.google.firebase:firebase-iid")
    implementation("com.google.firebase:firebase-messaging")
    implementation("com.google.firebase:firebase-perf-ktx")
    implementation("com.google.firebase:firebase-storage-ktx")
    implementation ("org.tensorflow:tensorflow-lite:1.13.1")

    // ML Kit
    implementation("com.google.android.gms:play-services-mlkit-image-labeling:16.0.5")

    // Firebase UI
    val firebaseUiVersion = "8.0.0"
    implementation("com.firebaseui:firebase-ui-firestore:$firebaseUiVersion")
    implementation("com.firebaseui:firebase-ui-storage:$firebaseUiVersion")

    // Glide
    val glideVersion = "4.12.0"
    implementation("com.github.bumptech.glide:glide:$glideVersion")
    kapt("com.github.bumptech.glide:compiler:$glideVersion")

    // Hilt
    val hiltAndroidVersion = "2.38.1"
    implementation("com.google.dagger:hilt-android:$hiltAndroidVersion")
    kapt("com.google.dagger:hilt-android-compiler:$hiltAndroidVersion")

    // Lifecycle
    val lifecycleVersion = "2.3.1"
    implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycleVersion")
    implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion")
    implementation("androidx.lifecycle:lifecycle-process:$lifecycleVersion")
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleVersion")
    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion")

    // Material Components
    implementation("com.google.android.material:material:1.4.0")

    // Navigation Component
    val navigationVersion = "2.3.5"
    implementation("androidx.navigation:navigation-fragment-ktx:$navigationVersion")
    implementation("androidx.navigation:navigation-ui-ktx:$navigationVersion")
}

kapt {
    correctErrorTypes = true
}

hilt {
    enableAggregatingTask = true
}


text:
Q: Shorter way to create datacontext object? I have a very simple question and would be great if someone could save me some typing in the future.
I see myself typing this statement often:
using (DataClasses1DataContext db = new DataClasses1DataContext())

I remember seeing a shorter version of it somewhere but can seem to find it. I believe it has  the name of the datacontext only typed once.
Thanks!

A: Like this?
using (var db = new DataClasses1DataContext())

To abbreviate it even further you could do something like this:
using (var db = DataClass.DB())

Where DataClass has a static method DB that returns a new instance of your data context.

A: using (var db = new DataClasses1DataContext())

A: I still have to do this too, usually in a repository. The only difference as others answered is to use the var db implicit definition. This works because you are instantiating a class explicitly with the new keyword so the compiler still knows that the type will be DataClasses1DataContext


text:
Q: Keep executing an observable in repository layer when UseCase is disposed What is the proper way to execute some kind of "background" action, like saving data in the database, when this action is triggered by a presenter, but the presenter is disposing the observable before the end of the query?
Should I decouple my Repository observable from the UseCase one?
Example
I'me developing an Android application following the Clean Architecture and MVP patterns, using RxJava and Dagger.
In a Dialog, I'm listing devices, and can connect to one when selecting it in the list.
When an element in the list is clicked, the dialog is dismissed, and I'm setting/saving this device as the 'current' device in my repository layer and animating a logo in the toolbar of the activity (somehow like the Chromecast is doing).
In my presenter, I dispose my UseCases when the view is detached, so if the saving is not complete when the dialog is dismissed, the observable gets disposed and the device is not set as 'current' device.
Presenter
@Override
public void deviceClicked(String id) {
    getMvpView().dismissView();
    mConnectToDeviceUseCase.execute(id, new DisposableCompletableObserver() {
        @Override
        public void onComplete() {
            Timber.d("Connected to device");
        }

        @Override
        public void onError(Throwable e) {
            Timber.e("Error while connecting to device: %s", e.getMessage());
        }
    });
}

UseCase
public class ConnectToDeviceUseCase extends UseCaseCompletableWithParameter<String, DevicesRepository> {

    @Inject
    public ConnectToDeviceUseCase(DevicesRepository DevicesRepository,
                                   @Named("Thread") Scheduler threadScheduler,
                                   @Named("PostExecution") Scheduler postExecutionScheduler) {
        super(devicesRepository, threadScheduler, postExecutionScheduler);
    }

    @Override
    protected Completable buildObservable(String id) {
        Timber.d("GetDevicesUseCase buildObservable");

        return repository.connectToDevice(id);
    }
}

Repository
private ReplaySubject<DeviceConnection> connectionStatus = ReplaySubject.create();

...
@Override
public Completable connectToDevice(String id) {
    Timber.d("connectToDevice IN");
    return mDLNADataSource.getDevices()
            .flatMapIterable(items -> items)
            .filter(item -> item.id().equals(id))
            .firstOrError()
            .flatMapCompletable(this::saveAsCurrent)
            .doOnSubscribe(a ->
                    {
                        Timber.d("connectToDevice doOnSubscribe");
                        connectionStatus.onNext(DeviceConnection.builder().setStatus(DeviceConnection.STATUS_CONNECTING).build());
                    }
            )
            .doOnComplete(() ->
                    {
                        Timber.d("connectToDevice doOnComplete");
                        connectionStatus.onNext(DeviceConnection.builder().setStatus(DeviceConnection.STATUS_CONNECTED).build());
                    }
            )
            .doOnError(a ->
                    {
                        Timber.d("connectToDevice doOnError");
                        connectionStatus.onNext(DeviceConnection.builder().setStatus(DeviceConnection.STATUS_NOT_CONNECTED).build());
                    }
            )
            .doOnDispose(() ->
            {
                Timber.d("connectToDevice doOnDispose");
            });

}

A: I am neither java nor Android expert but what you have described in your question sounds like controlflow issue to me.
If you trigger some async activity (e.g. save) you should also connect the cleanup to it. One possible solution could be using the concept of a "future" or "promise". Another one could be the actor pattern where save and cleanup would be messages executed sequentially.


text:
Q: Extract a number from a string after specific string in Oracle SQL I would like to extract from this string: FREQ=DAILY;BYDAY=MON,TUE,WED,THU,FRI;BYHOUR=7;BYMINUTE=0;BYSECOND=0
the number that is after 'BYHOUR=' string using Oracle pl/sql.
It can be 1 or 2 character long (0-23)
It is probably best to use regex regular expression but I was never fluent in creating them.
Can someone help and explain it?

A: Use REGEXP_SUBSTR:
SELECT REGEXP_SUBSTR(col, 'BYHOUR=(\d{1,2})')
FROM yourTable


text:
Q: Why in C++0x, the compiler chooses the generic move assignment over the specific one? I have the following code:
#include <iostream>
using namespace std;

template <class T> class Foo {
public:
    template <class U> void operator = (const U &u) {
        cout << "generic copy assigment\n";
    }

    void operator = (const Foo<T> &f) {
        cout << "specific copy assigment\n";
    }

    template <class U> void operator = (U &&u) {
        cout << "generic move assigment\n";
    }

    void operator = (Foo<T> &&f) {
        cout << "specific move assigment\n";
    }
};

int main() {
    Foo<int> i, j;
    i = j;
    return 0;
}

If this runs, it prints "generic move assignment", i.e. the compiler prefers the move over the copy. However, if I comment out the two move assignments:
template <class T> class Foo {
public:
    template <class U> void operator = (const U &u) {
        cout << "generic copy assigment\n";
    }

    void operator = (const Foo<T> &f) {
        cout << "specific copy assigment\n";
    }
};

the output is "specific copy assignment".
In other words, when the class is move-enabled, the generic move is selected over the specific one, whereas if the class is not move-enabled, the specific copy is selected over the generic one.
Is it a bug of Visual Studio 2010 or is this behavior defined in the c++0x specifications?

A: Your template is not a "generic move assignment". But it is a "perfect forwarder", except that in your case it doesn't forward. The rule in C++0x is that template argument deduction treats a parameter "T&&" specially: Lvalue arguments deduce T to ArgType&, and Rvalue arguments deduce it to ArgType. That way, an lvalue of type ArgType will yield to ultimate parameter type ArgType&, and an Rvalue will ultimately yield to ArgType&&.
In your case, the lvalue right hand side yields a deduced parameter type "Foo &", which perfectly well matches the lvalue argument.
The currently draft (n3126) forbids the compiler to use the template to perform the copy assignment (in a very confusingly worded paragraph), though. It depens on the resolution of issue 1080 whether that will change or not.

A: #include <iostream>
using namespace std;

template <class T> class Foo {
    public:
    template <class U> void operator = (const U &u) {
        cout << "generic copy assigment\n";
    }

    void operator = (const Foo<T> &f) {
        cout << "specific copy assigment\n";
    }

    template <class U> void operator = (U &&u) {
        cout << "generic move assigment\n";
    }

//    void operator = (Foo<T> &&f) {
//        cout << "specific move assigment\n";
//    }
};

int main() {
    Foo<int> i, j;
    i = std::move(j);
    return 0;
}


text:
Q: Nginx proxy server receiving dynamic proxy_pass in one location but unsure how to provide it in subsequent locations This is my first outing with nginx. I am using it as a workaround for a quirk of AWS ElasticSearch Kibana dashbaords, namely that I need to use an iframe and Cognito authentication does not work in iframes.
My problem is that, while I have a hard coded one off solution, trying to create a generalized solution is proving difficult.
I need my nginx server to be able to serve as proxy for one of several (properly configured) elasticsearch kibana dashboards the user can choose from.
I currently have the following kibana.conf file. When I pass the elasticsearch kibana dashboard url with my server ip address (ex. http://XX.XXX.XXX.XX/{elasticsearch kibana dash url}.us-east-1.es.amazonaws.com/_plugin/kibana/), the first location can pull the dash url from the request uri and set the proxy_pass to the correct address.
However, on the second location, which is required because the Kibana dashboard process requires a flurry of further calls, those are all requests such as http://XX.XXX.XXX.XX/_plugin/kibana/app/kibana. The way it is currently, with the kibana dashboard url hardcoded in proxy_pass, it works beautifully. But I have no idea how to pass the dashboard url dynamically the way I did with the first call.
Any insight would be greatly appreciated. Thank you!
server {

  listen 80;
  server_name XX.XXX.XXX.XX;

  # error logging
  error_log /var/log/nginx/kibana_error.log info;

  location ~ ^/(?<kibana_dash_url>.+)/_plugin/kibana/$ {

    proxy_http_version 1.1;
    proxy_set_header X-Real-IP XX.XXX.XXX.XX;
    proxy_set_header Connection "Keep-Alive";
    proxy_set_header Proxy-Connection "Keep-Alive";
    proxy_set_header Authorization "";

    proxy_pass https://$kibana_dash_url/_plugin/kibana/;
    proxy_redirect https://$kibana_dash_url/_plugin/kibana/ http://XX.XXX.XXX.XX/kibana/;

    }

      location ~ (/app/kibana|/app/timelion|/bundles|/built_assets|/translations|/es_admin|/plugins|/api|/ui|/elasticsearch) {
         proxy_pass              https://<hardcoded elasticsearch url here>.us-east-1.es.amazonaws.com;
        # proxy_pass              https://<no idea how to get dynamic elasticsearch url here>.us-east-1.es.amazonaws.com;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_set_header        X-Forwarded-Host $http_host;
        proxy_set_header        Authorization  "";
    }
}


text:
Q: In ffmpeg, how do I scale dvdsub subtitles to match video size, using scale2ref filter? I have an mpeg file, recorded from live TV, containing video and multiple audio and subtitles streams. My eventual goal is to be able to create a smaller video file as the mpeg file is multi-gigabytes in size. My first step on that path is just to be able to select one each of the video, audio and subtitle streams and copy them to an mkv file, discarding the streams I'm not interested in. (I chose mkv as it will allow storing a dvdsub subtitle stream where other container formats wont.)
The problem I'm having is that the dvdsub subtitles appear very small when I play the output video, when I researched this I found that ffmpeg doesn't automatically scale the subtitles to match the source video: https://trac.ffmpeg.org/ticket/4744
I have tried using the scale2ref filter, but I don't understand the documentation, and the example they give makes no sense to me (see examples below).
I have a command that selects the three streams and copies 1 minute to the output, as follows:
ffmpeg -ss 00:28:00.200 -i Hillary-2016-08-21.mpg -t 00:01:00.000 -map 0:0 -c:v copy -map 0:3 -c:a copy -map 0:6 -c:s dvdsub cut.mkv

Here's the output:
Input #0, mpegts, from 'Hillary-2016-08-21.mpg':
  Duration: 01:30:00.06, start: 20852.199389, bitrate: 6813 kb/s
  Program 1
    Stream #0:0[0xfa]: Video: h264 (Main) ([27][0][0][0] / 0x001B), yuv420p(tv, bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], 25 fps, 50 tbr, 90k tbn, 50 tbc
    Stream #0:1[0x12c](eng): Audio: aac_latm (HE-AAC) ([17][0][0][0] / 0x0011), 48000 Hz, stereo, fltp
    Stream #0:2[0x131](ita): Audio: aac_latm (HE-AAC) ([17][0][0][0] / 0x0011), 48000 Hz, stereo, fltp (visual impaired)
    Stream #0:3[0x191](eng): Audio: ac3 ([129][0][0][0] / 0x0081), 48000 Hz, 5.1(side), fltp, 384 kb/s
    Stream #0:4[0x3ea]: Unknown: none ([11][0][0][0] / 0x000B)
    Stream #0:5[0x3ec]: Unknown: none ([11][0][0][0] / 0x000B)
    Stream #0:6[0x3fc](eng): Subtitle: dvb_subtitle ([6][0][0][0] / 0x0006) (hearing impaired)
    Stream #0:7[0x1f40]: Unknown: none ([5][0][0][0] / 0x0005)
File 'cut.mkv' already exists. Overwrite ? [y/N] y
Output #0, matroska, to 'cut.mkv':
  Metadata:
    encoder         : Lavf57.56.100
    Stream #0:0: Video: h264 (Main) (H264 / 0x34363248), yuv420p(tv, bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 25 fps, 50 tbr, 1k tbn, 90k tbc
    Stream #0:1(eng): Audio: ac3 ([0] [0][0] / 0x2000), 48000 Hz, 5.1(side), 384 kb/s
    Stream #0:2(eng): Subtitle: dvd_subtitle (dvdsub) (hearing impaired)
    Metadata:
      encoder         : Lavc57.64.101 dvdsub
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:3 -> #0:1 (copy)
  Stream #0:6 -> #0:2 (dvb_subtitle (dvbsub) -> dvd_subtitle (dvdsub))
Press [q] to stop, [?] for help
frame= 2956 fps=0.0 q=-1.0 Lsize=   39612kB time=00:00:59.99 bitrate=5408.7kbits/s speed= 216x
video:36702kB audio:2896kB subtitle:23kB other streams:0kB global headers:0kB muxing overhead: unknown

The documentation for scale2ref gives an example with an overlay, and I don't want to overlay anything, I just want to resize the subtitles stream. Here's their example:
'scale2ref[b][a];[a][b]overlay'

The closest I've got is something like this:
ffmpeg -ss 00:28:00.200 -i Hillary-2016-08-21.mpg -t 00:01:00.000 -map 0:0 -c:v copy -map 0:3 -c:a copy -filter_complex "[0:6]scale2ref[b]" -map "[b]"   cut.mkv

And the output is:
Input #0, mpegts, from 'Hillary-2016-08-21.mpg':
  Duration: 01:30:00.06, start: 20852.199389, bitrate: 6813 kb/s
  Program 1
    Stream #0:0[0xfa]: Video: h264 (Main) ([27][0][0][0] / 0x001B), yuv420p(tv, bt709, top first), 1920x1080 [SAR 1:1 DAR 16:9], 25 fps, 50 tbr, 90k tbn, 50 tbc
    Stream #0:1[0x12c](eng): Audio: aac_latm (HE-AAC) ([17][0][0][0] / 0x0011), 48000 Hz, stereo, fltp
    Stream #0:2[0x131](ita): Audio: aac_latm (HE-AAC) ([17][0][0][0] / 0x0011), 48000 Hz, stereo, fltp (visual impaired)
    Stream #0:3[0x191](eng): Audio: ac3 ([129][0][0][0] / 0x0081), 48000 Hz, 5.1(side), fltp, 384 kb/s
    Stream #0:4[0x3ea]: Unknown: none ([11][0][0][0] / 0x000B)
    Stream #0:5[0x3ec]: Unknown: none ([11][0][0][0] / 0x000B)
    Stream #0:6[0x3fc](eng): Subtitle: dvb_subtitle ([6][0][0][0] / 0x0006) (hearing impaired)
    Stream #0:7[0x1f40]: Unknown: none ([5][0][0][0] / 0x0005)
Streamcopy requested for output stream 0:0, which is fed from a complex filtergraph. Filtering and streamcopy cannot be used together.

And I don't really understand how I can use a filter and direct my resized subtitle stream into the output file.
Any help appreciated! Thanks!

A: scale2ref tags both its output as video streams, which is what they almost always are. So ffmpeg is applying the value of c:v to the scaled subs.
Instead, you should try
ffmpeg -ss 28:00.2 -canvas_size 1920x1080 -i Hillary-2016-08-21.mpg -t 1:00 -map 0:0 -c:v copy -map 0:3 -c:a copy -map 0:6 -c:s dvdsub cut.mkv

Use
ffmpeg -ss 28:00.2 -i Hillary-2016-08-21.mpg -t 1:00 -filter_complex "[0:6][0:0]scale2ref[b][a]" -map 0:0 -c:v copy -map 0:3 -c:a copy -map "[b]" cut.mkv -map "[a]" -f null -

scale2ref takes two inputs and spits two outputs. The 2nd element at both ends is the reference video. So ffmpeg has to be told what to do with the passthrough copy of that reference. In the command above, the null muxer is assigned, which sends it to oblivion.


text:
Q: Files saved by carrierwave is being gotten visible to users not logged in Current Detail
[Env]
nginx puma mysql
Rails == 5.1.5
I mounted carrierwave to upload pictures and files in a post.
[Case]
Users not logged in type the file URL in browser, then they can access and view the file.
[Ideal]
Only users logged in is accessible to the file.
The file path is "uploads/post/images/1234(post_id)/sample.png".
So far, I locate uploads directory under public, app/assets/, and root directory in vain.
Any answers or suggestions are appreciated.

Source
Rails.application.routes.draw do
  get 'users/index'
  get 'users/show'
  get 'posts/index'

  devise_for :users, module: :users
  resources :users, :only => [:index, :show]

  get "/" => "posts#index"
  get "posts/like_ranking" => "posts#like_rank"
  get "posts/post_count_ranking" => "posts#post_count"
  get "posts/tags_search" => "posts#tags_search"
  get "posts/new" => "posts#new"
  get "posts/:id/reply" => "posts#new"
  post "posts/create" => "posts#create"
  get "posts/:id" => "posts#show"
  get "posts/:id/edit" => "posts#edit"
  post "posts/:id/update" => "posts#update"
  post "posts/:id/destroy" => "posts#destroy"

  get 'tags/:tag', to: 'posts#index', as: :tag

  get "users/:id/likes" => "users#likes"
  get "users/:id/reply" => "users#reply"

  resources :posts, only: %w(index)

  resources :posts, shallow: true do
    resources :likes, only: [:create, :destroy]
  end
end

"
class ImageUploader < CarrierWave::Uploader::Base
  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

A: All assets under the public folder is served by nginx. In order to make it available for logged users you can first upload files to other directory than public and create action which serve files by Rails app from that directory and check if users logged before serving.


text:
Q: comparing the contents of more than three files in linux In Linux
to compare the contents of two text files or three I've diff & diff3 command.
But what if I
need to compare more than 3 files at a time??

A: You can do a simple script to compare all the files that you want.
Example:
In directory that contains all files
for i in `ls | grep -v [file_want_compare]` ; do diff [file_want_compare] $i; done


text:
Q: HttpContext.Current.Session is null em thread Olá, Estou com um problema no meu código. Estou Fazendo uma função que dura cerca de 3/4 horas de duração, e então decidi fazer essa função em uma thread para que a mesma não bloqueie o funcionamento geral do sistema. após algumas pesquisas encontrei algumas soluções e testei.
Porem durante essa função eu faço acesso ao banco e quando faço isso a minha thread estoura erro:

HttpContext.Current.Session is null

então procurei aind amais meios de passar o context e a session e cheguei a esses 2 resultado:
var ctx = HttpContext.Current;
        ThreadPool.QueueUserWorkItem(new WaitCallback(ExecuteLongOperation), ctx);

e:
     HttpContext ctx = HttpContext.Current;
    Thread t = new Thread(new ThreadStart(() =>
    {
        HttpContext.Current = ctx;
        ExecuteLongOperation();
    }));
    t.Start();

até esse ponto o HttpContext.Current.Session tem a session com valor, com  tudo certo.
e no meu metodo:
  private void ExecuteLongOperation(object state)
    {
        try
        {
            HttpContext.Current = (HttpContext)state;  .....}

e quando dou um quickwatch no HttpContext.Current.Session, a mesma continua nula.
O que estou fazendo de errado? Ja tentei tambem passar a session mas ela é read-only.
Alguma sugestão?
Obrigado

A: A session faz parte do contexto da requisição. Quando a requisição termina, a session deixa de existir. Em outras palavras, você está tentando acessar um objeto que é dependente da requisição (session) em um método que não é.
Se você precisa de valores da session, passe esses valores para o seu método. Passar uma referência pra session também não vai funcionar pelo motivo dito acima.
Se você estiver usando .net >= 4.5.2, pode usar o HostingEnvironment.QueueBackgroundWorkItem pra isso.
Exemplo de uso aqui.


text:
Q: Listen to phone state even after boot In my app I listen to the phone state events(i.e call received, idle etc) using a Broadcast Receiver. Code as below:
public class PhoneCallreceiver extends BroadcastReceiver {
    private boolean ringing;
    private boolean received;

    public PhoneCallreceiver() {
    }

@Override
public void onReceive(Context context, Intent intent) {
    Log.v("ranjith", "enterted receiver");
    Bundle bundle = intent.getExtras();
    String incomingnumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
    String state = bundle.getString(TelephonyManager.EXTRA_STATE);
    Log.v("ranjapp", state);

    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        ringing = true;
        received = false;
    }
}

Manifest.xml
    <receiver
        android:name=".PhoneCallreceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE"/>
        </intent-filter>
    </receiver>

My problem is I want to start the BroadCast Receiverautomatically after the device is re-booted. I have a BroadCast Receiver to listen to boot but I am not sure how to start the PhoneCallreceiver BroadCast receiver.
Manifest.xml
   <receiver
        android:name=".backend.BootStarter"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

Code:
public class BootStarter extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        PhoneCallreceiver callreceiver = new PhoneCallreceiver();
        context.registerReceiver(callreceiver,new IntentFilter(**what to put here**));
            }
        }

A: Found the answer to my question, intentfilter action to receive phonestate is android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED
My updated code below:
public class BootStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    PhoneCallreceiver callreceiver = new PhoneCallreceiver();
            context.registerReceiver(new PhoneCallreceiver(), new IntentFilter(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED));
        }
    }


text:
Q: Embedded Structure with interface not working Below code not able to set or get the values from base entity
How to make it working to get base as well as inherited struct to return values
type BaseEntity struct {
    Id string
}

func (p BaseEntity) SetId(Id string) {
    p.Id = Id
}

func (p BaseEntity) GetId() string {
    return p.Id
}

type Employee struct {
    BaseEntity
    Name string
}

type DataInterface interface {
    SetId(Id string)
    GetId() string
}

func getObjFactory() DataInterface {
    //return Data.Employee{BaseEntity: Data.BaseEntity{}}
    return new(Employee)
}

func main() {
    entity := getObjFactory()

    entity.SetId("TEST")
    fmt.Printf(">> %s", entity.GetId())
}

A: The method SetId is using a value receiver so p is a copy of the object as opposed to a pointer to the object.
Instead, you want to use a pointer receiver as below:
func (p *BaseEntity) SetId(Id string) {
    p.Id = Id
}

You can find more details in the Tour of Go under section Choosing a value or pointer receiver.


text:
Q: Dynamic return type in templated method in c++03 Recently I've been tasked with rewriting some of my code from C++14 to C++03 so that I can make use of ompSs. However, I'm not sure if this particular snippet of code can be rewritten without making use of auto.
I have a template class Field< Type > which is a container for Type. The method from the snippet defines the behavior of the summation of two fields, as the sum of every entry in the field point by point.
Type, can be either a double, or a self designed class Vector. The
behaviour of Vector + Vector, Vector + double, and double + Vector, are fully defined in the definition of class Vector.
The code snippet is able to fully define the intended behaviour for the
summation of Fields in it's four possible scenarios:

*

*Field< double > + Field< Vector >,

*Field< Vector > + Field< double >,

*Field< double > + Field< double >,

*Field< Vector > + Field< Vector >
This is accomplished by creating a response Field, where Type is inferred by the result of the summation of the first element of both vectors.
How can I accomplish the same thing without making use of the awesome auto
operator?
template< typename Type_1, typename Type_2 > const auto operator+ (
const Field< Type_1 >& lhs, const Field< Type_2 >& rhs ) {

    auto response = Field <
       typename std::remove_const<decltype( lhs.get(0) + rhs.get(0) )>::type
    >( lhs.size() );

    for( size_t i = 0; i < lhs.size(); i++ ){
        response[i] = lhs.get(i) + rhs.get(i);
    }
    return response;
}

A: I'm pretty sure that you are out of luck here. The problem is mainly that you can't select a particular overload of operator+ without also specifying the return type, so you can't retrieve it independently in C++03.
What you can do, however, is to write a meta-function that gives the correct return type. If you use this function also to define the operator+ overloads you'll get the same compile-time guarantees and nice-enough errors:
template <typename Lhs, typename Rhs>
struct AddResult;

template <>
struct AddResult<Vector, Vector> { typedef Vector result_type; }
// ...

typename AddResult<Vector, Vector>::result_type operator+(Vector lhs, Vector rhs)
// ...

template< typename Type_1, typename Type_2 >
Field<typename AddResult<Type_1, Type_2>::result_type>
operator+ (const Field<Type_1>& lhs, const Field<Type_2>& rhs)
{
    Field<typename AddResult<Type_1, Type_2>::result_type> response(lhs.size());

    for (size_t i = 0; i != lhs.size(); i++) {
        response[i] = lhs.get(i) + rhs.get(i);
    }
    return response;
}

Very far from being pretty, but I can't think of a nicer solution.

A: You can always replace auto with an explicit type.
In this case, you can add a template parameter (to the front of the template so that Type1 and Type2 can still be deduced), and specify the result type at the call site.
template<typename Result, typename Type_1, typename Type_2 >
const Result operator+ ( const Field< Type_1 >& lhs, const Field< Type_2 >& rhs ) ...


text:
Q: Date difference showing wrong values I have used a function to calculate date difference between 2 dates.
Here is my function
function date_difference ($date_1, $date_2) {

    $val_1 = new DateTime($date_1);
    $val_2 = new DateTime($date_2);

    $interval = $val_1->diff($val_2);
    $year     = $interval->y;
    $month    = $interval->m;
    $day      = $interval->d;

    $output   = '';

    if($year > 0){
        if ($year > 1){
            $output .= $year." years ";
        } else {
            $output .= $year." year ";
        }
    }

    if($month > 0){
        if ($month > 1){
            $output .= $month." months ";
        } else {
            $output .= $month." month ";
        }
    }

    if($day > 0){
        if ($day > 1){
            $output .= $day." days ";
        } else {
            $output .= $day." day ";
        }
    }
    if($day == 0)
        $output.=' Almost Over';
    if($day < 0)
        $output.= ' Expired';
    return $output;
}

I am using it like this
echo date_difference(date('m/d/Y'),'02/06/2013');

It shows the result as 25 days where as it should show expired. Can anyone point where i am doing wrong.

A: As soon as I saw this XKCD page I wanted an opportunity to post it, and here it is!

When your code tries to parse 02/06/2013, how can it know whether you mean "February 2nd", or "June 6th"? You should ALWAYS use the YYYY-MM-DD format when giving a date to parse, or better yet hardcode the actual numeric timestamp (in this case 1360126800)

A: DateInterval won't have nagative values, you need to compare the two DateTime object.
Change to
if($val_1 < $val_2 && $day == 0)
    $output.=' Almost Over';
if($val_1 > $val_2)
    $output.= ' Expired';
return $output;

A: just use the UNIX time stamp, that way it should be a very easy calculation.
it can be shown in Y-D-M and you can even make a count down clock if you feel a bit fancy.
most MMO's and management systems use it to register the date & time of registration and to show how long the member has been on the community.
hope it helped!.


text:
Q: How can I ignore default property that Jackson added? I'm using jackson for making JSON object. I found that jackson add default property automatically. I really don't need this field, How can I remove that?
this is my code that simplified.
@JsonIgnoreProperties(value = {"@id"})
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, scope = CustomMessage.class)
public class SystemMessage {
     private String body;
     }
 }

Eventhoug I added JsonIgnoreProperties annotation, It is not removed. I think it is because "@id" is a default property.

{"@id":1,"body":"hello"}

this is the message I got by rabbitMQ.

A: The @Id is added because of the @JsonIdentityInfo annotation - see https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIdentityInfo.html where you can see that this is the default for the property field.
This annotation is used for parent-child relationships and especially when you have circular dependencies among your objects. So if this is not true for you, you can just omit this annotation


text:
Q: A loop in a try..catch Okay, I have a try..catch such that :
Try
  Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
Catch ex As Exception
  sheet = InputBox("Re-enter table:")
  Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
End Try

The above will only work for the first instance.
What I want to do is keep displaying the Input box until the dr is a success (i.e. values have been retrieved from the database.
I know I need some sort of while in the catch, but I am unsure how to proceed

A: Remove the performSelect from inside the catch block, otherwise you could throw an exception there too and it would need to be caught, etc.  Put the entire try catch block inside the while loop and exit when you have a value for sheet.

A: Have a look here why this is not a good idea.
If you are still interested, you can try this:
   Dim retries As Integer = 3
   While True
       Try
           Dim sheet as String = InputBox("Enter table:")
           Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & sheet, myConn)
           Exit While
       Catch
           retries -= 1
           If retries = 0 Then
               Throw
           Else
               System.Threading.Thread.Sleep(1000)
           End If
       End Try
   End While

Change the retries if you want more(infinite-> <=0), change or remove the thread.sleep if you want to retry immediately.

A: This might work:
    Dim inputOk As Boolean = False

    Do Until inputOk = True
        Try
            Dim dr As OleDbDataReader = performSelect("SELECT * FROM " & table, myConn)
            inputOk = True
        Catch ex As Exception
            sheet = InputBox("Re-enter table:")

        End Try
        End
    Loop

A: Catch block has been designed to handle exceptions, not to execute database queries... You should use Jeff's way. The same I was writing, but he's quicker than I


text:
Q: How to understand the meaning of this ActiveStorage Error Log? This log makes the majority of my error log on Heroku and I don't quite understand the meaning of the error. What is it and how can I make it go away?
2018-12-09T00:22:21.020684+00:00 app[web.3]: 00:22:21 worker.1 | E, [2018-12-09T00:22:21.016292 #15] ERROR -- : Retrying ActiveStorage::PurgeJob in 3 seconds, due to a StandardError. The original exception was #<ActiveRecord::RecordNotFound: Couldn't find ActiveStorage::Blob with 'id'=2>.
2018-12-09T00:22:21.020807+00:00 app[web.3]: 00:22:21 worker.1 | I, [2018-12-09T00:22:21.018923 #15]  INFO -- : [ActiveJob] Enqueued ActiveStorage::PurgeJob (Job ID: e89af631-9c28-4247-8897-887a55c68b64) to Sidekiq(default) at 2018-12-09 00:22:24 UTC
2018-12-09T00:22:25.744836+00:00 app[web.4]: 00:22:25 worker.1 | D, [2018-12-09T00:22:25.744555 #15] DEBUG -- :   [1m[36mActiveStorage::Blob Load (1.4ms)[0m  [1m[34mSELECT  "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2[0m  [["id", 2], ["LIMIT", 1]]
2018-12-09T00:22:25.745100+00:00 app[web.4]: 00:22:25 worker.1 | E, [2018-12-09T00:22:25.744923 #15] ERROR -- : Retrying ActiveStorage::PurgeJob in 3 seconds, due to a StandardError. The original exception was #<ActiveRecord::RecordNotFound: Couldn't find ActiveStorage::Blob with 'id'=2>.
2018-12-09T00:22:25.746754+00:00 app[web.4]: 00:22:25 worker.1 | I, [2018-12-09T00:22:25.746542 #15]  INFO -- : [ActiveJob] Enqueued ActiveStorage::PurgeJob (Job ID: e89af631-9c28-4247-8897-887a55c68b64) to Sidekiq(default) at 2018-12-09 00:22:28 UTC

All I understand is that it is looking for an image on S3 that doesn't exist. Where does it get the value of id from?
This makes 95% of our logs and its distracting us from focusing or discovering real issues. How can i fix it and make it go away?
My ActiveStorage::Blob at this moment is empty, but it keeps asking for urls to attachment that doesn't exist.


text:
Q: How to calculate pagination in magritte YAML configs? I'm looking to pull data from a REST API that uses a record offset system.  I need to perform basic arithmetic on the returned (current_offset + item_count) data to calculate the next offset.
Unfortunately, this API uses a variable page size, so simple offsets won't work.  Nor does it return the next offset to use in the response, just the component values.
However, it appears that there's no way to do even basic arithmetic that I can see.  Am I just missing it?


text:
Q: how can i split the string with the cammas that are not embeded in braces , brackets and qutations from a string with php --eddited--
how can i split the string with the cammas that are not embeded in braces , brackets and qutations from a string with php

A: One way would be to use lookarounds:
<?php

$data = <<<DATA
func('name','family,address') , "lorem ipsom, is a..." , ['name','part']
DATA;

$regex = '~(?<=\ ),(?=\h)~';

$parts = preg_split($regex, $data);
print_r($parts);
?>

See a working demo on ideone.com.

Even better yet would be a (*SKIP)(*FAIL) mechanism:

<?php

$data = <<<DATA
func('name','family,address') , "lorem ipsom, is a..." , ['name','part']
DATA;

$regex = '~
            (\w+\([^)]+\)
            |
            "[^"]+"
            |
            \[[^]]+\]
            (*SKIP)(*FAIL))
            |
            \h*,\h*
        ~x';

$parts = preg_split($regex, $data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($parts);
?>

See a demo for this one on ideone.com as well.

A: Try this :
$elements = explode(',', $string);


text:
Q: php Laravel- retrieve property of object I have something like that :
In my controller , I wrote this line :
dd($file->path);

and here is result :
UploadedFile {#294
  -test: false
  -originalName: "photo.png"
  -mimeType: "image/png"
  -size: 319216
  -error: 0
  path: "/tmp"
  basename: "phpLJA6Ge"
  pathname: "/tmp/phpLJA6Ge"
}

I want to return .png . How to retrieve originalName?

A: To get the name of the file with extension included: $file->getClientOriginalName()
To get the content: file_get_contents($file->getRealPath());


text:
Q: One large number in table with decimals I am using siunitx to align numbers in a column. Problem is I got by intention one row at the beginning which is a large number, indicated by ',' per 1,000. See the following example.
What I would like to achieve:
1) Align the decimals to the decimal point '.' This is row 2, 3 and 4.
2) center the big numbers, i.e. row 1 and 5 in this example. When I tested different options, the large numbers where always either too much to the left or too much to the right. If possible, they should simply be centered. I believe that makes the most sense in terms of formatting.
Is it possible?
\documentclass{article}
\usepackage{siunitx}

\sisetup{%
input-ignore={,},
input-decimal-markers = {.},
table-format = 2.2,
table-number-alignment = center,
}%

\begin{document}
\begin{tabular}{SS}
row & alignToDec \\
row1: & 19,000,000.0 \\
row2: & 12.38 \\
row3: & 1.97  \\
row4: & 91.01  \\
row5: & 87,000,000.0 \\
\end{tabular}
\end{document}

A: For some reason your code compiles, but:
1) You should not (at least you have no reason to do that) use an S column type for columns that doesn't contain math.
2) If the contents of a cell inside an 'S' column is text place it inside curly braces. (This way the content will be centered by default from siunitx because it will be considered as a text). [See your "broken" alignToDec in the second column if outside of braces and place it inside braces to see the difference]
3) Use the same method as above for your big numbers...
4) You could specify the table-format as an optional argument in your S columns. (siunitx behaves better like this in general)
\documentclass{article}
\usepackage{siunitx}

\sisetup{%
input-ignore={,},
input-decimal-markers = {.},
table-number-alignment = center,
}%

\begin{document}
\begin{tabular}{cS[table-format=2.2]}
row & {alignToDec} \\
row1: & {19,000,000.0} \\
row2: & 12.38 \\
row3: & 1.97  \\
row4: & 91.01  \\
row5: & {87,000,000.0} \\
\end{tabular}
\end{document}

PS: Remove the luatex tag.


text:
Q: How to make fields disappear after focusing out I have radio buttons, that open 3 different divs (one at a time)
In the second div, I added 4 text inputs, so that each one should be open after clicking in the previous one (click(function())).  Once they are opened, I want it to hide again when I select the other radio button and the actual div hides.
How this can be done?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" type="text/css" href="estilo.css">
<title>Documento sem título</title>

2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
3 Cars<input type="radio" name="cars" value="3" />
4 cars<input type="radio" name="cars" value="4" />

    2 Cars Selected

    <input type="text" id="campo1">

<input type="text" id="xxx" name="non"/>

<input type="text" id="eee" name="uuu"/>

<input type="text" id="www" name="ttt"/>

    4 Cars

A: Use .hide() https://api.jquery.com/hide/
You can show, so probably you can hide. :)
On focusout, that is.

A: You're probably looking for the focusout event...
Read this... http://api.jquery.com/focusout/
That should set you on tracks


text:
Q: Is there a way to generate pydoc for nested functions? I'm looking for a way to generate documentation, pydoc on this case, for nested functions. Is this possible with pydoc? Is it possible with other tools?
For example:
"""
Module docstring.
"""

def foo(x):
    """
    Foo does something.
    """
    ...

    def bar(y):
        """
        Bar does something
        """
        ...

Generating pydoc with: pydoc -w -filename- will generate pydoc for the module and foo() but not for bar().
Normally this would be ok; the problem is that I'm trying to build a library for educational purposes, and documenting what happens inside the closure is specially helpful. I want to find a way to document it without having to expose the inner functions to the global scope.

A: There is always the manual method:
"""
Module docstring.
"""

def foo(x):
    """
    Foo does something.
    N.B. Foo includes a local function bar() that does what bar does.
    """
    ...

    def bar(y):
        """
        Bar does something
        """
        ...

It is not automatic but it does mean that your students only get to see documentation on those private methods that you wish them to see.


text:
Q: 'Unsupported browser' when accessing router page Today, I wanted to make an app that accesses the router's web page to make managing it easier. However, my router said that the web browser that I'm using is unsupported.
Here's the activity:
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private TextView textView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView.loadUrl("192.168.1.1");
        webView.setWebViewClient(new WebViewClient() {

            //API Level under 24
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url){
                return false;
            }

            //API Level over 24
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {
                return false;
            }
        });

        urlBar();
        debugFinish();
    }

    public void debugFinish() {
        Log.d("MyApplication", "Finishing in 5 seconds.");
        new Handler().postDelayed(() -> Log.d("MyApplication", "Finishing in 4 seconds."),1000);
        new Handler().postDelayed(() -> Log.d("MyApplication", "Finishing in 3 seconds."),2000);
        new Handler().postDelayed(() -> Log.d("MyApplication", "Finishing in 2 seconds."),3000);
        new Handler().postDelayed(() -> Log.d("MyApplication", "Finishing in 1 second."),4000);
        new Handler().postDelayed(() -> {
            Log.d("MyApplication", "Finished.");
            finish();
        },5000);
    }

    public void urlBar() {
        new Handler().postDelayed(() -> {
            String webUrl = webView.getUrl();
            textView = findViewById(R.id.text);
            textView.setText(webUrl);
            urlBar();
        },100);
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

And here are the logs for the latest session:
08/23 18:19:57: Launching 'app' on samsung SM-A528B.
Install successfully finished in 325 ms.
$ adb shell am start -n "com.censored.censored/com.censored.censored.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.censored.censored
Connected to process 24423 on device 'samsung-sm_a528b-serialshoudbehere'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-1f2f27f8.jar
W/outerpageacces: DexFile /data/data/com.censored.censored/code_cache/.studio/instruments-1f2f27f8.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/outerpageacces: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/outerpageacces: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/ActivityThread: handleBindApplication()++ app=com.censored.censored
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10759; state: ENABLED
W/ActivityThread: Application com.censored.censored is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
Connecting to com.censored.censored
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-1f2f27f8.jar
W/outerpageacces: DexFile /data/data/com.censored.censored/code_cache/.studio/instruments-1f2f27f8.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/outerpageacces: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/outerpageacces: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/ActivityThread: handleBindApplication()++ app=com.censored.censored
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10759; state: ENABLED
W/ActivityThread: Application com.censored.censored is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:59305', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1429)
W/ActivityThread: Slow operation: 2612ms so far, now at handleBindApplication: Before HardwareRenderer
W/ActivityThread: Slow operation: 2621ms so far, now at handleBindApplication: After HardwareRenderer
W/ziparchive: Unable to open '/data/data/com.censored.censored/code_cache/.overlay/base.apk/classes3.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~as9uWR63HKmuwYZvqPYU3Q==/com.censored.censored-0ouQJlouEDKWFYvo3am4mg==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~as9uWR63HKmuwYZvqPYU3Q==/com.censored.censored-0ouQJlouEDKWFYvo3am4mg==/base.dm': No such file or directory
V/GraphicsEnvironment: ANGLE Developer option for 'com.censored.censored' set to: 'default'
V/GraphicsEnvironment: Updatable production driver is not supported on the device.
D/LoadedApk: LoadedApk::makeApplication() appContext.mOpPackageName=com.censored.censored appContext.mBasePackageName=com.censored.censored
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/ActivityThread: handleBindApplication() --
D/OpenGLRenderer: RenderThread::requireGlContext()
I/AdrenoGLES-0: QUALCOMM build                   : cac6e6f805, I5187d04b75
    Build Date                       : 11/22/21
    OpenGL ES Shader Compiler Version: EV031.35.01.10
    Local Branch                     :
    Remote Branch                    :
    Remote Branch                    :
    Reconstruct Branch               :
I/AdrenoGLES-0: Build Config                     : S P 10.0.7 AArch64
I/AdrenoGLES-0: Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: PFP: 0x016dc094, ME: 0x00000000
D/OpenGLRenderer: RenderThread::setGrContext()
I/DecorView: [INFO] isPopOver=false, config=true
I/DecorView: updateCaptionType >> DecorView@ad5ddd0[], isFloating=false, isApplication=true, hasWindowControllerCallback=true, hasWindowDecorCaption=false
D/DecorView: setCaptionType = 0, this = DecorView@ad5ddd0[]
I/DecorView: getCurrentDensityDpi: from real metrics. densityDpi=450 msg=resources_loaded
W/outerpageacces: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/outerpageacces: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
W/ziparchive: Unable to open '/data/app/~~YgYDZv4GpC9wYpwxXiO9DA==/com.google.android.trichromelibrary.dev_524300233-fAGblpk31Yjy1vkpqWEHyA==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~YgYDZv4GpC9wYpwxXiO9DA==/com.google.android.trichromelibrary.dev_524300233-fAGblpk31Yjy1vkpqWEHyA==/base.dm': No such file or directory
W/outerpageacces: Entry not found
I/WebViewFactory: Loading com.google.android.webview.dev version 106.0.5243.2 (code 524300233)
W/outerpageacces: Accessing hidden method Landroid/os/Trace;->isTagEnabled(J)Z (unsupported, reflection, allowed)
W/outerpageacces: Accessing hidden method Landroid/os/Trace;->traceBegin(JLjava/lang/String;)V (unsupported, reflection, allowed)
W/outerpageacces: Accessing hidden method Landroid/os/Trace;->traceEnd(J)V (unsupported, reflection, allowed)
W/outerpageacces: Accessing hidden method Landroid/os/Trace;->asyncTraceBegin(JLjava/lang/String;I)V (unsupported, reflection, allowed)
W/outerpageacces: Accessing hidden method Landroid/os/Trace;->asyncTraceEnd(JLjava/lang/String;I)V (unsupported, reflection, allowed)
I/cr_WVCFactoryProvider: Loaded version=106.0.5243.2 minSdkVersion=29 isBundle=true multiprocess=true packageId=2
I/cr_LibraryLoader: Successfully loaded native library
I/cr_CachingUmaRecorder: Flushed 9 samples from 9 histograms.
E/SchedPolicy: Failed to find cgroup for tid 24423
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/snapshot_blob_32.bin': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/snapshot_blob_64.bin': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/icudtl.dat': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/chrome_100_percent.pak': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/stored-locales/en-US.pak': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/stored-locales/en-US.pak': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/stored-locales/en-US.pak': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/resources.pak': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/stored-locales/en-US.pak': No such file or directory
W/chromium: [WARNING:dns_config_service_android.cc(115)] Failed to read DnsConfig.
D/CompatibilityChangeReporter: Compat change id reported: 171228096; UID 10759; state: ENABLED
W/outerpageacces: Accessing hidden method Landroid/media/AudioManager;->getOutputLatency(I)I (unsupported, reflection, allowed)
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/snapshot_blob_32.bin': No such file or directory
E/outerpageacces: Failed to open file '/data/data/com.censored.censored/code_cache/.overlay/base.apk/assets/snapshot_blob_64.bin': No such file or directory
W/cr_media: BLUETOOTH_CONNECT permission is missing.
W/cr_media: registerBluetoothIntentsIfNeeded: Requires BLUETOOTH permission
D/MyApplication: Finishing in 5 seconds.
D/NativeCustomFrequencyManager: [NativeCFMS] BpCustomFrequencyManager::BpCustomFrequencyManager()
I/DecorView: notifyKeepScreenOnChanged: keepScreenOn=true
I/ViewRootImpl@437d938[MainActivity]: setView = com.android.internal.policy.DecorView@ad5ddd0 TM=true
I/ViewRootImpl@437d938[MainActivity]: Relayout returned: old=(0,0,1080,2400) new=(0,0,1080,2400) req=(1080,2400)0 dur=6 res=0x7 s={true -5476376616297765184} ch=true fn=-1
I/ViewRootImpl@437d938[MainActivity]: [DP] dp(1) 1 android.view.ViewRootImpl.reportNextDraw:11420 android.view.ViewRootImpl.performTraversals:4193 android.view.ViewRootImpl.doTraversal:2919
D/ViewRootImpl@437d938[MainActivity]: Creating frameDrawingCallback nextDrawUseBlastSync=false reportNextDraw=true hasBlurUpdates=false
D/ViewRootImpl@437d938[MainActivity]: Creating frameCompleteCallback
D/OpenGLRenderer: eglCreateWindowSurface
D/ViewRootImpl@437d938[MainActivity]: Received frameDrawingCallback frameNum=1. Creating transactionCompleteCallback=false
I/BufferQueueProducer: [ViewRootImpl@437d938[MainActivity]#0(BLAST Consumer)0](id:5f6700000000,api:1,p:24423,c:24423) queueBuffer: queued for the first time.
D/OpenGLRenderer: GPIS:: SetUp Pid : 24423    Tid : 24468
D/ViewRootImpl@437d938[MainActivity]: Received frameCompleteCallback  lastAcquiredFrameNum=1 lastAttemptedDrawFrameNum=1
I/ViewRootImpl@437d938[MainActivity]: [DP] pdf(0) 1 android.view.ViewRootImpl.lambda$addFrameCompleteCallbackIfNeeded$3$ViewRootImpl:4995 android.view.ViewRootImpl$$ExternalSyntheticLambda16.run:6 android.os.Handler.handleCallback:938
I/ViewRootImpl@437d938[MainActivity]: [DP] rdf()
D/ViewRootImpl@437d938[MainActivity]: reportDrawFinished (fn: -1)
D/InsetsSourceConsumer: ensureControlAlpha: for ITYPE_NAVIGATION_BAR on com.censored.censored/com.censored.censored.MainActivity
D/InsetsSourceConsumer: ensureControlAlpha: for ITYPE_STATUS_BAR on com.censored.censored/com.censored.censored.MainActivity
I/ViewRootImpl@437d938[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1
D/InputMethodManager: startInputInner - Id : 0
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
D/InputMethodManager: startInputInner - Id : 0
D/MyApplication: Finishing in 4 seconds.
D/MyApplication: Finishing in 3 seconds.
D/MyApplication: Finishing in 2 seconds.
D/MyApplication: Finishing in 1 second.
I/outerpageacces: Compiler allocated 4564KB to compile void android.view.ViewRootImpl.performTraversals()
D/MyApplication: Finished.
I/ViewRootImpl@437d938[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1
D/InputTransport: Input channel destroyed: 'ClientS', fd=214
I/ViewRootImpl@437d938[MainActivity]: handleAppVisibility mAppVisible=true visible=false
D/OpenGLRenderer: setSurface called with nullptr
D/OpenGLRenderer: setSurface() destroyed EGLSurface
D/OpenGLRenderer: destroyEglSurface
I/ViewRootImpl@437d938[MainActivity]: Relayout returned: old=(0,0,1080,2400) new=(0,0,1080,2400) req=(1080,2400)8 dur=8 res=0x5 s={false 0} ch=true fn=55
I/ViewRootImpl@437d938[MainActivity]: stopped(true) old=false
D/OpenGLRenderer: setSurface called with nullptr
I/ViewRootImpl@437d938[MainActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: '3e2bfbb', fd=175
D/OpenGLRenderer: setSurface called with nullptr
W/System: A resource failed to call close.

In case you are wondering: yes. The page opens just fine in the Chrome app on my phone.

A: WebSettings.setDomStorageEnabled(true);

This did the trick


text:
Q: $|x+y|^p \leq |x|^p + |y|^p$ for $0 < p < 1$. How can I prove the inequality $|x+y|^p \leq |x|^p+ |y|^p$ for $0 < p < 1$ and $x,y \in \mathbb{C}$.
I have an idea when $x,y \in \mathbb{R}$: then I can prove the equivalent
$$(1+s)^p \leq 1+ s^p$$
where $s > 0$ but for the complex case I don't really have ideas.
Thanks for the help/reference!

A: For $x=y=0$ the inequality (or should I say equality) holds. Now we are going to prove it also holds for at least one non - zero $x$ or $y$.
$a^{p} \geq a$ for $0<p<1$ and $0 \leq a \leq 1$ where equality happens if $a$ is either $0$ or $1$.
$\left( \frac{|x|}{|x|+|y|} \right)^{p} \geq \frac{|x|}{|x|+|y|}$
$\left( \frac{|y|}{|x|+|y|} \right)^{p} \geq \frac{|y|}{|x|+|y|}$
Adding the two inequalities, we obtain
$\left( \frac{|x|}{|x|+|y|} \right)^{p} + \left( \frac{|y|}{|x|+|y|} \right)^{p} \geq 1$
$|x|^{p} + |y|^{p} \geq (|x|+|y|)^{p}$
Combine with triangle inequality $|x|+|y| \geq |x+y|$ to obtain
$|x|^{p} + |y|^{p} \geq |x+y|^{p}$, equality happens if any of $x,y$ is zero.

A: $x\mapsto x^p$ is increasing, so $|x+y|^p\leq (|x|+|y|)^p$ by the triangle inequality, so all you have to prove is that $(a+b)^p \leq a^p+b^p$ for all $a,b\geq 0$.
To see this, fix $b$ and define $g(x)=x^p+b^p-(x+b)^p$ and note that $g'(x)=px^{p-1}-p(x+b)^{p-1}\geq 0,$ so $g$ is increasing. We also see that $g(0)=0$ and therefore $g(x)\geq 0$. This establishes the desired result.


text:
Q: Converting SuiteSparse.SPQR.QRSparseQ to SparseMatrixCSC? I have this problem that converting the native sparse format for the QR decomposition of a sparse Matrix takes forever. However, I need it in the CSC format to use it for further computations.
using LinearAlgebra, SparseArrays
N = 1000
A = sprand(N,N,1e-4)
@time F = qr(A)
@time F.Q
@time Q_sparse = sparse(F.Q)

0.000420 seconds (1.15 k allocations: 241.017 KiB)
0.000008 seconds (6 allocations: 208 bytes)
6.067351 seconds (2.00 M allocations: 15.140 GiB, 36.25% gc time)

Any suggestions?

A: Okay, I found the problem. For other people trying to do it:
factors = F.Q.factors
τ       = F.Q.τ
Nτ = size(factors)[2]
Isp = sparse(I(N));
@time Q_constr = prod(Isp - factors[:,i]*τ[i]*factors[:,i]' for i in 1:Nτ)
Q_constr ≈ Q_sparse

0.084461 seconds (62.64 k allocations: 3.321 MiB, 18.28% gc time)
true

You see that the method sparse(F.Q) is somehow using the wrong representation. If you construct Q as I did above, it will be considerably faster.


text:
Q: An exterior angle theorem for n-dimensional polytopes? In the plane, the exterior angle of a vertex is $\pi -$ the standard ("interior") angle, which may be negative in some cases.  The following is true for non-weird polygons:

The sum of the exterior angles at each vertex is a full turn ($2\pi$ radians).

I am informally calling polygons with self-crossing edges or holes as "weird" -- please do let me know what the standard terminology is.  I have seen an extension to 3-dimensional polytopes of this form:

The sum of the exterior angles of a polytope is $4\pi$ radians.

In this case, the exterior angle of a vertex is $2\pi -$ (the sum of the face angles at that vertex).  I have not seen a proof, but I think it is true for non-weird polytopes, and a modified version is probably true for polytopes with nonzero genus.
My question is: is there a general n-dimensional version of these properties?

A: The standard terminology is ``non-crossing polygon'', I think.
Concerning the generalization in arbitrary dimension, it is possible at least in the convex case. Simply define the exterior angle at a point to be the measure (with respect to the usual invariant measure on the unit sphere) of the set of exterior normal vectors to the polytope at this point. The sum is then the total volume of the unit sphere.
The key word is Alexandrov measure, and it is a generalization of Gaussian curvature that can be defined for arbitrary convex compact sets. I do not know many references, but you can try the handbook of convex geometry. It is very likely that this can be generalized to more general polyedra.

A: Here's something a bit less numerical, but more satisfying, I think.
For each vertex $v$ of the polytope $P$, let $v'$ be the set of vectors $\vec w$
such that $\langle \vec w, v-p \rangle \geq 0$ for all $p\in P$. This is a polyhedral
cone. If $P$ is very round at $v$, then $v'$ is very sharp.
Theorem: if $P$ is a compact convex polytope, then the cones {$v'$} exactly cover space (at least,
their interiors don't intersect).
The set of cones $v^*$ is called the "dual fan" to $P$. You can read about it in Fulton's
book on toric varieties.

A: What you call exterior angles are the curvatures at the vertices, and the result you are referring to is the combinatorial Gauss-Bonnet theorem. It says that in an angled 2-complex $K$ the sum of the curvatures at the vertices plus the sum of the curvatures at the polygonal faces is $2\pi \chi(K)$ (Euler characteristic). When your complex is piecewise Euclidean then the curvature at each face is zero implying your result in the case of polyhedra. For polyhedra, another way to see this is to perform barycentric subdivision and sum the angles of all faces to reduce your identity to $V+F-E=2$. A possible reference is this paper (theorem 4.8).


text:
Q: Res.json not sending data in React app and appearing as undefined I am developing a React with Nodejs backend and I have implemented "stripe" in order to process payments. The problem appears when I need to get the URL which should redirect me to the Stripe payment form. I should get it from a json response, but it is empty, no matter what I send. I've even tried sending really simple data, but it still doesn't work. I've used it before without problems in this project, so I don't know what I am doing wrong here. Can anyone offer any help? Thank you!
This is the router file, which creats the session for the payment and which is also supposed to send the needed URL. I tested and the URL is correct, it is just a matter of sending it through res.json
router.post("/payment", async(req, res) => {
    const course = await Courses.findByPk(req.body.items[0].id);
    const storeItems = new Map([
        [course.id, { priceInCents: course.price, name: course.title }],
    ])
    try {
        const session = await stripe.checkout.sessions.create({
            payment_method_types: ['card'],
            mode: 'payment',
            line_items: req.body.items.map(item => {
                const storeItem = storeItems.get(item.id)
                return {
                    price_data: {
                        currency: "usd",
                        product_data: {
                            name: storeItem.name,
                        },
                        unit_amount: storeItem.priceInCents,
                    },
                    quantity: item.quantity,
                }
            }),
            success_url: 'http://localhost:3000/profile-page',
            cancel_url: `http://localhost:3000/course-details/${course.id}`
        })
        res.json({ url: session.url });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

And this is where I should be getting the URL back, but I don't. Instead, when I console.log it, I get "undefined".
 if (response.data.error) {
              alert(response.data.error);
            } else {
              axios.post("http://localhost:3001/users_courses/payment", {
                items: [
                    { id: data.id, quantity: 1 },
                  ],
            }, {
                headers: {
                    accessToken: localStorage.getItem("accessToken"),
                },
            }).then(res => {
                if(res.ok) return res.json();
                return res.json().then(json => Promise.reject(json));
            }).then (( { url }) => {
                window.location.href = url;
                console.log(url + " this is the url");
            }).catch(e => {
                console.error(e.error);
            })
          }

A: I think it has to do with how you're handling your axios post, I think with a small change like I suggested below this should work for you.
axios
  .post(
    "http://localhost:3001/users_courses/payment",
    {
      items: [{ id: response.data.id, quantity: 1 }],
    },
    {
      headers: {
        accessToken: localStorage.getItem("accessToken"),
      },
    }
  )
  .then(({ data: { url } }) => {
    window.location.replace(url);
    console.log(url + " this is the url");
  })
  .catch((e) => {
    console.error(e.error);
  });

Note that axios is not like the fetch API where you have to handle the transformation of the response body into the json object.


text:
Q: How do you move a circle in python? I am trying to make a circle that moves but I don't know how to make it work. I am using pygame as the package. I think it'll work if you update the circle but I don't know how to do that.
import os, sys, math, pygame, pygame.mixer
from pygame.locals import *

black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
white = (255,255,255)
run_me = True

screen_size = screen_width, screen_height = 600, 400
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('ha ha ha ha ha')

clock = pygame.time.Clock()
fps_limit = 60

#circle
    colorcircle = (red)
    posx = 300
    posy = 200
    circle = pygame.draw.circle(screen, colorcircle, (posx, posy), 50)

while run_me:
    clock.tick(fps_limit)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run_me = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                posx = posx - 10
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                posx = posx + 10
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                posy = posy + 10
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                posy = posy - 10

    pygame.display.flip()

pygame.quit()

I want the  to circle move somewhere depending on input.
However, the circle does nothing!

A: To move the circle, you have to redraw it every frame.
To do so, add the following to lines to your while loop (just before pygame.display.flip())
# fill the screen with black (otherwise, the circle will leave a trail)
screen.fill(black)
# redraw the circle
pygame.draw.circle(screen, colorcircle, (posx, posy), 50)


text:
Q: Should I use NEWID() as my primary key in the table? What datatype I should use for that column? I have read few posts and articles about NEWID() in MS SQL. Before I decide should I use this method or not I would like to get some information. My Single Page App has few tables. One of the tables should store unique key for each customer. I'm wondering if I should use NEWID() also how I should store that id in the table? I was looking over dataypes and there is unique-identifier type. Few articles mentioned that I will have potential problems with performance especially if I would be joining over 100k to some other tables. I will have this scenario where I would have to join these records to different tables. If anyone can provide some answers or suggestions that would be great. Thanks in advance!
Here is example of my Table:
   Column Name     Data Type           Allow Nulls
    hm_id           int                 Unchecked   // auto-increment id
    hm_studentID    uniqueidentifier    Unchecked   // primary key
    hm_firstName    varchar(50)         Checked
    hm_lastName     varchar(50)         Checked
    hm_dob          datetime            Checked


text:
Q: entity framework configuration addorupdate many-to-many seed records Defining the many-to-many relationship is not the problem.
I have a Rooms table (like rooms in a house) and each of these can have one or more colors from a Colors table.
Each has a List reference to the opposite table - see classes below.
In the Configuration class, Seed method, I am creating the various tables using AddOrUpdate.
            ctx.Rooms.AddOrUpdate(r => new { r.Name, r.HouseId },
            new Room
            {
                Name = "Kitchen",
                House = (from h in ctx.Houses where h.Address == "Littleton, MA" select h).First(),
                HouseId = (from h in ctx.Houses where h.Address == "Littleton, MA" select h.HouseId).First()
            });

(followed by ctx.SaveChanges of course)
And I can create many colors the same way:
            ctx.Colors.AddOrUpdate(c => new { c.ColorName },
            new Color
            {
                ColorName = "Green"
            });

With each room, I want to associate one or more of the colors.

(In SQL:)

Colors:

EF creates the table relating the two in the many-to-many relationship.

It seems like this should be easy, but I can't find a way and I have searched the web as well.
Thanks for your help.
:-)

A: Make sure you are initializing your list in the Room constructor
public class Room
{
   public Room()
   {
      Colors = new List<Color>();
   }
   // properties omitted
   public virtual IList<Color> Colors {get;set;}
}

Then just call
room.Colors.Add(Color color);

This is will add a color to your list.
This isn't the best solution as you should encapsulate your collections so that your aren't bypassing any business rules but EF 6 makes it difficult.
EF core makes it much easier.


text:
Q: Suggestion about category product relationship models I'm trying to get my mind going on a project to my college, but I can't seem to get it right. I'm can't fit my requirements in my models. Maybe someone that has worked on a store can help me out.
Let's say we have our so overused e-commerce model.
Category has many Products (I never understood where the SKU fits in here)
Ex:
    T-Shirts -> Summer 2010
                Happy New Year
Products can have many specifications based on what kind of product we are dealing with.
So Product has many specification that has many specification_items.
Ex:
    Summer 2010 P White
    Summer 2010 XXX Green
Edit: Or this can be called variantions, maybe its a better name.
Etc.. each of that is in fact a SKU, right? which has a stock quantity, price, weight etc.
How do I work this relationships out?
Thanks!
LiZarD

A: I have the same problem as the first commenter, however i'll try to translate your description into UML terms(there is object modeling tag assigned to this question).
Category is a class with one to many associatio towards Product class. Product class may include all the attributes you mentioned in SKU or maybe, if needed inherit them from separate SKU class or even realize SKU interface. Than you have one to one association between Product class and Specification class. Specification class will be composed of Specification_item class instances.
This pretty much covers what you have described.


text:
Q: lambda function in sorted dictionary list comprehension I have the following dictionary:
student_loan_portfolio = {
    'loan1': {'rate': .078, 'balance': 1000, 'payment': 100, 'prepayment': 0},
    'loan2': {'rate': .0645, 'balance': 10, 'payment': 5, 'prepayment': 0},
    'loan3': {'rate': .0871, 'balance': 250, 'payment': 60, 'prepayment': 0},
    'loan4': {'rate': .0842, 'balance': 200, 'payment': 37, 'prepayment': 0},
    'loan5': {'rate': .054, 'balance': 409, 'payment': 49, 'prepayment': 0},
    'loan6': {'rate': .055, 'balance': 350, 'payment': 50, 'prepayment': 0}
}

I would like to iterate through the containing dictionary (with keys loan1 through loan6) in order of the key containing the dictionary with the highest 'rate' value in its respective nested dictionary. That is, I would like to iterate in order of loan3, loan4, loan1, loan2, loan6, loan5
Thanks to @Jame Sharp the easiest way to do this that I know is:
for k,v in sorted(student_loan_portfolio.items(), key=lambda (k,v): v['rate'], reverse=True):

I am now reading about lambda and cannot really understand exactly how and why this works.
First, v['rate'] I believe is returning the value of those dictionary keys.  But its seems like it should be some kind of syntax error.  what is v['rate'] referencing and what is the logic behind the syntax?
On a related note, why, do we have to specify the inputs to the lambda function as a tuple?
And how are the following cases different?
#1

>>>f = lambda x,y,z:x + y + z
>>>f(1,2,3)

#6

>>>f = lambda (x,y,z): x + y + z
>>>f(1,2,3)

Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    f(1,2,3)
TypeError: <lambda>() takes exactly 1 argument (3 given)

Thank you for the clarification.

A: lambda (k,v): v['rate'] is a function that takes a single argument (a 2-tuple), and returns the 'rate' key of the second entry in the tuple. It is equivalent to lambda t: t[1]['rate']
lambda x,y,z:x + y + z is a function which takes 3 values and returns their sum.
lambda (x,y,z): x + y + z is a function that takes 1 value (a 3-tuple), and returns the sum of its elements.

A: The items() method on student_loan_portfolio.items() returns a list of key/value tuples.  So it returns something like [ ('loan1', dictOfLoan1), ('loan2', dictOfLoan2), ...].  The lambda accepts this tuple as an argument, and reads the "rate" item from the value dict (i.e., it reads dictOfLoan1['rate'], dictOfLoan2['rate'], etc.).
You could achieve the same effect by using, instead of the lambda you have, lambda item: item[1]['rate'].  item is a tuple (key, value), so item[1] is the value.
The difference between your two lambda examples is that the first one accepts three arguments, while the second accepts a single argument which is a three-element tuple.  The ability to define a function which accepts tuples as arguments but unpacks their contents into separate local variables was a quirk of Python that was removed in Python 3 (see PEP 3113).


text:
Q: How can I use Synergy when connected through different routers? I use synergy to control my laptop from my desktop when I have my laptop docked at my workstation.  Currently, I need to keep my laptop wired to the same router that my desktop is connected to in order to use synergy.  However, I will also take my laptop and work from other parts of the house.  I'd like to use just wireless on the laptop, so I don't have to switch connections to get up and move around.
My desktop has a wired connection to a router.  When I'm using wireless on my laptop, I'm connecting through a different router.  Is there a way to set up synergy to connect from the wireless router 192.168.17.* to the wired network 192.168.250.*?
I don't know much about network set up or terminology, so if I'm not including any pertinent details, please ask.

A: You don't need to change your subnets to match or anything fancy like that. You don't need a VPN either. What you do need is to establish traffic between those two end points.
The good news it that most routers have a facility for this. Two as a matter of fact. One is DMZ, the other port forwarding. Both basically amount to the same thing, but DMZ forwards everything instead of just a few ports. The idea is that you don't really need to talk to the ROUTER on ... say ... port 24800. Any traffic that comes to the router on that port can be passed along to a specific computer behind the router as if it was directed for it.
I assume your desktop is setup as the server with the laptop as the client. If this is not the case you'll need to reverse the procedure.
Synergy defaults to running on port 24800. If you changed this, be sure to adjust below.

*

*Open up the router that your desktop is connected to and add a port forwarding rule to forward port 24800 to your desktop.

*Change your laptop synergy config to connect to the desktop's router IP address as it's "server".

*Viola!

A: As long as the two machines can see each other, Synergy will work fine. From the command line, ping one machine from the other to test their connectivity (eg, on the laptop, type ifconfig (*nix)/ipconfig (win), find the ip address, and from the other, type ping  from the command line). This will probably not work the first time. At that point, you will need to configure your routers correctly- how to do this will depend on the specific routers. I would choose one to be the primary router for your setup, and let the other just be a fancy switch. If you have a cable/dsl modem, use the router closest to that to be the primary (in some cases, one of those two may be the modem itself).


text:
Q: Postgres 9.x Joining on Overlaping Date & Time Range I have several tables that have a TIMESTAMP WITH TIME ZONE column along with some additional information. I need to be able to join these tables such that all of the information on each row is "valid" as of a given date and time window (labeled begin and end in the desired result set).
My current approach:
Option #1

*

*Create a unique list of times.

*Convert each point in time into a window of time for the unique list (the "valid" window of time) and for each original table. [LEAD(...) OVER (...)]

*Join the original tables to the unique list of times.

Option #2

*

*Convert each point in time (TIMESTAMP WITH TIME ZONE) into a window of time for each table. [LEAD(...) OVER (...)]

*Join the tables where windows overlap.

*Return GREATEST(foo.start, bar.start) & LEAST(foo.stop, bar.stop) from each window to find true "valid" window.

For example:
Table: foo
  fooid  |  description  |       datetime
---------|---------------|-----------------------
    1    |   Varsion 1   |  2010-01-01 00:00:00
    2    |   Varsion 2   |  2010-07-01 00:00:00

Table: bar
  barid  |  fooid  |  description  |       datetime
---------|---------|---------------|-----------------------
    1    |    1    |   Varsion A   |  2010-01-01 00:00:00
    2    |    1    |   Varsion B   |  2010-02-01 00:00:00
    3    |    1    |   Varsion C   |  2010-03-01 00:00:00
    4    |    1    |   Varsion D   |  2010-04-01 00:00:00
    5    |    1    |   Varsion E   |  2010-05-01 00:00:00
    6    |    1    |   Varsion F   |  2010-06-01 00:00:00
    7    |    2    |   Varsion A   |  2010-07-01 00:00:00
    8    |    2    |   Varsion B   |  2010-08-01 00:00:00
    9    |    2    |   Varsion C   |  2010-09-01 00:00:00
    10   |    2    |   Varsion D   |  2010-10-01 00:00:00
    11   |    2    |   Varsion E   |  2010-11-01 00:00:00
    12   |    2    |   Varsion F   |  2010-12-01 00:00:00

Simplified Desired Results
        begin          |          end          |  fooid  |   foo_desc    |       foostart        |        foostop        |  barid  |   bar_desc   |       foostart        |        foostop
-----------------------|-----------------------|---------|---------------|-----------------------|-----------------------|---------|--------------|-----------------------|-----------------------
         ...           |         ...           |   ...   |      ...      |         ...           |         ...           |   ...   |     ...      |         ...           |         ...
  2010-05-01 00:00:00  |  2010-06-01 00:00:00  |    1    |   Varsion 1   |  2010-01-01 00:00:00  |  2010-07-01 00:00:00  |    5    |  Varsion E   |  2010-05-01 00:00:00  |  2010-06-01 00:00:00
  2010-06-01 00:00:00  |  2010-07-01 00:00:00  |    1    |   Varsion 1   |  2010-01-01 00:00:00  |  2010-07-01 00:00:00  |    6    |  Varsion F   |  2010-06-01 00:00:00  |        infinity
  2010-07-01 00:00:00  |  2010-08-01 00:00:00  |    2    |   Varsion 2   |  2010-07-01 00:00:00  |       infinity        |    7    |  Varsion A   |  2010-07-01 00:00:00  |  2010-08-01 00:00:00
  2010-08-01 00:00:00  |  2010-09-01 00:00:00  |    2    |   Varsion 2   |  2010-07-01 00:00:00  |       infinity        |    8    |  Varsion B   |  2010-08-01 00:00:00  |  2010-09-01 00:00:00
         ...           |         ...           |   ...   |      ...      |         ...           |         ...           |   ...   |     ...      |         ...           |         ...

My Question:
What is the best way to achieve this? I have created a fiddle showing two different solutions, and I would like to hear ideas on each as well as possible solutions not in the fiddle.
Update #1:
In the example, there are only two tables that need to be joined... however, in some cases I may need to join several tables 3, 4, or more.
Update #2:
With Option #1, my problem is that when I have large result sets I find that the initial sub query can be large and postgres can't use an index. This causes a large performance hit. On the other hand, I find it to be the most accurate as I can LEFT OUTER JOIN against it and get pertinent NULL data back.
With Option #2, the query planner is able to use the indexes on the TIMESTAMP WITH TIME ZONE columns; however, joining more then two tables becomes more complex in the FROM clause. I can move the (table1.start, table1.stop) OVERLAPS (table2.start, table2.stop) into the WHERE clause but then I loose the pertinent NULL data.
All of this makes me wonder if there is a better way...

A: *

*Use a default value for the window functions lead() and lag() instead of coalesce().

lead(datetime, 1, 'infinity') OVER (ORDER BY fooid, datetime) AS stop

instead of
COALESCE(LEAD(datetime) OVER (ORDER BY fooid, datetime), 'infinity'::TIMESTAMP) AS stop

*

*When you PARTITION BY fooid it is pointless to ORDER BY fooid.

PARTITION BY fooid ORDER BY datetime

instead of:
(PARTITION BY fooid ORDER BY fooid, datetime)

*

*You (or some tool) double-quoted every single identifier even though they are all legal without quotes. Makes the query a lot harder too read. Loose the noise.

Other than that: your question is too broad for stackoverflow and the description very hard to understand.
Consider: https://codereview.stackexchange.com/