text:
Q: Change NODATA pixel value in raster to arbitrary value I want to change the value in all pixels that are currently 0 to 800 in QGIS 2.6.1. 0 is listed as the no-data value in Properties > Transparency. I have unchecked the No Data Value box there. Then I have tried the following.
1) Set Settings > Option > Data Sources > Representation for NULL Values = 800. Save as... to make a new .tif raster layer, WITH and WITHOUT specifying a range for No Data Values in the Save As... dialog. I thought that maybe a range from -1 to 1 would handle real-representation zeroes better. Either way, the raster returned is just like the original, with no change to the no-data (value=0) pixels.
2) Processing Toolbox > Geoalgorithms > Raster > General Tools > Raster Calculator, with expression: ifelse(lt(a,1), (800), a). Still no dice, the no-data value is now -99999.
3) Raster menu > Raster Calculator, with expression: ("my layer here@1" >= 0) * "my layer here@1". Interestingly, now the no-data value is -3.40282...E+38.
4) Processing Toolbox > Geoalgorithms > Raster > Edition > Reclassify Grid Values. This tool didn't work at all. Tried [0] Single, [1] Range, and [2] Simple Table options, with and without saving to a file. Log gave a bunch of errors about being unable to load modules. The path to the .dlls is correct.
5) Processing Toolbox > Geoalgorithms > Raster > Edition > Reclassify (Simple), with range option -1 to 1. Returned a raster with the no-data value = -99999.
For the record, all tests were done with the Null Representation = 800, but I also tried several of the methods with the default representation of NULL. Results were the same. I have also exported the raster as XYZ format and looked at it in CloudCompare; the null values are being expressed as the value reported in Properties > Transparency.

A: You can use the r.null.to function via GRASS to transform all NULL value cells into a user-defined value, which in your case is 800:

Note: You will have to create a GRASS Mapset before you can use r.null.to as it is not available in the Processing Toolbox. Once you created a mapset, use the GRASS option to add a raster layer, select Open GRASS Tools and search the Module list:


text:
Q: Gmail gadget's "RecipientToEmailExtractor" doesn't return all recipients email addresses I have a Gmail contextual gadget app that uses some of the Google-offered content extractors.
I have noticed that the "google.com:RecipientToEmailExtractor" recently only returns one email address even if the email has multiple recipients. It used to work properly for me a while back, returning multiple addresses separated with ";".
Did anybody else encounter this problem? Is this a Google bug?

A: I too am using the google.com:RecipientToEmailExtractor extractor and when I have multiple emails in the to: field, I get multiple matches. ie. The result of the following call
google.contentmatch.getContentMatches()

Returns and array of the same length as their are emails in the to: field. Each member of the array is a js object with a key name of recipient_to_email and a value of the actual email.
The fact that you mentioned it used to return all addresses separated by a ; character suggests something may have changed

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPanel's size in function of another JPanel I would like to adjust the size of a JPanel in function of another panel which contains it.
When I run my code, the panel is tiny and centered on the top of the content panel.
So here's my code :
package test;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class CodeForStackOverFlow {
    public static void main(String[] args) {
        Frame frame = new Frame();
    }
}

class Frame extends JFrame {

    private class Panel extends JPanel {

        private JPanel content = new JPanel();

        Panel() {
            content.setBackground(Color.red);
            this.add(content);
        }

        void adjustSize() {
            this.content.setSize(new Dimension(this.getHeight(), this.getHeight()));
        }
    }

    private Panel contentPane = new Panel();

    Frame() {
        this.setSize(new Dimension(500, 400));
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.setContentPane(contentPane);
        contentPane.adjustSize();

        this.setVisible(true);
    }
}


text:
Q: In laravel how a super user to update a specific user with a user id I am creating an admin section where super user needs to edit another user details with specific id. Like User::create, how can I update user details?
if( empty($user_id) ){
    User::create([
        'name' => $data['name'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'mobile' => $data['mobile'],
        'role' => $data['role'],
        'password' => Hash::make($data['password']),
    ]);
}else{
    //update user details
}

A: There's a couple of options:
Here's one:
if (empty($user_id) ){
      User::create([
         'name' => $data['name'],
         'lastname' => $data['lastname'],
         'email' => $data['email'],
         'mobile' => $data['mobile'],
         'role' => $data['role'],
         'password' => Hash::make($data['password']),
      ]);

} else{
      User::where('id', $user_id)->update([
         'name' => $data['name'],
         'lastname' => $data['lastname'],
         'email' => $data['email'],
         'mobile' => $data['mobile'],
         'role' => $data['role'],
         'password' => Hash::make($data['password']),
      ]);
}

Another way would be:
 User::find($user_id)->fill([
    'name' => $data['name'],
    'lastname' => $data['lastname'],
    'email' => $data['email'],
    'mobile' => $data['mobile'],
    'role' => $data['role'],
    'password' => Hash::make($data['password']),
 ])->save();

The first way does the update in a single query so is faster but the 2nd way will trigger the model events like saving and updating so pick what you need.

A: You can try :
$user= User::firstOrCreate(
   [
       'unique_field_name' => 'value'
   ],
   [
      'name' => $data['name'],
      'lastname' => $data['lastname']
   ]
);

unique field name as email or user id or mobile number which are unique fields in your database

A: User::updateOrCreate(array('user_id' => $user_id), [
    'name' => $data['name'],
    'lastname' => $data['lastname'],
    'email' => $data['email'],
    'mobile' => $data['mobile'],
    'role' => $data['role'],
    'password' => Hash::make($data['password']),
]);

A: You can use the fields with the same name in the database table columns to fill them without putting them again in eloquent
like that:
$user = User::create($request->validated());

and in update :
$user = User::find($id)->update($request->validated());


text:
Q: flutter problem: how to manage height in tabbar I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
this is my cwctv page.
@override
  Widget build(BuildContext context) {
    return Scaffold(backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.black),
        automaticallyImplyLeading: true,
        backgroundColor: Colors.white,
        elevation: 0.5,      ),
      drawer: Drawer(
        child: SideBar(),
      ),
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(top: 18.0),
        child: Container(
          height: 80,
          width: 80,
          child: FittedBox(
            child: FloatingActionButton(
              focusColor: Colors.transparent,
              backgroundColor: selectBlueColor,
              onPressed: () {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => HomePage()));
              },
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              child: Image.asset(
                'assets/home_icon.png',
              ),
              elevation: 1.0,
              highlightElevation: 2,
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: Container(
          // height: MediaQuery.of(context).size.height * (10 / 100),
          child: BottomNavBarTV()),
      body: Stack(
        children: [
          Padding(
              padding: const EdgeInsets.only(left: 16.0,right: 16,bottom: 4,top: 0),
              child: SizedBox(
                  height: 60,
                  child:  TextField( keyboardType: TextInputType.text,
                          onChanged: (value) {
                            setState(() {
                              print("tab on cwctv page $cwcTvTab");
                            });
                          },
                          // controller: cwcTvTab == 3 ?searchImageQuery : cwcTvTab == 2 ?searchPdfQuery : cwcTvTab == 1 ? searchAudioQuery : searchVideoQuery,
                          controller: searchQuery,
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                              borderSide: BorderSide.none,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF1F2F6),
                            hintText: 'Search for Wellness Tips & Tricks',
                            suffixIcon: const Icon(
                              Icons.search_outlined,
                              color: Color(0xFF444444),
                            ),
                          ),
                        )
                     )),
          Padding(
            padding: EdgeInsets.only(top: 70.0),
            child: TestScreen(widget.selectTab),
          ),

          // CwcTVPageChanger(),
          // VideoComponent(),
        ],
      ),
    );
  }

This is my tab screen page.
import 'package:cwc/constants/constants.dart';
import 'package:cwc/ui/CwcTv/components/images/image_document.dart';
import 'package:cwc/ui/CwcTv/components/podcast/podcast_list.dart';
import 'package:cwc/ui/CwcTv/components/slides/slide_component.dart';
import 'package:cwc/ui/CwcTv/components/videos/video_component.dart';
import 'package:cwc/ui/CwcTv/cwc_tv.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:cwc/constants/constant_functions.dart';

class TestScreen extends StatefulWidget {
  int selectedPage;

  TestScreen(this.selectedPage);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  void _handleTabSelection() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        // _tabSection(context, widget.selectedPage,controller!),
        _tabSection(context, widget.selectedPage),
      ],
    );
  }
}

Widget _tabSection(BuildContext context, var selectedPage) {
  return DefaultTabController(
    initialIndex: selectedPage,
    length: 4,
    child: SafeArea(
      child: Column(
        // mainAxisSize: MainAxisSize.min,
        children: [
          TabBar(
            indicatorColor: Colors.black,
            onTap: (v) {

              cwcTvTab = v;

            },
            isScrollable: true,
            // physics: NeverScrollableScrollPhysics(),
            labelColor: Colors.black,
            tabs: [
              Tab(
                child: Text(
                  'Video',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Podcast',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Documents',
                  style: GoogleFonts.poppins(
                    color: Colors.black,
                  ),
                ),
              ),
              Tab(
                child: Text(
                  'Images',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
            ],
          ),
          Container(
            height: MediaQuery.of(context).size.height - 282,
            // height: MediaQuery.of(context).size.height - 205,
            // height: double.infinity,
            child:
                TabBarView( physics: NeverScrollableScrollPhysics(),
                    children: [
              VideoComponent(),
              PodcastList(),
              SlideComponent(),
              ImageDocument(),
            ]),
          ),
        ],
      ),
    ),
  );
}

this is my android Device's screenshot.

this is my IOS Device's screenshot.

A: There is 2 options you can use, first try with indicator like this one:
TabBar(
        indicator: UnderlineTabIndicator(
          borderSide: BorderSide(width: 5.0),
          insets: EdgeInsets.symmetric(horizontal:16.0)
        ),
        indicatorColor: Colors.black,
        onTap: (v) {

          cwcTvTab = v;

        },
        isScrollable: true,
        // physics: NeverScrollableScrollPhysics(),
        labelColor: Colors.black,
        tabs: [
          Tab(
            child: Text(
              'Video',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Podcast',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Documents',
              style: GoogleFonts.poppins(
                color: Colors.black,
              ),
            ),
          ),
          Tab(
            child: Text(
              'Images',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
        ],
      ),

Or you can just wrap it with a container.
    PreferredSize(
      preferredSize: const Size.fromHeight(10),
      child: Container(
        height: 50,
        child: TabBar(
          indicatorColor: Colors.black,
          isScrollable: true,
          labelColor: Colors.black,
          tabs: [
            Tab(
              child: Text(
                'Video',
              ),
            ),
            Tab(
              child: Text(
                'Podcast',
              ),
            ),
            Tab(
              child: Text(
                'Documents',
              ),
            ),
            Tab(
              child: Text(
                'Images',
              ),
            ),
          ],
        ),
      ),
    ),


text:
Q: javascript how do i find which elements contain a background image using the style attribute I am trying to add script to a web page that is generated as part of a go-daddy web site.
The image is presented in a div as a background image that was set using the style attribute.
style="background-image: url("//img1.wsimg.com/isteam/ip/c77f0810-0ea1-4425-b963-0e5820c70a3f/5a18a70f-82dc-45b6-bfb8-8f8e7ff1c875.jpg/:/cr=t:0%25,l:0%25,w:100%25,h:100%25/rs=w:1400,h:400,cg:true,m/cr=w:1400,h:400,ax:c,ay:c");"

The id of the div container is generated automatically and changes between runs.
Is there anyway I can find the elements on the page that have a background image set in the HTML style attribute using plain javascript ?

A: Try this:
var elements = document.body.getElementsByTagName("*")

for (var i = 0 ; i < elements.length ; i++) {
 if (elements[i].style.backgroundImage) {
    // DO SOMETHING HERE
    alert(elements[i].id + " has background image")
 }
}

https://jsfiddle.net/ckrm2eLL


text:
Q: How to get javascript caller source line number in SpiderMonkey JSNative callback? I want to implement a C++ function working like console.log. I need to know javascript caller's source line position in C++. I search MDN JSAPI/JS Debugger API documents but no result.
A concept usage in javascript.
console.log("blahblahblah");

And expected logic in C++.
JSBool consoleLog(JSContext *cx, unsigned argc, jsval *vp) {
    // expect to get caller info including filename, lineno.

    // write "blahblahblah" and caller info in my log system.

    return JS_TRUE;
}

==============
UPDATE
I finally find a way to get filename and lineno. Error handling code is omitted.
#include "jsdbgapi.h"

JSBool consoleLog(JSContext *cx, unsigned argc, jsval *vp) {
    JSScript *script;
    unsigned int lineno;
    JS_DescribeScriptedCaller(cx, &script, &lineno);
    const char *filename = JS_GetScriptFilename(cx, script);

    // use filename and lineno to write log...

    return JS_TRUE;
}

A: Generally you have to use the currently active function frame on the JS stack, accessible through cx -- that would tell you about the script and currently executing bytecode. Though I can't remember the exact API off the top of my head, there's some function that will produce lineno from that data (don't be avoid to forgo the docs and start reading jscntxt.h and friends, seeing as how the docs can be outdated -- they're not auto-generated).
There's also a caveat in that JSNatives conceptually execute in their caller's stack frame, so calling consoleLog from another JSNative it won't say something like <native code>. It'll only effectively do what you want when invoked from a JS-code caller.


text:
Q: Format Kotlin with minimal indent for code blocks in constructor parameters, like Foo({ bar }) When formatting this code block (from the Kotest documentation), Jetbrains Intellij or Android Studio adds a lot of unnecessary white space.
Original code:
class MyTests : FreeSpec({
     "String.length" - {
         "should return the length of the string" {
             "sammy".length shouldBe 5
             "".length shouldBe 0
         }
     }
})

After formating with ctrl+alt+L, this becomes
class MyTests : FreeSpec({
                             "String.length" - {
                                 "should return the length of the string" {
                                     "sammy".length shouldBe 5
                                     "".length shouldBe 0
                                 }
                             }
                         })

Is there a formatting setting to adjust this behavior?
I strongly suspect that there is a working combination of settings in Editor -> Code Style -> Kotlin, but after trying out various combinations I could not figure it out.

A: I tried to format your snippet in Android Studio Giraffe 2022.3.1 Canary 6 and it remains intact:

I suggest you to try a fresh installation of Android Studio/IntelliJ together with a fresh app using Kotest and see if the issue resurfaces.
If it doesn't then you can compare the following files of the two projects to figure out the difference:
$projectRootDir/.idea/codeStyles/Project.xml

A: You may duplicate a formating scheme to alter safely or just do the following things.
Editor > Code Style > Kotlin > Wrapping and Braces > Function call arguments
Uncheck Align when multiline
I also use Kotest FreeSpec. This was the tweak I made to have nice formatting.


text:
Q: Horizontally Align Position Fixed Div I've read a lot of the options on here to achieve this but for some reason i can't get anything to work the way i want it.
I'm trying to get a countdown timer to always stay horizontally centered. The problem is that because it changes ever so slightly with every second countdown i need it to have a position fixed, otherwise the start numbers jump left and right a little bit as the last number changes fractionally in size between different numbers .. Make sense ?
So giving it a fixed position allows the numbers to change smoothly, however it makes it very difficult to center perfectly, as once again the width changes depending on where the counter is set.
I've set up a little JSFiddle if anybody would be so kind as to take a look.
Greatly appreciated.

MATRIX

JSFiddle

A: Add the following to your CSS:
div#countdown {
    left: 50%; /* move #countdown's left edge to center */
    transform: translateX(-50%); /* shift #countdown to the left by half of it's width */
    white-space: nowrap; /* keep #countdown from word-breaking */
}

// set the date we're counting down to
            var target_date = new Date('Dec, 25, 2016').getTime();

            // variables for time units
            var days, hours, minutes, seconds, ms_step = 10;

            // get tag element
            var countdown = document.getElementById('countdown');

            setInterval(function () {
                var current_date = new Date().getTime();
                var seconds_left = (target_date - current_date) / 1000;
                days = parseInt(seconds_left / 86400);
                seconds_left = seconds_left % 86400;
                hours = parseInt(seconds_left / 3600);
                hours = hours < 10 ? '0' + hours : hours;
                seconds_left = seconds_left % 3600;
                min = parseInt(seconds_left / 60);
                min = min < 10 ? '0' + min : min;
                sec = parseInt(seconds_left % 60);
                sec = sec < 10 ? '0' + sec : sec;
                ms = parseInt(target_date - current_date);

                // format countdown string + set tag value
                countdown.innerHTML = '' +
                        '' + days + ': ' +
                        '' + hours + ': ' +
                        '' + min + ': ' +
                        '' + sec + '';
                // this is just for milliseconds only
                /* countdown.innerHTML =
                 ''+ms+' ms'; */
            }, ms_step);
html {
    background: url(../images/main_bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/main_bg.jpg', sizingMethod='scale');
    -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/main_bg.jpg', sizingMethod='scale')";
  background-color: lightgray;
}

html:after {
    content: "";
    background: url(../images/overlay.png) repeat;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

body{
    background-color : transparent;
    height:100%;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
}

.navbar {
    min-height : 90px;
}

.navbar-brand {
    position: absolute;
    width: 100%;
    left: 0;
    top: 10px;
    text-align: center;
    margin: auto;
}

.navbar-brand h1 {
    font-size : 36px;
    font-weight : 200;
    margin: 0px;
    color : #000;
}

.navbar-toggle {
    z-index:3;
}

.container {
    height:100%;
}
div#countdown {
    position: fixed;
    top: 230px;
    left: 50%; /* move element's left edge to center */
    transform: translateX(-50%); /* shift element to the left by half of it's width */
    white-space: nowrap; /* keep countdown from word-breaking */
}
#countdown span {
  font-family: 'Oswald', sans-serif;
  color: #fff;
  font-weight: 100;
}

#countdown span {
    display: inline-block;
    font-size: 50px;
    line-height: 60px;
    letter-spacing: 0.13em;
}

MATRIX


text:
Q: Firebase: Secure and atomic transfer of "credits" between user accounts A transaction of x "credits" from user account A to user account B. Security constraint: The transaction can only take place if there exists a corresponding application from user A to user B with status accepted and amount x. Once the transaction is complete the application status needs to be set to resolved.
Is it possible with Firebase to implement this transfer of credits atomically, so I don't end up with inconsistent data e.g. lost or generated credits, application status not 'resolved'...
I see how I can enforce the aforementioned security constraint with Firebase's rules, since I can reference and compare to data in arbitray paths within them.
But Firebase's transactions seem to only operate on a single path. So the only solution I see is implementing credits and applications on a single path and a user's number of credits is calculated by their history of 'applications'. Is this solution feasable?


text:
Q: CompletableFuture promises & Java Reflection I'm using a service that gives me back a CompletableFuture promise, the thing is, i can only access its methods through reflection which is working just fine.
But treating the return of the promise is leaving me puzzled.
Normally one would use something like this to work with a CompletableFuture:
promise.thenApply(returnValue -> {
                //do something with it
             });

How would one do that with reflection?
promise.getClass()
                .getMethod("thenApply", ??)
                .invoke(retorno, ??);

Basically i want to pass a Lambda function to treat the returning of my promise but i'm unsure on how to do it and if it's possible to do it.

A: CompletableFuture is part of the JDK so it will be loaded by the same parent classloader.
You should thus be able to cast your promise to CompletableFuture<?> and call thenApply() on it, with reflection inside the passed-in Function if needed.


text:
Q: How I can encode every file (not only bitmaps) to base64? I'm looking for a solution of my problem which is connected with encoding files to base64 and sending to my server. I found a solution for encoding bitmaps in the Internet:
public static String bitmapToEncodedString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    return Base64.encodeToString(imageBytes, Base64.NO_WRAP);
}

but this solution can be used only for bitmaps, and what about pdf-files or doc or smth like that. Maybe someone has a good solution for my problem? I will be so pleased if you will give me a solution of my problem.


text:
Q: android x design dependency How can I import androidx design dependency
I have tried to import : implementation 'androidx.design:design:1.0.2'
app compact version is : implementation 'androidx.appcompat:appcompat:1.0.2'
I have got this error -

ERROR: Failed to resolve: androidx.design:design:1.0.2

A: To know equivalent for new Androidx Artifacts from old build artifacts, please refer the below link
https://developer.android.com/jetpack/androidx/migrate/artifact-mappings
note: answer by Poyyamozhi Ramakrishnan is correct and I posted my answer for better understanding.

A: try this:
implementation 'com.google.android.material:material:1.0.0'

A: implementation 'com.google.android.material:material:1.2.0-alpha02'
Just copy paste this one in to your dependencies.

A: There is no design library in androidx. It uses material library. Get more info at
this

A: implementation 'com.google.android.material:material:1.2.0-alpha06'
Try this latest dependency.

A: Try this: 'com.google.android.material:material-rc01'


text:
Q: Python: how to add curves in an image I have an image as follows:

The image is generated in Python. I want to further plot a curve on top of the image, which encloses the white region. I have already got the pixel indices for the region border. I know in Matlab, e.g., it can be simply done by :
hold on
plot(x,y,'r-') %x and y are the indices of boundary pixels.

The resultant image should be like this:

How can I do that contour on top of the image in Python, not by cv2.drawContours? Anyone can help me with the problem?

A: You can use the Pillow library for it. Without going into the whole solution, there's a good example in their tutorial on how to read an image an do some postscript drawing on top of it: https://pillow.readthedocs.io/en/4.1.x/handbook/tutorial.html#drawing-postscript
You pretty much only need to change the rectangle to a circle instead.
The cut down example is:
from PIL import Image
from PIL import PSDraw

im = Image.open("lena.ppm")
box = (1*72, 2*72, 7*72, 10*72) # in points

ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)

# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)

ps.end_document()

PS. I'm assuming that by "I have an image as follows:" you mean, you have an image file and want to process that, not that you're generating that graph in python already. If you're using something like matplotlib to generate it in the first place, you can add it there instead.
If you're already doing it in matplotlib, then the question is likely a duplicate of matplotlib: add circle to plot


text:
Q: a partition device does not exist, though present on fdisk -l On Centos 7.7 I run commands:
# dd if=/dev/zero of=/root/500MB.img bs=1M count=500
500+0 records in
500+0 records out
524288000 bytes (524 MB) copied, 0.374844 s, 1.4 GB/s
# losetup --all
# losetup /dev/loop0 ./500MB.img
# losetup --all
/dev/loop0: [64768]:33575036 (/root/500MB.img)
# fdisk -l /dev/loop0

Disk /dev/loop0: 524 MB, 524288000 bytes, 1024000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
# fdisk /dev/loop0
[here set partition]
# fdisk -l /dev/loop0

Disk /dev/loop0: 524 MB, 524288000 bytes, 1024000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x2b7a6a60

      Device Boot      Start         End      Blocks   Id  System
/dev/loop0p1            2048     1023999      510976   83  Linux
#

However the /dev/loop0p1 doesn't exist in the system:
# pvcreate /dev/loop0p1
  Device /dev/loop0p1 not found.
# ls -ld /dev/loop0p1
ls: cannot access /dev/loop0p1: No such file or directory
# kpartx -l /dev/loop0
loop0p1 : 0 1021952 /dev/loop0 2048
# ls -ld /dev/loop0p1
ls: cannot access /dev/loop0p1: No such file or directory

Only the loop-disk device exists:
# ls -ld /dev/loop0
brw-rw----. 1 root disk 7, 0 Apr 23 09:31 /dev/loop0

Where is the partition showed on "fdisk -l"?
Update:
Fixed thanks to Stephen Kitt's hints.
All steps run to fix:
# losetup -d /dev/loop0
# losetup --all
# ls /dev/loop0
/dev/loop0
# fdisk -l /dev/loop0
fdisk: cannot open /dev/loop0: Inappropriate ioctl for device
# fdisk -l ./500MB.img

Disk ./500MB.img: 524 MB, 524288000 bytes, 1024000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x2b7a6a60

      Device Boot      Start         End      Blocks   Id  System
./500MB.img1            2048     1023999      510976   83  Linux
# losetup -P /dev/loop0 ./500MB.img
# losetup --all
/dev/loop0: [64768]:33575036 (/root/500MB.img)
# ls -ld /dev/loop0*
brw-rw----. 1 root disk   7, 0 Apr 23 10:16 /dev/loop0
brw-rw----. 1 root disk 259, 0 Apr 23 10:16 /dev/loop0p1
#

A: You need to tell the kernel to scan the partitions; one way to do that is to use losetup, assuming your partition table is written before the device is mounted:

*

*run fdisk on your image

*check the partition table with fdisk -l on the image

*add the -P option to losetup: losetup -P /dev/loop0 ./500MB.img
The last step will scan the partitions in the loop device, and you'll see /dev/loop0p1.


text:
Q: How can I set a fiscal month callendar, or sort the calendar from 10/Oct to 09/Sept? I need to sort Months by our company's fiscal calendar. As of now i can only be sorted alphabetically, April August,December, Feb..
I need it to sort October-September
Fiscal Year Month Name COUNT(DISTINCT CTL_NO)
2019        April                         437
2019        December                      707
2019        February                      600
2019        January                       730
2019        March                         542
2019        November                      745
2019        October                       955
2018        April                         600
2018        August                        902
2018        December                      728
2018        February                      593
2018        January                       745
2018        July                          812
2018        June                          704
2018        March                         671
2018        May                           589
2018        November                      590
2018        October                       769
2018        September                     810

A: One way to do it is to use a CASE expression to set your sort key. Because your table appears to store months as strings we need to convert them to DATE. Once we have a DATE datatype we can extract the month number, which we can use to sort
SELECT Fiscal_Year, Month_Name, COUNT(DISTINCT CTL_NO)
  FROM SOME_TABLE t
 group by Fiscal_Year, Month_Name
  ORDER BY Fiscal_year
           , CASE TRIM(TO_CHAR(to_date(Month_Name,'Month'), 'MM'))
              WHEN '10' THEN -2
              WHEN '11' THEN -1
              WHEN '12' THEN 0
              ELSE TO_NUMBER(TO_CHAR(to_date(Month_Name,'Month'), 'MM'))
            END

This is fine for one-off usage such as a school assignment, but it's not very robust and must be repeated every time you need it.
A much better way is to have a fiscal calendar table which tells you what fiscal year, fiscal month, fiscal week, etc, it is for every calendar day of every year. That's only 365/366 rows per year so there's not a lot of overhead. Tables such as this are commonly populated several years in advance of "now", and the data for past years is left in place for basically ever so that past dates can be looked up and the related fiscal dates determined easily.
Best of luck.


text:
Q: How to airflow variable with value containing foreign characters? I am trying to create an Airflow variable from the UI with the value containing foreign characters.  The Airflow variable is created successfully but the value is shown as invalid and the content/value is removed.
Below is an example of the variable value:
{
  "greeting": "你好"
}

Does Airflow support Airflow variables with values containing foreign characters?  Is there a configuration change in airflow.cfg that can allow this without having to change the Airflow code?
Thank you in advance.

A: Airflow supports UTF-8 by default but you can set it by changing environment variable AIRFLOW__CORE__SQL_ENGINE_ENCODING or changing sql_engine_encoding in airflow.cfg (see docs)
I'm having no trouble with creating such variable in Airflow 1.10.14


text:
Q: Aurelia - boosting performance of repeat.for view rendering I have a so called chat view that basically consists of a repeat.for that loops over all the messages and renders the message views using <compose>.
The problem is that it becomes quite slow once the message count exceeds 50 and the user navigates between chats (which triggers the repeat.for update, as I replace the dataset in the VM).
I feel like I am doing something wrong in regards of handling a view like this. Can I get some input regarding other alternatives?
I have tried UI virtualization, but unfortunately the current plugin does not offer support for features that I require (variable height items, bottom-up alignment).
I have also done quite a bit of optimizations regarding bindings, most are one-time and updates to the dataset are debounced. But this did not improve things, as the main bottleneck is the initial load (binding the views the first time).
Thanks!
Example of current approach:
<li repeat.for="message of chat.messages">
  <compose  view-model.bind="getMessageViewFromMessage(message) & oneTime"
            model.bind="message & oneTime"
            containerless>
  </compose>
</li>

A: I think you need to consider not using <compose> at all for this. Is there a reason you need <compose>? When you think about it, the <compose element has to re-run through the same view instantiation/binding logic Aurelia does for everything else, every time a message is displayed.
I would personally create a HTML partial with some bindable properties and inside of the loop, reference it. So you might have chat-message.html and then display it like this:
<li repeat.for="message of messages">
    <chat-message message.bind="message"></chat-message>
</li>

Where possible and in most cases it should be, avoid dynamic composition for potentially large sets of repeated items.

A: You should check out the aurelia-ui-virtualization library. Once you load it, you can replace repeat.for with virtual-repeat.for in places like this and you'll get a virtualized repeater that will help improve perf with this type of situation.


text:
Q: how to monitor dangling pointers that points to leakded memory? lets think we have a code like this :
 int * ptr = new int;
 int *nptr = ptr
 int * ptr2 = new int;
 int *nptr2 = 2*nptr+ptr2;
 delete ptr;
 delete ptr2;
 ptr = NULL;
 ptr2 = NULL;

So now the nptr and nptr2 is dangling pointer .I know that we can overload new allocating function to trace leaked memory (if we dont use delete command in code ) but dont know how to trace or monitor dangling pointers .

A:
dangling pointers that points to leakded memory?

A pointer that has leaked, by definition is not being pointed by anything. A dangling pointer by definition points to memory that hasn't been leaked. This is a contradiction.

int *nptr2 = 2*nptr+ptr2;

This is ill-formed. Pointers cannot be multiplied by integers, and pointers cannot be added to pointers (I'm assuming the assumption is that result of the ill-formed multiplication is also a pointer). Furthermore, if this pointer arithmetic produced anything other than nptr,  nptr+1, nptr2, nptr2+1, then the result would technically be undefined.

but dont know how to trace or monitor dangling pointers .

It's perfectly fine and normal to have dangling pointers. What isn't fine is indirecting through dangling pointers or relying on their value. At least for indirection, you can use an address sanitiser to try catch such bugs. It can find some uses of dangling pointers particularly those to dynamic memory such as the pointers in the question. It's not as good at detecting dangling pointers to automatic variables. On the other hand, compiler can catch simple cases such as returning pointer to local variable.
Alternatively, you can modify your program to use std::shared_ptr so that as long as you still hold a shared pointer, it cannot become dangling. This comes at a small cost of overhead, but it makes it much easier to reason about lifetime correctness.

A: First of all "dangling pointers that points to leakded memory" makes no sense. I suppose you mistakenly use "leaked memory" for objects that are already destroyed. In your code there is no memory leak. You have a memory leak when you do not have a pointer to some dynamically allocated obejct anymore, as in:
{
    int* x = new int;
} // x goes out of scope, no way to delete the int

Further, it is not clear what this line is supposed to do int *nptr2 = 2*nptr+ptr2;. It is not valid C++, hence I am going to ignore it for the rest of the answer. Also the last two lines are not that relevant (maybe for code that comes after the shwon code but not here).
So we are left with:
 int * ptr = new int;
 int *nptr = ptr
 int * ptr2 = new int;
 delete ptr;
 delete ptr2;

You create two int via new. You delete two int. No memory is leaked. After delete ptr the pointer nptr points to a no longer existing object. nptr is said to be a dangling pointer.
With that out of the way, we can turn to your actual question: How to monitor dangling raw pointers?
You cannot. A raw pointer is rather primitive. It stores an address. And thats all. The pointer is not aware whether there is an object at that adress or not. This is one reason you should not use new and delete and raw pointers to manage memory. Use smart pointers. For example if you share ownership between two std::shared_ptr then the pointee will be kept alive as long as one of the shared pointers is alive. A shared pointer cannot dangle (unless you do something wrong).

A: I would recommend that you not use raw pointers. If you use smart pointers that then you will never(*) have a dangling pointer. The whole purpose of smart pointers is to ensure that the lifetime of both the pointer and what is pointed to is managed together.
Use std::unique_ptr, std::shared_ptr (and std::weak_ptr if needed).
You can use tools like Valgrind and AddressSanitizer to ensure that you do not use dangling pointers.
(*) never is perhaps too strong, at least make it more difficult.


text:
Q: Spreading or mapping an array changes an array inside the attributes I'm trying to use an array of objects I get from an API to create the arrays of a reactjs app. The only problem I find is that somehow my array of routes gets corrupted when I spread or map it.
Here is the code snippet.
const childRoutes = (Layout, routes) => {
    console.log(routes);
    console.log([...routes]);

    return routes.map(({ children, path, component: Component }, index) => {
        return children ? (
            // Route item with children
            children.map(({ path, component: Component }, index) => {
                return (
                    <Route
                        key={index}
                        path={path}
                        exact
                        render={(props) => (
                            <Layout>
                                <Component {...props} />
                            </Layout>
                        )}
                    />
                );
            })
        ) : (
            // Route item without children
            <Route
                key={index}
                path={path}
                exact
                render={(props) => (
                    <Layout>
                        <Component {...props} />
                    </Layout>
                )}
            />
        );
    });
};

All the extra returns are because I was adding extra console.logs.
The routes come from another component. Here is the console.logs returned:
As you can see, the children array is emptied when I spread the array. It is also emptied when I try to map it to create the routes.


text:
Q: Split paths into lists Im struggeling to find a clever way of solving this problem.
I have a List containing paths for certain files.
The paths could look as such:
"Dinner/Soup/CurrySoup"
"Dinner/Soup/ChickenSoup/Croutons"
"Dinner/Beef/RibEye/Sauce/"
"Breakfast/Cereal/Kellogs"

I have to make a list containing the first part of the path for each String in the list, then a list containing the second part and so on. I believe using a splitter on each String is the way to go and adding it to an array before filling the lists. As far as I have understood, an array containing 3 substrings will be created if using .Split('/') of the first string described. I have come to the understanding that "Dinner" would be on Array[0], "Soup" on Array[1] and so on… Now to the real problem. I can make it work for 1 String, but making it happen using variables to define the index of which list the substring should go to seems to cause me trouble when doing it for more than just one path and creating 10 lists to be able to deal with paths, that could be long (say 10?) seems like overkill. Any idea?
For those who wanted to see what I tried myself, here is what I did:
            List<string> list = new List<string>();
        List<string> listCategory1 = new List<string>();
        List<string> listCategory2 = new List<string>();
        List<string> listCategory3 = new List<string>();

        string s;

        list.Add("category1/category2/category3");
        list.Add("category1/category2/category4");
        list.Add("category6/category7/category8");

        foreach (String s1 in list)
        {
            String[] a = s1.Split('/');

            int i = 0;

                if(i==0)
                {
                    listCategory1.Add(a.ElementAt(i));
                    i++;
                }
                if (i == 1)
                {
                    listCategory1.Add(a.ElementAt(i));
                    i++;
                }
                if (i == 2)
                {
                    listCategory1.Add(a.ElementAt(i));
                    i++;
                }
        }

        Console.WriteLine(listCategory1.ElementAt(0));
        Console.WriteLine(listCategory1.ElementAt(1));
        Console.WriteLine(listCategory1.ElementAt(2));

The console output being: category1, category2, category3.
I only managed to get the right answers for the first list. I thought about making a method taking in the string and calling the method multiple times.

A: You can use this approach:
var allTokens = paths.Select(p => p.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries));
int maxLength = allTokens.Max(tokens => tokens.Length);
var allLists = new List<List<string>>(maxLength);
for (int i = 0; i < maxLength; i++) allLists.Add(new List<string>());
foreach (string[] tokens in allTokens)
    for (int i = 0; i < tokens.Length; i++)
        allLists[i].Add(tokens[i]);

That's the most natural way to solve this. Here's the obligatory LINQ approach:
var indexLookup = allTokens
    .Select(arr => arr.Select((Token, Index) => new { Token, Index }))
    .SelectMany(x => x)
    .ToLookup(x => x.Index);

Now you have a lookup which is similar to a dictionary but allows duplicate keys and also to lookup a key which doesn't exist(returns an empty sequence).
You get a List<String> for a given index in the following way:
List<string> index2List = indexLookup[2].Select(x => x.Token).ToList();

Result:
"CurrySoup"
"ChickenSoup"
"RibEye"
"Kellogs"

If you want to know how to use the lookup-approach to get the List<List<string>>:
List<List<string>> allLists = Enumerable.Range(0, indexLookup.Count)
    .Select(i => indexLookup[i].Select(x => x.Token).ToList())
    .ToList();


text:
Q: Ionic - Android authorities: FacebookContentProvider undefined in android manifest Can't install because provider name com.facebook.app.FacebookContentProviderundefined (in package io.ionic.sxxxx) is already used by io.ionic.yyyyy]"
This is listed in a few android manifest files
<provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.app.FacebookContentProvider"
        android:exported="true" />

on build I get
<provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.app.FacebookContentProviderundefined"
        android:exported="true" />

— notice the undefined ----- should I be defining something somewhere? Is there another solution? Basically I have a pair of apps that will not install at the same time on a device because this output is the same. My understanding is undefined should be my facebook id. I do have a variety of values defined in my android strings file. I have seen a few answers from a couple years ago on here (Android Facebook content provider authority) , but the solutions do not work as the files in my android directory are different as are their contents. Any help would be much appreciated!
<string name="title_activity_main">xxxx</string>
<string name="package_name">io.ionic.xxxx</string>
<string name="custom_url_scheme">io.ionic.xxxx</string>
<string name="fb_app_id">xxxxx</string>
<string name="facebook_app_id">xxxxx</string>
<string name="fb_app_name">xxxxx</string>
<string name="fb_login_protocol_scheme">fbxxxxxx</string>
<string name="fb_auto_log_app_events_enabled">true</string>
<string name="fb_advertiser_id_collection_enabled">true</string>

I have tried deleting all of the tags from all of the android manifest files, but they are generated on build. I have tried adding a string called authority in my string.xml file. I have struggeled to figure out how to implement the solutions here, as they dont exactly align with the files in my ionic project. Android Facebook content provider authority.

A: There is an open issue about this on GitHub:
https://github.com/cordova-plugin-facebook-connect/cordova-plugin-facebook-connect/issues/100
Did you try the temporary solutions provided in the comments?
HCJSolutions commented on Dec 10, 2021

I found a temporary solution is add ${applicationId}
modified the platforms\android\app\src\main\AndroidManifest.xml find a
node 123456789"
android:exported="true"
android:name="com.facebook.FacebookContentProvider" />
or
change it at
plugin folder plugins\cordova-plugin-facebook-connect\plugin.xml find
the line <provider
android:authorities="com.facebook.app.FacebookContentProvider${applicationId}$APP_ID"

and
apren commented on Apr 24:

Another temporary solution:
Set any APP_ID, for example APP_ID = "app_package_name" After init app
use code
facebookConnectPlugin.setApplicationId('your_facebook_app_id')


text:
Q: css for leaving space among two button tag I want to leave some space among two buttons which is in div tag.I tried lot but still having problem.I created login div which has two buttons. login div is inside header div which I marked as 'h'.I want to leave some space among two buttons where I rounded in green.But now I drawn current displayed location in red color.

.login{
    margin:0;
    padding:0px 10px 10px 0px;
    text-align:right;
    width:40%;
    position:absolute;
  right:0;
  bottom:0;

}
.login button
{
   padding:0px 10px 10px 0px;
 }

        <button class="add">login</button>
        <button class="upload">Enquiry</button>

A:  .login button
 {
    margin-left:10px;
 }

add some left-margin?

A: ok try this.....i hope this will be okey...
  .login button
 {
  margin-left:10px;

 padding:0px 10px 10px 0px;
 }

This is the fiddle http://jsfiddle.net/41fhejfd/4/

A: like this type

.login{
    margin:0;
    padding:0px 10px 10px 0px;
    text-align:right;
    width:40%;
    position:absolute;
  right:0;
  bottom:0;

}
.login button
{
   padding:0px 10px 10px 0px;
   margin-left: 10px;
 }

        <button class="add">login</button>
        <button class="upload">Enquiry</button>

A: You could do:
.login button {
   margin-left: 30px;
}

Or you could add a container around your buttons, give that a width, and then float them to the left and right sides.
The HTML:

           <button class="add">login</button>
           <button class="upload">Enquiry</button>

The CSS:
.logincontainer {
    width: 200px;
}
.add {
    float: left;
}
.upload {
    float: right;
}


text:
Q: reading led requirements I'm still pretty new to electronics and I bought an led from radio shack that said 12vdc add max. It also said 20mA and 1.5mcd which says is it's intensity. Is 12vdc the max volts and 20mA the minimum volts (one I convert it to voltage). It also confess with a built in resister

A: Sounds like this is an indicator LED assembly, not a bare LED. (although I don't know what "add max" refers to.)
It includes a current limiting circuit in series with the LED, and is intended to operate directly from 12 volts, with no additional current limiting required.
If you connect it to 12 Volts, it will draw 20 mA.


text:
Q: Server push to c# client in GAE Is there any way to implement server push from GAE to c# client? I found channel-api is available only for Javascript applications & also GAE is not supporting comet solutions.

A: There's not currently any supported mechanism of doing client push to anything other than a Javascript client, unless you use an external service to do it.


text:
Q: Oracle throwing SP2-1502 where there is no http_proxy variable set I have a problem trying to conect to an Oracle database via sqlplus.
The command line looks like this:
C:\oracle\product\11.2.0\client_1>sqlplus
Error 46 initializing SQL*Plus
HTTP proxy setting has incorrect value
SP2-1502: The HTTP proxy server specified by http_proxy is not accessible

C:\oracle\product\11.2.0\client_1>http_proxy
'http_proxy' não é reconhecido como um comando interno
ou externo, um programa operável ou um arquivo em lotes.

Acording to this blog post! it apears to complain about the value on the http_proxy variable, but this variable don't even exist in the client machine.
Anyone had this same problem over windows?

Edit:
Sorry guys. I had http_proxy set as a user variable. I was just trying to look at it the wrong way.
Wrong:
C:\Users\ilson.bolzan>http_proxy

Right:
C:\Users\ilson.bolzan>echo %http_proxy%

A: I got the same problem on Linux.
When I unsetted 'http_proxy' environment variable as
unset http_proxy
or
export http_proxy=

the problem was repeated.
I found, that 'no_proxy' environment variable spoils the case.
I had right value for http_proxy
http_proxy=http://localhost:3128/

but I had no_proxy=localhost,127.0.0.0/8,::1 too.
I've unset 'no_proxy' environment variable and sqlplus start to work as expected.

A: http_proxy is variable, so on Windows you must set this value
c:\>set http_proxy = whatever

unset value
c:\>set http_proxy =

IMHO U have problem with your ORACLE_SID variable or ORACLE_HOME variable.
Please check this variables that are correctly filled with this command: c:\>set

A: I realise that this is an old question but am adding this as I've had a similar issue a few times and keep coming back to this post, so it may help others.
In Linux, I had both "NO_PROXY" and "no_proxy" set (different case matters).  I had to unset both of these, and left HTTP_PROXY populated.

A: The correct way to set http_proxy and so on is the following:
set http_proxy="http://<proxy_address>"

Note - the 'http://' at the start - some tools do a parsing on the variable and it might fail in case the protocol is missing at the start! The quotes are there for completeness; if you set it like this you will not have errors like SP2-1502.

A:
Just Run these command .

administrator@Rizwan:~$ unset http_proxy

administrator@Rizwan:~$ unset no_proxy

administrator@Rizwan:~$ sqlplus sys as sysdba

A: Same issue happens if the proxy uses authentication, as e.g. with
HTTP_PROXY=http://domain\\user@192.168.178.1

This blocked it for me. What worked to fix it was either to unset the HTTP_PROXY variable entirely, or kick out the domain\\user@ part – i.e., based on above example, change it to:
HTTP_PROXY=http://192.168.178.1

The NO_PROXY variable however didn't disturb the process in my case.

A: Edit your bash script. It runs everytime you open a new terminal.
sudo nano ~/.bash_profile
set on the last line
unset no_proxy
I was under a proxy. So when I added unset http_proxy sqlplus worked but curl fucntion stopped working.

A: Removing https_proxy from the env file helped me.
You can use printenv to see the env variable, and unset https_proxy to remove it.


text:
Q: How many triangle can be drawn with those points? There are 7 points on the circumference of a circle.How many acute triangle can be drawn with those points.        please help me to solve this problem.

A: Assuming that the points are distributed evenly across the circle:
Note that three points on a circle form a non-acute triangle exactly when they lie within the same semicircle.  It follows that the set of acute triangles that we can make from the seven points is the same as all of the triangles except for those that can be made from $4$ adjacent vertices.
Label the seven points on the circle as $1,2,\dots,7$.
There are $\binom 73 = \frac{7\times 6 \times 5}{3 \times 2 \times 1} = 35$ triangles total.
Of those, the $7$ can be made by rotating $\{1,2,3\}$ about the center of the circle (that is, $\{2,3,4\}, \{3,4,5\}$ and so forth) are not acute.  Those that can be made by rotating $\{1,2,4\}$ are also non-acute, as are those can be made by rotating $\{1,3,4\}$.
Thus, there are $7 \times 3 = 21$ non-acute triangles.  It follows that there are exactly $14$ acute triangles.


text:
Q: Does anyone know how to setup the latest playframe work project with Quill I running 2.12/play2.7 project and would like to use Quill.io as the database layer. Does anyone know how to set up such a combination?
I tried to use the https://github.com/getquill/play-quill-jdbc as starting point, but could not get it to work.
Thanks in advance.


text:
Q: Python xlsxwriter, export to a network drive I am wanting to export my .xlsx file to a network drive. I am currently doing this as below:
workbook = xlsxwriter.Workbook('z:/Company drive/Checking/Monthly Checks.xlsx')

I want my colleagues to be able to use this software and would be ideal if they did not have to remap the drive to Z:.
Is it possible to export to a path like "\servername\Checking\Monthly Checks.xlsx"?

A: Yes it is possible to use a UNC path instead of a mapped drive.
I would recommend putting the r'...' string literal modifier in front (link to an answer with a detailed explanation).
So your code would be
workbook = xlsxwriter.Workbook(r'\\servername\Company drive\Checking\Monthly Checks.xlsx')
instead of  workbook = xlsxwriter.Workbook('\\servername\Company drive\Checking\Monthly Checks.xlsx')


text:
Q: Is it safe to use dynamic-imported components in vue with laravel-mix I tried dynamic importing of vue components to increase performance of my app by loading components async and only when needed, as yu can see in the links bellow I had lots of problems with trying to get this to work, so I decided to ditch the idea, now I'm wondering if thave there been any news about this?
https://laracasts.com/discuss/channels/elixir/laravel-mix-dynamic-imports
https://laravel-mix.com/docs/5.0/upgrade
laravel and vue are used a lot so it's rare to see such a crazy bug hasn't been fixed yet.

A: Yes you can use it with laravel mix this bug was before v4 and they fixed it and every thing is working as a charm


text:
Q: Convergence of infinite $ \sum (\frac{n}{n+1})^{n^2} $? I have being trying to solve this convergence but with no success. Using the ratio test I have reached here:
$$
a_n = \left( \frac{n}{n+1} \right)^{n^2}
$$
And
$$
\frac{1}{a_n} = \left( \frac{n+1}{n} \right)^{n^2}
$$
Also
$$
a_{n+1} = \left(\frac{n+1}{n+2}\right)^{{(n+1)}^2} = \left(\frac{n+1}{n+2}\right)^{n^2+2n+1} = \\ a_{n+1} = \left(\frac{n+1}{n+2}\right)^{n^2} \cdot \left(\frac{n+1}{n+2}\right)^{2n} \cdot \left(\frac{n+1}{n+2}\right)
$$
Therefore
$$
\lim \frac{a_{n+1}}{a_n} = \lim \frac{1}{a_n} \cdot a_{n+1}  = \\
\lim \left[ \left( \frac{n+1}{n} \right)^{n^2} \cdot \left(\frac{n+1}{n+2}\right)^{n^2} \cdot \left(\frac{n+1}{n+2}\right)^{2n} \cdot \left(\frac{n+1}{n+2}\right) \right]
$$
And I dont know how to go any further, I have tried many possibilities none of them reaching any result.

A: Instead of the ratio test, try the root test:
$\displaystyle\lim_{n \to \infty}|a_n|^{1/n} = \lim_{n \to \infty}\left|\left(\dfrac{n}{n+1}\right)^{n^2}\right|^{1/n} = \lim_{n \to \infty}\left(\dfrac{n}{n+1}\right)^{n} = \lim_{n \to \infty}\left(1-\dfrac{1}{n+1}\right)^{n}$
Do you recongnize this limit?

A: The Bernoulli inequality proves that the sequence $\{a_n\}_{n\in\mathbb{N}^+}$ defined by:
$$ a_n = \left(1+\frac{a}{n}\right)^n $$
is an increasing sequence converging towards $e^a$. By taking $a=-1$, this gives that your series is positive and bounded by:
$$\sum_{n\geq 1}e^{1-n} = \frac{e^2}{e-1}.$$


text:
Q: Every projective module is a direct summand of free module. I was reading "Serial Rings" by Gennadi Puninski. There it is written that , "Since every module is a homomorphic image of a free module, every projective module is a direct summand of free module".(ie. if $P$ is a  projective module, there exists a free module F such that,
$ F=P \oplus T$ for some module $T$.)
But I can't understand how "Every module is a homomorphic image of a free module" implies that "Every projective module is a direct summand of free module".
(I have found a proof for "Every projective module is a direct summand of free module" but the first part of the above mentioned sentence wasn't used there.)

A: Let $P$ be a projective module. We wish to show that it is the direct summand of a free module. Let $\varphi : F \to P$ be a surjection, where $F$ is a free module.
Consider the following diagram below.

Since $P$ is projective, there exists a map $\psi : P \to F$ making the following diagram commute.

It now follows that $F = \operatorname{im} \psi \oplus \ker \varphi$. But $\varphi \circ \psi = \operatorname{id}_P$ implies that $\psi$ is injective and thus, $\operatorname{im} \psi \cong P$, as desired.


text:
Q: Sharing on FB not working When I try to share stuff on Facebook from my app, the "Post" button is not working. The cancel button on the left side is working, but the post button on the right is not.
This is my code:
@IBAction func saveToFB(sender: AnyObject) {
        if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){
            var facebookSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
            facebookSheet.setInitialText("Share on Facebook")
            self.presentViewController(facebookSheet, animated: true, completion: nil)
        } else {
            var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

A: So I tried this out...
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
                let fbcomposer = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
                fbcomposer.setInitalText(text)
                fbcomposer.addImage(UIImage(named: myimg.png))
                fbcomposer.addURL(NSURL(string: iosLink))
                presentViewController(fbcomposer, animated: true, completion: {})
            }

The problem is in your code you are only setting the InitialText. There is some issue with fb that does not allow third party apps to set text when posting. In my case, it was adding the image and the link as well. But the text was not added.
Try adding links or images and see if the problem still persists.
Hope this helps. :)


text:
Q: Is there a config for uploading big files in Django with a progress bar on IIS? I am using Django version 2.2 and IIS (Fastcgi) to create a web page to upload a big file with a progress bar. I used code from the following links:
https://djangosnippets.org/snippets/678/
https://djangosnippets.org/snippets/679/
My application works perfectly in a development environment, but in a production environment, when I watch the console browser it always returns a 'null' value, and the progreess bar is not showing, but the file uploaded on the server and returns '200'. Why? it is another config I should add on IIS or on my web?
The following code returns Null in the console:
def upload_progress(request):
    """
    Return JSON object with information about the progress of an upload.
    """
    progress_id = ''
    if 'X-Progress-ID' in request.GET:
        progress_id = request.GET['X-Progress-ID']
    elif 'X-Progress-ID' in request.META:
        progress_id = request.META['X-Progress-ID']
    if progress_id:
        cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
        data = cache.get(cache_key)
        return HttpResponse(json.dumps(data))
    else:
        return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.')

view.py :
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseServerError
from django.core.cache import cache
from .forms import UploadFile
from upbar.UploadProgressbar import UploadProgressCachedHandler
from django.views.decorators.csrf import csrf_exempt, csrf_protect
import json

@csrf_exempt
def upload_file(request):
    request.upload_handlers.insert(0, UploadProgressCachedHandler(request))
    return _upload_file(request)
# Create your views here.

def _upload_file(request):
    if request.method == 'POST':

        form = UploadFile(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponse('200')
    else:
        form = UploadFile()
    return render(request, 'upbar/home.html', {'form': form})

def handle_uploaded_file(f):
    with open(f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

# A view to report back on upload progress:
#
def upload_progress(request):
    """
    Return JSON object with information about the progress of an upload.
    """
    progress_id = ''
    if 'X-Progress-ID' in request.GET:
        progress_id = request.GET['X-Progress-ID']
    elif 'X-Progress-ID' in request.META:
        progress_id = request.META['X-Progress-ID']
    if progress_id:
        cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
        data = cache.get(cache_key)
        return HttpResponse(json.dumps(data))
    else:
        return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.')

setup.py:
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4u%-od)a^a-=)_g_@^_v1sssv%)s@95f25oifgpixtx8!f=*7v'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'upbar.apps.UpbarConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'uploadbar.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'uploadbar.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# DATA_UPLOAD_MAX_MEMORY_SIZE = 2147483648

form.py:
from django import forms

class UploadFile(forms.Form):
    """UploadFile definition."""

    file = forms.FileField()

UploadProgressbar.py:
from django.core.files.uploadhandler import TemporaryFileUploadHandler
from django.core.cache import cache
import time

class UploadProgressCachedHandler(TemporaryFileUploadHandler):
    """
    Tracks progress for file uploads.
    The http post request must contain a header or query parameter, 'X-Progress-ID'
    which should contain a unique string to identify the upload to be tracked.
    """

    def __init__(self, request=None):
        super(UploadProgressCachedHandler, self).__init__(request)
        self.progress_id = None
        self.cache_key = None

    def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
        self.content_length = content_length
        if 'X-Progress-ID' in self.request.GET:
            self.progress_id = self.request.GET['X-Progress-ID']
        elif 'X-Progress-ID' in self.request.META:
            self.progress_id = self.request.META['X-Progress-ID']
        if self.progress_id:
            self.cache_key = "%s_%s" % (
                self.request.META['REMOTE_ADDR'], self.progress_id)
            cache.set(self.cache_key, {
                'length': self.content_length,
                'uploaded': 0
            }, 30)

    def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_typ_extra=None):
        pass

    def receive_data_chunk(self, raw_data, start):
        if self.cache_key:
            data = cache.get(self.cache_key)
            data['uploaded'] += self.chunk_size
            cache.set(self.cache_key, data)
        return raw_data

    def file_complete(self, file_size):
        if self.cache_key:
            data = cache.get(self.cache_key)
            data['uploaded'] = self.content_length
            cache.set(self.cache_key, data)
            # sleep for give time to receive final response in request progress bar
            time.sleep(3)

    def upload_complete(self):
        if self.cache_key:
            cache.delete(self.cache_key)

upload.js:
$(document).ready(function () {
  function gen_uuid() {
    var uuid = ""
    for (var i = 0; i < 32; i++) {
      uuid += Math.floor(Math.random() * 16).toString(16);
    }
    return uuid
  }
  uuid = gen_uuid();
  // form submission
  $('form').submit(function () {
    // Prevent multiple submits
    if ($.data(this, 'submitted')) return false;
    // Append X-Progress-ID uuid form action
    this.action += (this.action.indexOf('?') == -1 ? '?' : '&') + 'X-Progress-ID=' + uuid;
    $('

 0%

').appendTo('body')

    upload_progress_url = '/upload_progress/'

    function update_progress_info() {
      $.getJSON(upload_progress_url, {
        'X-Progress-ID': uuid
      }, function (data, status) {
        console.log(data)
        if (data) {
          var progress = Math.round((parseInt(data.uploaded) * 100) / parseInt(data.length));
          $('#progressBar').attr('aria-valuenow', progress).css('width', progress + '%').text(progress + '%');

        }

        window.setTimeout(update_progress_info, 100);
      }).fail(function (jqxhr, textStatus, error) {
        console.log('jqxhr errorrr ==================')
        console.log(jqxhr);
        console.log('==================')
        console.log('textstatus ==================')
        console.log(textStatus);
        console.log('==================')
        console.log('jqxhr.responsetext errorrr ==================')
        console.log(jqxhr.responseText)
        console.log('==================')
        console.log('errorrr ==================')
        console.log(error);
      });
    }
    window.setTimeout(update_progress_info, 100);
    $.data(this, 'submitted', true); // mark form as submitted.
    return true;

  });
});

html:
<!DOCTYPE html>

    {% load static %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Home</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    Noting Here
    <form  method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

Here is a screenshot of my console browser:
.

A: You could use below options to increase the file upload limit in iis:
1) Modify the maxAllowedContentLength setting in the web.config
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="2147483648" />
    </requestFiltering>
  </security>
</system.webServer>

2)use iis request filtering feature:

*

*Open IIS Manager.

*Select the website that you want to configure.

*Select Requests Filtering feature from the feature view.

*From the Actions pane on the right-hand side of the screen click Edit Feature Settings... link. The Edit Request Filtering Settings window displays.

*In the Request Limits section, enter the appropriate Maximum allowed content length (Bytes) and then click the OK button.

3)Manually edit the ApplicationHost.config file

*

*Open notepad as administrator.

*Open file %windir%\system32\inetsrv\config\applicationhost.config.

*In the ApplicationHost.config file, locate the  node

*add <requestLimits maxAllowedContentLength ="<length>" />

*Save the ApplicationHost.config file.

Please do not forget to restart the iis server after doing changes.


text:
Q: Date to Megaseconds Is there any easy way to convert from erlang datetime notation to the now/0 notation?
Basically I need the inverse of this function:
{Date, Time} = calendar:now_to_datetime(now()).

So something like
{Megaseconds, Seconds, Microsecods} = datetime_to_now({Date, Time})

A: I retract my question. My google-fu was not warmed up yet it seems. The Following does exactly what I want.
-define(GREGORIAN_SECONDS_1970, 62167219200).

datetime_to_now(DateTime) ->
    GSeconds = calendar:datetime_to_gregorian_seconds(DateTime),
    ESeconds = GSeconds - ?GREGORIAN_SECONDS_1970,
    {ESeconds div 1000000, ESeconds rem 1000000, 0}.


text:
Q: Why am i getting a Syntax error using the following code I am using the following statement to develop a simple query. Unfortunately I continually get a syntax error when I run the page.
If I take out either of the RaisedInvoice Select or the Transaction Sum elements it works but fails when both are in.
It must be something stupid so, can I please apologise in advance for my silly mistake.
SELECT
RaisedInvoices.[Invoice Number], SUM(Transactions.sellgross) AS SumOfsellgross
FROM (RaisedInvoices LEFT JOIN Customers ON RaisedInvoices.[Customer WORef] = Customers.WORef)
LEFT JOIN Transactions ON RaisedInvoices.[Invoice Number] = Transactions.invnumber

A: You are aggregating one column but not the other one. In this case, you need to include a GROUP BY clause with the non-aggregated column(s).
For example:
SELECT
  RaisedInvoices.[Invoice Number], -- not aggegated
  SUM(Transactions.sellgross) AS SumOfsellgross -- aggregated
FROM RaisedInvoices
LEFT JOIN Customers
      ON RaisedInvoices.[Customer WORef] = Customers.WORef
LEFT JOIN Transactions
      ON RaisedInvoices.[Invoice Number] = Transactions.invnumber
GROUP BY RaisedInvoices.[Invoice Number] -- added GROUP BY here

A: Based on your query, I would say that you don't need the join with the Customers table.
Here is how I would write it:
$query = "SELECT RaisedInvoices.[Invoice Number], SUM(Transactions.sellgross) AS SumOfsellgross FROM RaisedInvoices LEFT JOIN Transactions ON RaisedInvoices.[Invoice Number] = Transactions.invnumber";

However, I'm not sure that the brackets syntax is something that the PDO will accept.


text:
Q: Warning Error on Datatable with My Gridview Here is my code using jQuery Datatable
<script type="text/javascript">
    $(function () {
        $("#<%=grdEmployee.ClientID%>").dataTable();
    })
</script>

Here is My GridView Code
<asp:GridView ID="grdEmployee" runat="server" PageSize="5" AutoGenerateColumns="false" OnPageIndexChanging="grdEmployee_PageIndexChanging" AllowPaging="true" AllowSorting="true">
    <Columns>
        <asp:TemplateField HeaderText="Emp ID" SortExpression="Emp ID">
            <ItemTemplate>
                <asp:Label ID="lblEmpID" runat="server" Text='<%#Eval("Empid") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Emp Name" SortExpression="Emp Name">
            <ItemTemplate>
                <asp:Label ID="lblEmpName" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Emp Salary" SortExpression="Emp Salary">
            <ItemTemplate>
                <asp:Label ID="lblEmpSalary" runat="server" Text='<%#Eval("Salary") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
                <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandArgument='<%#Eval("Empid") %>' CommandName="eEdit"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Delete">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandArgument='<%#Eval("Empid") %>' CommandName="eDelete"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

When I set GridView page size property to 5, it will give me a data table warning.
My database has 9 records and when I change the pagesize value from 5 to 10, it will not return any warning.


text:
Q: Using OOP plugin's methods throughout the website I'm making a plugin for a website, which methods I'd like to use in a few different places, such as page templates, shortcodes etc.
I don't want to make the plugin class global or create more than one instance (I'm creating one instance of it on plugin activation).
What's the best approach to do it? Should I make shortcodes that use those functions? Or is there a better way?

A: I'm not entirely sure what you want to do exactly. But basically you just create one instance and then add functions like public static function FunctionName() to be used anywhere you want after the plugin got activated. To fire your hooks simply use the public function __construct().
Taking the Sample Plugin from below, the FooBar method can be called in any template like that:
<div class="foobar">
  <?php echo MyPlugin::FooBar(); ?>
</div>

And to call FooBar inside its class in another function you'd do:
self::FooBar();

Sample Plugin
<?php
/*
Plugin Name: My Plugin
Description: Lorem ipsum dolor sit amet.
Version: 1.0
Author: You
Author URI: https://example.com
*/

class MyPlugin {

  // Fire your hooks from here.
  public function __construct() {

    add_action('wp_enqueue_scripts', [$this, 'scripts']);
  }

  // Use any generic function to be used for hooks.
  function scripts() {

    wp_enqueue_script('abc_snippets', plugin_dir_url(__FILE__) . 'js/scripts.js', ['jquery'], NULL, TRUE);
  }

  // Use static public functions to also be used outside of this class.
  public static function FooBar() {

    return 'Hello World';
  }

}

new MyPlugin();

A: One way is to use static methods from class itself, as @leymannx explained in his answer.
I prefer a little bit different approach, which is a little bit nicer/cleaner (but it's only my opinion, so feel free to argue with that statement). I do it like so:

*

*If some function should be available for use in templates, then I register is as a template tag (so I call it the same way WordPress does - get_X for getting something and the_X for printing something.

*If some function should be available for use as a shortcode, then I register such shortcode.

*I then register my own filters/actions hooks for the functions/shortcodes above and in my class I use these hooks and write proper code - this way the code is encapsulated in class properly.

And some (very basic) example:
In file template-tags.php I'll add this code:
function the_wpse_hello_world_message( $name = '' ) {
    echo get_wpse_hello_world_message( $name );
}

function get_wpse_hello_world_message( $name = '' ) {
    return apply_filters( 'get_wpse_hello_world_message', 'Hello World', $name );
}

So anyone can easily use both of these functions anywhere in the code, and it's pretty easy to find out what is the "public API" of my plugin.
And later in my class I do something like this:
class My_WPSE_Super_Plugin {

    protected function initHooks() {
        add_filter( 'get_wpse_hello_world_message', array( $this, 'get_wpse_hello_world_message_filter' ), 10, 2 );
    }

    ...

    protected get_wpse_hello_world_message_filter( $result, $name ) {
        if ( trim($name) ) {
            return 'Hello, ' . $name . '!';
        }

        return $result;  // or return 'Hello world!'.
    }
}

The pros for this method are (IMHO):

*

*it's easier to learn the "public API" of a plugin (which is important if the team is bigger, or if you will work with given site for a long time)

*the real code inside the class gets properly encapsulated

*the "public API" is separated from real implementation, so it's easy to document (write some comments for users) and to do refactoring later someday... Let's say the class gets to big and you want to divide it to smaller classes? What then? Will all users have to change all their templates?

*it allows to modify these parts using filters/actions (and we all love WP exactly for that, right?)


text:
Q: Unable to display NSString in Xcode 9.2 debugger Xcode has suddenly stopped being able to display NSString's to me - instead it will only show the addresses, even if I do po myString.
The program executes perfectly. If I use NSLog to send the string to the console then that works.
It's making debugging very hard - has anyone got a solution to this?

(lldb) p settingsPath
(NSString *) $1 = 0x00007ffeefbf9820
(lldb) po settingsPath
0x00007ffeefbf9820


text:
Q: Java's ExecutorService.awaitTermination vs Future.get() I am using ExecutorService and submitting 2 Callables.
Can you tell me what is the difference between using ExecutorService.awaitTermination vs using the Future.get() ?
I do not want the threads to keep running indefinitely, and also each Future's exception should not affect other thread's Future.
    ExecutorService executor = Executors.newFixedThreadPool(2);

    Future<MyObject1> obj1 = null;
    if (true) {
        task1 = executor.submit(<Callable1>);
    }

    Future<MyObject2> obj2 = null;
    if (<Condition>) {
        task2 = executor.submit(<Callable2>);
    }

    executor.shutdown();
    try {
        executor.awaitTermination(TIMEOUT_VALUE, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
    }finally {
        if( !executor.isTerminated()) {

        }

        try {
            executor.shutdownNow();
        }catch(Exception e) {
        }

    }

    MyObject1 myobj1 = null;

    try {
        myobj1 = task1 != null ? task1.get() : null;
    } catch (InterruptedException | ExecutionException e) {

    }

    MyObject2 myobj2 = null;

    try {
        myobj2 = task2 != null ? task2.get() : null;
    } catch (InterruptedException | ExecutionException e) {
    }

A: Similarity between ExecutorService.awaitTermination and Future.get(<TimeOut>) is that both are blocking in nature. Suppose you have called any of these methods in thread T then T will be blocked until condition associated with each is fulfilled.
In case of ExecutorService.awaitTermination, thread will be blocked until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. Read docs. While in case of Future.get(<TimeOut>) thread will be blocked until the task is submitted and result is returned or an exception occured etc. Read docs.
Difference between them is "usability" of each and key driver for that is as mentioned below:
ExecutorService.awaitTermination

*

*Should be use when you want to block the thread and do wish to proceed further until a specified time is elapsed (that is the time you will specify in awaitTermination(long timeout, TimeUnit unit)) Typically people either specify value like Long.MAX_VALUE so as to wait too long or smaller values which they think as per their business requirement, for example if I am waiting for response to be committed to GUI then I may not wait more than 5 minutes.

*Should be used when you do not care about the results returned by the threads executing tasks.

*Should be used when you do not want to wait infinitely for tasks to finish, and want to specify some threshold time.

Future.get(<TimeOut>)

*

*Key difference between this and later is that you should use it when you want the thread to return the results and until that happens you want to keep the thread blocked and do not want to proceed further, and that's the reason you will use Callable when submitting the tasks. So, when you call Future.get(<TimeOut>) then thread will be blocked until results are returned by the thread or some exception occurs in the executing thread.

Refer below sample code I have created to demonstrate the usability of each, I have provided inline code comments to better explanation.

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceFutureAndAwaitTermincationExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        testFutureGet(); // after testing comment out this and uncomment below
        //testAwaitTermination();
    }

    private static void testAwaitTermination() throws InterruptedException {
List<Future<String>> futuresList = new ArrayList<>();

        final ExecutorService executorService = Executors.newCachedThreadPool();

        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask1 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(2000, true);
        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask2 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(1000, true);
        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask3 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(3000, true);

        System.out.println("### Starting submitting tasks");

        // submit the callable and register the returned future object so that it can be processed later.
        futuresList.add(executorService.submit(callableTask1));
        futuresList.add(executorService.submit(callableTask2));
        futuresList.add(executorService.submit(callableTask3));

        executorService.shutdown();

        System.out.println("### Finished submitting tasks and shutdown executorService " + new Date());

        executorService.awaitTermination(1, TimeUnit.SECONDS); // try this with 10 seconds and you will see after 3 seconds it reaches next line

        // uncomment below and comment out above.
        /*new Thread(){
            public void run() {
                try {
                    System.out.println("@@@" + new Date());
                    executorService.awaitTermination(1, TimeUnit.SECONDS); // try this with 10 seconds and you will see after 3 seconds it reaches next line
                    System.out.println("@@@" + new Date());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
        }.start();*/

        System.out.println("### Finished. " + new Date());
    }

    private static void testFutureGet() throws InterruptedException, ExecutionException {
        List<Future<String>> futuresList = new ArrayList<>();

        ExecutorService executorService = Executors.newCachedThreadPool();

        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask1 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(2000, false);
        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask2 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(1000, false);
        ExecutorServiceFutureAndAwaitTermincationExample.CallableTask callableTask3 = new ExecutorServiceFutureAndAwaitTermincationExample.CallableTask(3000, false);

        System.out.println("### Starting submitting tasks");

        // submit the callable and register the returned future object so that it can be processed later.
        futuresList.add(executorService.submit(callableTask1));
        futuresList.add(executorService.submit(callableTask2));
        futuresList.add(executorService.submit(callableTask3));

        executorService.shutdown();

        System.out.println("### Finished submitting tasks and shutdown executorService");

        for (int i = 0; i < futuresList.size(); i++) {
            // here "get()" waits for the future tasks to be returned.
            System.out.println(futuresList.get(i).get());
        }

        System.out.println("### Finished.");
    }

    static class CallableTask implements Callable<String>{

        private long timeToSleep;
        private boolean shouldLog;

        CallableTask(long _timeToSleep, boolean _shouldLog){
            this.timeToSleep = _timeToSleep;
            this.shouldLog = _shouldLog;
        }

        @Override
        public String call() throws Exception {
            String str = new Date() + ": Processing - " + this.hashCode() + " | " + Thread.currentThread() + ", slept for seconds - " + timeToSleep;
            System.out.println(str);
            Thread.sleep(timeToSleep);
            if(this.shouldLog){
                System.out.println(str + " ||||| completed at: " + new Date());
            }
            return str + " ||||| completed at: " + new Date();
        }

    }
}

And for your point:

I do not want the threads to keep running indefinitely, and also each
  Future's exception should not affect other thread's Future.

ExecutorService.awaitTermination and Future.get(<TimeOut>) are not meant to control whether threads (which are processing your tasks) will run indefinitely or not, threads will run until the task they are performing is finished and run method of the thread is finished to completion. And I have explained the purpose of ExecutorService.awaitTermination and Future.get(<TimeOut>) above. And typically exception in one thread will not affect another thread, unless you are doing something which interrupt/affects other threads.

A:
Can you tell me what is the difference between using ExecutorService.awaitTermination vs using the Future.get() ?

ExecutorService.awaitTermination() should only be called after an ExecutorService.shutdown() request.  The spec doesn't define behavior if awaitTermination is called before shutdown.  But in a nutshell, awaitTermination should only be used if you are intending to throw away the ExecutorService and never use it again.  The Java EE Concurrency spec actually rejects applications calling this method.  Overall, this doesn't look like the right option for your use case.
Future.get(Timeout) is for waiting for a specific Future to complete, and has nothing to do with wanting to shutdown the ExecutorService that the future is running in.
Also related, see this answer:
How to check if all tasks running on ExecutorService are completed

A: Futire.get waits for task to complete. ExecutorService.awaitTermination waits for executor service to be stopped. Usually, you should create Executor once and reuse it until application shutdown.
You may want to use Fuitire.get with timeout then cancel a future, if task was not completed. In this case other tasks will not be affected:
import java.util.concurrent.*;

public class Test {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        Future task = executor.submit(() -> {
                Thread.sleep(200);
                return "1";
        });

        // later in time...
        try {
            Object result = task.get(150, TimeUnit.MILLISECONDS);
            System.out.println("result = " + result);
        } catch (InterruptedException e) {
            System.out.println("Task interrupted");
        } catch (ExecutionException e) {
            System.out.println("Task execution failed");
        } catch (TimeoutException e) {
            System.out.println("Task timed-out. isDone=" + task.isDone() + ", isCancelled=" + task.isCancelled());
            // cancel long-running task if you want to save resources
            task.cancel(true);
            System.out.println("Task Cancelled. isDone=" + task.isDone() + ", isCancelled=" + task.isCancelled());
        }

        // no more need for executor
        System.out.println("Shutting down executor");
        executor.shutdown();
    }
}

Output:
Task timed-out. isDone=false, isCancelled=false
Task Cancelled. isDone=true, isCancelled=true
Shutting down executor


text:
Q: How to set the default parameter value for jdbc inbound-channel-adapter? I have jdbc inbound-channel-adapter with select parametrized query.
How to set the default parameter value?

A: I believe you can use something like ExpressionEvaluatingSqlParameterSourceFactory.createParameterSourceNoCache(null):
/**
 * Create an expression evaluating {@link SqlParameterSource} that does not cache it's results. Useful for cases
 * where the source is used multiple times, for example in a {@code <int-jdbc:inbound-channel-adapter/>} for the
 * {@code select-sql-parameter-source} attribute.
 * @param input The root object for the evaluation.
 * @return The parameter source.
 */
public SqlParameterSource createParameterSourceNoCache(final Object input) {

There is no something like "default parameter value", but you can emulate it with the SpEL's Elvis operator for the particular parameter name. See public void setParameterExpressions(Map<String, String> parameterExpressions) { of the mentioned factory.

A: Solve it with creation class:
public class SqlParameterTransfer extends AbstractSqlParameterSource {

public void setValue(String key) {
    synchronized (lock) {
        this.key = key;
    }
}

@Override
public String getValue(String paramName) throws IllegalArgumentException {
    String value = null;
    if (KEY_PARAM_NAME.equals(paramName)) {
        value = key;
    }
    return value;
}

@Override
public boolean hasValue(String paramName) {
    return KEY_PARAM_NAME.equals(paramName);
}

private static final String KEY_PARAM_NAME = "key";
private Object lock = new Object();
private String key = "default_value";

}
Then use it in inbound-channel-adapter in this way (through the bean):
<int-jdbc:inbound-channel-adapter
    ...
    select-sql-parameter-source="sqlParameterTransfer">
    ...
</int-jdbc:inbound-channel-adapter>


text:
Q: AttributeError: 'Trivia' object has no attribute 'all_answers' So im making a trivia game, but when I call the method I get an "AttributeError: 'Trivia' object has no attribute 'all_answers'". I want it to print the answers/questions etc but I get an attribute error. I have also tried redoing my indentation, but to no avail. Any help is appreciated.
import urllib.request
import json
import html
import random

class Trivia:
    def __init__(self):
        self.url = "https://opentdb.com/api.php?amount=1&token=0df3b13c1e3961940cfc31352d6ef84aeb140dd8cc48388e84060855713ab982"
        self.openUrl = urllib.request.urlopen(self.url)
        self.data = json.load(self.openUrl)  # opening the json data

        for item in self.data["results"]:
            self.category = html.unescape(item["category"])
            self.question = html.unescape(item["question"])
            self.correct_answer = html.unescape(item["correct_answer"])
            self.incorrect_answers = html.unescape(item["incorrect_answers"])
            self.all_answers = html.unescape(item["incorrect_answers"])
            self.all_answers.insert(random.randint(0, len(self.incorrect_answers)), self.correct_answer)

    def return_category(self):
        return self.category

    def return_question(self):
        return self.question

    def return_correct_answer(self):
        return self.correct_answer

    def return_wrong_answers(self):
        return ", ".join(self.incorrect_answers)

    def return_all_answers(self):
        print(self.all_answers)
        return self.all_answers

t = Trivia()
print(t.return_all_answers())

A: My output with a print:
{'response_code': 3, 'results': []}
Traceback (most recent call last):
  File "C:\Users\nagyl\Desktop\Prog\test.py", line 41, in <module>
    print(t.return_all_answers())
  File "C:\Users\nagyl\Desktop\Prog\test.py", line 37, in return_all_answers
    print(self.all_answers)
AttributeError: 'Trivia' object has no attribute 'all_answers'

Your results array is empty, therefore all answers isn't created. In fact, all your variables are not created. Check your API call, or declare your variables, with initial values.

A: I found out what the problem was: it was the url. I guess I accidentally removed some characters. Thanks for the help


text:
Q: Is there a way to adjust image size in a button in iOS? As seen in the image below, the image of the button is crossing the button boundaries. Is there a way to make the image fit in the boundaries of the button either through the storyboard or programmatically?

A: Change the Button Style from Plain to Default:

Here is a button constrained to 60 x 60 with a 80 x 80 image with Style: Plain:

and with Style: Default: