Q: My Flutter App is Not Working on Android 11 But Working fine in emulator as well as android 8 || (OS Error: Operation not permitted, errno = 1) Here is My Code
import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.dart';
import 'package:sweld/globals.dart';
import 'package:geolocator/geolocator.dart';

class WeldSetup extends StatelessWidget {
  WeldSetup({Key? key}) : super(key: key);
  final pageNum = 211;

  @override
  Widget build(BuildContext context) {
    final _ssc = ScreenshotController();
    return Scaffold(
      appBar: AppBar(
        title: Text("Weld Setup"),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Icon(Icons.railway_alert_rounded),
          ),
        ],
      ),
      body: Screenshot(controller: _ssc, child: WsLocation()),
      persistentFooterButtons: [
        ElevatedButton(
            onPressed: () async {
              Globals.ss211 = await _ssc.captureAndSave(Globals.appDir,
                  fileName: "ss211.png",
                  pixelRatio: MediaQuery.of(context).devicePixelRatio,
                  delay: Duration(milliseconds: 100));

              Navigator.pushNamed(context, "/212");
            },
            child: Text("Next"))
      ],
      extendBody: true,
    );
  }
}

class WsLocation extends StatefulWidget {
  const WsLocation({Key? key}) : super(key: key);

  @override
  _WsLocationState createState() => _WsLocationState();
}

class _WsLocationState extends State<WsLocation> {
  late Position curPos;
  var longitute = Globals.longitude;
  var latitude = Globals.latitude;
  TimeOfDay sTime = TimeOfDay(hour: 00, minute: 00);
  TimeOfDay eTime = TimeOfDay(hour: 00, minute: 00);

  Widget selectTime(time) {
    if (time == TimeOfDay(hour: 00, minute: 00)) {
      return Text("Select Time");
    } else {
      if (time == sTime) {
        return Text("${Globals.stime}");
      } else {
        return Text("${Globals.etime}");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.all(15),
        color: Colors.white,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "LOCATION",
                  textScaleFactor: 2,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            Divider(
              thickness: 2,
              height: 50,
            ),
            Container(
              child: Form(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Flexible(
                          child: TextFormField(
                            initialValue: Globals.longitude,
                            decoration: InputDecoration(
                              labelText: "Longitude",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5),
                                borderSide: BorderSide(
                                  color: Colors.black,
                                  style: BorderStyle.solid,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                Globals.longitude = val;
                              });
                            },
                          ),
                        ),
                        Divider(
                          indent: 5,
                        ),
                        Flexible(
                          child: TextFormField(
                            initialValue: Globals.latitude,
                            decoration: InputDecoration(
                              labelText: "Latitude",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5),
                                borderSide: BorderSide(
                                  color: Colors.black,
                                  style: BorderStyle.solid,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                Globals.latitude = val;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.section,
                      decoration: InputDecoration(
                        labelText: "Section",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        setState(() {
                          Globals.section = val;
                        });
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.division,
                      decoration: InputDecoration(
                        labelText: "Division",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        Globals.division = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.distance,
                      decoration: InputDecoration(
                        labelText: "Distance",
                        hintText: "In kilometers(km)",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        Globals.distance = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    DropdownButtonFormField<String>(
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      hint: Text("Line"),
                      isExpanded: true,
                      items: <String>['Single', 'Up-Line', 'Down-Line']
                          .map((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                      onChanged: (val) {
                        Globals.line = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Flexible(
                            child: Row(
                              children: [
                                Divider(
                                  indent: 15,
                                  endIndent: 5,
                                ),
                                Text("Start Time "),
                                TextButton(
                                  onPressed: () {
                                    showTimePicker(
                                            context: context,
                                            initialTime: sTime)
                                        .then((value) {
                                      if (value != null) {
                                        setState(() {
                                          sTime = value;
                                          Globals.stime = value.format(context);
                                        });
                                      }
                                    });
                                  },
                                  child: Globals.stime == null
                                      ? selectTime(sTime)
                                      : Text(" ${Globals.stime} "),
                                ),
                              ],
                            ),
                          ),
                          // Divider(
                          //   thickness: 0,
                          //   indent: 5,
                          // ),
                          Flexible(
                            child: Row(
                              children: [
                                Divider(
                                  indent: 10,
                                ),
                                Text("End Time "),
                                TextButton(
                                  onPressed: () {
                                    showTimePicker(
                                            context: context,
                                            initialTime: eTime)
                                        .then((value) {
                                      if (value != null) {
                                        setState(() {
                                          eTime = value;
                                          Globals.etime = value.format(context);
                                        });
                                      }
                                    });
                                  },
                                  child: Globals.etime == null
                                      ? selectTime(eTime)
                                      : Text(" ${Globals.etime} "),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Divider(
              height: 50,
            ),
          ],
        ),
      ),
    );
  }
}

Here user is able to Input in Text fields, But when He presses Next He is not able to goto next Page. Moreover When I run it in emulator then it is working Totally Fine !.
And Yes its important to take screenshot of everypage therefore, I cannot Exclude it.
And sometime it returns Null, It Might be a problem But I dont know How to deal with it or What should I do Next.
Any Suggestions Please
Here is My Build Gradle File
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 plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.sweld"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    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
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

UpDate

I just Recieved the error, It is
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Creation failed, path = 'storage/emulated/0/sweld' (OS Error: Operation not permitted, errno = 1)
E/flutter ( 7337): #0      _Directory.create.<anonymous closure> (dart:io/directory_impl.dart:117:11)
E/flutter ( 7337): #1      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 7337): #2      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 7337): <asynchronous suspension>

So Please Tell me what SHow I DO ??

A: try to change  minSdkVersion 16 to  minSdkVersion 21

A: I solved this issue My getting Some additional Permissions.
MANAGE_EXTERNAL_STORAGE and INTERNET Permission

in Android Manifest File


Q: regex get text from next line I'm looking for a way to find text on the next line of a certain string using regex.

Say I have the following text:
Note:
Just some text on this line

Some more text here.

I just want to get the text 'Just some text on this line'.
I don't know exactly what the other text will be, so I can't search between 'Note:' and 'Some more text here'.
All I know is that the text I want is on the next line from 'Note:'.
How could I do this?
Cheers,
CJ

A: I'd go line by line down your string, and when a regex matches, then take the next line
string str;
// if you're not reading from a file, String.Split('\n'), can help you
using (StreamReader sr = new StreamReader("doc.txt"))
{
    while ((str = sr.ReadLine()) != null)
    {
        if (str.Trim() == "Note:") // you may also use a regex here if applicable
        {
            str = sr.ReadLine();
            break;
        }
    }
}

Console.WriteLine(str);

A: This can be done with a multiline regex, but are you sure you want to? It sounds more like a case for line-by-line processing.
The Regex would be something like:
new Regex(@"Note:$^(?<capture>.*)$", RegexOptions.MultiLine);

although you might need to make that first $ a \r?$ or a \s*$ because $ only matches \n not the \r in \r\n.
Your "Just some text on this line" would be in the group named capture. You might also need to strip a trailing \r from this because of the treatment of $.

A: You can do this
(?<=Note:(\r?\n)).*?(?=(\r?\n)|$)
---------------- --- ------------
      |           |        |->lookahead for \r\n or end of string
      |           |->Gotcha
      |->lookbehind for note followed by \r\n. \r is optional in some cases

So,it would be like this
string nextLine=Regex.Match(input,regex,RegexOptions.Singline | RegexOptions.IgnoreCase ).Value;


Q: Max application memory Limit in iPad? I have created iPad application which downloads images using web service. But my application crashes somewhere during manipulating with high quality images. So my question is - what is max memory limit for application running on iPad? When does the application hit LowMemoryWarning on iPad?

A: There is no per-application limit so to say. The amount of memory available to an application depends on the amount of free memory, which again depends on the amount of memory used by applications running in the background. These apps include permanently running system apps like SpringBoard, sometimes running system apps like Safari, iPod, etc and (when iOS 4 will come for iPad) user-apps that still run in background.
Nevertheless, I'd say an app should never use more than 50% of all available ram. On iPad this currently means 128 MB and should be quite a lot. Did you do a leak check on your app?


Q: Packages to verify the re-rendering in es5 components other than "WhyDidYouRender" Right now I'm using the WhyDidYourender package to verify the component re-rendering but there are few components in my repo that uses es2015. WhyDidYouRender is not working in es2015 components. Seeing below error:
TypeError: Class constructor MyComponent cannot be invoked without 'new'

So need a way to verify the re-rendering for es5 components. Also, tried Chrome highlights to verify the re-rendering, please don't recommend that.
Any help is appreciated, Thanks!
WhyDidYouRender repo link: https://github.com/welldone-software/why-did-you-render

A: Support the ES6 or not is rely on your Browser. It's more like you trying to use the class but there is no instance to access.
Transpiled to es5 class is available in PR#8656, the whole react class elements are supported to extend with this library. If you transpile your classes by ES5 or ES6, use below code:
// traspiled to es5
const whyDidYouRender = require('@welldone-software/why-did-you-render);
// traspiled to es6
const whyDidYouRender = require('@welldone-software/why-did-you-render/dist/no-classes-transpile/umd/whyDidYouRender.min.js');


Q: Security - Method returns internal array - Sonar security warning - even when I am returning a clone The below return statement gives me a Sonar security warning even when I am not returning the original array but a clone of it.
What is the "correct" way to do this?
public String[] getList() {
        return list!=null? list.clone():null;
}

A: Edited my previous answer for some obvious errors :)
List.clone() doesn't work because it returns a shallow copy of the list. So basically it just returns the reference to the original list. We don't want that here. What we want is a brand new array that doesn't have the same reference to be returned.
For that the best idea will always be to create a new array and run a for loop like this:
String[] newArr = new String[list.length];
int i = 0;
for (String s : list) {
    newArr[i++] = s
}

If you wanna know why this is the issue, refer to this answer :)


Q: Elasticsearch aggregation using Java api Hi I am trying to do query on elastic search by following the sql query and I want to implement same logic using Java API
select dttime, avg(cpu) from table cpustats where server="X" and dttime="Y" group by dttime,cpu

Now I have the following Java code but it does not return expected output
SearchResponse response = client.prepareSearch("cpuindex")
      .setTypes("cputype")
      .setQuery(QueryBuilders.matchAllQuery())
      .addAggregation(AggregationBuilders.terms("cpu_agg")
           .field("cpu").size(100))
      .execute().actionGet();

Please guide I am new to Elastic search. Thanks in advance.

A: since elastic search 2.3, FilterBuilders class has been removed from JavaAPI. you can use
QueryBuilder qb = QueryBuilders.boolQuery()
        .must(QueryBuilders.matchQuery("_all", "JPMORGAN"))
        .must(QueryBuilders.matchQuery(field, value)) ;

instead, and set it to
.setQuery(qb).

A: I think this will help.
SearchResponse response=
                client.prepareSearch("your_index_name_here").setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
                FilterBuilders.andFilter(
                        FilterBuilders.termFilter("server","x"),
                        FilterBuilders.termFilter("dt_time","x")
                ))).addAggregation(
                AggregationBuilders.terms("dt_timeaggs").field("dt_time").size(100).subAggregation(
                        AggregationBuilders.terms("cpu_aggs").field("cpu").size(100)
                )
        ).setSize(0).get();

please verify.


Q: QML rotating a Gauge needle - pivot correctly I am trying to rotate a Gauge needle, but instead of pivoting at the base of the needle which have a circle with cross.. needle is pivots around the tip of the needle.. please see the attached image.. tip of the image is fixed/pivots but base is rotating.. please suggest how to correct this ?
main.qml :--
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.5

Window
{
    visible: true
    x :0
    y :0
    width: 800
    height: 480
    color: "grey"

    Rectangle
    {
        id: cluster
        Speed_Needle{
          id: cluster_pointer_base
          x : 214+16
          y : 222
        }
     }

    Slider
    {
        id  : slide_1
        width: parent.width
        from: 0
        to: 360
        value: 0
        enabled: true
        onValueChanged:
        {
            cluster_pointer_base.value=slide_1.value
        }
    }

}

Speed_Needle.qml :--
import QtQuick 2.0

Item {

    property int value: 0
    width: 186
    height: 36

    Image
    {
        id: root
        source: "files/pointer_needle2.png"
        x : 0
        y : 0
        transform: Rotation  {
            id: needleRotation
            angle : value

            Behavior on angle  {

                SmoothedAnimation { velocity: 50 }
            }
        }

    }

}

A: You have to set the origin of the Rotation:
Speed_Needle.qml :--
import QtQuick 2.0

Item {

    property int value: 0
    width: 186
    height: 36

    Image
    {
        id: root
        source: "files/REE Demo images/pointer_needle2.png"
        x : 0
        y : 0
        transform: Rotation  {
            id: needleRotation
            angle : value
            origin.x: root.width / 2    // here!
            origin.y: root.height / 2

            Behavior on angle  {

                SmoothedAnimation { velocity: 50 }
            }
        }
    }
}


Q: Response from Postman shows 200, But Android returns 403 I was trying to develop an android app using Volley, The api I used to communicate is working fine when I checked with POSTMAN and retrieves 200 .
But when I use the same API in my App its returns me 403 "Forbidden"
<p〉You don't have permission to access /API/checkPassOtp on this server.〈/p〉
Please find the screenshot.

I have tried multiple solution for this issue, But nothing worked for me.
Can anyone please help me.
Attaching volley code and error response
JSONObject jsonBody = new JSONObject();
try {
    jsonBody.put("otp", otp);
    Log.e("jsonBody", jsonBody.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        // handle response data
        VolleyHelper.progressDialog.dismiss();
        Log.e("onResponse", response.toString());

    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyHelper.progressDialog.dismiss();
        Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_SHORT).show();
        Log.e("onErrorResponse", error.toString());

    }

}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json");
        return params;
    }
};

jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Application.getInstance().addToRequestQueue(jsonObjReq, "app");
volleyHelper.showProgressDialogWithTitle(MainActivity.this);

A: Try to use

"Accept", "application/json"

in your params (use both).
I have to use x-api-key when connecting with my company's webserver, but I'm not sure if you'll need it.

A: --> Use https instead of http in android , Postman seems fine with the http, but OkHttp needed https.
I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .


Q: Cocoa: loading a bundle in which some classes inherit from a custom framework SHORT VERSION:
How can I load classes during runtime from a bundle, when those classes inherit from superclasses not defined in the bundle, but from another framework which was loaded prior?  When loading my framework, classes contained therein work fine.  When loading the plugin afterwards, any classes which inherit from NSObject work fine but classes inheriting from the framework are not being loaded.
LONG VERSION:
Cocoa allows you to control the Dock icon explicitly via the "Dock Tile Plugin" mechanism.  In a nutshell, when your app is added to the Dock, the OS looks inside the app's bundle plugins directory for a bundle called "MyDockTilePlugin.docktileplugin".  It then loads this plugin's principal class which must conform to the NSDockTilePlugIn protocol.
I have built such a bundle according to Apple's guide.  Now I want to reuse this code by making the component classes superclasses in my custom framework.  Subclasses specific to a given project can load the framework.
Surprisingly, this is not very straightforward.
Here is the process in psuedocode:

*

*The docktileplugin is loaded by the Dock.

*In its +initialize class method, the class loads the custom framework, which is set to "optional" in build settings.

*The class then loads its own plugin which contains classes inheriting from framework classes.

*Something like NSLog(@"%@", NSStringFromClass(NSClassFromString(classInheritingFromFramework))); will always display (null)

How does inheritance work across plugin bundles?  THANKS...
If this isn't enough information, please ask for more.  I'm trying to be concise and thorough.
MORE CODE:
+ (void)initialize {
[[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
    NSLog(@"bundle loaded %@", note);
}];

//Plugin bundle
NSBundle *selfBundle = [NSBundle bundleForClass:[self class]];

//Load Custom Framework
NSString *frameworkName = @"Custom.framwork";
NSString *frameworkPath = [[selfBundle bundlePath] stringByAppendingPathComponent:[@"Contents/Frameworks" stringByAppendingPathComponent:frameworkName]];
NSLog(@"Framework %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:frameworkPath]? @"EXISTS" : @"DOES NOT EXISTS"), frameworkPath);
if( [[NSBundle bundleWithPath:frameworkPath] load] ) {
    NSLog(@"Framework loaded...");
    NSLog(@"Framework provided classes such as DockTilePlugin (%@) and UndoManager (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"UndoManager")));
} else {
    NSLog(@"Error, framework failed to load.");
    exit(1);
}

//Load Dock Tile Plugin
NSString *pluginName = [[selfBundle infoDictionary] objectForKey:@"DockTilePluginCoreBundle"];
NSString *pluginPath = [[selfBundle builtInPlugInsPath] stringByAppendingPathComponent:[pluginName stringByAppendingPathExtension:@"bundle"]];
NSLog(@"Plugin %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:pluginPath]? @"EXISTS" : @"DOES NOT EXISTS"), pluginPath);
if( [[NSBundle bundleWithPath:pluginPath] load] ) {
    NSLog(@"Plugin loaded...");
    NSLog(@"Plugin provided classes such as DockTilePlugin (%@) and DockTileView (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"DockTileView")));
} else {
    NSLog(@"Error, Plugin failed to load.");
    exit(1);
}
}

What output I see in the Console.app is that the first two "classes such as" show up (class names appear), but in the second two I get "Plugin Provided classes such as DockTilePlugin (null) and DockTileView (null)".
Also, the notifications are received for both bundles.  In the framework, I see in the "NSLoadedClasses" key that all framework classes are loaded and available.  In the Plugin bundle, this list is empty (although there should be several classes from the bundle, but they all inherit from the framework).
If I add a third class to the plugin, which inherits from Cocoa, that class appears fine.  Something about bundle-loading a class which inherits from another bundle-loaded class is tricky.  That is the heart of it I think.

A: Mike from http://mikeash.com - an amazing resource - provided me with the tip that solved this problem.  The cause of the problem eludes me, but it was fixed by doing two things:

*

*In the Framework's project, setting its build location to @rpath as described in this article: http://mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html

*In the plugins loading the framework, weak reference during build, don't copy the framework during build, and then set the -rpath build setting to the location of the framework in the containing app.  This ensures all items are using the same copy of the framework.


Q: VSCode pylint not displaying relative import failures I am running a Django application in VSCode, using pylint, and the relative imports errors are not displaying. They were before I installed a newer version of VSCode.
I have tried changing user settings and also workspace settings, but still can't get the errors to show.
User Settings
{
    "window.zoomLevel": 1,
    "explorer.confirmDelete": false,
    "workbench.startupEditor": "newUntitledFile",
    "window.menuBarVisibility": "default",
    "explorer.confirmDragAndDrop": false,
    "workbench.colorTheme": "Visual Studio Dark",
    "update.enableWindowsBackgroundUpdates": false,
    "update.channel": "none",
    "php.validate.run": "onSave",
}

Workspace settings
{
    "python.linting.enabled": true,
    "python.linting.pep8Enabled": false,
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"],
    "python.linting.pylintEnabled": true,
    "python.pythonPath": "/home/justin/anaconda3/bin/python",
    "python.linting.pylintPath": "/home/justin/anaconda3/bin/pylint"
}

At the top of one of my functions, a couple of different relative imports. Which one is right or wrong, VSCode should show me. Both imports are in the same project directory in Django, therefore import should be a single '.' I believe.
from .performance import get_perf_dates, get_perf_data
from ..models import DistributionList, Legend


Q: ListViewItem ItemSelectionChangedEvent Fires 4 times [e.Selected fires twice] leads to Win32 Exception Unhandled I am using a button and a listview to display a list of options to the user. Selection is made with a mouse click, the listview removes its self from the .Controls array + un-registers eventlistener and loads a new listview else where on the screen.
My problem is both listviews trigger e.selected twice:
' private void _lvKids_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (e.IsSelected)//fires twice per click
        {
            HideKidsList();//--REMOVE CURRENT LISTVIEW
            ValidateUser();//CREATE NEW LISTVIEW
        }`

If the button is clicked a second time to restart the process, it causes a win32 Exception. After much research, this exception is the often the cause of a memory leak. So I'm thinking memory leak?
When I first started, listboxes were used which worked perfectly. I'd love to able to use them, but my form has a graphic for a background and listbox doesn't. Listview does.
I don't have anyone to turn to so any thing you can offer would be appreciated.
Thanks;
Sam

A: An update if anyone else has the same issue. Selecting the listview item called for it to be removed from Controls array. Removing the listview also cause the selected item to be deselected, thus 4 calls to the handler.


Q: Start EC2 for specific time XX hours and then terminate A customer requested an  EC2 instance for XX hours.
I created an on-demand EC2 instance and I sent the credentials to the user. He used it for a short lived calculation.
How can I terminate that EC2 instance exactly after XX hours?
Thank you in advance.

A: The simplest way to terminate an instance after a given time period is:

*

*Provide a User Data script when launching the Amazon EC2 instance

*The script should wait the given period then issue a shutdown command, such as:

sleep 3600; shutdown now -h

Also, when launching the instance, set Shutdown Behavior = Terminate. This means that when the instance is stopped from within the instance, it will actually be terminated.
Alternatively, you could code a Stopinator that would trigger at times and determine which instances to stop/terminate. For some examples see: Simple Lambda Stopinator: Start/Stop EC2 instances on schedule or duration

A: Thanks, John(@john-rotenstein).
I tested all your suggestions.
I used the following User Data script for
Windows instances:
<script>
shutdown -s -t 3600
</script>
<persist>true</persist>

Linux instances:
...
#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
sleep 3600
shutdown now -h

In addition, Stopinator Type 2 is working perfectly well for me, but only with Stop-After tag


Q: How to avoid spurious 'unused parameter' warnings in TypeScript I've encountered this a bunch and have finally decided to figure out what the right way to do it is.  If I have an abstract parent class that declares a method, and then some of the concrete sub-classes implement real logic in their implementation (and, obviously, use the method parameters), but some of the sub-classes don't need to do anything in that method (so don't use the method parameters) - the ones that don't have to do anything generate spurious (in my view) warnings in my code.
For instance, if I have some classes that look like:
abstract class Child {
  constructor(protected name: string) {
    connsole.log(name + " was just born.");
  }

  abstract tellThemToDoSomething(command: string);
}

class GoodChild extends Child {
  constructor(name: string) { super(name); }
  tellThemToDoSomething(command: string) {
    console.log("I will do " + command);
  }
}

class BadChild extends Child {
  constructor(name: string) { super(name); }
  tellThemToDoSomething(command: string) {
    // bad children just ignore what their parents tell them
  }
}

Then I get a (TSLint? JSLint? WebStorm?) warning in WebStorm for the unused parameter in the BadChild tellThemToDoSomethign() method.
I know of a few options, but none seem great.
1) Ignore it (but that seems suboptimal, since I'll grow blind to real warnings)
2) Remove the parameter from the BadChild's method implementation (but that unfortunately removes useful information, since I may later want to implement it, and not having the signature there makes it more difficult, and I also get errors from callers expecting there to be parameters - though given that I should be able to call a method with extraneous parameters in JavaScript, I be there's a way around that problem)
3) Tell WebStorm(TSLint) to stop warning on unused parameters (but that seems suboptimal since I won't get warnings in other real problem situations)
4) Do something meaningless with the parameter so it is not unused (obviously not great)
What is do experienced Java/TypeScript coders do in situations like this?  Is there an easy way to tell WebStorm/TSLint to ignore the parameter in individual cases like this?  Or, even better, a way to tell it to ignore unused parameters in sub-class implementations of abstract methods, as long as some implementations actually use the parameters?
I'm a little unsure on where the warning is coming from, though, since my brief googling shows a TSLint warning for unused-variables but not unused-parameters, and adding a // tslint:ignore-next-line:no-unused-parameter (or no-unused-variable) didn't make the warning go away.  So I guess it's possible the warning is coming from WebStorm itself?  Further, the warning is "Unused parameter Foo: Checks JavaScript parameter, local variable, function, classes and private member declarations to be used in given file scope".  So it doesn't look like a TSLint warning.  And if I look in my WebStorm Preferences -> Languages & Frameworks -> Javascript -> Code Quality Tools, none of the linters are enabled (JSLint, JSHint, ESLint, etc.).  So any idea where the error is coming from?
I've not coded in TypeScript long enough to have a feel for what the ideal dial on this warning should be.

A: This warning is caused by JetBrains PhpStorm/WebStorm inspections.
A conventional way that is properly handled by TypeScript is to underscore unused parameters. Unfortunately, this convention isn't supported by JetBrains IDEs.
It's possible to suppress inspections in-place in some cases by triggering suggestion list with Alt+Enter/⌥+Enter and choosing Suppress for statement (this never worked for me for IDE inspections).
It's possible to suppress inspections in inspections results.
This results in adding a comment above the method and affects all unused parameters in this method signature:
// noinspection JSUnusedLocalSymbols
tellThemToDoSomething(_command: string) {}

This can be added to live templates, etc.


Q: How Can I Terminate a Thread Using a Throw Exception Method - Python I found some code online that will stop a thread via an exception after a wait period of some time.
def raise_exception(self):
  thread_id = self.get_id()
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
          ctypes.py_object(SystemExit))
  if res > 1:
    ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
    print('Exception raise failure')

An exception is called after some time by:
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(1/1000)
t1.raise_exception()
t1.join()

I would like to call an exception that would specify how many time a process occurs. Such as:
t1 = thread_with_exception('Thread 1')
t1.start()
if t1.count >= 3:
    t1.raise_exception()
    t1.join()

This however fails to call an exception when t1.count >= 3.
Can an exception not be called in this manner?

A: Rather than calling the raise_exception outside the class, calling it from within the run method for the thread will work. Ex.
def run(self):
    if count>3:
         self.raise_exception()


Q: Unable to POST data using TLS 1.2 I am trying to POST data to a server who is just using TLS1.2
When i am running the code i am getting the following response from server.
HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Date: Wed, 07 Sep 2016 17:42:57 CST, Server: , Strict-Transport-Security: max-age=63072000; includeSubdomains; preload, Pragma: no-cache, Content-Length: 0, charset: ISO-8859-1, X-ORACLE-DMS-RID: 0, X-ORACLE-DMS-ECID: 343fa6c0-ed24-4003-ad58-342caf000404-00000383, Set-Cookie: JSESSIONID=1ZMIvt1NqrtWpHgHs4mMmYyTPUGTOQgrA9biCE3Dok5v0gDCPXu6!681252631; path=/; secure; HttpOnly;HttpOnly;Secure, Cache-Control: no-store, P3P: policyref="/w3c/p3p.xml", CP="WBP DSP NOR AMT ADM DOT URT POT NOT", Keep-Alive: timeout=5, max=250, Connection: Keep-Alive, Content-Type: text/xml, Content-Language: en] [Content-Type: text/xml,Content-Length: 0,Chunked: false]}

I am using the below code to post the data to server . I am using apache httpcomponents-client-4.5.2.
private static Registry<ConnectionSocketFactory> getRegistry() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext sslContext = SSLContexts.custom().build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("https", sslConnectionSocketFactory)
                .build();
    }

    public static void main(String[] args) throws Exception
    {
        PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(getRegistry());
        clientConnectionManager.setMaxTotal(100);
        clientConnectionManager.setDefaultMaxPerRoute(20);
        HttpClient client = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
        HttpPost  request = new HttpPost("https://someserver.com/dataupload");
        File file = new File("C://Nible//code//_client//Request.xml");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setContentType(ContentType.TEXT_XML);
        FileBody fileBody = new FileBody(file);
        builder.addPart("my_file", fileBody);
        HttpEntity reqEntity = builder.build();
        request.setEntity(reqEntity);
        HttpResponse response = client.execute(request);
       System.out.println(response);
    }

Can you please tell me what wrong am i doing?
I tried using below code instead of MultipartEntityBuilder. I am still getting the same error.
EntityBuilder builder = EntityBuilder.create();
builder.setFile(file);
builder.setContentType(ContentType.TEXT_XML);

If i am sending the BLANK REQUEST to server then also i am getting the same error. Blank error means i am not putting any thing in request just
HttpPost  request = new HttpPost("https://someserver.com/dataupload");
 HttpResponse response = client.execute(request);

A: I suspect of these lines in your code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.TEXT_XML);

Multipart entities cannot be of content-type xml. They must be one of these types:

*

*multipart/mixed

*multipart/alternative

*multipart/digest

*multipart/parallel

(See RFC 1341 7.2)
I guess you should use one of these content-types for the multipart entity, and set text/xml as the content type of the single part:
FileBody fileBody = new FileBody(file, ContentType.TEXT_XML);

(Another issue is that I don't see necessary to send a multipart for just one file: You could leave out the MultipartEntityBuilder object and build directly a FileEntity.)


Q: Mapping attributes using @JsonProperty when binding play.data.Form from JsonNode I have the following class
public static class Thing {
    @JsonProperty("_name_")
    String name;
}

and I'm trying to bind it to the form and get instance of this class this way
ObjectNode node = Json.newObject();
node.put("_name_", "some name");

Form<Thing> thingForm = Form.form(Thing.class);
thingForm = thingForm.bind(node);
Thing thing = thingForm.get();

So, I expect that thing.name will be "some name" but it's not, it is null. I understant that @JsonProperty is for Json (de)serialization, just tried if it works. The question is how to achieve this with Play's Form?
I also tried to Register a custom DataBinder as described in docs, but its methods never gets called.
Any help is appreciated.

A: Have you tried thingForm.bindFromRequest() instead of thingForm.bind()? I am using exactly same thing where I make an ajax post with json data and it is working fine for me. It doesn't look like it has anything to do with @JsonProperty().
Are you sure if you want to have class Thing static ? I am assuming you have public getter/setters for your form properties.


Q: PaypalPlus iFrame integration with Payment Logos How can I add the payment logo to the PaypalPlus iFrame integration? We have 2 extensions for PaypalPlus, the old one shows payment logos for Paypal, direct debit etc. but the new one not.  (The Image has class class="paymentMethodIcon")
In all SDK & Integration guides I did not find any information about this.
Who can help? Is this something which depends on integration and is controlled by Paypal or is there any setting?
Thats how it should look

A: The payment wall iframe is configured by paypal with a whitelist of allowed domains (see Content Security Policy).

*

*The image URL must be https (specified in the docs)

*Your images must be on a server on the whitelist.

*This includes: The image URL can not have a custom port.

*PayPal automatically adds the domain containing the PPP script to the whitelist.

If you look into the browser console you might be able to see an error like this:
Refused to load the image 'https://my-domain.de:7443/images/payment_sofort_small.png' because it violates the following Content Security Policy directive: "img-src https://*.paypalobjects.com https://ak1s.abmr.net https://ak1.abmr.net https://ak1s.mathtag.com https://akamai.mathtag.com https://my-domain.de".
This is how it looked in my case:


Q: create distinct objects in a loop in js var subject = [] ;
var subjectTemplate = {GUID:"", Title:"", Description:""};
for (var x = 0; x < 5; x++) {
var  clsSubject =   subjectTemplate;

    clsSubject.GUID = id.generateRandomNumber()
    clsSubject.Title = "Intorduction to js";
    clsSubject.Description = "Subject to learn js";
    subject.push = clsSubject;

}
what is happening is that there are 5 references of the same object in the array. So after the last run; all the 5 objects in the array have the same values. The five objects in the array are identical.
I need to create 5 distinct objects with distinct values in an array.

A: After doing some research and have come with the following:
var subjects = [];
var subjectTemplate = {GUID:""};

for (var x = 0; x < 5; x++)
{
  var subject = Object.Create(subjectTemplate);
      subject.GUID = <generate GUID>;
      subjects[x] = subject;
}

A: With javascript you do not need to declare or initialize the fields when you first initialize the object.
Replace
var  clsSubject =   subjectTemplate;

with
var clsSubject = {};

With your current implementation you set all clsSubject to the same object instance, namely subjectTemplate.

A: You can just change the delcaration of clsSubject to create a new object. You can actually just fill in the properties directly if you want. Also you didn't push to the array correctly.
var clsSubject = {
    GUID: id.generateRandomNumber(),
    Title: "Intorduction to js",
    Description: "Subject to learn js"
};
subject.push(clsSubject);


Q: Rails - Running tests with unexpected results - should be failing but instead its passing I am doing Hartl's tutorial.
https://www.railstutorial.org/book/static_pages
On section 3.3.3
I am running test but running into unexpected results.
In my static_pages_controller_test.rb I have the following:
test "should get about" do
    get :about
    assert_response :success
 end

According to Listing 3.17, I should be getting:
AbstractController::ActionNotFound:
The action 'about' could not be found for StaticPagesController

However, the test still passes even though there is no about action defined in my static_pages_controller.rb
gemfile:
group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace',     '0.1.3'
  gem 'guard-minitest',     '2.3.1'
end

Guardfile (though I'm not actively running it to execute test)
# Defines the matching rules for Guard.
guard :minitest, spring: true, all_on_start: false do
  watch(%r{^test/(.*)/?(.*)_test\.rb$})
  watch('test/test_helper.rb') { 'test' }
  watch('config/routes.rb')    { integration_tests }
  watch(%r{^app/models/(.*?)\.rb$}) do |matches|
    "test/models/#{matches[1]}_test.rb"
  end
  watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|
    resource_tests(matches[1])
  end
  watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|
    ["test/controllers/#{matches[1]}_controller_test.rb"] +
    integration_tests(matches[1])
  end
  watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|
    integration_tests(matches[1])
  end
  watch('app/views/layouts/application.html.erb') do
    'test/integration/site_layout_test.rb'
  end
  watch('app/helpers/sessions_helper.rb') do
    integration_tests << 'test/helpers/sessions_helper_test.rb'
  end
  watch('app/controllers/sessions_controller.rb') do
    ['test/controllers/sessions_controller_test.rb',
     'test/integration/users_login_test.rb']
  end
  watch('app/controllers/account_activations_controller.rb') do
    'test/integration/users_signup_test.rb'
  end
  watch(%r{app/views/users/*}) do
    resource_tests('users') +
    ['test/integration/microposts_interface_test.rb']
  end
end

# Returns the integration tests corresponding to the given resource.
def integration_tests(resource = :all)
  if resource == :all
    Dir["test/integration/*"]
  else
    Dir["test/integration/#{resource}_*.rb"]
  end
end

# Returns the controller tests corresponding to the given resource.
def controller_test(resource)
  "test/controllers/#{resource}_controller_test.rb"
end

# Returns all tests for the given resource.
def resource_tests(resource)
  integration_tests(resource) << controller_test(resource)
end

A: Do you have a view named about in static_pages_controller's corresponding view folder?
If so, rails assumes controller action just being empty and proceeds with render.
To have test fail - rename or delete the view


Q: How to make two UIGestures respond simultaneously on two different views? I have View (A) has two subviews: view B and view C. View (B) that has a UILongPressGestureRecognizer and View (C) has a UIPanGestureRecognizer and is hidden by default. When I long press on a View B, view C is shown (isHidden = false).
Now, when I long press on view B, view C is shown but gesture defined in it is not responding, gesture defined in view B is still active.
I want to be able to respond to UIPanGestureRecognizer of View C when it is shown, and when I release touch I want to ended both gestures a UILongPressGestureRecognizer of View B, and UIPanGestureRecognizer of View C.
Is it possible?

A: I think there is no necessary to add UIPanGestureRecognizer to View(C), you can recognize finger position in UILongPressGestureRecognizer handle method. look at sample code
declare variables:
@IBOutlet var cView: UIView?

Here is UILongPressGestureRecognizer handle method:
 @IBAction func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
    switch gesture.state {
    case .began:
        cView?.isHidden = false
    case .changed:
        if let cView = cView, cView.isHidden == false {
            let location = gesture.location(in: self.cView)
            print("Finger Location - (\(location.x),\(location.y))")
        }
    case .ended, .cancelled:
        cView?.isHidden = true
    default: break
    }
}

The code performs your requirements.


Q: Outlook Manifest functional in web Outlook, won't properly install in desktop Outlook I'm working on an Outlook Add-In. I've been working so far in the web version, but my understanding is that a manifest that functions in Web should automatically also function in Desktop.
However, I'm encountering an issue where I install my add-in on the desktop, it succeeds, but then instantly disappears. If I go to the "Get Add-ins" page again and go to My Addins, my addin which I just installed does not show up.
This add-in is fully functional in web outlook, so I'm not at all sure what the issue may be. I've tried validating it using
npx office-addin-manifest validate MANIFEST_FILE

But it passes this. I've also tried enabling runtime logging, but I just get an empty log file if I install it while logging. I'm not sure where to go from here. I've confirmed that the same issue occurs on another machine.
My suspicion is that it may have something to do with the utilization of VersionOverrides 1.1 (we're using this to support pinning a task pane open), but I have no idea why this would cause an issue in Desktop. Minus the resources section, our buttons/tabs are defined with the VersionOverrides 1.1 section.
Appreciate any suggestions for further debugging!
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
  xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
  xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0"
  xsi:type="MailApp">

  <!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
  <Id>d0aa58bd-1618-45ed-a773-9e8353a85215</Id>

  <Version>1.0.0.0</Version>
  <ProviderName>Test Name</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Onvio Add-In" />
  <Description DefaultValue="Onvio Outlook Add-In For Interaction With Document Management Service"/>
  <IconUrl DefaultValue="https://img.icons8.com/clouds/2x/cloud-network.png" />
  <HighResolutionIconUrl DefaultValue="https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/256x256/earth.png" />

 <SupportUrl DefaultValue="https://localhost:4200"/>
  <!--End Basic Settings. -->

  <Hosts>
    <Host Name="Mailbox" />
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="Mailbox" MinVersion="1.1" />
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://localhost:4200"/>
      </DesktopSettings>
    </Form>
  </FormSettings>

  <Permissions>ReadWriteItem</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>
  <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
    <Resources>
      <bt:Images>
        <bt:Image id="Onvio.PaneButton.Icon" DefaultValue="https://i.imgur.com/FkSShX9.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="Onvio.FunctionFile.Url" DefaultValue="https://localhost:4200" />
        <bt:Url id="Onvio.Taskpane.Url" DefaultValue="https://localhost:4200" />
      </bt:Urls>
      <bt:ShortStrings>
        <bt:String id="Onvio.Pane.Title" DefaultValue="Onvio Side Panel" />
        <bt:String id="Onvio.Pane.Label" DefaultValue="Show Taskpane" />
        <bt:String id="Onvio.Tab.Label" DefaultValue="Onvio Tab Label" />
        <bt:String id="Onvio.OpenedMessageTools.Label" DefaultValue="Onvio.OpenedMessageTools.Label" />
        <bt:String id="Onvio.ComposeMessageTools.Label" DefaultValue="Onvio.ComposeMessageTools.Label" />
      </bt:ShortStrings>
      <bt:LongStrings>
        <bt:String id="Onvio.Pane.Description" DefaultValue="Onvio Side Panel Description" />
      </bt:LongStrings>
    </Resources>
    <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
      <Description resid="residDescription" />
      <Requirements>
        <Sets xmlns="http://schemas.microsoft.com/office/officeappbasictypes/1.0">
          <Set Name="Mailbox" MinVersion="1.1" />
        </Sets>
      </Requirements>
      <Hosts>
        <Host xsi:type="MailHost">
          <DesktopFormFactor>
            <ExtensionPoint xsi:type="MessageComposeCommandSurface">
              <OfficeTab id="TabDefault">
                <Group id="Message" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
                  <Label resid="Onvio.ComposeMessageTools.Label" />

                  <Control xsi:type="Button" id="Onvio.ComposePane.Button">
                    <Label resid="Onvio.Pane.Label" />
                    <Supertip>
                      <Title resid="Onvio.Pane.Title" />
                      <Description resid="Onvio.Pane.Description" />
                    </Supertip>
                    <Icon>
                      <bt:Image size="16" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="32" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="80" resid="Onvio.PaneButton.Icon" />
                    </Icon>
                    <Action xsi:type="ShowTaskpane">
                      <SourceLocation resid="Onvio.Taskpane.Url" />
                      <SupportsPinning>true</SupportsPinning>
                    </Action>
                  </Control>
                </Group>
              </OfficeTab>
            </ExtensionPoint>
            <ExtensionPoint xsi:type="MessageReadCommandSurface">
              <CustomTab id="Onvio.OpenedMessageTools.Tabs">
                <Group id="Onvio.OpenedMessageTools.Group" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
                  <Label resid="Onvio.OpenedMessageTools.Label" />
                  <Control xsi:type="Button" id="Onvio.Pane.Button">
                    <Label resid="Onvio.Pane.Label" />
                    <Supertip>
                      <Title resid="Onvio.Pane.Title" />
                      <Description resid="Onvio.Pane.Description" />
                    </Supertip>
                    <Icon>
                      <bt:Image size="16" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="32" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="80" resid="Onvio.PaneButton.Icon" />
                    </Icon>
                    <Action xsi:type="ShowTaskpane">
                      <SourceLocation resid="Onvio.Taskpane.Url" />
                      <SupportsPinning>true</SupportsPinning>
                    </Action>
                  </Control>
                </Group>
                <Label resid="Onvio.Tab.Label" />
              </CustomTab>
            </ExtensionPoint>
          </DesktopFormFactor>
        </Host>
      </Hosts>
    </VersionOverrides>
  </VersionOverrides>
</OfficeApp>


Q: Injecting application level dependency into node module I'm trying to create package from higher order components that are currently in application.
The issue is that in some of those components application routes are being used ( through helper that imports all the routes and returns url based on route name ).
I have no idea how to inject those routes to my module from app level.
For example in Symfony ( PHP ) this issue would be fairly simple, due to dependency injection. But with imports inside each file I'm really lost here.
I'm using NextJS and here is code sample ( I would love to inject those routes instead of directly importing them ):
import { routes } from "../../routes";

export default (routeName, params) =>
  routes.find(route => route.name === routeName).toPath(params);

A: You could build your own dependency injection module.
Using NodeJs it's fairly simple to do.
This one for instance.


Q: Can I create an HTML list in a D3.js SVG container Here is the code I am working on. I want to plot events for a certain year as an unordered list.
Is it possible to do using d3.js?
Code-
var mevent = svg.append("text")
        .attr("class", "year mevent")
        .attr("text-anchor", "end")
        .attr("y", height - 450)
        .attr("x", width - 300)
        .attr("width", 1000)
        .attr("height", 200)
        .text("");

  // Updates the display to show the specified year.
  function displayYear(year) {
    dot.data(interpolateData(year), key).call(position).sort(order);
    year = Math.round(year);
    label.text(year);
    price.text("$ " + iacprices[year]);
    mevents_text = "";
    for (var i = 0; i < (mevents[year]).length; i++) {
        mevents_text = "*" + mevents_text
        + (mevents[year])[i];
    }
    mevent.text(mevents_text);

A: Yes, you can place HTML elements in a SVG with a foreignObject.
Example w/ d3


Q: SQL Server SMO script generation throwing deadlock error I have a huge database with nearly 16k tables. Some of these tables are transnational tables and always receive some insert/select/update queries.I am using SMO to transfer the definition of all these 16K tables to some test database. But my code is failing while scripting tables and throwing deadlock issue (especially while copying those transaction heavy tables). I was just wondering "why deadlock" as SMO internally use some SYS tables to extract definition and shouldn't be messing up with any other transaction.
Stack trace:
<SqlException>
          <Message>Transaction (Process ID 670) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.</Message>
          <Server>p01db107</Server>
          <Source>.Net SqlClient Data Provider</Source>
          <StackTrace>   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
   at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
   at System.Data.SqlClient.SqlDataReader.Read()
   at Microsoft.SqlServer.Management.Smo.DataProvider.ReadInternal()
   at Microsoft.SqlServer.Management.Smo.DataProvider.Read()
   at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitObjectsFromEnumResults(Urn levelFilter, IDataReader reader, Boolean forScripting, List`1 urnList, Int32 startLeafIdx, Boolean skipServer)
   at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitQueryUrns(Urn levelFilter, String[] queryFields, OrderBy[] orderByFields, String[] infrastructureFields, ScriptingPreferences sp, Urn initializeCollectionsFilter)
   at Microsoft.SqlServer.Management.Smo.DefaultDatabasePrefetch.PrefetchUsingIN(String idFilter, String initializeCollectionsFilter, String type, IEnumerable`1 prefetchingList)
   at Microsoft.SqlServer.Management.Smo.DatabasePrefetchBase.<PrefetchObjects>d__1.MoveNext()
   at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.SfcChildrenDiscovery(HashSet`1 discoveredUrns)
   at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.Discover(IEnumerable`1 urns)
   at Microsoft.SqlServer.Management.Smo.ScriptMaker.DiscoverOrderScript(IEnumerable`1 urns)
   at Microsoft.SqlServer.Management.Smo.ScriptMaker.ScriptWorker(List`1 urns, ISmoScriptWriter writer)
   at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithListWorker(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)
   at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithList(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)</StackTrace>


Q: How to calculate number of post which have particular meta_key? I am using repeatable meta boxes what i want to achieve is display number of post which have particular meta key such as
Country Pakistan
City Islamabad
Age 12
Age 12
Meta key "Age" is used in 2 posts.
No i want structure like Age in Post 2 , Islamabad in Post 1 , Pakistan in Post 1.
/**
* Display callback for the submenu page.
*/
function iif_register_submenu_form_details_callback() {

$id = get_current_user_id();

    $loop = new WP_Query( array(
    'post_type'         => 'iff-info-forms',
    'post_status'       => 'publish',
    'author'            => $id,
    'meta_query'        => array(
                        array(
                            'key'   => 'repeatable_fields',
                            //'value' => $user_data_new,
                            'compare'   => 'LIKE'
                        ))
     ) );
    //print_r($loop);
    while ( $loop->have_posts() ) : $loop->the_post();
    $info = get_post_meta(get_the_id(), 'repeatable_fields', true);

    if ( $info ) {
      //  echo 'Emergency Contacts:
';

        foreach ( $info as $emergency_contact_metas ) {
            echo '' . esc_html( $emergency_contact_metas['iif_label'] ) .' ' . esc_html( $emergency_contact_metas['iif_details'] ) . '
';
        }
    }

    endwhile;

}

OUTPUT SHOWING IS Below
Country Pakistan
City Islamabad
Age 12
Age 12


Q: Using C++ to receive int inputs and displaying the larger and smaller number The instructions are to

*

*Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating 'I' is entered.

*Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.

I got the program to run but it terminates with a Range error: Can anybody correct my mistake in this code?
/*a drill in the Programming Principles
and Practice Using C++ by Bjarne Stroustrup*/
#include "std_lib_facilities.h"     /*standard library from the author's website*/
int main()
{
    vector<int>values;
    int a, b;       //ints declared
    while(cin>>a>>b){   //ints read
        values.push_back(a);    //ints put into vector
        values.push_back(b);    //********************
    }
    for(int i = 0; i < values.size(); ++i){     //loop
        if(values[i]>values[i+1]){
            cout << "The larger value is: " << values[i] << endl;   /*print larger value on screen*/
        }
        else
            cout << "The smaller value is: " << values[i] << endl;  /*prints smaller value on screen*/
    }
    return 0;
}

A: values[i+1] goes out of bounds for the last value, so you need to change your for loop condition
for(int i = 0; i < values.size() - 1; ++i){
                              // ^^^

A: 1.Write a program that consists of a while-loop that (each time around
    the loop) reads in two ints and then prints them. Exit the program
    when a terminating 'I' is entered.
int a, b = 0;
//  anything that isn't a int terminate the input e.g. 2 3 |
while (cin >> a >> b)
  cout << a << " " << b << "\n";

2.Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.
int a, b;
const string smaller = "smaller value is: ";
const string larger = "larger value is: ";

while (cin >> a >> b) {
    if (a < b)
        cout << smaller << a << larger << b << endl;
    else
        cout << smaller << b << larger << a << endl;
}

if (cin.fail()) {
    cin.clear();
    char ch;
    if (!(cin >> ch && ch == '|'))
        throw runtime_error(string {"Bad termination"});
}


Q: Get C Code Stack Trace in Go Program I'm using the rana/ora oracle driver in my Go program to query some Oracle tables.
The program somehow always gets SIGSEGV from a C library after running for a while and exits on segfault. It also gets a lot of query timeouts (context deadline exceeded) before it hits segfault error.
I'm using the driver in a pretty standard way:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Seconds)
defer cancel()
rows, err := initialedDb.QueryContext(ctx, "sql_query")

The stack trace from the 1st Goroutine is:
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x70 pc=0x7fbb03e5d193]
runtime stack:
runtime.throw(0xa4a0a4, 0x2a)
    /usr/local/go/src/runtime/panic.go:596 +0x95
runtime.sigpanic()
    /usr/local/go/src/runtime/signal_unix.go:274 +0x2db
goroutine 5230 [syscall, locked to thread]:
runtime.cgocall(0x921850, 0xc421667348, 0xa495f1)
    /usr/local/go/src/runtime/cgocall.go:131 +0xe2 fp=0xc421667308 sp=0xc4216672c8
gopkg.in/rana/ora%2ev4._Cfunc_OCIAttrGet(0x2c92f08, 0x35, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xc400000000)
    gopkg.in/rana/ora.v4/_obj/_cgo_gotypes.go:347 +0x4d fp=0xc421667348 sp=0xc421667308
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr.func1(0x2c92f08, 0xc400000035, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xf1ef01)
    /go/src/gopkg.in/rana/ora.v4/rset.go:970 +0xfc fp=0xc421667390 sp=0xc421667348
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr(0xc4211f22d0, 0x2c92f08, 0xc421cb8be4, 0xc421cb8be8, 0xc400000005, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/rset.go:976 +0x88 fp=0xc4216673e0 sp=0xc421667390
gopkg.in/rana/ora%2ev4.(*Rset).open(0xc4211f22d0, 0xc421358000, 0x7fbae405ed28, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/rset.go:554 +0xd43 fp=0xc421667b98 sp=0xc4216673e0
gopkg.in/rana/ora%2ev4.(*Stmt).qryC(0xc421358000, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1, 0xc4211f22d0, 0x0, 0x0)
    /go/src/gopkg.in/rana/ora.v4/stmt.go:442 +0x3e0 fp=0xc421667f18 sp=0xc421667b98
gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext.func1(0xc421b73260, 0xc420e789e8, 0xc420e789e0, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1)
    /go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:76 +0xa6 fp=0xc421667fa0 sp=0xc421667f18
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc421667fa8 sp=0xc421667fa0
created by gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext
    /go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:82 +0x30c

I checked my program many times and I don't think I'm causing any memory leaks, double frees or anything like that.
I wonder how I can debug this since Go doesn't give me C's stack trace. Will Valgrind's Memcheck tool help?


Q: Different effects of ORDER BY clause on two servers My query:
SELECT * FROM table GROUP BY id;

id field is a primary key, of course;
In 9.4.4 I get expected error:
column "table.name" must appear in the GROUP BY clause or be used in an aggregate function

BUT! In 9.4.5 it works, like in MySQL.
Can anybody tell me - why? :)

A: Postgres version does not matter here. The tables are not identical. Most likely in your 9.4.5 table the column id is a primary key, while in 9.4.4 is not.


Q: Google Apps Script - Use Column Name (not In row1) rather than column number I have an Apps Script linked to my Google Sheet which grabs a range from one sheet and copies it to another. The issue I face now (and one that cannot be reasoned with) is that users will add columns to the destination sheet.  What I am trying to do instead is look for the column names; to add another slight spanner in the works the column names are on row 7 instead of 1.
    function OPupdates() {

// I have tried looking at this but couldn't get it to work for me- https://stackoverflow.com/questions/45901162/refer-to-column-name-instead-of-number-in-google-app-script

//Copies Status From One Sheet To Another
  var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
  var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied

  sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,8, sheetfrom2.getLastRow()-2, 1), {
    contentsOnly: true
  });
//row 8 column 8.  This is what needs to be changes to reflect the column name regardless of where it sits in row 8

}

I have tried looking at a similar issue/solution (link in the code above) but try as I might I could not figure out how to get this to work for my particular issue.

A: Instead of copying the range you'll need to create a value array that matches the target structure.
In lieu of sample data I'll play with the following toy example:
Sheet "Source":

A
B
C

1
1
2

Sheet "Target":

_
A
B
C
D

1

2

3

4

5

6

7

8
B
E
C
A

function copyOver() {
  const source = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Source")
      .getDataRange()
      .getValues();

  const target = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Target");

  const headerRow = 8;
  const targetHeaders = target.getDataRange().getValues()[headerRow - 1];
  const sourceHeaders = source[0];
  const sourceValues = source.slice(1);
  const columnLookup = targetHeaders.map(h => sourceHeaders.indexOf(h));

  function buildRow(row) {
    return columnLookup.map(c => c == -1 ? "" : row[c]);
  }

  const output = sourceValues.map(buildRow);
  if (output.length > 0) {
    target
        .getRange(headerRow + 1, 1, output.length, output[0].length)
        .setValues(output);
  }
}

A: First of all try yelling at users and making them understand that they may not mess with sheets with active programming (This is successful 75% of the time). Otherwise, you'll want to check your columns before you copy.
function OPupdates() {
  var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
  var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied

var statuscolumn = -1;
var headerWewant = "STATUS";//modify for the correct column name
var targetSheetHeader = sheetto2.getRange(1,1,1,sheetto2.getLastColumn().getValues();
for (var j=0; i<targetSheetHeader[0].length;i++)
    {
    if (data[0][j] == headerWeWant) statuscolumn = j+1;
    }
if (statuscolumn == -1) {console.error("Couldn't find the status column"; return;}

  sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,statuscolumn, sheetfrom2.getLastRow()-2, 1), {
    contentsOnly: true
  });

}

But training the users to go in fear of your wroth is a better long term strategy ;).


Q: Insert contents of a file in middle of another file with Python? There is already a question on SO that explains how to insert a line into the middle of a python file at a specific line number.
But what if I have 2 files. inputfile.txt and outputfile.txt (which already has some text) and I want to insert all of inputfile.txt (with formatting preserved) into the middle of outputfile.txt?

A: Why do you think it is any different from this probable SO question you are referring to?
Its just that instead of inserting a line, you need to read your inputfile.txt into a variable as shown here
and insert that into the file, instead of the value as clearly shown in the question. (links provided above)

A: insert contents of "/inputFile.txt" into "/outputFile.txt" at line 90
with open("/inputFile.txt", "r") as f1:
    t1 = f1.readlines()
with open("/outputFile.txt", "r") as f2:
    t2 = f2.readlines()
t2.insert(90, t1)
with open("/outputFile.txt", "w") as f2:
    f2.writelines(t2)

That should do it


Q: Is SparseArray good for resource id keys? Is it advisable to use a SparseArray when the integer keys are resources id's? Or is it aimed at keys with lower numbers?
Yes, I know the definition of SparseArray, and the compiler always issues a warning when one uses ArrayList with integer keys, advising to use SparseArray.
But maybe when SparseArray was defined, they had in mind an array where you do have elements, but not all of them.
In my case, I want to use Resource IDs as keys, which are, for those of you who had a pick at the generated R.java file, very big numbers only. So I though that it may not fit, not only the intention, but also the implementation of SparseArray.

A: SparseArray is exactly for values which are of an unknown range.  So it seems to fit your need.

A: in R.java the resrource ids are all integer so there is no problem using sparse array.

A: Do not use the SparseArray together with the Resourse IDs as keys. SparseArraysorts keys in ascending order for efficient access. Since resource ids are generated automatically, you cannot guarantee their order within SparseArray. This means that when you iterate over the SparseArray, you will not follow the same order as you would when filling in the FW.
I think you should use LinkedHashMap instead.


Q: How Do I Ensure a Candidate Latin Square Is a Valid Damm Operation Table I am attempting to write a function in Scala that takes a valid Latin Square as input and then returns a Boolean value indicating whether the input Latin Square is a valid instance of an operation-table for the Damm Algorithm, or not. The Damm Algorithm appears to be of the "Check digit" class of error detection mechanisms.
The desired function is an implementation of the implication described in the Design section of the Wikipedia article for the Damm Algorithm. The implication is captured by the assertion of:

a weak totally anti-symmetric quasigroup with the property x ∗ x = 0

I'm insufficient in both the math skills to properly read and interpret Damm's paper, and then having enough German (the language within which the paper was written) reading skills to be able to confidently interpret how I would encode a correct validation function.
Given the following function definition:
def validate(latinSquare: List[List[Int]]): Boolean =
  ???

With what would I replace the ????
Within the paper, a single instance of a valid 10x10 Latin Square is provided. It is reproduced within the Wikipedia article and looks like this:
 |0 1 2 3 4 5 6 7 8 9
-+-------------------
0|0 3 1 7 5 9 8 6 4 2
1|7 0 9 2 1 5 4 8 6 3
2|4 2 0 6 8 7 1 3 5 9
3|1 7 5 0 9 8 3 4 2 6
4|6 1 2 3 0 4 5 9 7 8
5|3 6 7 4 2 0 9 5 8 1
6|5 8 6 9 7 2 0 1 3 4
7|8 9 4 5 3 6 2 0 1 7
8|9 4 3 8 6 1 7 2 0 5
9|2 5 8 1 4 3 6 7 9 0

I can see there are others who have sought an answer to this. However, no one has yet provided a requested code-based valid Latin Square solution.
I have coded up a generic Latin Square generator, but need the above validation function which will serve as the filter to eliminate each candidate Latin Square that does not meet the necessary condition(s) of the above implication.

A: In functional programming terms, the checksum algorithm is foldLeft with a carefully chosen binary operation. The requirements for this binary operation, in English:

*

*In every two-digit input, if we change one of the digits, then the checksum changes (Latin square…);

*In every three-digit input, if the latter two digits are distinct and we swap them, then the checksum changes (…with weak total antisymmetry);

*The Latin square has zeros on the diagonal.

In Python 3:
def validate(latinSquare):
    Q = range(len(latinSquare))
    return all(
        x == y
        for c in Q
        for x in Q
        for y in Q
        if latinSquare[latinSquare[c][x]][y] == latinSquare[latinSquare[c][y]][x]
    ) and all(latinSquare[x][x] == 0 for x in Q)

print(
    validate(
        [
            [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
            [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
            [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
            [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
            [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
            [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
            [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
            [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
            [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
            [2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
        ]
    )
)

A: This is a conversion into Scala of the Python 3 Answer that was provided by David Eisenstat's answer.
View in Scastie:
def isValidDammOperationTable(validLatinSquare: List[List[Int]]): Boolean = {
  val indices = validLatinSquare.indices.toList
  (
        indices.forall(index => validLatinSquare(index)(index) == 0)
    &&  indices.forall(
          c =>
            indices.forall(
              x =>
                indices.forall(
                  y =>
                        (validLatinSquare(validLatinSquare(c)(x))(y) != validLatinSquare(validLatinSquare(c)(y))(x))
                    ||  (x == y)
                )
            )
        )
  )
}

val exampleLatinSquareX10: List[List[Int]] =
  List(
      List(0, 3, 1, 7, 5, 9, 8, 6, 4, 2)
    , List(7, 0, 9, 2, 1, 5, 4, 8, 6, 3)
    , List(4, 2, 0, 6, 8, 7, 1, 3, 5, 9)
    , List(1, 7, 5, 0, 9, 8, 3, 4, 2, 6)
    , List(6, 1, 2, 3, 0, 4, 5, 9, 7, 8)
    , List(3, 6, 7, 4, 2, 0, 9, 5, 8, 1)
    , List(5, 8, 6, 9, 7, 2, 0, 1, 3, 4)
    , List(8, 9, 4, 5, 3, 6, 2, 0, 1, 7)
    , List(9, 4, 3, 8, 6, 1, 7, 2, 0, 5)
    , List(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
  )

println(isValidDammOperationTable(exampleLatinSquareX10)) //prints "true"


Q: Unable to set full-text index to 'active' in table-designer In SQL Server 2008 R2 Management Studio, I have set my database to be full-text indexed and ran the command
EXEC sp_fulltext_database 'enable'

along with creating a catalog. When I open the table design mode, and right click the Primary Key, then click Full-Text Indexes in the context menu, I add my columns under the 'General' section, but when I go to set it to Active = Yes, it's grayed out.
How can I change this?  Here is a screen-shot of what it's looking like.
http://snag.gy/2QSDN.jpg

A: For some reason you can't enable or disable the full text index from that screen. Instead you have to right-click the table in Object Explorer, then choose Full-Text index > Enable Full-Text index.


Q: It gives this error while running: undefined is not a function (evaluating '_reactNativr.default.createElement') This section of code is not running it always return en error saying undefined or not a function in the render function().

Heading
'use strict';
import React, {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    AlertIOS,
    Dimensions,
    BackHandler,
    PropTypes,
    Component,
} from 'react-native';

import NavigationExperimental from 'react-native-deprecated-custom-
components';

var _navigator;
//var Navipanel=require('./App/Navigation/Navipanel.js');
var Dashboard= require('./App/Dashboard/dashboard.js');
//var Sample= require('./App/Navigation/sample.js');
var Matches = require('./App/Components/Matches.js');
var Users = require('./App/Components/Users.js');
var SCREEN_WIDTH =require('Dimensions').get('window').width;
var BaseConfig=NavigationExperimental.Navigator.SceneConfigs.FloatFromRight;

var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop,
    {
        snapVelocity: 8,
        edgeHitWidth: SCREEN_WIDTH,
    });

BackHandler.addEventListener('hardwareBackPress', () => {
     if (_navigator.getCurrentRoutes().length === 1) {
         return false;
     }

     _navigator.pop();
     return true;
});

var CustomSceneConfig = Object.assign({}, BaseConfig, {
    // A very tighly wound spring will make this transition fast
    springTension: 100,
    springFriction: 1,
    // Use our custom gesture defined above
    gestures: {
        pop: CustomLeftToRightGesture,
    }
});

//var createReactElement = require('create-react-element');
var createReactClass = require('create-react-class');
var test = createReactClass({
    _renderScene(route,navigator) {
        _navigator = navigator;

        if (route.id === 1) {
            return <Dashboard navigator={navigator}/>;
        }
        else if(route.id === 2) {
            return <Sample navigator={navigator} /> ;
        }
        else if(route.id === 3) {
            return <Navipanel navigator={navigator} /> ;
        }
        else if(route.id === 4){
            return <Matches navigator={navigator} /> ;
        }
        else if(route.id === 5) {
            return <Users navigator={navigator} />
        }
    },

    _configureScene(route) {
        return CustomSceneConfig;
    },

    render:function() {
        return (
            <NavigationExperimental.Navigator  [//error in this line]
            initialRoute = {{id:1}}
            renderScene = {this._renderScene}
            configureScene = {this._configureScene} />
        );
    }
});

Undefined error _reactNative.default.createElement

A: You imported React from "react-native";
import React, {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  Dimensions,
  BackHandler,
  PropTypes,
  Component,
} from 'react-native';

instead of this, you need to import React from "react";
import React from 'react';

When we use JSX in our render functions, in the background JSX runs React.createElement(...). And in your code, React is not defined. Because of this, it gives that error.


Q: Wordpress SQL query different results I added a custom Visual Composer element and want to output a result of a query. However when I output this query(1) it gives other results then when I output this query(2).
// declared vars
global $wpdb;
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;

 1)   $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526 AND guid like '%pdf'", OBJECT );
 2)  $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );

When I output the 526 string(query 1) it gives the right result however I want the output to be with the var because every post has its unique ID.
I've also tried to put the var in a string so it isn't being seen as a POST_ID
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;

Any ideas to where this is failing?
What i've tried in the meantime:
$nn1 = (string)$nn;
$nn2 = strval($nn);
$nn3 = settype($nn, "string");

$results1 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );
$results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn2." AND guid like '%pdf'", OBJECT );
$results3 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn3." AND guid like '%pdf'", OBJECT );
$results4 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = %d AND guid like '%pdf'", $nn3, OBJECT );

All of the above are returning an empty string which means there is still something wrong with the var
When I echo the whole string it returns the right mysql query:
echo ("SELECT guid FROM wp_posts WHERE post_parent = ".$nn."");
//output
SELECT guid FROM wp_posts WHERE post_parent = 526;

When I execute that query, it gives me the right solution:
$results6 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526", OBJECT );
// output
[6]=>object(stdClass)#8030 (1) {
["guid"]=>
string(69) "http://blabla.pdf"}

Greetz

A: None of your tests seem to include the one query you've shown to be working:
$GLOBALS['wpdb']->get_results(
    "SELECT guid FROM wp_posts WHERE post_parent = $nn",
    OBJECT
);

There's no need to do any type conversions, especially not to string. $nn should contain int 526.
full disclosure: I'm not a WP dev and I have no idea how you got from '{{ post_data:ID }}' to 256, also string(18) "526" seems like a very weird output to me. (groetjes aan de daddykaters!)


Q: How to Solve PHP7.2 use of undefined constant priority warning In trying the next PHP 7.2 release out on my site (previously we've been on 7.1 with no problems) I noticed that one of our older scripts suddenly began throwing up this warning.
Warning: Use of undefined constant priority - assumed 'priority' (this will throw an Error in a future version of PHP) in /../plugins.inc.php on line 146
Of course I could hide this as it's only a warning but I'd rather figure out the problem than store them up for PHP8.0. The code it relates to is this block and nothing else in the file appears to be related to it.
function SortByActionPriority($a, $b) {
    return $a[priority] > $b[priority] ? 1 : -1;
}

Sadly this is not a system I'm familiar with (it's an older one) and it has thousands of PHP files, so I'm not entirely sure where else in the program this is being used for full context.


Q: ERLANG - Pattern Matching specifc pattern in unknown size list Ok now I think Im getting warmer, I have to pattern match whatever comes in.
So if I had say
Message = = [[<<>>],
 [<<"10">>,<<"171">>],
 [<<"112">>,<<"Gen20267">>],
 [<<"52">>,<<"20100812-06:32:30.687">>]]

And I was looking to pattern match the field <<"112">>
Such as the 112 is always going to say 112, but the Gen2067 can change whenever to whatever.. its the data, it will be stored in a variable.
Also the fields can be in any order, whatever function im trying to do has to be able to find the field and parse it.
This is the code I am using right now:
loop() ->
receive
    [_,[<<"112">>, Data], _] when is_list(X) -> %% Just dosen't work in anyway..
        ?DEBUG("Got a list ~p~n", [X]),
        loop();
    _Other ->
        ?DEBUG("I don't understand ~p~n", [_Other]),
        loop()
end.

I feel im close, but not 100%
-B

A: You can extract your data this way:
1> Message = [[<<>>],
1>  [<<"10">>,<<"171">>],
1>  [<<"112">>,<<"Gen20267">>],
1>  [<<"52">>,<<"20100812-06:32:30.687">>]] .
[[<<>>],
 [<<"10">>,<<"171">>],
 [<<"112">>,<<"Gen20267">>],
 [<<"52">>,<<"20100812-06:32:30.687">>]]
2> [Data] = [X || [<<"112">>, X] <- Message ].
[<<"Gen20267">>]
3> Data.
<<"Gen20267">>

Another way:
4> [_, Data] = hd(lists:dropwhile(fun([<<"112">>|_]) -> false; (_)->true end, Message)).
[<<"112">>,<<"Gen20267">>]
5> Data.
<<"Gen20267">>

And another one as function in module (probably fastest):
% take_data(Message) -> Data | not_found
take_data([]) -> not_found;
take_data([[<<"112">>, Data]|_]) -> Data;
take_data([_|T]) -> take_data(T).


Q: Getting multiple ints from string I have a string:
"3, V, 11, H, 21, H"

and I am trying to get
int first = 3
int second = 11
int third = 21

I'm not exactly sure how to do this since the numbers could be one or two digits, there are non-digit characters between the numbers, and I have to capture multiple numbers. I tried regex but then I'm left with "31121" which does not indicate what the three numbers are.

A: Try this code. Should get you the job done.
public static void main(String[] args){
    String s = "3, V, 11, H, 21, H";
    String[] t = s.split(" [ ,]*|,[ ,]*");
    int first = Integer.parseInt(t[0]);
    int second = Integer.parseInt(t[2]);
    int third = Integer.parseInt(t[4]);
    System.out.println(first);
    System.out.println(second);
    System.out.println(third);
}

A: You can split your String by "," and check if it's a number using  NumberUtils.isNumber (String str) from org.apache.commons.lang.math.NumberUtils :

Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier,
  scientific notation and numbers marked with a type qualifier (e.g.
  123L).
Null and empty String will return false.

String s = "3, V, 11, H, 21, H";
for(String st : s.split(",")){
    if(NumberUtils.isNumber(st.trim()))
        System.out.println(st);
}

If you want to check that the String contains only digits, you can use NumberUtils.isDigits(String str)

A: public static void main(String[] args) {

    String in = "3, V, 11, H, 21, H";

    List<String> storage = Arrays.asList(in.split(","));
    List<Integer> output = new ArrayList<Integer>();

    int first = 0;
    int second = 0;
    int third = 0;

    for(String str : storage){
        if(str.trim().matches("[0-9]+") ){ // or if(NumberUtils.isNumber(str) )
            output.add(Integer.parseInt(str.trim()));
        }
    }

    if(output.size() == 3){
         first = output.get(0);
         second = output.get(1);
         third = output.get(2);
    }

    System.out.print("first: "); System.out.println(first);
    System.out.print("second: "); System.out.println(second);
    System.out.print("third: "); System.out.println(third);

}

Output:
first: 3
second: 11
third: 21

A: You can split this string by , and then check if every part is a number like this :
import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        String str = "3, V, 11, H, 21, H";
        String[] parts = str.split(", ");
        ArrayList<Integer> listNumbers = new ArrayList<Integer>();
        for(String x : parts){
         try{
           listNumbers.add( Integer.parseInt(x) );
         }
         catch(Exception e){}
        }

        for(int i=0;i<listNumbers.size();i++) System.out.println("Number "+(i+1)+" : "+listNumbers.get(i));
    }

}


Q: Facebook api shows only statuses of the last year i'm working with a facebook app that  aims to show all user statuses, after a couple of questions here on stackoverflow ,  i got this (almost )working.
The problem is that graph api show only statuses of last year.
Is not a script problem because if i use the Graph Api explorer tool , the json output is the same (now - october 2013).
tested with several facebook account, same problem.
Any idea / help? thanks
UPDATE:
Basically i get data from : https://graph.facebook.com/v2.1/me?fields=statuses (this is from Explorer api tool), script code is
" $request = new FacebookRequest( $session, 'GET', '/me/statuses' ); "

In both ways i got same result. (using explorer tool or by script). few statuses and i cant go back untill very old statuses.
But the problem is not my code , i'm asking because maybe there are some limitation , not listed in docs. As Wizkid suggest i've filed a bug.

A: Is a Bug.
https://developers.facebook.com/bugs/298184123723116/

We have managed to reproduce this issue and it appears to be a valid
  bug. We are assigning this to the appropriate team.


Q: How to set the background of a custom shaped ImageButton in a RecyclerView? In a recyclerView I have list of imageButtons with a custom shape applied as the background of all ImageButtons. Each ImageButton currently has a solid color from a colorlist: colors[]
This is how it looks right now:

I want to put a icon.png in the place of index 0 (brown colored button) instead of the solid color. So far I have used many days of trying to find a solution myself but without any succses.
Here is all relevant code:
This is the code in the recyclerView adapter that sets the colors:
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    Drawable drawable = holder.colorButton.getBackground();

    //This is here where each ImageButton gets a color from the colorlist colors[]

    if (drawable instanceof GradientDrawable) {
        GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
        gd.setColor(Color.parseColor(colors[position]));

        //This does nothing
    } else if (drawable instanceof RippleDrawable) {
        RippleDrawable rd = (RippleDrawable) drawable;
        int color = Color.parseColor(colors[position]);
        rd.setColor(newColorStateList(color));
    }
}

The colorStatList code for each imageButton:
 private static ColorStateList newColorStateList(int color) {
    int[][] states = new int[][]{

            new int[]{android.R.attr.state_enabled}, // enabled
            new int[]{-android.R.attr.state_enabled}, // disabled
    };

    int[] colors = new int[]{
            color, color
    };
    return new ColorStateList(states, colors);
}

My Custom button for the recyclerView Adapter:
public class ColorButton{

private ImageButton button;
private String color;
public static List<ColorButton> colorButtonList;

public ColorButton(ImageButton button, String color) {
    this.button = button;
    this.color = color;
}

static ColorButton colorButton = new ColorButton(new ImageButton(App.getAppContext()), null);

public static List<ColorButton> initColorButtons(){
    colorButtonList = new ArrayList<>();

    Resources resources = App.getAppContext().getResources();
    String colors[] = resources.getStringArray(R.array.backgroundcolors);

    for(int i=0; i<colors.length; i++){

        colorButtonList.add(new ColorButton(new ImageButton(App.getAppContext()), colors[i]));
    }

    return colorButtonList;
}

You may wonder why I have String color;
This is for setting the background color of my app when the user clicks on a colorbutton:mEditText.setBackgroundColor(Color.parseColor((mColorButtons.get(position).getColor())));

A: Try this:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position ==0){
holder.colorButton.setBackgroundResource(R.drawable.colorpicker2);
}
else
{
GradientDrawable gd = context.getResources().getDrawable(R.drawable.bbshape);
gd.setColor(Color.parseColor(colors[position]));
holder.colorButton.setBackGroundDrawable(gd);
}
}


Q: How to clean JVM heap memory in spark scala or pyspark How to clean my JVM occupied memory in spark scala streaming application. I am running streaming job which is in 60 sec interval of time. For my first six hours no issue after that, I am facing JVM heap memory issue. Is there any way programmatically I can clean my GC or JVM memory in spark scala.
In my application, I am using Dataframe, registertemptable also end of my program I am writing the result into HDFS. Presently in my application spark SQL context level, I am uncaching, like this any other way we can release the memory?
Error msg: Exception in thread "dag-scheduler-event-loop" java.lang.outofmemoryError: Java heap space
Thanks
Venkat

A: I would suggest you to see if there is any thread leak in the application.
You can look at the thread dump in the application master near the executor logs.
Try to set this parameter. --conf spark.cleaner.ttl=10000.
If you are using cache I would suggest you to use persist() it in both memory and disc