Q: How to run android instrumental test using `androidx` and `navgation architecture`? I'm trying to write tests for an android app. Which has one Activity and two fragments (i.e FragmentOne and FragmentTwo) by clicking a button on FragmentOne it goes to the FragmentTwo. And I wrote the test for the same and I'm using androidx and navigation architecture. I have read this link and this link but didn't succeed.
Here is my current code-
ExampleInstrumentedTest
@RunWith(JUnit4::class)
class ExampleInstrumentedTest {

    @Test
    fun checkSecondFrag() {
        // Create a mock NavController
        val mockNavController = mock(NavController::class.java)

        // Create a graphical FragmentScenario for the OneFragment
        val oneFragmentScenario = launchFragmentInContainer<OneFragment>()

        // Set the NavController property on the fragment
        oneFragmentScenario.onFragment { fragment ->
            Navigation.setViewNavController(fragment.requireView(), mockNavController)
        }

        // Verify that performing a click prompts the correct Navigation action
        onView(ViewMatchers.withId(R.id.nextFragment)).perform(ViewActions.click())
        verify(mockNavController).navigate(R.id.action_oneFragment_to_twoFragment)
    }
}

Gradle(App)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.varun.navtesting"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Core library
    androidTestImplementation 'androidx.test:core:1.2.0'

    // AndroidJUnitRunner and JUnit Rules
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

    // Assertions
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.ext:truth:1.2.0'
    androidTestImplementation 'com.google.truth:truth:0.42'

    // Espresso dependencies
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'

    testImplementation 'junit:junit:4.12'

    implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0'
    implementation 'androidx.navigation:navigation-ui-ktx:2.0.0'

    // required if you want to use Mockito for unit tests
    testImplementation 'org.mockito:mockito-core:2.25.0'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'org.mockito:mockito-android:2.19.0'

    // Fragment test
    implementation 'androidx.fragment:fragment:1.2.0-alpha01'
    androidTestImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'

    implementation 'com.android.support:support-annotations:28.0.0'
}

Mainfiest
<?xml version="1.0" encoding="utf-8"?>
<manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.varun.navtesting">

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <uses-library android:name="android.test.runner"
                      android:required="false"/>

        <uses-library android:name="android.test.base"
                      android:required="false"/>
        <uses-library android:name="android.test.mock"
                      android:required="false"/>
    </application>
    <instrumentation android:targetPackage="com.varun.navtesting"
                     android:name="android.test.ExampleInstrumentedTest"/>
</manifest>

This line
<instrumentation
          android:targetPackage="com.varun.navtesting"
          android:name="android.test.ExampleInstrumentedTest"/>

is showing in red color in android studio.
Here is the
Logcat
2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: failed: checkSecondFrag(com.varun.navtesting.ExampleInstrumentedTest)
2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: ----- begin exception -----
2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.varun.navtesting/androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity (has extras) }
        at androidx.test.core.app.InstrumentationActivityInvoker.startActivity(InstrumentationActivityInvoker.java:344)
        at androidx.test.core.app.ActivityScenario.launchInternal(ActivityScenario.java:231)
        at androidx.test.core.app.ActivityScenario.launch(ActivityScenario.java:209)
        at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:299)
        at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
        at com.varun.navtesting.ExampleInstrumentedTest.checkSecondFrag(ExampleInstrumentedTest.kt:39)
        at java.lang.reflect.Method.invoke(Native Method)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: ----- end exception -----

Any help will be appriciated.

A: As per the Fragment testing page, you must use debugImplementation for the fragment-testing artifact:
debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'


Q: Day of week last year Im trying to calculate the date of the equivalent current day last year same week in standard SQL BigQuery.
For instance if the current date 2019-07-01 is a monday of week 27. I want to know the date of monday of week 27 last year (2018).
Current week would be select extract(isoweek from current_date())
but I don't know how to use this to calculate a date.
Expected output is 2018-07-02 if current date is 2019-07-01
The reason for this is that I want to compare current sales with same week and day of week as last year.
Any suggestions are appreciated.

A: Something like this should get you going...
with dates as (select * from unnest(generate_date_array('2018-01-01','2019-12-31', interval 1 day)) as cal_date),
       cal as (select cal_date, cast(format_date('%Y', cal_date) as int64) as year, cast(format_date('%V', cal_date) as int64) as week_num, format_date('%A', cal_date) as weekday_name from dates)
select c1.cal_date, c1.week_num, c1.weekday_name, c2.cal_date as previous_year_same_weekday
from cal c1
inner join cal c2
  on c1.year = c2.year+1 and c1.week_num = c2.week_num and c1.weekday_name = c2.weekday_name

The above query uses a week starting on a Monday, you may need to play around with the format_date() arguments as seen here to modify it for your needs.

A: This query returns no results, implying that SHIFT works. The function returns NULL if a year does not have the same number of weeks as its predecessor.
CREATE TEMP FUNCTION P_YEAR(y INT64) AS (
  MOD(CAST(y + FLOOR(y / 4.0) - FLOOR(y / 100.0) + FLOOR(y / 400.0) AS INT64), 7)
);

CREATE TEMP FUNCTION WEEKS_YEAR(y INT64) AS (
  52 + IF(P_YEAR(y) = 4 OR P_YEAR(y - 1) = 3, 1, 0)
);

CREATE TEMP FUNCTION SHIFT(d DATE) RETURNS DATE AS (
  CASE
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) != WEEKS_YEAR(EXTRACT(ISOYEAR FROM d) - 1)
      THEN null
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) = 52
      THEN DATE_SUB(d, INTERVAL 52 WEEK)
    ELSE d
  END
);

WITH dates AS (
SELECT d
FROM UNNEST(GENERATE_DATE_ARRAY('2000-12-31', '2020-12-31', INTERVAL 1 DAY)) AS d
)
SELECT
 d,
 EXTRACT(ISOWEEK FROM d) AS orig_iso_week,
 EXTRACT(ISOWEEK FROM SHIFT(d)) AS new_iso_week,
 SHIFT(d) AS new_d
FROM dates
WHERE EXTRACT(ISOWEEK FROM d) != EXTRACT(ISOWEEK FROM SHIFT(d))
  AND SHIFT(d) IS NOT NULL


Q: NSTextView Chinese/Unicode Characters I have a piece of text drawn in my cocoa app but I also need to draw it in a NSTextField and a NSTextView and look exactly the same, they all usually draw fine but if there are unicode or Chinese characters in the text then the NSTextView has large line spaces between the lines, it works perfectly in the nstextfield and when drawing normally.
I have tried every setting that I can find but none affect this issue, has anyone run into this issue before and know of a fix?
You can see the issue in a screenshot at http://cl.ly/3e0U1T2U2G2z341j3O3T

Here is my test code to show the issue
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(5, 50, 100, 100)];
[textField setStringValue:@"え？移転！？ TESTTestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"];
[textField setBordered:NO];
[textField setBezeled:NO];
[textField setAllowsEditingTextAttributes:YES];
[textField setDelegate:self];
[textField setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]];
[textField setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]];
[[window contentView] addSubview: textField];

NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(200, 50, 100, 100)];
[textView setString:@"え？移転！？ TEST TestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"];
[textView setDelegate:self];
[textView setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]];
[textView setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]];
[[textView layoutManager] setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility];
[[textView textContainer] setLineFragmentPadding:0.0];
[[window contentView] addSubview: textView];


Q: Reset my app on Fortrabbit I created app on Fortrabbit and purchased a service for my app. I pushed some my app (Laravel) and created my database. Now I want to reset my app. How can I do that? Could somebody help?

A: This is the script I use myself using laravel 4 to flush a complete DB in Fortrabbit
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$tables= DB::select('SHOW TABLES;');
foreach ($tables as $table) {
  foreach ($table as $key=>$tableName) {
    $tables= DB::statement("DROP TABLE $tableName;");
  }
}
DB::statement('SET FOREIGN_KEY_CHECKS=1');

A: This answer is from Fortrabbit Support:
sorry, it's not possible to reset the git repo (for now).
But you can push new code any time. You can also delete files when you ssh into you App.

If you want to start form the scratch, I suggest to spin up a new App.


Q: STL and UTF-8 file input/output. How to do it? I use wchar_t for internal strings and UTF-8 for storage in files. I need to use STL to input/output text to screen and also do it by using full Lithuanian charset.
It's all fine because I'm not forced to do the same for files, so the following example does the job just fine:#include <io.h>
#include <fcntl.h>
#include <iostream>
    _setmode (_fileno(stdout), _O_U16TEXT);
    wcout << L"AaĄąﬂ" << endl;
But I became curious and attempted to do the same with files with no success. Of course I could use formatted input/output, but that is... discouraged.    FILE* fp;
    _wfopen_s (&fp, L"utf-8_out_test.txt", L"w");
    _setmode (_fileno (fp), _O_U8TEXT);
    _fwprintf_p (fp, L"AaĄą\nﬂ");
    fclose (fp);
    _wfopen_s (&fp, L"utf-8_in_test.txt", L"r");
    _setmode (_fileno (fp), _O_U8TEXT);
    wchar_t text[256];
    fseek (fp, NULL, SEEK_SET);
    fwscanf (fp, L"%s", text);
    wcout << text << endl;
    fwscanf (fp, L"%s", text);
    wcout << text << endl;
    fclose (fp);This snippet works perfectly (although I am not sure how it handles malformed chars). So, is there any way to:

*

*get FILE* or integer file handle form a std::basic_*fstream?

*simulate _setmode () on it?

*extend std::basic_*fstream so it handles UTF-8 I/O?

Yes, I am studying at an university and this is somewhat related to my assignments, but I am trying to figure this out for myself. It won't influence my grade or anything like that.

A: Use std::codecvt_facet template to perform the conversion.
You may use standard std::codecvt_byname, or a non-standard codecvt_facet implementation.
#include <locale>
using namespace std;
typedef codecvt_facet<wchar_t, char, mbstate_t> Cvt;
locale utf8locale(locale(), new codecvt_byname<wchar_t, char, mbstate_t> ("en_US.UTF-8"));
wcout.pubimbue(utf8locale);
wcout << L"Hello, wide to multybyte world!" << endl;

Beware that on some platforms codecvt_byname can only emit conversion only for locales that are installed in the system.

A: Well, after some testing I figured out that FILE is accepted for _iobuf (in the w*fstream constructor). So, the following code does what I need.#include <iostream>
#include <fstream>
#include <io.h>
#include <fcntl.h>
//For writing
    FILE* fp;
    _wfopen_s (&fp, L"utf-8_out_test.txt", L"w");
    _setmode (_fileno (fp), _O_U8TEXT);
    wofstream fs (fp);
    fs << L"ąﬂ";
    fclose (fp);
//And reading
    FILE* fp;
    _wfopen_s (&fp, L"utf-8_in_test.txt", L"r");
    _setmode (_fileno (fp), _O_U8TEXT);
    wifstream fs (fp);
    wchar_t array[6];
    fs.getline (array, 5);
    wcout << array << endl;//For debug
    fclose (fp);This sample reads and writes legit UTF-8 files (without BOM) in Windows compiled with Visual Studio 2k8.

Can someone give any comments about portability? Improvements?

A: The easiest way would be to do the conversion to UTF-8 yourself before trying to output. You might get some inspiration from this question: UTF8 to/from wide char conversion in STL

A:
get FILE* or integer file handle form a std::basic_*fstream?

Answered elsewhere.

A: You can't make STL to directly work with UTF-8. The basic reason is that STL indirectly forbids multi-char characters. Each character has to be one char/wchar_t.
Microsoft actually breaks the standard with their UTF-16 encoding, so maybe you can get some inspiration there.


Q: Accessing a javascript variable outside its assigned method I want to access the javascript variable called locations outside of its assigned method.
Javascript code:
$(document).ready(function() {
    var locations;
    console.log('document ready');
    function initializeMap() {
      $.ajax({url: "getlocation.php",
            success: function(result){
              locations = $.parseJSON(result);
              alert(locations);
            }
      });

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

  }
  initializeMap();
});

How can I get the json parsed data passed to the locations variable so I can get data outside of its assigned method and into the loop?
Here is the finished code that solves my problem:
$(document).ready(function() {

    console.log('document ready');

    function initializeMap() {
    var locations;
    $.ajax({url: "getlocation.php",

            success: function(result){
            alert(result);
             locations = $.parseJSON(result);
            alert(locations);
             }
        });

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

  }
  initializeMap();
});

"Pass by Reference" and "Pass by Value" are two programming terms that describe how a method behaves when passing a variable into a method.

A: The function is called after excecuting the block of code, so the var location was assigned a value after it was adressed, this is why you saw undefined. There are two ways to fix this, 1) put the block of code inside the function or 2) call the function directly after initializing it !
General tip: do not use the ready function instead put the script just before body tag ends and avoid many problems !


Q: How to execute python script from another python script and send it's output in text file I have a script test.py which is used for server automation task and have other script server.py which list out all  server name.
server.py list all sevrer name in text.log file and this log file is used by test.py as a input.
I want one single script test.py to execute server.py from inside it and also redirect server.py script output to text.log file as well.
So far i have tried with execfile("server.py") >text.log in test.py which didn't worked.

A: Use subprocess.call with stdout argument:
import subprocess
import sys

with open('text.log', 'w') as f:
    subprocess.call([sys.executable, 'server.py'], stdout=f)
    # ADD stderr=subprocess.STDOUT  if you want also catch standard error output


Q: Angular universal-starter prerender with 4 levels nesting parameters For some reasons I want to create prerender build of my angular 5 project using https://github.com/angular/universal-starter instead of server-side rendering.
There are 4 levels in my routes like this:
example.com/category/:id/subcategory/:id/event/:id/ticket/:id

Also, There is a rest api backend which I'm using for fetching data for each section. For example, /category/1 is sport, /category/1/subcategory/1 is football and so on.
First question: How can I create a html file for each of these levels by using prerender.js and How should my static.paths.ts look like?
Second question: How can I set meta tags for each of these pages?
Third question: How should my app-routing.module look like? Should I use children approach?
I'm using Angular 5.0.0 and ngx-restangular 2.0.2
Thank you.

A: The setup for prerender and runtime server-side render is mostly similar, the only difference is one is static, the other dynamic. You will still configure everything Universal requires you to set up for it to work.
Before I go into your questions, I highly recommend you to follow this (step-by-step configurations)  and this (useful sections about Angular Universal pitfalls) guides to configure Angular Universal as it is one of the more comprehensive and up-to-date write ups that I've read.

First question: How can I create a html file for each of these levels by using prerender.js and How should my static.paths.ts look like?

Your static.path.ts should contain all routes that you want to prerender:
export const ROUTES = [
  '/',
  '/category/1/subcategory/1/event/1/ticket/1',
  '/category/1/subcategory/1/event/1/ticket/2',
  ...
];

Look tedious right? This is the trade off for having a static generated HTML as opposed to flexible run-time server-side rendering. You could and probably should write your own scripts to generate all routes available to your app (querying the database, generating all possible values, etc) to prerender all the pages that you want.

Second question: How can I set meta tags for each of these pages?

No different to how you set metatags or any Angular app, you can use the Title and Meta services that Angular provides.
Example:
constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private meta: Meta,
    private title: Title,
    private pageMetaService: PageMetaService
) { }

ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
        this.title.setTitle((`${this.article.title} - Tilt Report`));

        let metadata = [
            { name: 'title', content: 'Title' },
            { name: 'description', content: 'This is my description' },
            { property: 'og:title', content: 'og:Title' },
            { property: 'og:description', content: 'og:Description' },
            { property: 'og:url', content: 'http://www.example.com' },
        ];
        metadata.forEach((tag) => { this.meta.updateTag(tag) });
    };
}

Third question: How should my app-routing.module look like? Should I use children approach

You can choose to or not to use the 'children' approach, which I assume is lazy loading modules. As you configure Angular Universal, you should do certain setups to enable lazy loaded module to work server-side.


Q: Auth fail : Running maven plugin with JGit I am facing this issue while building a maven project
[INFO] Cloning git@bitbucket.org:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git:refs/tags/v5.0.0 into /Users/shubhamjain/bookkeeper/de/bookkeeper-ui-service/service/bookkeeper-api/bookkeeper-platform-hosted-ui-configuration-5.0.0
[ERROR] Failed to fetch bookkeeper-platform-hosted-ui-configuration API (5.0.0):
org.eclipse.jgit.api.errors.TransportException: git@bitbucket.org:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git: Auth fail
    at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:222)
----
----
Caused by: org.eclipse.jgit.errors.TransportException: git@bitbucket.org:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git: Auth fail
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession (JschConfigSessionFactory.java:162)
    at org.eclipse.jgit.transport.SshTransport.getSession (SshTransport.java:107)

Initially I had issues in access to the mentioned repository but then I got required permissions.
In the pom.xml
-----
-----
<plugin>
    <groupId>com.bookkeeper</groupId>
    <artifactId>bookkeeper-api-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>generate-hosted-ui-configuration-openapi-hook</id>
            <goals>
                <goal>generate-client</goal>
            </goals>
            <configuration>
                <apiName>bookkeeper-platform-hosted-ui-configuration</apiName>
                <apiVersion>5.0.0</apiVersion>
                <repositorySpecPath>bookkeeper-platform-hosted-ui-configuration/application-hosted-ui-configuration.yaml</repositorySpecPath>
                <gitUrlTemplate>git@bitbucket.org:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git</gitUrlTemplate>
                <openapiConfigurationOverrides>
                    <isExperimental>false</isExperimental>
                    <apiName>hosted-ui-configuration</apiName>
                </openapiConfigurationOverrides>
            </configuration>
        </execution>
    </executions>
</plugin>
-----
-----

What could be missing ? Thanks in advance.

A: Issue was Maven couldn't find ssh binary path on the environment
Setting GIT_SSH environment variable worked.
export GIT_SSH=${SSH_BINARY_PATH}

In my case
export GIT_SSH=/usr/bin/ssh


Q: Forgot Password showing 401 (Unauthorized) error I am trying to use forgot password function from strapi's Authentication documentation. When trying to send forgot password request to the api returning an 401 error. I am using vue js as frontend framework.
<template>
<form @submit.prevent="onForgetPassword">
   <label for="name">your email</label>
    <input type="email" class="from-input" placeholder="Enter Your Email..." v-model="email"/>
    <button type="submit" class="form-btn">reset password</button>
 </form>
</template>

data() {
    return {
      email: ""
    };
  },
  methods: {
    onForgetPassword() {
      axios
        .post("http://localhost:1337/auth/forgot-password", {
          email: this.email
        })
        .then(response => {
          // Handle success.
          console.log("Your user received an email");
        })
        .catch(error => {
          // Handle error.
          console.log("An error occurred:", error);
        });
    }
  }


Q: How to create several variables in a for loop increasing each one by 3 months in R? I need to create 12 variables starting from a certain date t1, increasing each one by 3 months.
Here's an example:
 t1           t2           t3
01-01-2000  01-04-2000   01-07-2000

I've tried something like this (with package lubridate):
for (i in 1:12) {
     month(AAA$t(i+1)) <- month(AAA$t(i)) + 3 }

But I'm obtaining:

Error in as.POSIXlt(x) : attempt to apply non-function

A: If you want to create a dataframe with t1 through t12 containing a range of dates:
t = seq(mdy("01/01/2000"), by = "3 months", length.out = 12) #this replaces the loop
names(t) <- paste0("t", c(1:12)) #this names your vector
data.frame(as.list(t)) #this creates the df


Q: HealthKit permissions not opening My app is not opening the HealthKit permissions screen where the user can allow access to Healthkit.
I receive the screen on my watch that my app "would like to access your health data". But the phone simply moves to the app launch screen then first page instead of bringing up the settings. There is no error. The app is coded below to request authorisations. Any ideas?
In the phone AppDelegate:
import UIKit
import WatchConnectivity
import HealthKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {

var window: UIWindow?
let healthStore = HKHealthStore()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    WatchSessionManager.sharedManager.startSession()

    return true
}

// authorization from watch
func applicationShouldRequestHealthAuthorization(application: UIApplication) {

    let healthStore = HKHealthStore()

    let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)

    let calorieQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)

    let dataTypesToRead = NSSet(objects: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!)
   healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead as! Set<HKObjectType>, completion: { (success, error) in
        if success {
        } else {
            print(error!.description)
        }
        })

    healthStore.handleAuthorizationForExtensionWithCompletion { success, error in

    }
}

A:     let healthKitStore:HKHealthStore = HKHealthStore()

        func authorizeHealthKit(completion: ((_ success:Bool, _ error:NSError?) -> Void)!)
        {
            //check app is running on iPhone not other devices(iPad does not have health app)
            if !HKHealthStore.isHealthDataAvailable()
            {
                let error = NSError(domain: "DomainName.HealthKitTest", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
                if completion != nil
                {
                    completion(false, error)
                }
                return;
            }

            healthKitStore.requestAuthorization(toShare: healthKitTypeToWrite() as? Set<HKSampleType>, read: nil) { (success, error) -> Void in

                if completion != nil
                {
                    print("Success: \(success)")
                    print("Error: \(error)")
                    completion?(success, error as NSError?)
                }
            }
        }

        func healthKitTypeToWrite() -> NSSet {
            let typesToWrite = NSSet(objects: HKQuantityType.quantityType(forIdentifier: .dietaryFatTotal),
                                              HKQuantityType.quantityType(forIdentifier: .dietaryFatSaturated),
                                              HKQuantityType.quantityType(forIdentifier: .dietaryCarbohydrates),
                                              HKQuantityType.quantityType(forIdentifier: .dietarySugar),
                                              HKQuantityType.quantityType(forIdentifier: .dietaryProtein),
                                              HKQuantityType.quantityType(forIdentifier: .dietarySodium))
            return typesToWrite
        }

And make sure you add 'NSHealthUpdateUsageDescription' to your info.plist and description saying why you need access to your app.
Hope this will help you.

A: Adding NSHealthUpdateUsageDescription in my info.plist fixed the issue for me.


Q: LLVM traverse the IR and look for all calls to @llvm.dbg.declare I am writing an LLVM pass that bookeeps the number of declared variables in an openCL Kernel. To do so, I need to enable debugging information and access the @llvm.dbg.declare info.
I iterate through all the instructions of a function and I use the isa<CallInst> template to identify the calling instructions.
Now there are two cases here, I can have either
call void @llvm.dbg.declare(metadata float addrspace(1)** %4, metadata !20, metadata !DIExpression()), !dbg !21
or
%6 = call i32 @get_global_id(i32 0), !dbg !25
How can I check that a CallInst has metadata associated with it, that is, it has @llvm.dbg.declare inside and then how do I extract the name of the variable declaration (I suspect via a getOperand() method ?


Q: proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong This is all in the form...
namespace Proxy_Pattern
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        double bankAmount = 1000.00;
    private void btnCheck_Click(object sender, EventArgs e)
    {
        double amount;
        amount = double.Parse(txtAmount.Text);

        CheckProxy cp =new CheckProxy();
        cp.CheckTransactionRequest(amount);
        lbltotal.Text = bankAmount.ToString();
    }

    private void btnCreditCard_Click(object sender, EventArgs e)
    {

    }
}

abstract class BankSubject
{

    public abstract void CreditTransactionRequest(double amount);
    public abstract void CheckTransactionRequest(double amount);
}

class RealBankSubject : BankSubject
{
    double bank;
    public RealBankSubject(double m_bacc)

    {
        bank = m_bacc;
    }

    public override void CreditTransactionRequest(double num)
    {
        bank -= num;
    }

    public override void CheckTransactionRequest(double num)
    {
        bank += num;
    }
}

Does not implement inherited abstract members.... but why?
    class CreditCardProxy : BankSubject
    {
        RealBankSubject realSubject;
        double amount;
    public CreditCardProxy (double m_bacc)

    {
        amount = m_bacc ;
    }

no suitable method to override?... how is this an error? I have a method right here?
    public override void CreditTransactionRequest()
    {

         if (realSubject == null)
        {
            realSubject = new RealBankSubject(amount);
        }

        realSubject.CreditTransactionRequest(amount);
    }

    public override void CheckTransactionRequest()
    {

    }
}

class CheckProxy : BankSubject
{
    RealBankSubject realSubject;
    double amount;

    public override void CreditTransactionRequest()
    {

    }

    public override void CheckTransactionRequest()
    {

       if (realSubject == null)
        {
            realSubject = new RealBankSubject(amount);
        }

        realSubject.CheckTransactionRequest(amount);
    }
}

}

A: CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match.

A: In your proxy, you are not specifying the amount as a parameter to the method:
public override void CreditTransactionRequest();

So it cannot override
public abstract void CreditTransactionRequest(double amount);

as the method signature doesn't not match


Q: How can I calculate the number of occurrences that is followed by a specific value? (add if statement) How can I calculate the number of occurrences that are ONLY followed by a specific value that is after E*? e.g:'EXXXX' ?
file.txt:
E2dd,Rv0761,Rv1408
2s32,Rv0761,Rv1862,Rv3086
6r87,Rv0761
Rv2fd90c,Rv1408
Esf62,Rv0761
Evsf62,Rv3086

i tried
input:
awk -F, '{map[$2]++} END { for (key in map) { print key, map[key] } }' file.txt

and add:
if [[ $line2 == `E*` ]];then

but not working, have syntax error
Expected Output:
total no of occurrences:
Rv0761: 2
Rv3086:1

Now i can only count all number of occurrences of the second value

A: if [[ $line2 == `E*` ]];then

This definitely is not legal GNU AWK if statement, consult If Statement to find what is allowed, though it is not required in this case as you might as follows, let file.txt content be
E2dd,Rv0761,Rv1408
2s32,Rv0761,Rv1862,Rv3086
6r87,Rv0761
Rv2fd90c,Rv1408
Esf62,Rv0761
Evsf62,Rv3086

then
awk 'BEGIN{FS=","}($1~/^E/){map[$2]++} END { for (key in map) { print key, map[key] } }' file.txt

gives output
Rv3086 1
Rv0761 2

Explanation: actions (enclosed in {...}) could be preceeded by pattern, which does restrict their execution to lines which does match pattern (in other words: condition does hold) in above example pattern is $1~/^E/ which means 1st column does starts with E.
(tested in gawk 4.2.1)

A: You are so close. You are only missing the REGEX to identify records beginning with 'E' and then a ":" concatenated on output to produce your desired results (not in sort-order). For example you can do:
awk -F, '/^E/{map[$2]++} END { for (key in map) { print key ":", map[key] } }' file.txt

Example Output
With your data in file.txt you would get:
Rv3086: 1
Rv0761: 2

If you need the output sorted in some way, just pipe the output of the awk command to sort with whatever option you need.


Q: Store pandastable dataframe into variable I currently have the below script that reads an imported csv file and displays as pandastable in the tkinter GUI.
As the file is imported its adds x2 additional columns self.table.addColumn("Current Status") and self.table.addColumn("Assign Technician").
How can I store the updated pandastable dataframe into a variable outside of class TestApp(tk.Frame): so that I can call other functions on the dataframe later in my code?
I have used the global variable before so that I can call a variable created from within a function outside of it later but not sure if thats what I need for this purpose.
import csv
import tkinter as tk
import tkinter.ttk as tkrttk
from tkinter import *
from tkinter import filedialog

import pandas as pd
from pandastable import Table, TableModel

root = tk.Tk()
root.geometry("2000x1000")
root.title('Workshop Manager')

def select_input_file():
    global input_file_path
    input_file_path = filedialog.askopenfilename(
    filetypes=(("CSV files", "*.csv"),))
    app = TestApp(root, input_file_path)
    app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50)

class TestApp(tk.Frame):
     def __init__(self, parent, input_file_path, editable = True, enable_menus = True):
        super().__init__(parent)
        self.table = Table(self, showtoolbar=False, showstatusbar=False)
        self.table.importCSV(input_file_path)
        self.table.show(input_file_path)
        self.table.addColumn('Current Status')
        self.table.addColumn('Assign Technician')
        self.table.autoResizeColumns()

root.mainloop()

A: You don't necessarily need a global variable here. You can directly access the member attributes of a class by using the object itself. So in this case, you can access the table attr of the class TestApp using app.table, which would look something like this,
def select_input_file():
    #...
    app = TestApp(root, input_file_path)
    app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50)

    df = app.table     # contains the updated table which can be passed to other functions
    newFunc( df )      # sample call

A: Avoid global to achieve this.
Currently, all your stateful variables exist in the module (file).  You can do the same for your table, outside of TestApp, and then pass it though __init__:
import csv
import tkinter as tk
import tkinter.ttk as tkrttk
from tkinter import *
from tkinter import filedialog

import pandas as pd
from pandastable import Table, TableModel

table = Table(showtoolbar=False, showstatusbar=False)

root = tk.Tk()
root.geometry("2000x1000")
root.title('Workshop Manager')

def select_input_file():
    global input_file_path
    input_file_path = filedialog.askopenfilename(
    filetypes=(("CSV files", "*.csv"),))
    app = TestApp(root, input_file_path)
    app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50)

class TestApp(tk.Frame):
     def __init__(self, parent, input_file_path, editable = True, enable_menus = True, table=table):
        super().__init__(parent)
        self.table = table
        self.table.importCSV(input_file_path)
        self.table.show(input_file_path)
        self.table.addColumn('Current Status')
        self.table.addColumn('Assign Technician')
        self.table.autoResizeColumns()

root.mainloop()

Your table object is now accessible to anything that can see the module namespace.  Here table is a mutable object, and all changes will be reflected to any function that accesses that object.
One suggestion: it is preferable to separate out your definitions (classes, functions) from your stateful bits that are created at run time.  This will greatly help clarify dependencies.  It is typical to use the line if __name__ == "__main__": at the bottom of the file to start the "script" part of your app, keeping all definitions above.  I've seen some packages (looking at you, Flask!) break this convention a bit, and it can cause headaches.
On that note, your select_input_file function has a few issues.  There's no good reason to create an app instance there.  A better option would be to make this a method in the App class for example.


Q: Created shell script for mac but I am getting an error when I run it run_QA.sh:
#!/bin/bash
set v

# -------------------------------------------------------
# 0 : Do NOT execute tests for the platform
# Anything else(e.g. 1)  Execute tests for the platform
# -------------------------------------------------------
export PROJECT_DIR=$CD
# TEST SUITE CAPBILITIES
# include or exclude test scenarios and/or story files (e.g. "-    skip,+checkout")
# -: means exclude
# +: means include
export PARAM="-skip,+Delta"

# MAVEN EXECUTION PROFILE
export SINGLETHREAD=singlethread
export PARALLEL=parallel
export MULTITHREAD=multithread

# set profile for building
export PROFILE=$SINGLETHREAD

# TEST RESULTS LOCATION
export TEST_RESULTS=TestResults

# =================================== DESKTOP   ========================================

# ---------- Delta (English) ----------

#:DESKTOP_DT_EN

# chrome, iexplorer, firefox
export BROWSER=firefox
export BRAND=TIMBERLAND
export TEST_ENV=NA
export LAN=EN
export PLATFORM=DESKTOP

export  SOURCE=${PROJECT_DIR}/src/test/resources/test_data/$BRAND/$TEST_ENV
export DESTINATION=${PROJECT_DIR}/src/test/resources

echo --- Creating Test Results folder...

#MD       $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS$/site/serenity

#echo --- Testing DESKTOP_DT_EN
export BASE_URL=http://qa.timberland.com/

export META_FILTER=$PARAM
echo --- calling run.sh file...

#$PROJECT_DIR
#echo "test"
#source=/Users/oletis/git/automation/TimberlandSuite
call %PROJECT_DIR%\run.sh

run.sh:
#!/bin/bash
#set v
echo --------------------------------------------------------------------------------------
echo Test Environment: $BRAND:$TEST_ENV_$PLATFORM_$LAN
echo $BRAND
echo $TEST_ENV
echo $PLATFORM
echo $LAN
echo $BASE_URL
echo --------------------------------------------------------------------------------------

#::echo Removing previous test results...
#::IF exist     $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS  DEL /S /Q /F  $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS |  echo > /dev/null
#::echo Done
#::echo

echo cd to project directory…
cd "${PROJECT_DIR}"
echo Done
echo .

set DEFAULTPROFILE=$SINGLETHREAD

echo thread

if [ $PROFILE=$MULTITHREAD ]
then
    export DEFAULTPROFILE=$MULTITHREAD
    echo here
elif
    [ $PROFILE=$SINGLETHREAD ]
then
    export DEFAULTPROFILE=$SINGLETHREAD
    echo hereo
elif
    [ $PROFILE=$PARALLEL ]
then
    export DEFAULTPROFILE=$PARALLEL
    echo sdsf
else
    echo ****************** Invalid profile configuration...
    echo ****************** Using default profile: "$DEFAULTPROFILE"
fi

echo bush

echo --- Running in $DEFAULTPROFILE mode ---

echo --- Deleting table files from $DESTINATION...
if [ -e $destionation/*.table ] DEL /Q /F $DESTINATION/*.table
    echo Done
else
    echo ****** No files deleted
    echo.
fi

echo Preparing test-data files...
# copy test_data to appropriate files
cp -f "$SOURCE/$LAN_General.table" "$DESTINATION/General.table"
echo Done
echo
# )

echo Cleaning...
.mvn clean
echo Done
echo.

echo Compiling...
.mvn compile
echo Done
echo.

echo Executing...
# the metafilter=-skip is configured in Serenity.properties file, so no need to pass it as a parameter
# . mvn verify -Dmetafilter="-skip" | echo >> log.txt
# to run with checkstyle and OMD use -DskipTests. To disable code compliance use -DskipCodeCompliance=true
# . mvn verify -DskipTests -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL"
# . mvn verify -Dmetafilter=$META_FILTER  -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dbrand="$BRAND"

if [ $PROFILE==$MULTITHREAD ]; then{
    #echo Starting in myversion
    .mvn integration-test -P $DEFAULTPROFILE -Dlan=$LAN -Dbrand=$BRAND -Dtestenv=$TEST_ENV -Dmetafilter=$META_FILTER  -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dplatform=$PLATFORM
    .mvn serenity:aggregate -P $DEFAULTPROFILE
}

elif [ $PROFILE==$SINGLETHREAD ];
then {
    echo SINGLETHREAD
    # .mvn verify -Dmetafilter=$META_FILTER  -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dbrand.name="$BRAND"

    if [ $PLATFORM=="BROWSERSTACK" ]; then {
        .mvn verify -P $DEFAULTPROFILE -DproxySet=true -DproxyHost=proxy4.wipro.com -DproxyPort=8080 -DproxyUser=PA257736 -DproxyPass=Fossil#in -Dlan=$LAN -Dbrand=$BRAND -Dmetafilter=$META_FILTER -Dplatform=$PLATFORM -Dbrowserstack.os=$BROWSERSTACK_OS -Dbrowserstack.os.version=$BROWSERSTACK_OS_VERSION -Dbrowserstack.browser=$BROWSER -Dbrowserstack.browser.version=$BROWSER_VERSION -Dbrowserstack.build=BROWSERSTACK_BUILD -Dbrowserstack.url=$BROWSERSTACK_URL -Dwebdriver.base.url="$BASE_URL"
    }
    else
        .mvn verify -P $DEFAULTPROFILE -Dlan=$LAN -Dbrand=$BRAND -Dtestenv=$TEST_ENV -Dmetafilter=$META_FILTER  -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dplatform=$PLATFORM
    fi
}

fi

echo Execution Done
echo

echo a

date=$(date +"%d%m%y")
echo $date
timestamp=$(date +"%H%M")
echo $timestamp
echo s

echo --- Copying test result to $TEST_RESULTS folder...
if ![ -e $PROJECT_DIR/$TEST_RESULTS MD $PROJECT_DIR/$TEST_RESULTS ]
    #XCP /E "$PROJECT_DIR/target/*.*" "$PROJECT_DIR/"$TEST_RESULTS"/"$BRAND"_"$TEST_ENV"_"$PLATFORM"_"$LAN"_"$TEST_RESULTS"/*.*"  | echo > /dev/null
    XCP /E "$PROJECT_DIR/target/*.*" "$PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$BROWSER_$LAN_$date_$timestamp/*.*"  | echo > /dev/null
fi
echo Done
echo

When I run it, command not found error is coming.

l-185002536:timberlandsuite imguser$ sh run_QA.sh
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
: command not found
--- Creating Test Results folder...
: command not found
: command not found
: command not found
--- calling run.sh file...
: command not found
run_QA.sh: line 63: call: command not found


Q: PostScript Path Combine I have just begun learning PostScript in order to produce graphics for LaTeX and I have no idea how to combine a path with itself so the stroke only affect the outer border of the drawn shape. My code is as follows:
/black { 0 0 0 1 setcmykcolor } def
/gold { 0.02 0.17 0.72 0.05 setcmykcolor } def
newpath
  % the center is 1/2w and 1/2h
  /cx { 1200 2.0 div } def % center-x
  /cy {  600 2.0 div } def % center-y
  /r  {  600 9.0 div
               4 mul
             2.0 div } def % star's radius
  cx r   0 cos mul add
  cy r   0 sin mul add moveto
  cx r 144 cos mul add
  cy r 144 sin mul add lineto
  cx r 288 cos mul add
  cy r 288 sin mul add lineto
  cx r  72 cos mul add
  cy r  72 sin mul add lineto
  cx r 216 cos mul add
  cy r 216 sin mul add lineto
closepath
gsave
gold fill
grestore
1 setlinewidth
black stroke

When the stroke is drawn, the lines crossing the shape are drawn. I would like to know if there is a way to only have the outer border of the shape stricken and not the inner lines. i would rather not have to calculate where the lines forming the star intersect, i.e. keep 5 lines instead of getting 10 smaller ones.
Note also, that I am learning PS as-is and am not wanting to use external programs (read Illustrator and the like). The purpose of this question is to built up my knowledge of PostScript.

A: Simplest would be to do the stroke first and then the fill. You may want to double your linewidth as doing this effectively cuts the lines in half.
%...
closepath
gsave
  2 setlinewidth
  black stroke
grestore
gold fill

A: PostScript is missing an anticlip operator, which should restrict painting to outside the current path. There is clip, which restricts painting to inside, but that doesn’t help with this problem.
As previously suggested, you could stroke at double linewidth, and then fill white, but if you want to paint this on top of something else, that strategy obscures whatever is below.
Or you could make the star a little bigger (I suspect, but haven’t checked, by currentlinewidth 2 5 sqrt 2 mul 5 div add sqrt mul 2 div), but that would only look right if 1 setlinejoin.


Q: Power BI dashboard with reports based on a push dataset do not alwasy update regularly I have written a little C# program which pushes data to a a streaming push dataset on Power BI Service.  I have a report with a couple of simple visuals (nothing fancy) which are in turn pinned to a dashboard.
About half the time I open the dashboard the Dashboard updates every few seconds.  But half the time it does not update at all and is laggy even if I push the refresh button.
Why is it inconsistent?  I know the data pusher is running as I can refresh the base report and see the new data points come in.
What is it that I am missing?
Thanks


Q: Can't insert a function to a element on onclick event (JS) I have problem with this code:
    var xButton = document.createElement("a");
    xButton.className = "cXButton";
    xButton.href = "#";
    xButton.onclick = "closePanel()";
    xButton.innerHTML = "X";

While "closePanel()" is a function I already wrote. I used Firebug and found out that "onclick" attribute doesn't appear in a tag.
I saw some threads where instead of the name of the function there is it's implementation (function closePanel(){...}). This is not what I'm looking for.
Any suggestions how to solve it?

A: Your have two problems in your original code:

*

*"closePanel()" is a string.

*closePanel() attempts to (or would if it wasn't a string) call the function and assign it's output to xButton.onclick
It should be this instead:
xButton.onClick = closePanel;

This will assign a reference to the function closePanel() to xButton.onClick, calling closePanel() when the xButton.onClick event is triggered.
Remember you can use this inside the declaration of closePanel() to reference the clicked element.


Q: What's the difference between @observable and @published in polymer.dart? In polymer.dart, if you want to expose a variable defined in controller to the view side, you define the variable with @observable and use double mustache to embed the variable. However, some docs and tutorials use @published to meet the same purpose. The official docs also uses both, so I don't think @published is legacy and deprecated way of defining variables.
So is there any difference between the two? And which one should I use in my code?

A: @published - is two way binding ( model to view and view to model)
Use case for @published is ,if your model property is also attribute in a tag.
Example : For a table-element you want to provide data from external source ,so you'll define attribute data,in this case data property should be @published .
<polymer-element name = "table-element" attributes ="structure data">
     <template>

                     {{col}}

              etc......
     </template>

</polymer-element>

@CustomTag("table-element")
class Table extends PolymerElement {

 @published  List<Map<String,String>>  structure; // table struture column name and value factory
 @published List<dynamic> data; // table data

@observable - is one way binding - ( model to view)
If you just want to pass data from  model to view use @observable
Example : To use above table element i have to provide data ,in this case data and structure will be observable in my table-test dart code.
<polymer-element name = "table-test">
 <template>
     <search-box data ="{{data}}" ></search-box>

 </template>

</polymer-element>

dart code
CustomTag("table-test")
class Test extends PolymerElement {

  @observable List<People> data = toObservable([new People("chandra"," kode"), new People("ravi","kiran"),new People("justin","mat")]);
  @observable List<Map<String,String>> structure = [{ "columnName" : "First Name", "fieldName" : "fname"},
                                                     {"columnName" : "Last Name", "fieldName" : "lname","cellFactory" :"html"}];
  Test.created():super.created();

Examples are taken from My Repo


Q: Can Kafka replication deploy on different machine? I'm running a project. My goal is to design a Kafka cluster. Preventing the condition that when one machine die, the data on that Kafka all disappear. I wonder if Kafka replication can be set on different machine in order to back-up?

A: In addition to setting a replication factor of 2 or 3 on your topics to ensure backup replica copies are eventually created, you should also publish messages with acks=all to ensure that acknowledgements indicate a guarantee that the data has been written to all the replicas. Otherwise with acks=1 you get an ack after only 1 copy is committed, and with acks=0 you get no acks at all so you would never know if your published messages ever made it into the Kafka commit log or not.
Also set unclean leader election parameter to false to ensure that only insync replicas can ever become the leader.

A: In Kafka you can define the replication factor for a topic and in this way each partition is replicated on more broker. One of them is a leader where producer and consumer connect for exchanging messages. The other will be followers which get copies of messages from the leader to be in sync. If the leader goes down, a new leader election starts between all in sync replicas. Kafka will support N-1 failed brokers where N is the replication factor.

A: yes , the replication factor defines this.


Q: Flutter Webrtc Build error on M1 android and ios I am trying to build a webrtc flutter app on my m1 macbook air. But I got different issues both on android and ios. Latest one ^0.8.2 has error on both then  ^0.7.0+hotfix.1 demo demo only works for android.
On iOS part 'Libyuv''s deployment target is set to 8.0 but min deployment target is 9.0 occurs. I set the deployment target above 10 then it still happens.
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCMediaStream.m:3:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.m:8:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.h:6:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.m:2:
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.h:1:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
    /Users/alperenbaskaya/AndroidStudioProjects/flutter-webrtc-demo/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 4.3, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Libyuv' from project 'Pods')
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.

After a workaround I updated libyuv deployment target but now I got following ios Error;
        objc[66512]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c10) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c2b8). One of the two will be used. Which one is undefined.
    objc[66512]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c60) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c308). One of the two will be used. Which one is undefined.
    ** BUILD FAILED **
Xcode's output:
↳
    warning: [CP] Unable to find matching .xcframework slice in 'ios-arm64_x86_64-simulator ios-arm64_armv7' for the current build architectures (arm64 x86_64 i386).
In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterRTCPeerConnection.m:2:
/Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
Could not build the application for the simulator.
Error launching application on iPhone 8 Plus.

On android side I got following;
Execution failed for task ':flutter_webrtc:compileDebugJavaWithJavac'.

A: For version ^0.8.2 following solutions work for me.
iOS
in ios/Podfile add following to end of file.
    post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |build_configuration|
      build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
    end
  end
end

Then clean your project and follow these steps as santoshakil mentioned santoshakilsanswer; (Those steps work for me if not follow all steps mentioned in link)
flutter clean && flutter pub get
cd ios
arch -x86_64 pod update
arch -x86_64 pod install
then at the top of your Pod file, paste this line platform :ios, '10.0'
right click on ios folder and open in xcode and then set all deployment target to 10

Android
Your android/app/build.gradle look like below as webrtcflutterdemo
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.cloudwebrtc.flutterwebrtcdemo"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

android/app/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cloudwebrtc.flutterwebrtcdemo">

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:label="flutter_webrtc_demo"
        android:icon="@mipmap/ic_launcher">
        <meta-data

EDIT
For Android side, i can not build for compilesdk and targetsdk 31. Temporary solution is downgrading compilesdk to 30. It is about jdk version on your mac device.


Q: Not able to click on the button using Selenium

<button class="css-obkt16-button" type="button">Download CSV</button>

I am trying to click on the highlighted button 'Download CSV'  having the above HTML code and save the csv file at some particular location, but I am not able to do so. The file is getting downloaded in Downloads folder.
My python code:
def scrape_data():
    DRIVER_PATH = r"C:\chrome\chromedriver.exe"
    driver = webdriver.Chrome(DRIVER_PATH)
    driver.get('Link to the dashboard')
    time.sleep(20)
    buttons = driver.find_element(By.XPATH,"//button/span[text()='Download CSV']")
    time.sleep(5)
    driver.execute_script("arguments[0].click();", buttons)
    driver.quit()

So please suggest a way to search via the button text) and save the file to a particular location??

A: To download the file on specific location you can try like blow.
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Data_Files\output_files"
  })
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)

A: *

*You should not use hardcoded sleeps like time.sleep(20).  WebDriverWait expected_conditions should be used instead.

*Adding a sleep between getting element and clicking it doesn't help in most cases.

*Clicking element with JavaScript should be never used until you really have no alternative.

*This should work in case the button you trying to click is inside the visible screen area and the locator is unique.

def scrape_data():
    DRIVER_PATH = r"C:\chrome\chromedriver.exe"
    driver = webdriver.Chrome(DRIVER_PATH)
    wait = WebDriverWait(driver, 30)
    driver.get('Link to the dashboard')
    wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Download CSV')]"))).click()


Q: How to instrumentation test activity going into background (STOPPED) then foreground (RESUMED)? I'm trying to do an instrumentation test to test behaviour when the app has been backgrounded then brought back to the foreground.
I thought it would be easy to use ActivityScenario.moveToState(), then it doesn't have an enum for the stopped state.
I was then thinking to use UiAutomator to press the home button, then somehow find the app icon and click on it again to launch it. It might be possible...but also very fragile.
Is there any easy and solid way to just bring the activity to stopped state, then bring it back to resumed?


Q: Voximplant – the callSIP method to call a phone number I want to use the Voximplant's callSIP method to call a phone number. Is it possible? How do I specify a number to call in the VoxEngine.callSIP() method?

A: When you call via callSIP, you make a call to a 3rd-party PBX. If the PBX allows calling to phone numbers, yes, you can do it, but you need to find out what format the PBX accepts.
In most cases, you can specify the number in the To field in the username part of the SIP address, for example: number_to_call@domain. Alternatively, you can call a phone number directly through Voximplant via the callPSTN() method.


Q: Is a graph library (eg NetworkX) the right solution for my Python problem? I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays.
However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application.
I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?)
We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation.
Here's an edited excerpt of the table. Columns are:
keyword   innode   outnode   component
acs 1 20 clear
default 1 100 clear
noota 20 30 clear
default 20 30 hst_ota
ota 20 30 hst_ota
acs 30 10000 clear
cos 30 11000 clear
sbc 10000 10199 clear
hrc 10000 10150 clear
wfc1 10000 10100 clear
default 10100 10101 clear
default 10101 10130 acs_wfc_im123
f606w 10130 10140 acs_f606w
f550m 10130 10140 acs_f550m
f555w 10130 10140 acs_f555w
default 10140 10300 clear
wfc1 10300 10310 acs_wfc_ebe_win12f
default 10310 10320 acs_wfc_ccd1

Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is:

*

*Start at node 1; "acs" is in the string, so go to node 20.

*None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30.

*"acs" is in the string, so go to node 10000.

*"wfc1" is in the string, so go to node 10100.

*Only one choice; go to node 10101.

*Only one choice, so pick up acs_wfc_im123 and go to node 10130.

*"f555w" is in the string, so pick up acs_f555w and go to node 10140.

*Only one choice, so go to node 10300.

*"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310.

*Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done.
Thus the final list of components is
hst_ota
acs_wfc_im123
acs_f555w
acs_wfc_ebe_win12f
acs_wfc_ccd1

I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities.
Updated to add examples of the other use cases:

*

*Given a string "acs", return ("hrc","wfc1") as possible legal next choices

*Given a string "acs, wfc1, foo", raise an exception due to an unused keyword

*Return all possible legal strings:

*

*cos

*acs, hrc

*acs, wfc1, f606w

*acs, wfc1, f550m

*acs, wfc1, f555w

*Validate that all nodes can be reached and that there are no loops.
I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two.

A: Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply).  Just write the table as a dict from node to tuple (default stuff, dict from word to specific stuff) where each stuff is a tuple (destination, word-to-add) (and use None for the special "word-to-add" clear).  So e.g.:
tab = {1: (100, None), {'acs': (20, None)}),
       20: ((30, 'hst_ota'), {'ota': (30, 'hst_ota'), 'noota': (30, None)}),
       30: ((None, None), {'acs': (10000,None), 'cos':(11000,None)}),
       etc etc

Now handling this table and an input comma-separated string is easy, thanks to set operations -- e.g.:
def f(icss):
  kws = set(icss.split(','))
  N = 1
  while N in tab:
    stuff, others = tab[N]
    found = kws & set(others)
    if found:
      # maybe error if len(found) > 1 ?
      stuff = others[found.pop()]
    N, word_to_add = stuff
    if word_to_add is not None:
      print word_to_add

A: Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For "all nodes can be reached and there are no loops", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should help even if there's some typo &c):
def add_descendants(someset, node):
  "auxiliary function: add all descendants of node to someset"
  stuff, others = tab[node]
  othernode, _ = stuff
  if othernode is not None:
    someset.add(othernode)
  for othernode, _ in others.values():
    if othernode is not None:
      someset.add(othernode)

def islegal():
  "Return bool, message (bool is True for OK tab, False if not OK)"
  # make set of all nodes ever mentioned in the table
  all_nodes = set()
  for node in tab:
    all_nodes.add(node)
    add_desendants(all_nodes, node)

  # check for loops and connectivity
  previously_seen = set()
  currently_seen = set([1])
  while currently_seen:
    node = currently_seen.pop()
    if node in previously_seen:
      return False, "loop involving node %s" % node
    previously_seen.add(node)
    add_descendants(currently_seen, node)

  unreachable = all_nodes - currently_seen
  if unreachable:
    return False, "%d unreachable nodes: %s" % (len(unreachable), unreachable)
  else:
    terminal = currently_seen - set(tab)
    if terminal:
      return True, "%d terminal nodes: %s" % (len(terminal), terminal)
    return True, "Everything hunky-dory"

For the "legal strings" you'll need some other code, but I can't write it for you because I have not yet understood what makes a string legal or otherwise...!


Q: toXmlString analog in XmlService? currently I am trying to rewrite my old script which uses Xml, the only trouble I have is that I cannot find in XmlService documentation any method similar to .toXmlString() from Xml.
This issue isn't critical since I was using it for debug purposes only, but if possible I'd like to keep this functionality.
tl;dr; The question is - how can I get raw xml string representation of element in new google's XmlService? I tried almost all methods of Element class and none of them produce this
Not sure if this specific info would be helpful or not - I am using google script to populate google sheet from rss feed.
Below is a simple code snippet I used for testing various XmlService methods. I left items[0].getValue() which I used to confirm that I have correct items array with real data (in log I see all values of subelements, concatenated into single string)
var stream = UrlFetchApp.fetch(url).getContentText()
var xmldata = XmlService.parse(stream);
Logger.log("XMLDATA fetch from " + url)

var channel = xmldata.getRootElement().getChild('channel')
var items = channel.getChildren("item")
Logger.log("Items count: " + items.length)
Logger.log(items[0].getValue())
return

To be precise, instead of getValue() I need some method that would convert inner xml object into it's string representation

A: Found an answer - Element class doesn't have this functionality anymore, it's been moved to global XmlService, like this:
XmlService.getCompactFormat().format(items[0])

produces what I need - one text line containing xml-formatted items[0] element


Q: Messenger on different windows issue I have a messenger on PHP/js, imported to all pages of the website. The messenger works through ajax, checking for new messages each 5 seconds.
Also I have desktop and sound notifications.
The problem is, if I opened multiple pages, and I'm currently on one of them, the reminder may come from another page, which is currently not active. However, inactive pages should notify only if the active page is not the same website.
Ideas?

A: Check for window focus:
var window_focus;

$(window).focus(function() {
    window_focus = true;
}).blur(function() {
    window_focus = false;
});

Check if location.host matches specified domain and window is focused:
if((location.host == "example.com")&&(window_focus == true))
{
    //window is focused and on specified domain for that website.
    //sounds, notifications, etc. here
}

Not completely sure if this is what you mean, but I hope it helps.


Q: Uploading images for inline content without an html editor I've got a client with a D7 site in which all content is created by a single employee who knows html and css, but never accesses the back end. Is there a way to let them upload images to embed in content (not a field) without installing an html editor? No styles are used or needed. The images are created just as they need to use them.

A: Have you already looked at the IMCE module?
IMCE is an image/file uploader and browser that supports personal directories and quota.
https://drupal.org/project/imce


Q: Xcode 11 Beta 3 animation no longer works I have just changed from Xcode 11 Beta 2, to Beta 3, and although I had to also change the navigationButton to navigationLink, all is ok, expect for the .animation()
Has anyone else seen this issue? Have they changed something? I was working just fine in Beta 2.
Thanks !!
import SwiftUI

struct BackGround : View {
  var body: some View {
    ZStack{
      Rectangle()
        .fill(Color.gray)
        .opacity(0.9)
        .cornerRadius(15.0)
        .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
        .blur(radius: 5)
        .padding(20)
        .animation(.basic())
    }

  }
}

A: I found that if I wrapped the content of a view in a VStack, perhaps other Stacks would also work, the view will animate in the previewer
Heres a quick example of a view that if wrapped in a VStack in the PreviewProvider previews the button will animate. But if the VStack is removed it will no longer animate. Try it out!
struct AnimatedButton : View {

  @State var isAnimating: Bool = false

  var body: some View {
    Button(action: {
      self.isAnimating.toggle()
    }) {
      Text("asdf")
    }.foregroundColor(Color.yellow)
      .padding()
      .background(Color(.Green))
      .cornerRadius(20)
      .animation(.spring())
      .scaleEffect(isAnimating ? 2.0 : 1.0)
  }
}

#if DEBUG
struct FunButton_Previews : PreviewProvider {
  static var previews: some View {
    VStack {
      AnimatedButton()
    }
  }
}
#endif


Q: Bag of Words encoding for Python with vocabulary I am trying to implement new columns into my ML model. A numeric column should be created if a specific word is found in the text of the scraped data. For this I created a dummy script for testing.
import pandas as pd

bagOfWords = ["cool", "place"]
wordsFound = ""

mystring = "This is a cool new place"
mystring = mystring.lower()

for word in bagOfWords:
    if word in mystring:
        wordsFound = wordsFound + word + " "

print(wordsFound)
pd.get_dummies(wordsFound)

The output is
    cool place
0   1

This means there is one sentence "0" and one entry of "cool place". This is not correct. Expectations would be like this:
    cool place
0   1    1

A: Found a different solution, as I cound not find any way forward. Its a simple direct hot encoding. For this I enter for every word I need a new column into the dataframe and create the encoding directly.
vocabulary = ["achtung", "suchen"]

for word in vocabulary:
    df2[word] = 0

    for index, row in df2.iterrows():
        if word in row["title"].lower():
            df2.set_value(index, word, 1)


Q: Selecting Individual rows using LIMIT I'm trying to figure out if there's anyway to use GROUP_CONCAT to select rows based on these parameters.

What I'm trying to to get the lowest time for every single style/zonegroup.
AKA:
Lowest Time for Style 0 ZoneGroup 0
Lowest Time for Style 0 ZoneGroup 1
Lowest Time for Style 0 ZoneGroup 2
Lowest Time for Style 1 ZoneGroup 0
Lowest Time for Style 2 ZoneGroup 0
...

I could have multiple queries sent through my plugin, but I would like to know if this could be firstly eliminated with a GROUP_CONCAT function, and if so -how.
Here's what I could do, but I'ld like to know if this could be converted into one line.
for (int i = 0; i < MAX_STYLES; i++) {
    for (int x = 0; x < MAX_ZONEGROUPS; x++) {
        Transaction.AddQuery("SELECT * FROM `t_records` WHERE mapname = 'de_dust2' AND style = i AND zonegroup = x ORDER BY time ASC LIMIT 1;");
    }
}

Thanks.

A: You don't need group_concat().  You want to filter records, so use WHERE . . . in this case with a correlated subquery:
select r.*
from t_records r
where r.mapname = 'de_dust2' and
      r.timestamp = (select min(r2.timestamp)
                     from t_records r2
                     where r2.mapname = r.mapname and
                           r2.style = r.style and
                           r2.zonegroup = r.zonegroup
                    );


Q: Generic Try[T] function I want to refactor some common error handling logic in a generic Try[T] handler, similar to this:
def handler[T](t: Try[T], successFunc: T => Unit) = {

  t.map {
    case Success(res) => { // type mismatch required T, found Any (in successFunc line)
    //case Success(res: T) => { // Type abstract type pattern T is unchecked since it is eliminated by erasure
      successFunc(res)
    }
    case Failure(e: CustomException) => {
      // custom actions
    }
    case Failure(e) => {
      // custom actions
    }
  }
}

Seems I can't match against the type T because of type erasure. But I can't pass an Any to successFunc.
How can I implement this function?

A: Mapping on a try applies a function to the value held by a success of that try, what you have there is not a Success or a Failure, it's a T, what you want is a match:
def handler[T](t: Try[T], successFunc: T => Unit) = {
  t match {
    case Success(res) =>
      successFunc(res)
    case Failure(e: FileNotFoundException) =>
    case Failure(e) =>
  }
}

The usage in your case of map would be:
t.map(someT => successFunc(someT))


Q: Integrated Windows Authentication with IIS, Firefox and SQL Server I have a web site running on IIS on my localhost. This web site has directory security set to only allow Integrated Windows Authentication. It is part of an intranet and needs to authenticate by our domain accounts.
I then connect to SQL Server with Integrated Security = SSPI in the connection string.
This works fine with Microsoft Internet Explorer, it automatically authenticates me as I am logged into the domain, and I can see that the logon_user is my domain account, and the SQL Server connection string works just fine.
However, when I log-in using Firefox, things are different.
Firstly, I am prompted to authenticate, which is fine and correct as Firefox is not configured to trust the localhost enough to automatically send credentials (and indeed I am aware of how to introduce this trust already, this is not the problem). I then login, which again is fine, provided I enter the domain account details everything is fine. Indeed, a debug statement or two show that logon_user is still my domain account and everything is fine.
However, when I come to connect to SQL Server (which is running on a remote server box, to which my domain account has full sysadmin privileges), I get the following error:
Microsoft OLE DB Provider for SQL Server (0x80040E4D)
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.

This indicates to me that something is wrong in the authentication stack, for some reason, IIS is not running as the authenticated account when I authenticate using windows authentication from firefox.
This also works fine when using Google Chrome.
Any suggestions?

A: *

*Open Firefox

*In the address bar type: about:config

*Firefox3.x and later requires you to agree that you will proceed with caution.

*After the config page loads, in the filter box type: network.automatic

*Modify network.automatic-ntlm-auth.trusted-uris by double clicking the row and enter http://www.replacewithyoursite.com

*Multiple sites can be added by comma delimiting them such as http://www.replacewithyoursite.com, http://www.replacewithyourintranetsite.com
I also use IEtab add-on for the intranet sites

A: IIS needs to pass a Kerberos ticket to SQL Server for this scenario to work. MSIE is picking up the workstation session ticket, whereas Firefox is negotiating its own authentication (and not Kerberos).
Check out e.g. this dense blog post as a starting point for understanding what is needed. I'm not sure if FF support MS-Kerberos.
Be aware that even getting MSIE->IIS->SQL Server authentication can be tricky if you have the wrong versions or trust configuration...

A: AS noted by Pontus Gagge, IIS needs to pass a Kerberos ticket to SQL Server. That was enough to tip my Google-fu in the right direction.
Firefox supports Kerberos, but, you have to tell it which domains it trusts to send the Kerberos tokens too.

*

*Open Firefox

*In the address bar type: about:config

*Firefox3.x and later requires you to agree that you will proceed with caution.

*After the config page loads, in the filter box type: network.negotiate-auth

*Modify network.negotiate-auth.trusted-uris by double clicking the row and enter yourdomain.com

*Multiple domains can be added by comma delimiting them such as yourdomain.com, yourotherdomain.com

Note: This is not the same as gbn's solution which just configures firefox to not prompt you to enter domain account details on login.
Also, if you have already tried to authenticate through the stack in your current Firefox session, you will need to restart Firefox for this to work.


Q: Is it possible to use the Twitter API to get replies older than 7 days? I've seen this question, but the answers are a bit of a mess: outdated, focused on various libraries' capabilities, and/or not clear about whether they apply to old tweets.
I'm trying to look up replies to historical tweets (months or years old). I want to know if it's theoretically possible to use the Twitter API to directly or indirectly find those replies. At first glance, the conversation_id introduced in v2 seems intended for things like this, but the only way I've found to use it is in the recent search endpoint, which only goes back 7 days. This is nearly useless for me.
The closest I've got is to look up tweets from the original author's timeline and look for ones in the same conversation. But that's limited to their most recent 3,200 tweets, and won't find replies from other people.
FYI, I'm only interested in the endpoints available to the general public for free, not the Academic or Enterprise ones. I think this is called the Standard product track (Basic access level).


Q: Best way to write onClick multiline function? I have this onClick function that shows the details of the user and then sets another state back to true. Would it be better to declare this function outside of the return as it is multiline? and if so how should I write it?
 <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button>

Here the rest of my code as reference:
const UserList = () => {

  const [users, setUsers] = useState([])
  const [selectedUser, setSelectedUser] = useState()
  const [showUser, setShowUser] = useState(true)

  const onHandleClick = () => setShowUser(false)

  useEffect(() => {
    fetch(URL)
      .then(res => res.json())
      .then(json => setUsers(json));
  }, [])

  return (
    <>

Contact list

      <Container>

          {users.map(user => (

              <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button>

          ))}

        {selectedUser && (
          <>
            {showUser ?
            <UserDetail
              name={selectedUser.name}
              username={selectedUser.username}
              email={selectedUser.email}
              address={selectedUser.address.street}
              phone={selectedUser.phone}
              company={selectedUser.company.name}
              onClick={onHandleClick}
            />
            : false}
          </>
        )}
      </Container>
    </>
  )
}

A: If you want to declare function outside of the JSX then you can do as:
<Button onClick={() => changeUser(user)}>{user.name}</Button>

Declaration of function
function changeUser(user) {
  setSelectedUser(user);
  setShowUser(true);
}


Q: Issue with retrieving some values out of my Database <?php
include 'session.php';
?>

<link href="css/adminOpmaak.css" rel="stylesheet" type="text/css"/>
<?php
        mysql_connect("localhost", "admin", "") or die(mysql_error());
        mysql_select_db("test") or die(mysql_error());
?>

<form action="Login.php" method="POST">

<input type="text" align="center" name="Account"  value="<?php echo isset     ($_POST['Account'])?$_POST['Account']:"";?>"/>

<input type="text" align="center" name="Password" value="<?php echo isset    ($_POST['Password'])?$_POST['Password']:"";?>" />

<input type="submit" name="Login" value="Login"/>

<?php
if(isset ($_POST ['Login']))
{
    $querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';";
    $result = mysql_query($querystring);

    mysql_query($querystring)or die (mysql_error());

    if (empty($_POST['Account']) || empty($_POST['Password']))
    {
        echo "niet alles is ingevoerd";

    }
    elseif (mysql_num_rows($result) == 1)
    {
        $user = mysql_fetch_assoc($result);
    }
    else
    {
        echo "dit account bestaat niet";
    }

    if(md5($_POST['Password']) != $user['Password'])
    {
        echo "wachtwoord is niet correct";?>
 <?php
        echo "Het account is:".$user['Account'];?>
 <?php
        echo "het wachtwoord is: ".$user['Password'];?>
 <?php
        echo mysql_fetch_assoc($result);
    }
}
?>
</form>

It's kinda strange since he does recognize the $user['Account'];
and he doesnt recognize the password version.
My database has the right values. This is what he echo's:
wachtwoord is niet correct
Het account is:Probeersel
het wachtwoord is:

So I dont know why he DOES recognize the account but he doesn't recognize wachtwoord. Why is that?

A: There are a few problems.
First, your mysql statement is wrong.
Change this:
$querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';";

To this:
$querystring ="SELECT * FROM Admins WHERE Account ='" .$_POST['Account']. "'";

Next, for one test, echo out the account name and password that you get from the db query, just so you can make sure you are getting what you expect (perhaps the capitalization is wrong for the field name or something like that).
$user = mysql_fetch_assoc($result);
echo 'Got this username: ' .$user['Account']. '
';
echo 'Got this password: ' .$user['Password']. '
';

Once you have confidence that you are getting the correct data, then you can finish your script.

This:
if(md5($_POST['Password']) != $user['Password'])
{
    echo "wachtwoord is niet correct";?>
 <?php
    echo "Het account is:".$user['Account'];?>
 <?php
    echo "het wachtwoord is: ".$user['Password'];?>
 <?php
    echo mysql_fetch_assoc($result);
}

Can be re-written as:
if(md5($_POST['Password']) != $user['Password'])
{
    echo "wachtwoord is niet correct
";
    echo "Het account is: " .$user['Account']. "
";
    echo "het wachtwoord is: " .$user['Password']. "
";
}


Q: Delete the entire row of selected item in listbox, VBA Excel I'm trying to delete the entire row of the item(s) selected in my listbox, but the problem is the code deletes the very first row. Here is the code.
Private Sub Mature_Click()

Dim I As Long

With ListBox1
  For I = .ListCount - 1 To 0 Step -1
    If .Selected(I) Then
       .RemoveItem I
       Sheets("Sheet1").Rows(I + 2).EntireRow.Delete
    End If
  Next I
End With

End Sub


Q: Why is TryParse in C#7 syntax (empty out parameter) emitting a warning if you compile it? In C#7, you are allowed to do
            if (int.TryParse("123", out int result))
                Console.WriteLine($"Parsed: {result}");

or - if you don't use the result and just want to check if the parsing succeeds, discard the out value:
           if (int.TryParse("123", out _))
                Console.WriteLine("Syntax OK");

That works fine usually, but in Visual Studio 2017 the second example, where the out parameter is empty, generates the warning

Warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames.CSharpSimplifyTypeNamesDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'.

The Visual Studio Versions where I could verify that it occurs is

Visual Studio Enterprise 2017 Version 15.1 (26403.7) Release
Visual Studio Enterprise 2017 Version 15.2 (26430.4) Release

Is this a bug, or is the usage of int.TryParse("123", out _) not officially supported? I could not find any hint so far.

For completeness, here's the code of the console application showing the issue:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            if (int.TryParse("123", out _))
                Console.WriteLine("Syntax OK");
        }
    }
}

A: I submitted a bug request (request #19180) to the development team, and they confirmed it is a bug.
You can see the entire status here at GitHub dotnet/roslyn.

Pilchie  commented 16 hours ago
  I can repro that in 15.2, but not 15.3. Moving to compiler based on the stack, >Abut I'm pretty sure this is a dupe. @jcouv?
jcouv  commented 16 hours ago
  Yes, this is a duplicate (of #17229 and possibly another one too).
  It was fixed in dev15.3 (#17544) and we were unfortunately unable to pull the >fix into dev15.2.
  Thanks @Matt11 for filing the issue and sorry for the bug.

It seems to be already fixed and will be - as far as I understood - available in the next update. But there is no announced date when it will be included by Microsoft, so I submitted an issue through "Send Feedback/Report a Problem" in Visual Studio 2017.
Notes:

*

*The issue is not limited to TryParse. I verified that it also occurs if you write your own function, i.e. the following sample shows the warning AD0001 as well:
static void Main(string[] args)
{
        bool myOutDemo(string str, out int result)
        {
                result = (str??"").Length;
                return result > 0;
        }
        // discard out parameter
        if (myOutDemo("123", out _)) Console.WriteLine("String not empty");
}

*I noticed that there is now a VS Version 15.3 preview available, which should contain the fix mentioned in the GitHub comments. Check out the following link: Visual Studio 2017 Version 15.3 Preview. After installing it, I verified the issue again and can confirm it is fixed there.

Thanks to all who participated in the discussion above! (question comments)


Q: How to create dynamic table in sqlite-3 using python when user give your email address Sql = "CREATE TABLE IF NOT EXISTS ℅s (℅s text, ℅s text)" ℅ (Username, "first", " Second ")
con. execute(sql)
#Error- sqlite3.OperationError:near "@gmail": syntax error
#help me sir

A: Though I must admit that it seems strange to me to create tables with data-depending names, but technically the solution is to put the table name in square parentheses. This is the way to escape special characters like '@'.
Something like this:
Sql = "CREATE TABLE IF NOT EXISTS [℅s] (℅s text, ℅s text)" ℅ (Username, "first", " Second ")


Q: Javascript: Not picking up my "src" <input class="textBox" id="userWebsite" type="text" />
<input type="button" id="button" value="Store" onclick="submit();"/>

<!-- Storage START -->
<select id="webLinks">
  <option id="webPageOne">Web Page One</option>
  <option id="webPageTwo">http://www.example.com</option>
  <option id="webPageThree">http://www.example.com</option>
  <option id="webPageFour">http://www.example.com</option>
</select>
<input type="button" id="button" value="Goto" onclick="goto();"/>
<!-- Storage END -->

<iframe src="http://www.freedom.tm/dashboard" id="iframe"></iframe>
<!-- Default Promotor END -->

<script>
    var userWebsite = document.getElementById('userWebsite');
    function submit() {
        document.getElementById("webPageOne").innerHTML = userWebsite.value;
    }

    var webPageOne = document.getElementById('webPageOne');

    function goto() {
        document.getElementById("iframe").src = document.getElementsByTagName("option");
    }
</script>

Ok, currently the problem is the end part
    function goto() {
        document.getElementById("iframe").src = document.getElementsByTagName("option");
    }

I was wondering why it isn't picking up the option that's selected. For example, if webpage two is selected, Why it doesn't select the website selected and change the source to what ever website two is set as?

A: try:
function goto() {
    document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text;
}

A: you have a js error, edit following function
function goto() {
    document.getElementById("iframe").src = document.getElementsByTagName("option")[1].value;
}

or common approach
 function goto() {
        document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text;
    }


Q: Add observable to existing Subject I have an observable (Angular Subject) called event$. When screens are loaded I want to add DOM controls as emitters to this observable. The observable will already have subscribers. I'm achieving this by subscribing to an observable based on the control with the existing event$ as below. (Subscription management details omitted for clarity.)
shared service:
private _event$: Subject<Event> = new Subject();
public addEventEmitter(event: Observable<Event>) {
  event.subscribe(this._event$);
}

component code:
@ViewChild('leftSide', { read: ElementRef }) leftSide: ElementRef;

const leftClick$: Observable<Event> = fromEvent(this.leftSide.nativeElement, 'click');
this.comms.addEventEmitter(leftClick$.pipe(mapTo(anEvent)));

I'm having, possibly unrelated, issues with an ion-toggle control intermittently showing the incorrect state. Is this a reasonable method of merging an observable with one that already has subscribers?  Would I be better off having an onChange or click event call event$.next()? To my mind combining the observables is more reactive whereas calling the next method on the event$ for each control interaction is very imperative.

A: Disregarding the simplicity and the elegance of being able to write event.subscribe(this._event$);, this is not a good idea. From what I noticed by doing this, is that whenever your _event$ completes, the event will also complete, which I don't think is the behavior you want. You're better off emitting the value manually like this:
event.subscribe(e => this._event$.next(e));

And even though you said you omitted the subscription management details, I feel it's important to mention again that you need to manage this subscription in order to avoid memory leaks.